text
stringlengths
54
60.6k
<commit_before>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP #define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err/is_scal_finite.hpp> #include <stan/math/prim/err/throw_domain_error.hpp> #include <stan/math/prim/err/throw_domain_error_vec.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/get.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <cmath> namespace stan { namespace math { namespace internal { /** * Return true if y is finite * * @tparam T_y type of y * @param y parameter to check * @return boolean */ template <typename T_y> bool is_finite(const T_y& y) { return is_scal_finite(y); } /** * Return true if every element of the matrix y is finite * * @tparam T_y type of elements y * @param y matrix to check * @return boolean */ template <typename T_y, int R, int C> bool is_finite(const Eigen::Matrix<T_y, R, C>& y) { bool all = true; for (size_t n = 0; n < y.size(); ++n) { all &= is_finite(y(n)); } return all; } /** * Return true if every element of the vector y is finite * * @tparam T_y type of elements y * @param y vector to check * @return boolean */ template <typename T_y> bool is_finite(const std::vector<T_y>& y) { bool all = true; for (size_t n = 0; n < stan::math::size(y); ++n) { all &= is_finite(y[n]); } return all; } } // namespace internal /** * Check if <code>y</code> is finite. * This function is vectorized and will check each element of * <code>y</code>. * @tparam T_y Type of y * @param function Function name (for error messages) * @param name Variable name (for error messages) * @param y Variable to check * @throw <code>domain_error</code> if y is infinity, -infinity, or NaN */ template <typename T_y, require_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const T_y& y) { if (!internal::is_finite(y)) { throw_domain_error(function, name, y, "is ", ", but must be finite!"); } } /** * Return <code>true</code> if all values in the std::vector are finite. * * @tparam T_y type of elements in the std::vector * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y std::vector to test * @return <code>true</code> if all values are finite **/ template <typename T_y, require_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const std::vector<T_y>& y) { for (size_t n = 0; n < stan::math::size(y); n++) { if (!internal::is_finite(stan::get(y, n))) { throw_domain_error_vec(function, name, y, n, "is ", ", but must be finite!"); } } } /** * Return <code>true</code> is the specified matrix is finite. * * @tparam Derived Eigen derived type * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y matrix to test * @return <code>true</code> if the matrix is finite **/ template <typename EigMat, require_eigen_t<EigMat>* = nullptr> inline void check_finite(const char* function, const char* name, const EigMat& y) { if (!value_of(y).allFinite()) { for (int n = 0; n < y.size(); ++n) { if (!std::isfinite(value_of_rec(y(n)))) { throw_domain_error_vec(function, name, y, n, "is ", ", but must be finite!"); } } } } /** * Return <code>true</code> if all values in the std::vector are finite. * * @tparam T_y type of elements in the std::vector * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y std::vector to test * @return <code>true</code> if all values are finite **/ template <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const std::vector<T_y>& y) { for (size_t n = 0; n < stan::math::size(y); n++) { if (!internal::is_finite(stan::get(y, n))) { throw_domain_error(function, name, "", "", "is not finite!"); } } } } // namespace math } // namespace stan #endif <commit_msg>Updated check_finite to support `var<mat>` s (Issue #2101)<commit_after>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP #define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err/is_scal_finite.hpp> #include <stan/math/prim/err/throw_domain_error.hpp> #include <stan/math/prim/err/throw_domain_error_vec.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/get.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <cmath> namespace stan { namespace math { namespace internal { /** * Return true if y is finite * * @tparam T_y type of y * @param y parameter to check * @return boolean */ template <typename T_y> bool is_finite(const T_y& y) { return is_scal_finite(y); } /** * Return true if every element of the matrix y is finite * * @tparam T_y type of elements y * @param y matrix to check * @return boolean */ template <typename T_y, int R, int C> bool is_finite(const Eigen::Matrix<T_y, R, C>& y) { bool all = true; for (size_t n = 0; n < y.size(); ++n) { all &= is_finite(y(n)); } return all; } /** * Return true if every element of the vector y is finite * * @tparam T_y type of elements y * @param y vector to check * @return boolean */ template <typename T_y> bool is_finite(const std::vector<T_y>& y) { bool all = true; for (size_t n = 0; n < stan::math::size(y); ++n) { all &= is_finite(y[n]); } return all; } } // namespace internal /** * Check if <code>y</code> is finite. * This function is vectorized and will check each element of * <code>y</code>. * @tparam T_y Type of y * @param function Function name (for error messages) * @param name Variable name (for error messages) * @param y Variable to check * @throw <code>domain_error</code> if y is infinity, -infinity, or NaN */ template <typename T_y, require_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const T_y& y) { if (!internal::is_finite(y)) { throw_domain_error(function, name, y, "is ", ", but must be finite!"); } } /** * Return <code>true</code> if all values in the std::vector are finite. * * @tparam T_y type of elements in the std::vector * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y std::vector to test * @return <code>true</code> if all values are finite **/ template <typename T_y, require_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const std::vector<T_y>& y) { for (size_t n = 0; n < stan::math::size(y); n++) { if (!internal::is_finite(stan::get(y, n))) { throw_domain_error_vec(function, name, y, n, "is ", ", but must be finite!"); } } } /** * Return <code>true</code> is the specified matrix is finite. * * @tparam Derived Eigen derived type * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y matrix to test * @return <code>true</code> if the matrix is finite **/ template <typename Mat, require_matrix_t<Mat>* = nullptr> inline void check_finite(const char* function, const char* name, const Mat& y) { if (!value_of(y).allFinite()) { for (int n = 0; n < y.size(); ++n) { if (!std::isfinite(value_of_rec(y(n)))) { throw_domain_error_vec(function, name, value_of(y), n, "is ", ", but must be finite!"); } } } } /** * Return <code>true</code> if all values in the std::vector are finite. * * @tparam T_y type of elements in the std::vector * * @param function name of function (for error messages) * @param name variable name (for error messages) * @param y std::vector to test * @return <code>true</code> if all values are finite **/ template <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr> inline void check_finite(const char* function, const char* name, const std::vector<T_y>& y) { for (size_t n = 0; n < stan::math::size(y); n++) { if (!internal::is_finite(stan::get(y, n))) { throw_domain_error(function, name, "", "", "is not finite!"); } } } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_defines.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PM_RECOVERY_FFDC_DEFINES_ #define __PM_RECOVERY_FFDC_DEFINES_ #include <p9_hcd_memmap_base.H> #include <endian.h> #if( __BYTE_ORDER == __BIG_ENDIAN ) #define REV_2_BYTE(WORD) WORD #else #define REV_2_BYTE(WORD) \ ( (((WORD) >> 8) & 0x00FF) | (((WORD) << 8) & 0xFF00) ) #endif namespace p9_stop_recov_ffdc { /** * @brief enumerates all the platforms involved with STOP Recovery. */ enum PmComplexPlatId { PLAT_CME = 0x01, PLAT_SGPE = 0x02, PLAT_PGPE = 0x03, PLAT_OCC = 0x04, PLAT_PPM = 0x05, }; /** * @brief enumerates type of FFDC data */ enum FfdcDataType { IMAGE_HEADER = 0x01, DASH_BOARD_VAR = 0x02, TRACES = 0x03, INTERNAL_REG = 0x04, SCOM_REG = 0x05, }; /** * @brief enumerates bit position used as validity mark of PPE FFDC sub-section. */ enum PpeFfdcValidStatus { PPE_FFDC_INVALID = 0x00, //entire PPE FFDC is not valid PPE_DASHBOARD_VALID = 0x01, // PPE globals are valid PPE_IMAGE_HEADER_VALID = 0x02, // PPE image header is valid PPE_TRACE_VALID = 0x04, // PPE Traces are valid PPE_STATE_VALID = 0x08, // PPE XIRS, GPES and SPRs are valid PPE_INT_REG_VALID = 0x10, // PPE Int Regs are valid PPE_HALT_STATE_VALID = 0x20, // PPE Halt State Info is valid PPE_FFDC_ALL_VALID = 0x3F, // Entire PPE FFDC is valid }; /** * @brief enumerates PPE's HALT conditions as inteprreted from XSR[0:3] */ enum PpeHaltCondition { PPE_HALT_COND_NONE = 0x00, // Not halted PPE_HALT_COND_BAD = 0x08, // Halted, but cannot map source PPE_HALT_COND_XCR = 0x09, // Halted via XCR PPE_HALT_COND_WDT = 0x0A, // Halted via Watch Dog PPE_HALT_COND_NMI = 0x0B, // Halted via unmaskable intr PPE_HALT_COND_DBG = 0x0C, // Debug halt PPE_HALT_COND_DBCR = 0x0D, // Halt via Debug Control Reg PPE_HALT_COND_EXT_HLT = 0x0E, // Ext halt_req input active PPE_HALT_COND_HW = 0x0F, // Halted with a HW failure PPE_HALT_COND_UNKNOWN = 0xFF // Could not read or interpret XSR }; /** * @brief models header of FFDC region of HOMER associated with a CME. */ struct __attribute__((packed)) PpeFfdcHeader { uint32_t iv_ppeMagicNumber; uint8_t iv_ppeNumber; uint8_t iv_headerSize; uint16_t iv_sectionSize; uint8_t iv_ffdcValid; uint8_t iv_ppeHaltCondition; uint16_t iv_dashBoardOffset; uint16_t iv_sramHeaderOffset; uint16_t iv_sprOffset; uint16_t iv_intRegOffset; uint16_t iv_offsetTraces; uint8_t iv_reserve[4]; }; /** * @brief models Quad FFDC header. */ struct __attribute__((packed)) QuadFfdcHeader { uint32_t iv_quadMagicWord; uint8_t iv_quadInstance; uint8_t iv_quadHeaderSize; uint16_t iv_sectionSize; uint16_t iv_offsetCppm0; uint16_t iv_offsetCppm1; uint16_t iv_offsetCppm2; uint16_t iv_offsetCppm3; uint16_t iv_offsetCme0; uint16_t iv_offsetCme1; uint16_t iv_offsetQppm; uint8_t iv_reserve[2]; }; /** * @brief enumerates bit position used as validity mark of OCC FFDC sub-section. */ enum OccFfdcValidStatus { OCC_FFDC_INVALID = 0x00, // None of the FFDC section is valid OCC_FFDC_TRACE_ERR_VALID = 0x01, // OCC ERR traces section valid OCC_FFDC_TRACE_IMP_VALID = 0x02, // OCC IMP traces section valid OCC_FFDC_TRACE_INF_VALID = 0x04, // OCC INF traces section valid OCC_FFDC_TRACE_SSX_VALID = 0x08, // OCC SSX trace section valid OCC_FFDC_TRACE_GPE0_VALID = 0x10, // OCC GPE0 Trace Section valid OCC_FFDC_TRACE_GPE1_VALID = 0x20, // OCC GPE1 Trace Section Valid OCC_FFDC_SHARED_REGION_VALID = 0x40, // OCC Shared Region Section valid OCC_FFDC_REGISTERS_VALID = 0x80, // OCC Register Section valid OCC_FFDC_VALID_ALL = ( OCC_FFDC_TRACE_ERR_VALID | OCC_FFDC_TRACE_IMP_VALID | OCC_FFDC_TRACE_INF_VALID | OCC_FFDC_TRACE_SSX_VALID | OCC_FFDC_TRACE_GPE0_VALID | OCC_FFDC_TRACE_GPE1_VALID | OCC_FFDC_SHARED_REGION_VALID | OCC_FFDC_REGISTERS_VALID ) }; /** * * @brief models OCC Region FFDC header. * */ struct __attribute__((packed)) OccFfdcHeader { uint32_t iv_magicWord; uint8_t iv_ffdcValid; uint8_t iv_headerSize; uint16_t iv_sectionSize; uint16_t iv_offsetErrTrace; uint16_t iv_offsetImpTrace; uint16_t iv_offsetInfTrace; uint16_t iv_offsetSsxTrace; uint16_t iv_offsetGpe0Trace; uint16_t iv_offsetGpe1Trace; uint16_t iv_offsetSharedSram; uint16_t iv_offsetOccRegs; }; /** * @brief a union modelling PPE FFDC region's header area. */ union PpeFfdcHdrRegion { uint8_t iv_ppeFfdcHdrArea[FFDC_PPE_HDR_SIZE]; PpeFfdcHeader iv_ppeFfdcHdr; }; /** * * @brief a union modelling OCC FFDC region's header area. * */ union OccFfdcHdrRegion { uint8_t iv_ppeFfdcHdrArea[FFDC_OCC_REGION_HDR_SIZE]; OccFfdcHeader iv_occFfdcHdr; }; /** * @brief models CME's FFDC region. */ struct __attribute__((packed)) PpeFfdcLayout { PpeFfdcHdrRegion iv_ppeFfdcHdr; uint8_t iv_ppeGlobals[FFDC_PPE_SCORE_BOARD_SIZE]; uint8_t iv_ppeImageHeader[FFDC_PPE_IMG_HDR_SIZE]; uint8_t iv_ppeXirReg[FFDC_PPE_XIR_SIZE]; uint8_t iv_ppeSpr[FFDC_PPE_SPR_SIZE]; uint8_t iv_ppeGprs[FFDC_PPE_GPR_SIZE]; uint8_t iv_ppeInternalReg[FFDC_PPE_INTERNAL_REG_SIZE]; uint8_t iv_ppeTraces[FFDC_PPE_TRACES_SIZE]; }; /** * @brief models Quad FFDC region of HOMER. */ struct __attribute__((packed)) HomerQuadFfdcRegion { uint8_t iv_quadFfdcHeader[FFDC_QUAD_HDR_SIZE]; uint8_t iv_quadCppmRegion[FFDC_CPPM_REGISTERS_SIZE]; uint8_t iv_quadCmeBlock[MAX_CMES_PER_QUAD][FFDC_PPE_BLOCK_SIZE]; uint8_t iv_quadQppmRegion[FFDC_QPPM_REGISTERS_SIZE]; }; /** * @brief models OCC FFDC region of HOMER. */ struct __attribute__((packed)) OccFfdcRegion { uint8_t iv_occFfdcHeader[FFDC_OCC_REGION_HDR_SIZE]; uint8_t iv_occTraceErr[FFDC_TRACE_ERR_SIZE]; uint8_t iv_occTraceImp[FFDC_TRACE_IMP_SIZE]; uint8_t iv_occTraceInf[FFDC_TRACE_INF_SIZE]; uint8_t iv_occTraceSsx[FFDC_TRACE_SSX_SIZE]; uint8_t iv_occTraceGpe0[FFDC_TRACE_GPE0_SIZE]; uint8_t iv_occTraceGpe1[FFDC_TRACE_GPE1_SIZE]; uint8_t iv_occSharedSram[FFDC_SHARED_SRAM_SIZE]; uint8_t iv_occRegs[FFDC_OCC_REGS_SIZE]; }; /** * @brief models full FFDC region of HOMER. */ struct __attribute__((packed)) HomerFfdcRegion { uint8_t iv_homerFfdcHeader[FFDC_HOMER_TOP_HEADER]; HomerQuadFfdcRegion iv_quadFfdc[MAX_QUADS_PER_CHIP]; PpeFfdcLayout iv_sgpeFfdcRegion; PpeFfdcLayout iv_pgpeFfdcRegion; OccFfdcRegion iv_occFfdcRegion; }; } //namespace p9_stop_recov_ffdc ends #endif //__PM_RECOVERY_FFDC_DEFINES_ <commit_msg>PM Recovery FFDC: Added support to collect Register data for PPM<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_defines.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PM_RECOVERY_FFDC_DEFINES_ #define __PM_RECOVERY_FFDC_DEFINES_ #include <p9_hcd_memmap_base.H> #include <endian.h> #if( __BYTE_ORDER == __BIG_ENDIAN ) #define REV_2_BYTE(WORD) WORD #else #define REV_2_BYTE(WORD) \ ( (((WORD) >> 8) & 0x00FF) | (((WORD) << 8) & 0xFF00) ) #endif namespace p9_stop_recov_ffdc { /** * @brief enumerates all the platforms involved with STOP Recovery. */ enum PmComplexPlatId { PLAT_CME = 0x01, PLAT_SGPE = 0x02, PLAT_PGPE = 0x03, PLAT_OCC = 0x04, PLAT_PPM = 0x05, }; /** * @brief enumerates type of FFDC data */ enum FfdcDataType { IMAGE_HEADER = 0x01, DASH_BOARD_VAR = 0x02, TRACES = 0x03, INTERNAL_REG = 0x04, SCOM_REG = 0x05, }; /** * @brief enumerates bit position used as validity mark of PPE FFDC sub-section. */ enum PpeFfdcValidStatus { PPE_FFDC_INVALID = 0x00, //entire PPE FFDC is not valid PPE_DASHBOARD_VALID = 0x01, // PPE globals are valid PPE_IMAGE_HEADER_VALID = 0x02, // PPE image header is valid PPE_TRACE_VALID = 0x04, // PPE Traces are valid PPE_STATE_VALID = 0x08, // PPE XIRS, GPES and SPRs are valid PPE_INT_REG_VALID = 0x10, // PPE Int Regs are valid PPE_HALT_STATE_VALID = 0x20, // PPE Halt State Info is valid PPE_FFDC_ALL_VALID = 0x3F, // Entire PPE FFDC is valid }; /** * @brief enumerates PPE's HALT conditions as inteprreted from XSR[0:3] */ enum PpeHaltCondition { PPE_HALT_COND_NONE = 0x00, // Not halted PPE_HALT_COND_BAD = 0x08, // Halted, but cannot map source PPE_HALT_COND_XCR = 0x09, // Halted via XCR PPE_HALT_COND_WDT = 0x0A, // Halted via Watch Dog PPE_HALT_COND_NMI = 0x0B, // Halted via unmaskable intr PPE_HALT_COND_DBG = 0x0C, // Debug halt PPE_HALT_COND_DBCR = 0x0D, // Halt via Debug Control Reg PPE_HALT_COND_EXT_HLT = 0x0E, // Ext halt_req input active PPE_HALT_COND_HW = 0x0F, // Halted with a HW failure PPE_HALT_COND_UNKNOWN = 0xFF // Could not read or interpret XSR }; /** * @brief models header of FFDC region of HOMER associated with a CME. */ struct __attribute__((packed)) PpeFfdcHeader { uint32_t iv_ppeMagicNumber; uint8_t iv_ppeNumber; uint8_t iv_headerSize; uint16_t iv_sectionSize; uint8_t iv_ffdcValid; uint8_t iv_ppeHaltCondition; uint16_t iv_dashBoardOffset; uint16_t iv_sramHeaderOffset; uint16_t iv_sprOffset; uint16_t iv_intRegOffset; uint16_t iv_offsetTraces; uint8_t iv_reserve[4]; }; /** * @brief models Quad FFDC header. */ struct __attribute__((packed)) QuadFfdcHeader { uint32_t iv_quadMagicWord; uint8_t iv_quadInstance; uint8_t iv_quadHeaderSize; uint16_t iv_sectionSize; uint16_t iv_offsetCppm0; uint16_t iv_offsetCppm1; uint16_t iv_offsetCppm2; uint16_t iv_offsetCppm3; uint16_t iv_offsetCme0; uint16_t iv_offsetCme1; uint16_t iv_offsetQppm; uint8_t iv_ffdcValid; uint8_t iv_reserve; }; /** * @brief enumerates bit position used as validity mark of OCC FFDC sub-section. */ enum OccFfdcValidStatus { OCC_FFDC_INVALID = 0x00, // None of the FFDC section is valid OCC_FFDC_TRACE_ERR_VALID = 0x01, // OCC ERR traces section valid OCC_FFDC_TRACE_IMP_VALID = 0x02, // OCC IMP traces section valid OCC_FFDC_TRACE_INF_VALID = 0x04, // OCC INF traces section valid OCC_FFDC_TRACE_SSX_VALID = 0x08, // OCC SSX trace section valid OCC_FFDC_TRACE_GPE0_VALID = 0x10, // OCC GPE0 Trace Section valid OCC_FFDC_TRACE_GPE1_VALID = 0x20, // OCC GPE1 Trace Section Valid OCC_FFDC_SHARED_REGION_VALID = 0x40, // OCC Shared Region Section valid OCC_FFDC_REGISTERS_VALID = 0x80, // OCC Register Section valid OCC_FFDC_VALID_ALL = ( OCC_FFDC_TRACE_ERR_VALID | OCC_FFDC_TRACE_IMP_VALID | OCC_FFDC_TRACE_INF_VALID | OCC_FFDC_TRACE_SSX_VALID | OCC_FFDC_TRACE_GPE0_VALID | OCC_FFDC_TRACE_GPE1_VALID | OCC_FFDC_SHARED_REGION_VALID | OCC_FFDC_REGISTERS_VALID ) }; /** * @brief models C_Q_PPM FFDC header. */ struct __attribute__((packed)) PpmFfdcHeader { uint32_t iv_ppmMagicWord; uint8_t iv_Instance; uint8_t iv_ppmHeaderSize; uint16_t iv_sectionSize; uint8_t iv_ffdcValid; uint8_t iv_reserved[7]; }; /** * * @brief models OCC Region FFDC header. * */ struct __attribute__((packed)) OccFfdcHeader { uint32_t iv_magicWord; uint8_t iv_ffdcValid; uint8_t iv_headerSize; uint16_t iv_sectionSize; uint16_t iv_offsetErrTrace; uint16_t iv_offsetImpTrace; uint16_t iv_offsetInfTrace; uint16_t iv_offsetSsxTrace; uint16_t iv_offsetGpe0Trace; uint16_t iv_offsetGpe1Trace; uint16_t iv_offsetSharedSram; uint16_t iv_offsetOccRegs; }; /** * @brief a union modelling PPE FFDC region's header area. */ union PpeFfdcHdrRegion { uint8_t iv_ppeFfdcHdrArea[FFDC_PPE_HDR_SIZE]; PpeFfdcHeader iv_ppeFfdcHdr; }; /** * * @brief a union modelling OCC FFDC region's header area. * */ union OccFfdcHdrRegion { uint8_t iv_ppeFfdcHdrArea[FFDC_OCC_REGION_HDR_SIZE]; OccFfdcHeader iv_occFfdcHdr; }; /** * @brief models CME's FFDC region. */ struct __attribute__((packed)) PpeFfdcLayout { PpeFfdcHdrRegion iv_ppeFfdcHdr; uint8_t iv_ppeGlobals[FFDC_PPE_SCORE_BOARD_SIZE]; uint8_t iv_ppeImageHeader[FFDC_PPE_IMG_HDR_SIZE]; uint8_t iv_ppeXirReg[FFDC_PPE_XIR_SIZE]; uint8_t iv_ppeSpr[FFDC_PPE_SPR_SIZE]; uint8_t iv_ppeGprs[FFDC_PPE_GPR_SIZE]; uint8_t iv_ppeInternalReg[FFDC_PPE_INTERNAL_REG_SIZE]; uint8_t iv_ppeTraces[FFDC_PPE_TRACES_SIZE]; }; /** * @brief models Quad FFDC region of HOMER. */ struct __attribute__((packed)) HomerQuadFfdcRegion { uint8_t iv_quadFfdcHeader[FFDC_QUAD_HDR_SIZE]; uint8_t iv_quadCppmRegion[MAX_CORES_PER_QUAD][FFDC_CPPM_REGISTERS_SIZE]; uint8_t iv_quadCmeBlock[MAX_CMES_PER_QUAD][FFDC_PPE_BLOCK_SIZE]; uint8_t iv_quadQppmRegion[FFDC_QPPM_REGISTERS_SIZE]; }; /** * @brief models OCC FFDC region of HOMER. */ struct __attribute__((packed)) OccFfdcRegion { uint8_t iv_occFfdcHeader[FFDC_OCC_REGION_HDR_SIZE]; uint8_t iv_occTraceErr[FFDC_TRACE_ERR_SIZE]; uint8_t iv_occTraceImp[FFDC_TRACE_IMP_SIZE]; uint8_t iv_occTraceInf[FFDC_TRACE_INF_SIZE]; uint8_t iv_occTraceSsx[FFDC_TRACE_SSX_SIZE]; uint8_t iv_occTraceGpe0[FFDC_TRACE_GPE0_SIZE]; uint8_t iv_occTraceGpe1[FFDC_TRACE_GPE1_SIZE]; uint8_t iv_occSharedSram[FFDC_SHARED_SRAM_SIZE]; uint8_t iv_occRegs[FFDC_OCC_REGS_SIZE]; }; /** * @brief models full FFDC region of HOMER. */ struct __attribute__((packed)) HomerFfdcRegion { uint8_t iv_homerFfdcHeader[FFDC_HOMER_TOP_HEADER]; HomerQuadFfdcRegion iv_quadFfdc[MAX_QUADS_PER_CHIP]; PpeFfdcLayout iv_sgpeFfdcRegion; PpeFfdcLayout iv_pgpeFfdcRegion; OccFfdcRegion iv_occFfdcRegion; }; } //namespace p9_stop_recov_ffdc ends #endif //__PM_RECOVERY_FFDC_DEFINES_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = C_PPM_SSHFSP; } else { l_stop_state_reg = C_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <commit_msg>Update p9_query_cache_access_state to use the correct scom register<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; const uint32_t SSH_REG_STOP_GATED = 0; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; //Looking at the stop states is only valid if quad is stop gated -- else it is fully running if (l_qsshsrc.getBit(SSH_REG_STOP_GATED)) { // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } else { //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } } } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <commit_msg>Improve power and clock checking when checking for stop states<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; const uint32_t SSH_REG_STOP_GATED = 0; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the quad stop state if (l_qsshsrc.getBit(SSH_REG_STOP_GATED)) { l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); } FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attributes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; //Looking at the stop states is only valid if quad is stop gated -- else it is fully running if (l_qsshsrc.getBit(SSH_REG_STOP_GATED)) { // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } else { //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } } } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <|endoftext|>
<commit_before>#pragma once #include "libkrbn/impl/libkrbn_complex_modifications_assets_manager.hpp" #include "libkrbn/impl/libkrbn_configuration_monitor.hpp" #include "libkrbn/impl/libkrbn_connected_devices_monitor.hpp" #include "libkrbn/impl/libkrbn_file_monitor.hpp" #include "libkrbn/impl/libkrbn_frontmost_application_monitor.hpp" #include "libkrbn/impl/libkrbn_grabber_client.hpp" #include "libkrbn/impl/libkrbn_hid_value_monitor.hpp" #include "libkrbn/impl/libkrbn_log_monitor.hpp" #include "libkrbn/impl/libkrbn_system_preferences_monitor.hpp" #include "libkrbn/impl/libkrbn_version_monitor.hpp" class libkrbn_components_manager { public: // // version_monitor_ // void enable_version_monitor(libkrbn_version_monitor_callback callback, void* refcon) { version_monitor_ = std::make_unique<libkrbn_version_monitor>(callback, refcon); } void disable_version_monitor(void) { version_monitor_ = nullptr; } // // configuration_monitor_ // void enable_configuration_monitor(libkrbn_configuration_monitor_callback callback, void* refcon) { configuration_monitor_ = std::make_unique<libkrbn_configuration_monitor>(callback, refcon); } void disable_configuration_monitor(void) { configuration_monitor_ = nullptr; } // // complex_modifications_assets_manager_; // void enable_complex_modifications_assets_manager(void) { complex_modifications_assets_manager_ = std::make_unique<libkrbn_complex_modifications_assets_manager>(); } void disable_complex_modifications_assets_manager(void) { complex_modifications_assets_manager_ = nullptr; } std::shared_ptr<libkrbn_complex_modifications_assets_manager> get_complex_modifications_assets_manager(void) const { return complex_modifications_assets_manager_; } // // system_preferences_monitor_ // void enable_system_preferences_monitor(libkrbn_system_preferences_monitor_callback callback, void* refcon) { system_preferences_monitor_ = std::make_unique<libkrbn_system_preferences_monitor>(callback, refcon); } void disable_system_preferences_monitor(void) { system_preferences_monitor_ = nullptr; } // // connected_devices_monitor_ // void enable_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback, void* refcon) { connected_devices_monitor_ = std::make_unique<libkrbn_connected_devices_monitor>(callback, refcon); } void disable_connected_devices_monitor(void) { connected_devices_monitor_ = nullptr; } // // kextd_state_json_file_monitor // void enable_kextd_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { kextd_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_kextd_state_json_file_path(), callback, refcon); } void disable_kextd_state_json_file_monitor(void) { kextd_state_json_file_monitor_ = nullptr; } // // observer_state_json_file_monitor // void enable_observer_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { observer_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_observer_state_json_file_path(), callback, refcon); } void disable_observer_state_json_file_monitor(void) { observer_state_json_file_monitor_ = nullptr; } // // grabber_state_json_file_monitor // void enable_grabber_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { grabber_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_grabber_state_json_file_path(), callback, refcon); } void disable_grabber_state_json_file_monitor(void) { grabber_state_json_file_monitor_ = nullptr; } // // device_details_json_file_monitor // void enable_device_details_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { device_details_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_device_details_json_file_path(), callback, refcon); } void disable_device_details_json_file_monitor(void) { device_details_json_file_monitor_ = nullptr; } // // manipulator_environment_json_file_monitor // void enable_manipulator_environment_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { manipulator_environment_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_manipulator_environment_json_file_path(), callback, refcon); } void disable_manipulator_environment_json_file_monitor(void) { manipulator_environment_json_file_monitor_ = nullptr; } // // notification_message_json_file_monitor // void enable_notification_message_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { notification_message_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_user_notification_message_file_path(), callback, refcon); } void disable_notification_message_json_file_monitor(void) { notification_message_json_file_monitor_ = nullptr; } // // frontmost_application_monitor_ // void enable_frontmost_application_monitor(libkrbn_frontmost_application_monitor_callback callback, void* refcon) { frontmost_application_monitor_ = std::make_unique<libkrbn_frontmost_application_monitor>(callback, refcon); } void disable_frontmost_application_monitor(void) { frontmost_application_monitor_ = nullptr; } // // log_monitor_ // void enable_log_monitor(libkrbn_log_monitor_callback callback, void* refcon) { log_monitor_ = std::make_unique<libkrbn_log_monitor>(callback, refcon); } void disable_log_monitor(void) { log_monitor_ = nullptr; } // // hid_value_monitor_ // void enable_hid_value_monitor(libkrbn_hid_value_monitor_callback callback, void* refcon) { hid_value_monitor_ = std::make_unique<libkrbn_hid_value_monitor>(callback, refcon); } void disable_hid_value_monitor(void) { hid_value_monitor_ = nullptr; } bool hid_value_monitor_observed(void) { if (hid_value_monitor_) { return hid_value_monitor_->get_observed(); } return false; } // // grabber_client_ // void enable_grabber_client(libkrbn_grabber_client_connected_callback connected_callback, libkrbn_grabber_client_connect_failed_callback connect_failed_callback, libkrbn_grabber_client_closed_callback closed_callback) { grabber_client_ = std::make_unique<libkrbn_grabber_client>(connected_callback, connect_failed_callback, closed_callback); } void disable_grabber_client(void) { grabber_client_ = nullptr; } void grabber_client_async_set_variable(const std::string& name, int value) { grabber_client_->async_set_variable(name, value); } void grabber_client_sync_set_variable(const std::string& name, int value) { grabber_client_->sync_set_variable(name, value); } private: std::unique_ptr<libkrbn_version_monitor> version_monitor_; std::unique_ptr<libkrbn_configuration_monitor> configuration_monitor_; std::shared_ptr<libkrbn_complex_modifications_assets_manager> complex_modifications_assets_manager_; std::unique_ptr<libkrbn_system_preferences_monitor> system_preferences_monitor_; std::unique_ptr<libkrbn_connected_devices_monitor> connected_devices_monitor_; std::unique_ptr<libkrbn_file_monitor> kextd_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> observer_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> grabber_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> device_details_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> manipulator_environment_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> notification_message_json_file_monitor_; std::unique_ptr<libkrbn_frontmost_application_monitor> frontmost_application_monitor_; std::unique_ptr<libkrbn_log_monitor> log_monitor_; std::unique_ptr<libkrbn_hid_value_monitor> hid_value_monitor_; std::unique_ptr<libkrbn_grabber_client> grabber_client_; }; <commit_msg>add nullptr check<commit_after>#pragma once #include "libkrbn/impl/libkrbn_complex_modifications_assets_manager.hpp" #include "libkrbn/impl/libkrbn_configuration_monitor.hpp" #include "libkrbn/impl/libkrbn_connected_devices_monitor.hpp" #include "libkrbn/impl/libkrbn_file_monitor.hpp" #include "libkrbn/impl/libkrbn_frontmost_application_monitor.hpp" #include "libkrbn/impl/libkrbn_grabber_client.hpp" #include "libkrbn/impl/libkrbn_hid_value_monitor.hpp" #include "libkrbn/impl/libkrbn_log_monitor.hpp" #include "libkrbn/impl/libkrbn_system_preferences_monitor.hpp" #include "libkrbn/impl/libkrbn_version_monitor.hpp" class libkrbn_components_manager { public: // // version_monitor_ // void enable_version_monitor(libkrbn_version_monitor_callback callback, void* refcon) { version_monitor_ = std::make_unique<libkrbn_version_monitor>(callback, refcon); } void disable_version_monitor(void) { version_monitor_ = nullptr; } // // configuration_monitor_ // void enable_configuration_monitor(libkrbn_configuration_monitor_callback callback, void* refcon) { configuration_monitor_ = std::make_unique<libkrbn_configuration_monitor>(callback, refcon); } void disable_configuration_monitor(void) { configuration_monitor_ = nullptr; } // // complex_modifications_assets_manager_; // void enable_complex_modifications_assets_manager(void) { complex_modifications_assets_manager_ = std::make_unique<libkrbn_complex_modifications_assets_manager>(); } void disable_complex_modifications_assets_manager(void) { complex_modifications_assets_manager_ = nullptr; } std::shared_ptr<libkrbn_complex_modifications_assets_manager> get_complex_modifications_assets_manager(void) const { return complex_modifications_assets_manager_; } // // system_preferences_monitor_ // void enable_system_preferences_monitor(libkrbn_system_preferences_monitor_callback callback, void* refcon) { system_preferences_monitor_ = std::make_unique<libkrbn_system_preferences_monitor>(callback, refcon); } void disable_system_preferences_monitor(void) { system_preferences_monitor_ = nullptr; } // // connected_devices_monitor_ // void enable_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback, void* refcon) { connected_devices_monitor_ = std::make_unique<libkrbn_connected_devices_monitor>(callback, refcon); } void disable_connected_devices_monitor(void) { connected_devices_monitor_ = nullptr; } // // kextd_state_json_file_monitor // void enable_kextd_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { kextd_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_kextd_state_json_file_path(), callback, refcon); } void disable_kextd_state_json_file_monitor(void) { kextd_state_json_file_monitor_ = nullptr; } // // observer_state_json_file_monitor // void enable_observer_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { observer_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_observer_state_json_file_path(), callback, refcon); } void disable_observer_state_json_file_monitor(void) { observer_state_json_file_monitor_ = nullptr; } // // grabber_state_json_file_monitor // void enable_grabber_state_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { grabber_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_grabber_state_json_file_path(), callback, refcon); } void disable_grabber_state_json_file_monitor(void) { grabber_state_json_file_monitor_ = nullptr; } // // device_details_json_file_monitor // void enable_device_details_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { device_details_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_device_details_json_file_path(), callback, refcon); } void disable_device_details_json_file_monitor(void) { device_details_json_file_monitor_ = nullptr; } // // manipulator_environment_json_file_monitor // void enable_manipulator_environment_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { manipulator_environment_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_manipulator_environment_json_file_path(), callback, refcon); } void disable_manipulator_environment_json_file_monitor(void) { manipulator_environment_json_file_monitor_ = nullptr; } // // notification_message_json_file_monitor // void enable_notification_message_json_file_monitor(libkrbn_file_monitor_callback callback, void* refcon) { notification_message_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_user_notification_message_file_path(), callback, refcon); } void disable_notification_message_json_file_monitor(void) { notification_message_json_file_monitor_ = nullptr; } // // frontmost_application_monitor_ // void enable_frontmost_application_monitor(libkrbn_frontmost_application_monitor_callback callback, void* refcon) { frontmost_application_monitor_ = std::make_unique<libkrbn_frontmost_application_monitor>(callback, refcon); } void disable_frontmost_application_monitor(void) { frontmost_application_monitor_ = nullptr; } // // log_monitor_ // void enable_log_monitor(libkrbn_log_monitor_callback callback, void* refcon) { log_monitor_ = std::make_unique<libkrbn_log_monitor>(callback, refcon); } void disable_log_monitor(void) { log_monitor_ = nullptr; } // // hid_value_monitor_ // void enable_hid_value_monitor(libkrbn_hid_value_monitor_callback callback, void* refcon) { hid_value_monitor_ = std::make_unique<libkrbn_hid_value_monitor>(callback, refcon); } void disable_hid_value_monitor(void) { hid_value_monitor_ = nullptr; } bool hid_value_monitor_observed(void) { if (hid_value_monitor_) { return hid_value_monitor_->get_observed(); } return false; } // // grabber_client_ // void enable_grabber_client(libkrbn_grabber_client_connected_callback connected_callback, libkrbn_grabber_client_connect_failed_callback connect_failed_callback, libkrbn_grabber_client_closed_callback closed_callback) { grabber_client_ = std::make_unique<libkrbn_grabber_client>(connected_callback, connect_failed_callback, closed_callback); } void disable_grabber_client(void) { grabber_client_ = nullptr; } void grabber_client_async_set_variable(const std::string& name, int value) { if (grabber_client_) { grabber_client_->async_set_variable(name, value); } } void grabber_client_sync_set_variable(const std::string& name, int value) { if (grabber_client_) { grabber_client_->sync_set_variable(name, value); } } private: std::unique_ptr<libkrbn_version_monitor> version_monitor_; std::unique_ptr<libkrbn_configuration_monitor> configuration_monitor_; std::shared_ptr<libkrbn_complex_modifications_assets_manager> complex_modifications_assets_manager_; std::unique_ptr<libkrbn_system_preferences_monitor> system_preferences_monitor_; std::unique_ptr<libkrbn_connected_devices_monitor> connected_devices_monitor_; std::unique_ptr<libkrbn_file_monitor> kextd_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> observer_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> grabber_state_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> device_details_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> manipulator_environment_json_file_monitor_; std::unique_ptr<libkrbn_file_monitor> notification_message_json_file_monitor_; std::unique_ptr<libkrbn_frontmost_application_monitor> frontmost_application_monitor_; std::unique_ptr<libkrbn_log_monitor> log_monitor_; std::unique_ptr<libkrbn_hid_value_monitor> hid_value_monitor_; std::unique_ptr<libkrbn_grabber_client> grabber_client_; }; <|endoftext|>
<commit_before>#include <uv.h> #include "../../../ui.h" #include "nbind/nbind.h" extern int uiConnectionNumber(); extern int uiEventsPending(); uv_poll_t * handle; static void onEventsPending(uv_poll_t* handle, int status, int events) { Nan::HandleScope scope; while(uiEventsPending()) { uiMainStep(0); } } bool running = false; struct EventLoop { static void start () { if (running) { return; } running = true; uiMainSteps(); int fd = uiConnectionNumber(); handle = new uv_poll_t(); uv_poll_init(uv_default_loop(), handle, fd); uv_poll_start(handle, UV_WRITABLE, onEventsPending); } static void stop () { if (!running) { return; } running = false; uiQuit(); uv_poll_stop(handle); } }; NBIND_CLASS(EventLoop) { method(start); method(stop); } <commit_msg>switch to readable<commit_after>#include <uv.h> #include "../../../ui.h" #include "nbind/nbind.h" extern int uiConnectionNumber(); extern int uiEventsPending(); uv_poll_t * handle; static void onEventsPending(uv_poll_t* handle, int status, int events) { printf("onEventsPending\n"); Nan::HandleScope scope; while(uiEventsPending()) { uiMainStep(0); } printf("onEventsPending exited\n"); } bool running = false; struct EventLoop { static void start () { if (running) { return; } running = true; uiMainSteps(); int fd = uiConnectionNumber(); handle = new uv_poll_t(); uv_poll_init(uv_default_loop(), handle, fd); uv_poll_start(handle, UV_READABLE, onEventsPending); } static void stop () { if (!running) { return; } running = false; uiQuit(); uv_poll_stop(handle); } }; NBIND_CLASS(EventLoop) { method(start); method(stop); } <|endoftext|>
<commit_before>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "asmith/serial/json.hpp" #include <cctype> namespace asmith { namespace serial { void json_skip_whitespace(std::istream& aStream) { char c = aStream.peek(); while(std::isspace(c)) { aStream.read(&c, 1); } } value::type json_determine_type(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); switch(c) { case 'n': return value::NULL_T; case 't': case 'f': return value::BOOl_T; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return value::NUMBER_T; case '"': return value::STRING_T; case '[': return value::ARRAY_T; case '{': return value::OBJECT_T; default: throw std::runtime_error("asmith::json_format::read_serial : Could not determin JSON type"); } } value json_read_value(std::istream&); value json_read_null(std::istream& aStream) { json_skip_whitespace(aStream); char buf[4]; aStream.read(buf, 4); if(memcmp(buf, "null", 4) != 0) throw std::runtime_error("asmith::json_format::read_serial : Expected 'null'"); return value(); } value json_read_bool(std::istream& aStream) { json_skip_whitespace(aStream); char buf[5]; aStream.read(buf, 4); if(memcmp(buf, "true", 4) == 0) { return value(true); }else if(memcmp(buf, "fals", 4) == 0) { aStream.read(buf, 1); if(buf[0] == 'e') return value(false); } throw std::runtime_error("asmith::json_format::read_serial : Expected 'true' or 'false'"); } value json_read_number(std::istream& aStream) { json_skip_whitespace(aStream); static const auto is_number = [](const char c)->bool { return (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'; }; char buf[32]; size_t s = 0; char c = aStream.peek(); while(is_number(c)) { buf[s++] = c; aStream.read(&c, 1); } buf[s] = '\0'; return value(atof(buf)); } value json_read_string(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); if(c != '"') throw std::runtime_error("asmith::json_format::read_serial : Expected string to begin with '\"'"); value tmp; value::string_t& str = tmp.set_string(); aStream.read(&c, 1); while(c != '"') { str += c; aStream.read(&c, 1); if(aStream.eof()) throw std::runtime_error("asmith::json_format::read_serial : Expected string to end with '\"'"); } return tmp; } value json_read_array(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); if(c != '[') throw std::runtime_error("asmith::json_format::read_serial : Expected array to begin with '['"); json_skip_whitespace(aStream); value tmp; value::array_t& array_ = tmp.set_array(); c = aStream.peek(); while(c != ']') { if(aStream.eof()) throw std::runtime_error("asmith::json_format::read_serial : Expected array to end with ']'"); array_.push_back(json_read_value(aStream)); json_skip_whitespace(aStream); c = aStream.peek(); if(c == ']') break; else if(c != ',') throw std::runtime_error("asmith::json_format::read_serial : Expected array elements to be seperated with ','"); aStream.read(&c, 1); json_skip_whitespace(aStream); } aStream.read(&c, 1); return tmp; } value json_read_object(std::istream& aStream) { json_skip_whitespace(aStream); //! \todo Implement return value(); } value json_read_value(std::istream& aStream) { switch(json_determine_type(aStream)) { case value::NULL_T: return json_read_null(aStream); case value::BOOl_T: return json_read_bool(aStream); case value::NUMBER_T: return json_read_number(aStream); case value::STRING_T: return json_read_string(aStream); case value::ARRAY_T: return json_read_array(aStream); case value::OBJECT_T: return json_read_object(aStream); default: throw std::runtime_error("asmith::json_format::read_serial : Could not determin JSON type"); } } void json_format::write_serial(const value& aType, std::ostream& aStream) { const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "null"; break; case value::BOOl_T: aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << '"' << aType.get_char() << '"'; break; case value::NUMBER_T: aStream << aType.get_number(); break; case value::STRING_T: aStream << '"' << aType.get_string() << '"'; break; case value::ARRAY_T: { aStream << '['; const value::array_t tmp = aType.get_array(); const size_t s = tmp.size(); for(size_t i = 0; i < s; ++i) { write_serial(tmp[i], aStream); if(i + 1 < s) aStream << ','; } aStream << ']'; } break; case value::OBJECT_T: { aStream << '{'; const value::object_t tmp = aType.get_object(); const size_t s = tmp.size(); size_t i = 0; for(const auto& v : tmp) { aStream << '"' << v.first<< '"' << ':'; write_serial(v.second, aStream); if(i + 1 < s) aStream << ','; ++i; } aStream << '}'; } break; default: throw std::runtime_error("json_format : Invalid serial type"); break; } } value json_format::read_serial(std::istream& aStream) { //! \todo Implement return value(); } }}<commit_msg>Implemented object reading<commit_after>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "asmith/serial/json.hpp" #include <cctype> namespace asmith { namespace serial { void json_skip_whitespace(std::istream& aStream) { char c = aStream.peek(); while(std::isspace(c)) { aStream.read(&c, 1); } } value::type json_determine_type(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); switch(c) { case 'n': return value::NULL_T; case 't': case 'f': return value::BOOl_T; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return value::NUMBER_T; case '"': return value::STRING_T; case '[': return value::ARRAY_T; case '{': return value::OBJECT_T; default: throw std::runtime_error("asmith::json_format::read_serial : Could not determin JSON type"); } } value json_read_value(std::istream&); value json_read_null(std::istream& aStream) { json_skip_whitespace(aStream); char buf[4]; aStream.read(buf, 4); if(memcmp(buf, "null", 4) != 0) throw std::runtime_error("asmith::json_format::read_serial : Expected 'null'"); return value(); } value json_read_bool(std::istream& aStream) { json_skip_whitespace(aStream); char buf[5]; aStream.read(buf, 4); if(memcmp(buf, "true", 4) == 0) { return value(true); }else if(memcmp(buf, "fals", 4) == 0) { aStream.read(buf, 1); if(buf[0] == 'e') return value(false); } throw std::runtime_error("asmith::json_format::read_serial : Expected 'true' or 'false'"); } value json_read_number(std::istream& aStream) { json_skip_whitespace(aStream); static const auto is_number = [](const char c)->bool { return (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'; }; char buf[32]; size_t s = 0; char c = aStream.peek(); while(is_number(c)) { buf[s++] = c; aStream.read(&c, 1); } buf[s] = '\0'; return value(atof(buf)); } value json_read_string(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); if(c != '"') throw std::runtime_error("asmith::json_format::read_serial : Expected string to begin with '\"'"); value tmp; value::string_t& str = tmp.set_string(); aStream.read(&c, 1); while(c != '"') { str += c; aStream.read(&c, 1); if(aStream.eof()) throw std::runtime_error("asmith::json_format::read_serial : Expected string to end with '\"'"); } return tmp; } value json_read_array(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); if(c != '[') throw std::runtime_error("asmith::json_format::read_serial : Expected array to begin with '['"); json_skip_whitespace(aStream); value tmp; value::array_t& array_ = tmp.set_array(); c = aStream.peek(); while(c != ']') { if(aStream.eof()) throw std::runtime_error("asmith::json_format::read_serial : Expected array to end with ']'"); array_.push_back(json_read_value(aStream)); json_skip_whitespace(aStream); c = aStream.peek(); if(c == ']') break; else if(c != ',') throw std::runtime_error("asmith::json_format::read_serial : Expected array elements to be seperated with ','"); aStream.read(&c, 1); json_skip_whitespace(aStream); } aStream.read(&c, 1); return tmp; } value json_read_object(std::istream& aStream) { json_skip_whitespace(aStream); char c = aStream.peek(); if(c != '{') throw std::runtime_error("asmith::json_format::read_serial : Expected object to begin with '{'"); json_skip_whitespace(aStream); value tmp; value::object_t& object = tmp.set_object(); c = aStream.peek(); while(c != '}') { if(aStream.eof()) throw std::runtime_error("asmith::json_format::read_serial : Expected object to end with '}'"); const value::string_t name = json_read_string(aStream).get_string(); json_skip_whitespace(aStream); aStream.read(&c, 1); if(c != ':') throw std::runtime_error("asmith::json_format::read_serial : Expected object name to be end with ':'"); json_skip_whitespace(aStream); object.emplace(name, json_read_value(aStream)); json_skip_whitespace(aStream); c = aStream.peek(); if(c == '}') break; else if(c != ',') throw std::runtime_error("asmith::json_format::read_serial : Expected object elements to be seperated with ','"); aStream.read(&c, 1); json_skip_whitespace(aStream); } aStream.read(&c, 1); return tmp; } value json_read_value(std::istream& aStream) { switch(json_determine_type(aStream)) { case value::NULL_T: return json_read_null(aStream); case value::BOOl_T: return json_read_bool(aStream); case value::NUMBER_T: return json_read_number(aStream); case value::STRING_T: return json_read_string(aStream); case value::ARRAY_T: return json_read_array(aStream); case value::OBJECT_T: return json_read_object(aStream); default: throw std::runtime_error("asmith::json_format::read_serial : Could not determin JSON type"); } } void json_format::write_serial(const value& aType, std::ostream& aStream) { const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "null"; break; case value::BOOl_T: aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << '"' << aType.get_char() << '"'; break; case value::NUMBER_T: aStream << aType.get_number(); break; case value::STRING_T: aStream << '"' << aType.get_string() << '"'; break; case value::ARRAY_T: { aStream << '['; const value::array_t tmp = aType.get_array(); const size_t s = tmp.size(); for(size_t i = 0; i < s; ++i) { write_serial(tmp[i], aStream); if(i + 1 < s) aStream << ','; } aStream << ']'; } break; case value::OBJECT_T: { aStream << '{'; const value::object_t tmp = aType.get_object(); const size_t s = tmp.size(); size_t i = 0; for(const auto& v : tmp) { aStream << '"' << v.first<< '"' << ':'; write_serial(v.second, aStream); if(i + 1 < s) aStream << ','; ++i; } aStream << '}'; } break; default: throw std::runtime_error("json_format : Invalid serial type"); break; } } value json_format::read_serial(std::istream& aStream) { //! \todo Implement return value(); } }}<|endoftext|>
<commit_before>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * * Copyright (C) 2010 Aldebaran Robotics */ #ifndef _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_ #define _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_ #include <string> #include <qi/transport/buffer.hpp> namespace qi { namespace transport { class TransportContext { public: TransportContext(); ~TransportContext(); //TODO: protected: template <typename T> T &getContext(const std::string &address) { //we only have one context type, so we dont need address ATM (void) address; return *static_cast<T*>(_ctx); } protected: void *_ctx; }; } } #endif // _QI_TRANSPORT_TRANSPORT_CLIENT_HPP_ <commit_msg>transport: make getContext protected. users dont need that function<commit_after>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * * Copyright (C) 2010 Aldebaran Robotics */ #ifndef _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_ #define _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_ #include <string> #include <qi/transport/buffer.hpp> namespace qi { namespace transport { class TransportContext { public: TransportContext(); ~TransportContext(); protected: friend class TransportClient; friend class TransportServer; friend class TransportSubscriber; friend class TransportPublisher; //protected because, this return implementation detail not relevant for users. //that's why we have friend classes. template <typename T> T &getContext(const std::string &address) { //we only have one context type, so we dont need address ATM (void) address; return *static_cast<T*>(_ctx); } protected: void *_ctx; }; } } #endif // _QI_TRANSPORT_TRANSPORT_CLIENT_HPP_ <|endoftext|>
<commit_before>#include "matrix.h" // // Public member functions // Matrix::Matrix() { // USAGE: Constructor for the matrix class lines = 0; score = 0; active_piece = nullptr; initGrid(); } void Matrix::printGrid(bool mode) { // USAGE: Prints out contents of cells in the grid if (mode) { for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { auto temp = grid[i][j].label; if (grid[i][j].isActive()) temp[0] = std::toupper(temp[0]); std::cout << temp << " "; } std::cout << std::endl; } } else { for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { std::cout << backup_grid[i][j].label << " "; } std::cout << std::endl; } } if (game_over) std::cout << "Game Over\n"; } void Matrix::printActive() { // USAGE: Prints out the current active piece active_piece -> print(); } void Matrix::given() { // USAGE: Allows an input stream of 22 characters to set table initGrid(); for (int i = 0; i < 22; i++) { for (int j = 0; j < 10; j++) { std::string temp; std::cin >> temp; if (temp != ".") { auto temp_ptr = std::make_shared<Tetramino>(temp); grid[i][j].assign(temp_ptr); } } } updateBackup(); } void Matrix::clear() { // USAGE: Clears the board initGrid(); } int Matrix::get_score() { // USAGE: Prints current user score with cout return score; } int Matrix::get_lines() { // USAGE: Prints current liens cleared by user with cout return lines; } void Matrix::step() { // USAGE: Checks for filled rows and updates grid accordingly //int pushes[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; for (int i = 0; i < 22; ++i) { // Check if row is completely filled bool filled = true; for (int j = 0; j < 10; ++j) { if (grid[i][j].checkOccupied() == nullptr) filled = false; } if (filled) { // Clear the cells in the row for (int j = 0; j < 10; ++j) grid[i][j].remove(); // Increment # of pushes for above rows //for (int x = i-1; x >= 0; ++x) pushes[x]++; lines += 1; score += 100; } } updateBackup(); if (!checkTopEmpty()) game_over = true; /* // Update the grid starting from the bottom for (int i = 21; i >= 0; --i) { if (pushes[i] > 0) { // Push everything in current row i to row i + pushes[i] int new_row = i + pushes[i]; for (int j = 0; j < 10; ++j) { auto temp = grid[i][j].checkOccupied(); grid[new_row][j].assign(temp); grid[i][j].remove(); } } }*/ } auto Matrix::setActive(char type) -> std::shared_ptr<Tetramino> { if (game_over) return nullptr; if (active_piece != nullptr) { active_piece->active = false; active_piece = nullptr; } switch(type) { case 'I': active_piece = std::make_shared<I_Type>(); initPiece(type); return active_piece; break; case 'O': active_piece = std::make_shared<O_Type>(); initPiece(type); return active_piece; break; case 'Z': active_piece = std::make_shared<Z_Type>(); initPiece(type); return active_piece; break; case 'S': active_piece = std::make_shared<S_Type>(); initPiece(type); return active_piece; break; case 'J': active_piece = std::make_shared<J_Type>(); initPiece(type); return active_piece; break; case 'L': active_piece = std::make_shared<L_Type>(); initPiece(type); return active_piece; break; case 'T': active_piece = std::make_shared<T_Type>(); initPiece(type); return active_piece; break; default: return nullptr; break; } } void Matrix::rotateCW() { // USAGE: Checks if rotation is allowed and do it if it is if (game_over) return; auto cell_list = active_piece -> checkCW(); if (checkSpaceEmpty(cell_list)) { move(cell_list); active_piece -> rotateCW(); } } void Matrix::rotateCCW() { // USAGE: Checks if rotation is allowed and does it if it is if (game_over) return; auto cell_list = active_piece -> checkCCW(); if (checkSpaceEmpty(cell_list)) { move(cell_list); active_piece -> rotateCCW(); } } void Matrix::moveLeft() { // USAGE: Check if current active piece can move to left and if it can, move there if (game_over) return; auto cell_list = active_piece -> checkLeft(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } } void Matrix::moveRight() { // USAGE: Check if current active piece can move to right and if it can, move there if (game_over) return; auto cell_list = active_piece -> checkRight(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } } void Matrix::moveDown() { // USAGE: Check if current active piece can move to right and if it can, move there if (game_over) return; auto cell_list = active_piece -> checkDown(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } } void Matrix::moveHardDown() { // USAGE: Moves active piece down until it hits a boundary or another piece if (game_over) return; auto cell_list = active_piece -> checkDown(); while (checkSpaceEmpty(cell_list)) { move(cell_list); cell_list = active_piece -> checkDown(); } active_piece -> active = false; active_piece = nullptr; step(); } // // Private member functions // void Matrix::initGrid() { // USAGE: Creates a blank grid and sets it to the matrix object for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { grid[i][j] = Cell(); grid[i][j].setCoordinates(i,j); } } active_piece = nullptr; game_over = false; updateBackup(); } void Matrix::initPiece(char type) { //USAGE: Places a newly made active piece on the grid switch(type) { case 'I': assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); assert(grid[1][6].assign(active_piece) != 1); break; case 'O': assert(grid[0][4].assign(active_piece) != 1); assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'S': assert(grid[0][4].assign(active_piece) != 1); assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); break; case 'Z': assert(grid[0][3].assign(active_piece) != 1); assert(grid[0][4].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'J': assert(grid[0][3].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'L': assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'T': assert(grid[0][4].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; default: break; } } void Matrix::updateBackup() { // USAGE: Updates backup_grid after every init, step, and given function call for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { backup_grid[i][j] = grid[i][j]; } } } bool Matrix::checkSpaceEmpty(const std::vector<std::tuple<int,int>> & cell_list) { // USAGE: Helper function for checking if cells in a list are occupied for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) { int x = std::get<0>(*itr); int y = std::get<1>(*itr); // Check for boundary collision if (x < 0 || x > 21 || y < 0 || y > 9) return false; // Check if there is a piece already there if (grid[x][y].checkOccupied() != nullptr && !grid[x][y].isActive()) return false; } return true; } bool Matrix::checkTopEmpty() { // USAGE: Helper function to check top rows before setting new active piece for (int i = 0; i < 2; ++i) { for (int j = 0; j < 10; ++j) { if (grid[i][j].checkOccupied() != nullptr) return false; } } return true; } int Matrix::move(const std::vector<std::tuple<int,int>> & cell_list) { // USAGE: Accepts a tuple vector of new coordinates after a move auto old_cells = active_piece -> getCells(); for (auto itr = old_cells.begin(); itr != old_cells.end(); ++itr) { (*itr) -> remove(); } for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) { int x = std::get<0>(*itr); int y = std::get<1>(*itr); grid[x][y].assign(active_piece); } return 0; } <commit_msg>Fix seg fault with move<commit_after>#include "matrix.h" // // Public member functions // Matrix::Matrix() { // USAGE: Constructor for the matrix class lines = 0; score = 0; active_piece = nullptr; initGrid(); } void Matrix::printGrid(bool mode) { // USAGE: Prints out contents of cells in the grid if (mode) { for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { auto temp = grid[i][j].label; if (grid[i][j].isActive()) temp[0] = std::toupper(temp[0]); std::cout << temp << " "; } std::cout << std::endl; } } else { for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { std::cout << backup_grid[i][j].label << " "; } std::cout << std::endl; } } if (game_over) std::cout << "Game Over\n"; } void Matrix::printActive() { // USAGE: Prints out the current active piece active_piece -> print(); } void Matrix::given() { // USAGE: Allows an input stream of 22 characters to set table initGrid(); for (int i = 0; i < 22; i++) { for (int j = 0; j < 10; j++) { std::string temp; std::cin >> temp; if (temp != ".") { auto temp_ptr = std::make_shared<Tetramino>(temp); grid[i][j].assign(temp_ptr); } } } updateBackup(); } void Matrix::clear() { // USAGE: Clears the board initGrid(); } int Matrix::get_score() { // USAGE: Prints current user score with cout return score; } int Matrix::get_lines() { // USAGE: Prints current liens cleared by user with cout return lines; } void Matrix::step() { // USAGE: Checks for filled rows and updates grid accordingly int pushes[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; for (int i = 0; i < 22; ++i) { // Check if row is completely filled bool filled = true; for (int j = 0; j < 10; ++j) { if (grid[i][j].checkOccupied() == nullptr) filled = false; } if (filled) { // Clear the cells in the row for (int j = 0; j < 10; ++j) grid[i][j].remove(); // Increment # of pushes for above rows for (int x = i-1; x >= 0; --x) pushes[x]++; lines += 1; score += 100; } } // Update the grid starting from the bottom for (int i = 21; i >= 0; --i) { if (pushes[i] > 0) { // Push everything in current row i to row i + pushes[i] int new_row = i + pushes[i]; assert (new_row < 22); for (int j = 0; j < 10; ++j) { auto temp = grid[i][j].checkOccupied(); if (temp != nullptr) { grid[new_row][j].assign(temp); grid[i][j].remove(); } } } } updateBackup(); if (!checkTopEmpty()) game_over = true; } auto Matrix::setActive(char type) -> std::shared_ptr<Tetramino> { if (game_over) return nullptr; if (active_piece != nullptr) { active_piece->active = false; active_piece = nullptr; } switch(type) { case 'I': active_piece = std::make_shared<I_Type>(); initPiece(type); return active_piece; break; case 'O': active_piece = std::make_shared<O_Type>(); initPiece(type); return active_piece; break; case 'Z': active_piece = std::make_shared<Z_Type>(); initPiece(type); return active_piece; break; case 'S': active_piece = std::make_shared<S_Type>(); initPiece(type); return active_piece; break; case 'J': active_piece = std::make_shared<J_Type>(); initPiece(type); return active_piece; break; case 'L': active_piece = std::make_shared<L_Type>(); initPiece(type); return active_piece; break; case 'T': active_piece = std::make_shared<T_Type>(); initPiece(type); return active_piece; break; default: return nullptr; break; } } void Matrix::rotateCW() { // USAGE: Checks if rotation is allowed and do it if it is if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkCW(); if (checkSpaceEmpty(cell_list)) { move(cell_list); active_piece -> rotateCW(); } } void Matrix::rotateCCW() { // USAGE: Checks if rotation is allowed and does it if it is if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkCCW(); if (checkSpaceEmpty(cell_list)) { move(cell_list); active_piece -> rotateCCW(); } } void Matrix::moveLeft() { // USAGE: Check if current active piece can move to left and if it can, move there if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkLeft(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } } void Matrix::moveRight() { // USAGE: Check if current active piece can move to right and if it can, move there if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkRight(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } } void Matrix::moveDown() { // USAGE: Check if current active piece can move to right and if it can, move there if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkDown(); if (checkSpaceEmpty(cell_list)) { move(cell_list); } else { active_piece -> active = false; active_piece = nullptr; step(); } } void Matrix::moveHardDown() { // USAGE: Moves active piece down until it hits a boundary or another piece if (game_over || active_piece == nullptr) return; auto cell_list = active_piece -> checkDown(); while (checkSpaceEmpty(cell_list)) { move(cell_list); cell_list = active_piece -> checkDown(); } active_piece -> active = false; active_piece = nullptr; step(); } // // Private member functions // void Matrix::initGrid() { // USAGE: Creates a blank grid and sets it to the matrix object for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { grid[i][j] = Cell(); grid[i][j].setCoordinates(i,j); } } active_piece = nullptr; game_over = false; updateBackup(); } void Matrix::initPiece(char type) { //USAGE: Places a newly made active piece on the grid switch(type) { case 'I': assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); assert(grid[1][6].assign(active_piece) != 1); break; case 'O': assert(grid[0][4].assign(active_piece) != 1); assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'S': assert(grid[0][4].assign(active_piece) != 1); assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); break; case 'Z': assert(grid[0][3].assign(active_piece) != 1); assert(grid[0][4].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'J': assert(grid[0][3].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'L': assert(grid[0][5].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; case 'T': assert(grid[0][4].assign(active_piece) != 1); assert(grid[1][3].assign(active_piece) != 1); assert(grid[1][4].assign(active_piece) != 1); assert(grid[1][5].assign(active_piece) != 1); break; default: break; } } void Matrix::updateBackup() { // USAGE: Updates backup_grid after every init, step, and given function call for (int i = 0; i < 22; ++i) { for (int j = 0; j < 10; ++j) { backup_grid[i][j] = grid[i][j]; } } } bool Matrix::checkSpaceEmpty(const std::vector<std::tuple<int,int>> & cell_list) { // USAGE: Helper function for checking if cells in a list are occupied for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) { int x = std::get<0>(*itr); int y = std::get<1>(*itr); // Check for boundary collision if (x < 0 || x > 21 || y < 0 || y > 9) return false; // Check if there is a piece already there if (grid[x][y].checkOccupied() != nullptr && !grid[x][y].isActive()) return false; } return true; } bool Matrix::checkTopEmpty() { // USAGE: Helper function to check top rows before setting new active piece for (int i = 0; i < 2; ++i) { for (int j = 0; j < 10; ++j) { if (grid[i][j].checkOccupied() != nullptr) return false; } } return true; } int Matrix::move(const std::vector<std::tuple<int,int>> & cell_list) { // USAGE: Accepts a tuple vector of new coordinates after a move auto old_cells = active_piece -> getCells(); for (auto itr = old_cells.begin(); itr != old_cells.end(); ++itr) { (*itr) -> remove(); } for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) { int x = std::get<0>(*itr); int y = std::get<1>(*itr); grid[x][y].assign(active_piece); } return 0; } <|endoftext|>
<commit_before>#include "memory.h" #include "cartridge.h" #include <assert.h> u8 Memory::read_byte(uint address) const { if (address < 0x8000 || (address >= 0xa000 && address < 0xc000)) { // ROM / external RAM return cart.get8(address); } else if (address >= 0x8000 && address < 0xa000) { // VRAM - Video RAM return vram[address - 0x8000]; } else if (address >= 0xc000 && address < 0xd000) { // WRAM - Work RAM bank 0 return wram[address - 0xc000]; } else if (address >= 0xd000 && address < 0xe000) { // Switchable Work RAM bank (1 - 7) // TODO make switchable return wram[address - 0xc000]; } else if (address >= 0xe000 && address < 0xfe00) { // ECHO - Mirror of C000 - DDFF return wram[address - 0xe000]; } else if (address >= 0xfe00 && address < 0xfea0) { // Sprite attribute table } else if (address >= 0xfea0 && address < 0xff00) { // Not usable } else if (address >= 0xff00 && address < 0xff80) { // IO registers } else if (address >= 0xff80 && address < 0xffff) { // HRAM - High RAM } else if (address == 0xffff) { // Interrupt enable register } // Should never get here abort(); } void Memory::write_byte(uint address, u8 value) { if (address < 0x8000 || (address >= 0xa000 && address < 0xc000)) { // ROM / external RAM cart.set8(address, value); } // TODO } <commit_msg>Memory: use memory map for writing too<commit_after>#include "memory.h" #include "cartridge.h" #include <assert.h> u8 Memory::read_byte(uint address) const { if (address < 0x8000 || (address >= 0xa000 && address < 0xc000)) { // ROM / external RAM return cart.get8(address); } else if (address >= 0x8000 && address < 0xa000) { // VRAM - Video RAM return vram[address - 0x8000]; } else if (address >= 0xc000 && address < 0xd000) { // WRAM - Work RAM bank 0 return wram[address - 0xc000]; } else if (address >= 0xd000 && address < 0xe000) { // Switchable Work RAM bank (1 - 7) // TODO make switchable return wram[address - 0xc000]; } else if (address >= 0xe000 && address < 0xfe00) { // ECHO - Mirror of C000 - DDFF return wram[address - 0xe000]; } else if (address >= 0xfe00 && address < 0xfea0) { // Sprite attribute table } else if (address >= 0xfea0 && address < 0xff00) { // Not usable } else if (address >= 0xff00 && address < 0xff80) { // IO registers } else if (address >= 0xff80 && address < 0xffff) { // HRAM - High RAM } else if (address == 0xffff) { // Interrupt enable register } // Should never get here abort(); } void Memory::write_byte(uint address, u8 value) { if (address < 0x8000 || (address >= 0xa000 && address < 0xc000)) { // ROM / external RAM cart.set8(address, value); } else if (address >= 0x8000 && address < 0xa000) { // VRAM - Video RAM vram[address - 0x8000] = value; } else if (address >= 0xc000 && address < 0xd000) { // WRAM - Work RAM bank 0 wram[address - 0xc000] = value; } else if (address >= 0xd000 && address < 0xe000) { // Switchable Work RAM bank (1 - 7) // TODO make switchable wram[address - 0xc000] = value; } else if (address >= 0xe000 && address < 0xfe00) { // ECHO - Mirror of C000 - DDFF wram[address - 0xe000] = value; } else if (address >= 0xfe00 && address < 0xfea0) { // Sprite attribute table } else if (address >= 0xfea0 && address < 0xff00) { // Not usable } else if (address >= 0xff00 && address < 0xff80) { // IO registers } else if (address >= 0xff80 && address < 0xffff) { // HRAM - High RAM } else if (address == 0xffff) { // Interrupt enable register } else { // Should never get here abort(); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; } RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } // namespace class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} // Show a tab, activating the current one if there is one, and wait for // the renderer process to be created or foregrounded, returning the process // handle. base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); // Ensure that the backgrounding / foregrounding gets a chance to run. content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), MessageLoop::QuitClosure()); MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } // When we hit the max number of renderers, verify that the way we do process // sharing behaves correctly. In particular, this test is verifying that even // when we hit the max process limit, that renderers of each type will wind up // in a process of that type, even if that means creating a new process. void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new TYPE_TABBED tab. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); // Create another TYPE_TABBED tab. It should share the previous process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); // Create another TYPE_WEBUI tab. It should share the process with newtab. // Note: intentionally create this tab after the TYPE_TABBED tabs to // exercise bug 43448 where extension and WebUI tabs could get combined into // normal renderers. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); // Create a TYPE_EXTENSION tab. It should be in its own process. // (the bookmark manager is implemented as an extension) GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new TYPE_TABBED tab. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another TYPE_TABBED tab. It should share the previous process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another new tab. It should share the process with the other WebUI. ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another new tab. It should share the process with the other WebUI. ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } // We don't change process priorities on Mac or Posix because the user lacks the // permission to raise a process' priority even after lowering it. #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); // Create a new tab. It should be foreground. GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); // Create another tab. It should be foreground, and the first tab should // now be background. GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); // Navigate back to first page. It should be foreground again, and the second // tab should be background. EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessOverflow) { // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } // Variation of the ProcessOverflow test, which is driven through command line // parameter instead of direct function call into the class. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } // Ensure that DevTools opened to debug DevTools is launched in a separate // process when --process-per-tab is set. See crbug.com/69873. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // DevTools start in docked mode (no new tab), in a separate process. chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); // DevTools start in a separate process. DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } // Ensure that DevTools opened to debug DevTools is launched in a separate // process. See crbug.com/69873. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // DevTools start in docked mode (no new tab), in a separate process. chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); // DevTools start in a separate process. DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } <commit_msg>Mark ProcessOverflow test as SLOW<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; } RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } // namespace class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} // Show a tab, activating the current one if there is one, and wait for // the renderer process to be created or foregrounded, returning the process // handle. base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); // Ensure that the backgrounding / foregrounding gets a chance to run. content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), MessageLoop::QuitClosure()); MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } // When we hit the max number of renderers, verify that the way we do process // sharing behaves correctly. In particular, this test is verifying that even // when we hit the max process limit, that renderers of each type will wind up // in a process of that type, even if that means creating a new process. void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new TYPE_TABBED tab. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); // Create another TYPE_TABBED tab. It should share the previous process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); // Create another TYPE_WEBUI tab. It should share the process with newtab. // Note: intentionally create this tab after the TYPE_TABBED tabs to // exercise bug 43448 where extension and WebUI tabs could get combined into // normal renderers. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); // Create a TYPE_EXTENSION tab. It should be in its own process. // (the bookmark manager is implemented as an extension) GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new TYPE_TABBED tab. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another TYPE_TABBED tab. It should share the previous process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another new tab. It should share the process with the other WebUI. ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create another new tab. It should share the process with the other WebUI. ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } // We don't change process priorities on Mac or Posix because the user lacks the // permission to raise a process' priority even after lowering it. #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); // Change the first tab to be the new tab page (TYPE_WEBUI). GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); // Create a new tab. It should be foreground. GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); // Create another tab. It should be foreground, and the first tab should // now be background. GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); // Navigate back to first page. It should be foreground again, and the second // tab should be background. EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, SLOW_ProcessOverflow) { // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } // Variation of the ProcessOverflow test, which is driven through command line // parameter instead of direct function call into the class. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } // Ensure that DevTools opened to debug DevTools is launched in a separate // process when --process-per-tab is set. See crbug.com/69873. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // DevTools start in docked mode (no new tab), in a separate process. chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); // DevTools start in a separate process. DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } // Ensure that DevTools opened to debug DevTools is launched in a separate // process. See crbug.com/69873. IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); // DevTools start in docked mode (no new tab), in a separate process. chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); // DevTools start in a separate process. DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prnsetup.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <tools/debug.hxx> #ifndef _VCL_PRINT_HXX #include <vcl/print.hxx> #endif #ifndef GCC #endif #include <svtools/svtdata.hxx> #include "prnsetup.hrc" #include <svtools/prnsetup.hxx> // ======================================================================= void ImplFillPrnDlgListBox( const Printer* pPrinter, ListBox* pBox, PushButton* pPropBtn ) { ImplFreePrnDlgListBox( pBox ); const std::vector<rtl::OUString>& rPrinters = Printer::GetPrinterQueues(); unsigned int nCount = rPrinters.size(); if ( nCount ) { for( unsigned int i = 0; i < nCount; i++ ) pBox->InsertEntry( rPrinters[i] ); pBox->SelectEntry( pPrinter->GetName() ); } pBox->Enable( nCount != 0 ); pPropBtn->Enable( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); } // ----------------------------------------------------------------------- void ImplFreePrnDlgListBox( ListBox* pBox, BOOL bClear ) { if ( bClear ) pBox->Clear(); } // ----------------------------------------------------------------------- Printer* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn, Printer* pPrinter, Printer* pTempPrinter ) { if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) { const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true ); if( pInfo) { if ( !pTempPrinter ) { if ( (pPrinter->GetName() == pInfo->GetPrinterName()) && (pPrinter->GetDriverName() == pInfo->GetDriver()) ) pTempPrinter = new Printer( pPrinter->GetJobSetup() ); else pTempPrinter = new Printer( *pInfo ); } else { if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) || (pTempPrinter->GetDriverName() != pInfo->GetDriver()) ) { delete pTempPrinter; pTempPrinter = new Printer( *pInfo ); } } pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); } else pPropBtn->Disable(); } else pPropBtn->Disable(); return pTempPrinter; } // ----------------------------------------------------------------------- Printer* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter ) { XubString aPrnName; if ( pTempPrinter ) aPrnName = pTempPrinter->GetName(); else aPrnName = pPrinter->GetName(); if ( ! Printer::GetQueueInfo( aPrnName, false ) ) { if ( pTempPrinter ) delete pTempPrinter; pTempPrinter = new Printer; } return pTempPrinter; } // ----------------------------------------------------------------------- void ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo ) { if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) { const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true ); if( pInfo ) rInfo = *pInfo; } } // ----------------------------------------------------------------------- static void ImplPrnDlgAddString( XubString& rStr, const XubString& rAddStr ) { if ( rStr.Len() ) rStr.AppendAscii( "; " ); rStr += rAddStr; } // ----------------------------------------------------------------------- static void ImplPrnDlgAddResString( XubString& rStr, USHORT nResId ) { SvtResId aResId( nResId ); XubString aAddStr( aResId ); ImplPrnDlgAddString( rStr, aAddStr ); } // ----------------------------------------------------------------------- XubString ImplPrnDlgGetStatusText( const QueueInfo& rInfo ) { XubString aStr; ULONG nStatus = rInfo.GetStatus(); // Default-Printer if ( rInfo.GetPrinterName().Len() && (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER ); // Status if ( nStatus & QUEUE_STATUS_READY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY ); if ( nStatus & QUEUE_STATUS_PAUSED ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED ); if ( nStatus & QUEUE_STATUS_PENDING_DELETION ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING ); if ( nStatus & QUEUE_STATUS_BUSY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY ); if ( nStatus & QUEUE_STATUS_INITIALIZING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING ); if ( nStatus & QUEUE_STATUS_WAITING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING ); if ( nStatus & QUEUE_STATUS_WARMING_UP ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP ); if ( nStatus & QUEUE_STATUS_PROCESSING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING ); if ( nStatus & QUEUE_STATUS_PRINTING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING ); if ( nStatus & QUEUE_STATUS_OFFLINE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE ); if ( nStatus & QUEUE_STATUS_ERROR ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR ); if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN ); if ( nStatus & QUEUE_STATUS_PAPER_JAM ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM ); if ( nStatus & QUEUE_STATUS_PAPER_OUT ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT ); if ( nStatus & QUEUE_STATUS_MANUAL_FEED ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED ); if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM ); if ( nStatus & QUEUE_STATUS_IO_ACTIVE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE ); if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL ); if ( nStatus & QUEUE_STATUS_TONER_LOW ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW ); if ( nStatus & QUEUE_STATUS_NO_TONER ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER ); if ( nStatus & QUEUE_STATUS_PAGE_PUNT ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT ); if ( nStatus & QUEUE_STATUS_USER_INTERVENTION ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION ); if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY ); if ( nStatus & QUEUE_STATUS_DOOR_OPEN ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN ); if ( nStatus & QUEUE_STATUS_POWER_SAVE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE ); // Anzahl Jobs ULONG nJobs = rInfo.GetJobs(); if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) ) { XubString aJobStr( SvtResId( STR_SVT_PRNDLG_JOBCOUNT ) ); XubString aJobs( XubString::CreateFromInt32( nJobs ) ); aJobStr.SearchAndReplaceAscii( "%d", aJobs ); ImplPrnDlgAddString( aStr, aJobStr ); } return aStr; } // ======================================================================= PrinterSetupDialog::PrinterSetupDialog( Window* pWindow ) : ModalDialog ( pWindow, SvtResId( DLG_SVT_PRNDLG_PRNSETUPDLG ) ), maFlPrinter ( this, SvtResId( FL_PRINTER ) ), maFtName ( this, SvtResId( FT_NAME ) ), maLbName ( this, SvtResId( LB_NAMES ) ), maBtnProperties ( this, SvtResId( BTN_PROPERTIES ) ), maBtnOptions ( this, SvtResId( BTN_OPTIONS ) ), maFtStatus ( this, SvtResId( FT_STATUS ) ), maFiStatus ( this, SvtResId( FI_STATUS ) ), maFtType ( this, SvtResId( FT_TYPE ) ), maFiType ( this, SvtResId( FI_TYPE ) ), maFtLocation ( this, SvtResId( FT_LOCATION ) ), maFiLocation ( this, SvtResId( FI_LOCATION ) ), maFtComment ( this, SvtResId( FT_COMMENT ) ), maFiComment ( this, SvtResId( FI_COMMENT ) ), maFlSepButton ( this, SvtResId( FL_SEPBUTTON ) ), maBtnOK ( this, SvtResId( BTN_OK ) ), maBtnCancel ( this, SvtResId( BTN_CANCEL ) ), maBtnHelp ( this, SvtResId( BTN_HELP ) ) { FreeResource(); // show options button only if link is set maBtnOptions.Hide(); mpPrinter = NULL; mpTempPrinter = NULL; maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE ); maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) ); maBtnProperties.SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) ); maLbName.SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) ); } // ----------------------------------------------------------------------- PrinterSetupDialog::~PrinterSetupDialog() { ImplFreePrnDlgListBox( &maLbName, FALSE ); delete mpTempPrinter; } // ----------------------------------------------------------------------- void PrinterSetupDialog::SetOptionsHdl( const Link& rLink ) { maBtnOptions.SetClickHdl( rLink ); maBtnOptions.Show( rLink.IsSet() ); } const Link& PrinterSetupDialog::GetOptionsHdl() const { return maBtnOptions.GetClickHdl(); } void PrinterSetupDialog::ImplSetInfo() { const QueueInfo* pInfo = Printer::GetQueueInfo(maLbName.GetSelectEntry(), true); if ( pInfo ) { maFiType.SetText( pInfo->GetDriver() ); maFiLocation.SetText( pInfo->GetLocation() ); maFiComment.SetText( pInfo->GetComment() ); maFiStatus.SetText( ImplPrnDlgGetStatusText( *pInfo ) ); } else { XubString aTempStr; maFiType.SetText( aTempStr ); maFiLocation.SetText( aTempStr ); maFiComment.SetText( aTempStr ); maFiStatus.SetText( aTempStr ); } } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplStatusHdl, Timer*, EMPTYARG ) { QueueInfo aInfo; ImplPrnDlgUpdateQueueInfo( &maLbName, aInfo ); maFiStatus.SetText( ImplPrnDlgGetStatusText( aInfo ) ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplPropertiesHdl, void*, EMPTYARG ) { if ( !mpTempPrinter ) mpTempPrinter = new Printer( mpPrinter->GetJobSetup() ); mpTempPrinter->Setup( this ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplChangePrinterHdl, void*, EMPTYARG ) { mpTempPrinter = ImplPrnDlgListBoxSelect( &maLbName, &maBtnProperties, mpPrinter, mpTempPrinter ); ImplSetInfo(); return 0; } // ----------------------------------------------------------------------- long PrinterSetupDialog::Notify( NotifyEvent& rNEvt ) { if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() ) ImplStatusHdl( &maStatusTimer ); return ModalDialog::Notify( rNEvt ); } // ----------------------------------------------------------------------- void PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt ) { if ( rDCEvt.GetType() == DATACHANGED_PRINTER ) { mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter ); Printer* pPrn; if ( mpTempPrinter ) pPrn = mpTempPrinter; else pPrn = mpPrinter; ImplFillPrnDlgListBox( pPrn, &maLbName, &maBtnProperties ); ImplSetInfo(); } ModalDialog::DataChanged( rDCEvt ); } // ----------------------------------------------------------------------- short PrinterSetupDialog::Execute() { if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() ) { DBG_ERRORFILE( "PrinterSetupDialog::Execute() - No Printer or printer is printing" ); return FALSE; } Printer::updatePrinters(); ImplFillPrnDlgListBox( mpPrinter, &maLbName, &maBtnProperties ); ImplSetInfo(); maStatusTimer.Start(); // Dialog starten short nRet = ModalDialog::Execute(); // Wenn Dialog mit OK beendet wurde, dann die Daten updaten if ( nRet == TRUE ) { if ( mpTempPrinter ) mpPrinter->SetPrinterProps( mpTempPrinter ); } maStatusTimer.Stop(); return nRet; } <commit_msg>printerpullpages: #i106762# hide properties button instead of disabling it when no printer setup dialog is available<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prnsetup.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <tools/debug.hxx> #ifndef _VCL_PRINT_HXX #include <vcl/print.hxx> #endif #ifndef GCC #endif #include <svtools/svtdata.hxx> #include "prnsetup.hrc" #include <svtools/prnsetup.hxx> // ======================================================================= void ImplFillPrnDlgListBox( const Printer* pPrinter, ListBox* pBox, PushButton* pPropBtn ) { ImplFreePrnDlgListBox( pBox ); const std::vector<rtl::OUString>& rPrinters = Printer::GetPrinterQueues(); unsigned int nCount = rPrinters.size(); if ( nCount ) { for( unsigned int i = 0; i < nCount; i++ ) pBox->InsertEntry( rPrinters[i] ); pBox->SelectEntry( pPrinter->GetName() ); } pBox->Enable( nCount != 0 ); pPropBtn->Show( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); } // ----------------------------------------------------------------------- void ImplFreePrnDlgListBox( ListBox* pBox, BOOL bClear ) { if ( bClear ) pBox->Clear(); } // ----------------------------------------------------------------------- Printer* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn, Printer* pPrinter, Printer* pTempPrinter ) { if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) { const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true ); if( pInfo) { if ( !pTempPrinter ) { if ( (pPrinter->GetName() == pInfo->GetPrinterName()) && (pPrinter->GetDriverName() == pInfo->GetDriver()) ) pTempPrinter = new Printer( pPrinter->GetJobSetup() ); else pTempPrinter = new Printer( *pInfo ); } else { if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) || (pTempPrinter->GetDriverName() != pInfo->GetDriver()) ) { delete pTempPrinter; pTempPrinter = new Printer( *pInfo ); } } pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); } else pPropBtn->Disable(); } else pPropBtn->Disable(); return pTempPrinter; } // ----------------------------------------------------------------------- Printer* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter ) { XubString aPrnName; if ( pTempPrinter ) aPrnName = pTempPrinter->GetName(); else aPrnName = pPrinter->GetName(); if ( ! Printer::GetQueueInfo( aPrnName, false ) ) { if ( pTempPrinter ) delete pTempPrinter; pTempPrinter = new Printer; } return pTempPrinter; } // ----------------------------------------------------------------------- void ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo ) { if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) { const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true ); if( pInfo ) rInfo = *pInfo; } } // ----------------------------------------------------------------------- static void ImplPrnDlgAddString( XubString& rStr, const XubString& rAddStr ) { if ( rStr.Len() ) rStr.AppendAscii( "; " ); rStr += rAddStr; } // ----------------------------------------------------------------------- static void ImplPrnDlgAddResString( XubString& rStr, USHORT nResId ) { SvtResId aResId( nResId ); XubString aAddStr( aResId ); ImplPrnDlgAddString( rStr, aAddStr ); } // ----------------------------------------------------------------------- XubString ImplPrnDlgGetStatusText( const QueueInfo& rInfo ) { XubString aStr; ULONG nStatus = rInfo.GetStatus(); // Default-Printer if ( rInfo.GetPrinterName().Len() && (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER ); // Status if ( nStatus & QUEUE_STATUS_READY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY ); if ( nStatus & QUEUE_STATUS_PAUSED ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED ); if ( nStatus & QUEUE_STATUS_PENDING_DELETION ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING ); if ( nStatus & QUEUE_STATUS_BUSY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY ); if ( nStatus & QUEUE_STATUS_INITIALIZING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING ); if ( nStatus & QUEUE_STATUS_WAITING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING ); if ( nStatus & QUEUE_STATUS_WARMING_UP ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP ); if ( nStatus & QUEUE_STATUS_PROCESSING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING ); if ( nStatus & QUEUE_STATUS_PRINTING ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING ); if ( nStatus & QUEUE_STATUS_OFFLINE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE ); if ( nStatus & QUEUE_STATUS_ERROR ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR ); if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN ); if ( nStatus & QUEUE_STATUS_PAPER_JAM ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM ); if ( nStatus & QUEUE_STATUS_PAPER_OUT ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT ); if ( nStatus & QUEUE_STATUS_MANUAL_FEED ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED ); if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM ); if ( nStatus & QUEUE_STATUS_IO_ACTIVE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE ); if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL ); if ( nStatus & QUEUE_STATUS_TONER_LOW ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW ); if ( nStatus & QUEUE_STATUS_NO_TONER ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER ); if ( nStatus & QUEUE_STATUS_PAGE_PUNT ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT ); if ( nStatus & QUEUE_STATUS_USER_INTERVENTION ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION ); if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY ); if ( nStatus & QUEUE_STATUS_DOOR_OPEN ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN ); if ( nStatus & QUEUE_STATUS_POWER_SAVE ) ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE ); // Anzahl Jobs ULONG nJobs = rInfo.GetJobs(); if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) ) { XubString aJobStr( SvtResId( STR_SVT_PRNDLG_JOBCOUNT ) ); XubString aJobs( XubString::CreateFromInt32( nJobs ) ); aJobStr.SearchAndReplaceAscii( "%d", aJobs ); ImplPrnDlgAddString( aStr, aJobStr ); } return aStr; } // ======================================================================= PrinterSetupDialog::PrinterSetupDialog( Window* pWindow ) : ModalDialog ( pWindow, SvtResId( DLG_SVT_PRNDLG_PRNSETUPDLG ) ), maFlPrinter ( this, SvtResId( FL_PRINTER ) ), maFtName ( this, SvtResId( FT_NAME ) ), maLbName ( this, SvtResId( LB_NAMES ) ), maBtnProperties ( this, SvtResId( BTN_PROPERTIES ) ), maBtnOptions ( this, SvtResId( BTN_OPTIONS ) ), maFtStatus ( this, SvtResId( FT_STATUS ) ), maFiStatus ( this, SvtResId( FI_STATUS ) ), maFtType ( this, SvtResId( FT_TYPE ) ), maFiType ( this, SvtResId( FI_TYPE ) ), maFtLocation ( this, SvtResId( FT_LOCATION ) ), maFiLocation ( this, SvtResId( FI_LOCATION ) ), maFtComment ( this, SvtResId( FT_COMMENT ) ), maFiComment ( this, SvtResId( FI_COMMENT ) ), maFlSepButton ( this, SvtResId( FL_SEPBUTTON ) ), maBtnOK ( this, SvtResId( BTN_OK ) ), maBtnCancel ( this, SvtResId( BTN_CANCEL ) ), maBtnHelp ( this, SvtResId( BTN_HELP ) ) { FreeResource(); // show options button only if link is set maBtnOptions.Hide(); mpPrinter = NULL; mpTempPrinter = NULL; maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE ); maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) ); maBtnProperties.SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) ); maLbName.SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) ); } // ----------------------------------------------------------------------- PrinterSetupDialog::~PrinterSetupDialog() { ImplFreePrnDlgListBox( &maLbName, FALSE ); delete mpTempPrinter; } // ----------------------------------------------------------------------- void PrinterSetupDialog::SetOptionsHdl( const Link& rLink ) { maBtnOptions.SetClickHdl( rLink ); maBtnOptions.Show( rLink.IsSet() ); } const Link& PrinterSetupDialog::GetOptionsHdl() const { return maBtnOptions.GetClickHdl(); } void PrinterSetupDialog::ImplSetInfo() { const QueueInfo* pInfo = Printer::GetQueueInfo(maLbName.GetSelectEntry(), true); if ( pInfo ) { maFiType.SetText( pInfo->GetDriver() ); maFiLocation.SetText( pInfo->GetLocation() ); maFiComment.SetText( pInfo->GetComment() ); maFiStatus.SetText( ImplPrnDlgGetStatusText( *pInfo ) ); } else { XubString aTempStr; maFiType.SetText( aTempStr ); maFiLocation.SetText( aTempStr ); maFiComment.SetText( aTempStr ); maFiStatus.SetText( aTempStr ); } } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplStatusHdl, Timer*, EMPTYARG ) { QueueInfo aInfo; ImplPrnDlgUpdateQueueInfo( &maLbName, aInfo ); maFiStatus.SetText( ImplPrnDlgGetStatusText( aInfo ) ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplPropertiesHdl, void*, EMPTYARG ) { if ( !mpTempPrinter ) mpTempPrinter = new Printer( mpPrinter->GetJobSetup() ); mpTempPrinter->Setup( this ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( PrinterSetupDialog, ImplChangePrinterHdl, void*, EMPTYARG ) { mpTempPrinter = ImplPrnDlgListBoxSelect( &maLbName, &maBtnProperties, mpPrinter, mpTempPrinter ); ImplSetInfo(); return 0; } // ----------------------------------------------------------------------- long PrinterSetupDialog::Notify( NotifyEvent& rNEvt ) { if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() ) ImplStatusHdl( &maStatusTimer ); return ModalDialog::Notify( rNEvt ); } // ----------------------------------------------------------------------- void PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt ) { if ( rDCEvt.GetType() == DATACHANGED_PRINTER ) { mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter ); Printer* pPrn; if ( mpTempPrinter ) pPrn = mpTempPrinter; else pPrn = mpPrinter; ImplFillPrnDlgListBox( pPrn, &maLbName, &maBtnProperties ); ImplSetInfo(); } ModalDialog::DataChanged( rDCEvt ); } // ----------------------------------------------------------------------- short PrinterSetupDialog::Execute() { if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() ) { DBG_ERRORFILE( "PrinterSetupDialog::Execute() - No Printer or printer is printing" ); return FALSE; } Printer::updatePrinters(); ImplFillPrnDlgListBox( mpPrinter, &maLbName, &maBtnProperties ); ImplSetInfo(); maStatusTimer.Start(); // Dialog starten short nRet = ModalDialog::Execute(); // Wenn Dialog mit OK beendet wurde, dann die Daten updaten if ( nRet == TRUE ) { if ( mpTempPrinter ) mpPrinter->SetPrinterProps( mpTempPrinter ); } maStatusTimer.Stop(); return nRet; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 INRA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __Benchmark_models_hpp__ #define __Benchmark_models_hpp__ #include "linpackc.hpp" #include "defs.hpp" #include <vle/mpi-synchronous.hpp> #include <vle/utils.hpp> #include <fstream> #include <numeric> namespace bench { struct TopPixel : AtomicModel { int m_id; std::string m_name; long int m_duration; TopPixel(const vle::Context& ctx) : AtomicModel(ctx, {}, {"0"}) {} virtual ~TopPixel() {} virtual double init(const vle::Common& common, const double&) override final { try { m_id = boost::any_cast <int>(common.at("id")); m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name")); m_duration = boost::any_cast <long int>(common.at("duration")); } catch (const std::exception &e) { throw std::invalid_argument("TopPixel: failed to find name " "or duration parameters"); } return 0.0; } virtual double delta(const double&) override final { if (m_duration > 0) bench::sleep_and_work(m_duration); return 1.0; } virtual void lambda() const override final { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } }; struct NormalPixel : AtomicModel { enum Phase { WAIT, SEND }; int m_id; std::string m_name; double m_current_time; double m_last_time; long int m_duration; unsigned int m_neighbour_number; unsigned int m_received; unsigned int m_total_received; Phase m_phase; double m_simulation_duration; NormalPixel(const vle::Context& ctx) : AtomicModel(ctx, {"0"}, {"0"}) , m_current_time(Infinity <double>::negative) , m_last_time(Infinity <double>::negative) , m_neighbour_number(0) , m_received(0) , m_total_received(0) , m_phase(WAIT) { try { m_simulation_duration = boost::any_cast <double>(ctx->get_user_data()); } catch (const std::exception &e) { throw std::invalid_argument("Normal pixel can not read the " "simulation duration parameter"); } } virtual ~NormalPixel() { if (m_total_received != (m_simulation_duration * m_neighbour_number)) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %" PRIuMAX " messages (%" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); #ifdef NDEBUG throw std::runtime_error("Bad end\n"); #endif } } virtual double init(const vle::Common& common, const double& t) override final { m_current_time = t; m_last_time = Infinity <double>::negative; try { m_id = boost::any_cast <int>(common.at("id")); m_duration = boost::any_cast <long int>(common.at("duration")); m_name = std::string("normal-") + boost::any_cast <std::string>(common.at("name")); m_neighbour_number = boost::any_cast <unsigned int>(common.at("neighbour_number")); } catch (const std::exception &e) { throw std::invalid_argument("NormalPixel: failed to find duration," "name or neighbour_number parameters"); } m_received = 0; m_total_received = 0; m_phase = WAIT; return Infinity <double>::positive; } virtual double delta(const double& time) override final { m_current_time += time; if (x.empty()) dint(m_current_time); else dext(m_current_time); if (m_phase == WAIT) return Infinity <double>::positive; return 0.0; } void dint(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time); if (m_duration > 0) bench::sleep_and_work(m_duration); if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX " (neighbour_number : %" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * m_simulation_duration)); m_phase = WAIT; m_total_received += m_received; m_received = 0; m_last_time = time; } } void dext(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n", m_name.c_str(), time, static_cast <std::uintmax_t>(x[0].size()), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_neighbour_number)); if (m_last_time == time) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time); throw std::runtime_error("Oups event\n"); } for (size_t i = 0, e = x[0].size(); i != e; ++i) vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]); m_received += x[0].size(); if (m_received == m_neighbour_number) m_phase = SEND; } virtual void lambda() const override final { if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } } }; template <typename T> struct Coupled : T { std::string m_name; Coupled(const vle::Context& ctx) : T(ctx) {} Coupled(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Coupled() {} virtual void apply_common(const vle::Common& common) override { m_name = vle::common_get <std::string>(common, "name"); } virtual vle::Common update_common(const vle::Common& common, const typename Coupled::vertices& v, const typename Coupled::edges& e, int child) override { auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); vle::Common ret(common); vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n", m_name.c_str(), vle::stringf("%s-%d", m_name.c_str(), child).c_str(), mdl, static_cast <std::uintmax_t>(nb)); ret["id"] = child; ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child); ret["neighbour_number"] = nb; return std::move(ret); } }; template <typename T> struct RootMPI : T { boost::mpi::communicator com; RootMPI(const vle::Context& ctx) : T(ctx) , com() {} virtual ~RootMPI() {} virtual vle::Common update_common(const vle::Common& common, const typename RootMPI::vertices& v, const typename RootMPI::edges& e, int child) override { (void)v; (void)e; if (com.size() <= child + 1) throw std::invalid_argument("MPI size < children size"); bench::SynchronousProxyModel* mdl = dynamic_cast <bench::SynchronousProxyModel*>(T::m_children[child].get()); if (!mdl) throw std::invalid_argument("RootMPI without SynchronousProxyModel"); mdl->rank = child + 1; vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child); vle::Common ret(common); return std::move(ret); } }; template <typename T> struct Root : T { Root(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Root() {} virtual vle::Common update_common(const vle::Common& common, const typename Root::vertices& v, const typename Root::edges& e, int child) override { vle::Common ret(common); auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); ret["id"] = child; ret["name"] = vle::stringf("S%d", child); ret["neighbour_number"] = nb; ret["tgf-filesource"] = vle::stringf("S%d.tgf", child); ret["tgf-format"] = (int)1; return std::move(ret); } }; using RootThread = Root <GenericCoupledModelThread>; using RootMono = Root <GenericCoupledModelMono>; using RootMPIThread = RootMPI <GenericCoupledModelThread>; using RootMPIMono = RootMPI <GenericCoupledModelMono>; using CoupledThread = Coupled <GenericCoupledModelThread>; using CoupledMono = Coupled <GenericCoupledModelMono>; } #endif <commit_msg>models: throw exception without NDEBUG<commit_after>/* * Copyright (C) 2014 INRA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __Benchmark_models_hpp__ #define __Benchmark_models_hpp__ #include "linpackc.hpp" #include "defs.hpp" #include <vle/mpi-synchronous.hpp> #include <vle/utils.hpp> #include <fstream> #include <numeric> namespace bench { struct TopPixel : AtomicModel { int m_id; std::string m_name; long int m_duration; TopPixel(const vle::Context& ctx) : AtomicModel(ctx, {}, {"0"}) {} virtual ~TopPixel() {} virtual double init(const vle::Common& common, const double&) override final { try { m_id = boost::any_cast <int>(common.at("id")); m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name")); m_duration = boost::any_cast <long int>(common.at("duration")); } catch (const std::exception &e) { throw std::invalid_argument("TopPixel: failed to find name " "or duration parameters"); } return 0.0; } virtual double delta(const double&) override final { if (m_duration > 0) bench::sleep_and_work(m_duration); return 1.0; } virtual void lambda() const override final { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } }; struct NormalPixel : AtomicModel { enum Phase { WAIT, SEND }; int m_id; std::string m_name; double m_current_time; double m_last_time; long int m_duration; unsigned int m_neighbour_number; unsigned int m_received; unsigned int m_total_received; Phase m_phase; double m_simulation_duration; NormalPixel(const vle::Context& ctx) : AtomicModel(ctx, {"0"}, {"0"}) , m_current_time(Infinity <double>::negative) , m_last_time(Infinity <double>::negative) , m_neighbour_number(0) , m_received(0) , m_total_received(0) , m_phase(WAIT) { try { m_simulation_duration = boost::any_cast <double>(ctx->get_user_data()); } catch (const std::exception &e) { throw std::invalid_argument("Normal pixel can not read the " "simulation duration parameter"); } } virtual ~NormalPixel() { if (m_total_received != (m_simulation_duration * m_neighbour_number)) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %" PRIuMAX " messages (%" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); //#ifdef NDEBUG throw std::runtime_error("Bad end\n"); //#endif } } virtual double init(const vle::Common& common, const double& t) override final { m_current_time = t; m_last_time = Infinity <double>::negative; try { m_id = boost::any_cast <int>(common.at("id")); m_duration = boost::any_cast <long int>(common.at("duration")); m_name = std::string("normal-") + boost::any_cast <std::string>(common.at("name")); m_neighbour_number = boost::any_cast <unsigned int>(common.at("neighbour_number")); } catch (const std::exception &e) { throw std::invalid_argument("NormalPixel: failed to find duration," "name or neighbour_number parameters"); } m_received = 0; m_total_received = 0; m_phase = WAIT; return Infinity <double>::positive; } virtual double delta(const double& time) override final { m_current_time += time; if (x.empty()) dint(m_current_time); else dext(m_current_time); if (m_phase == WAIT) return Infinity <double>::positive; return 0.0; } void dint(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time); if (m_duration > 0) bench::sleep_and_work(m_duration); if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX " (neighbour_number : %" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * m_simulation_duration)); m_phase = WAIT; m_total_received += m_received; m_received = 0; m_last_time = time; } } void dext(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n", m_name.c_str(), time, static_cast <std::uintmax_t>(x[0].size()), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_neighbour_number)); if (m_last_time == time) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time); throw std::runtime_error("Oups event\n"); } for (size_t i = 0, e = x[0].size(); i != e; ++i) vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]); m_received += x[0].size(); if (m_received == m_neighbour_number) m_phase = SEND; } virtual void lambda() const override final { if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } } }; template <typename T> struct Coupled : T { std::string m_name; Coupled(const vle::Context& ctx) : T(ctx) {} Coupled(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Coupled() {} virtual void apply_common(const vle::Common& common) override { m_name = vle::common_get <std::string>(common, "name"); } virtual vle::Common update_common(const vle::Common& common, const typename Coupled::vertices& v, const typename Coupled::edges& e, int child) override { auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); vle::Common ret(common); vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n", m_name.c_str(), vle::stringf("%s-%d", m_name.c_str(), child).c_str(), mdl, static_cast <std::uintmax_t>(nb)); ret["id"] = child; ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child); ret["neighbour_number"] = nb; return std::move(ret); } }; template <typename T> struct RootMPI : T { boost::mpi::communicator com; RootMPI(const vle::Context& ctx) : T(ctx) , com() {} virtual ~RootMPI() {} virtual vle::Common update_common(const vle::Common& common, const typename RootMPI::vertices& v, const typename RootMPI::edges& e, int child) override { (void)v; (void)e; if (com.size() <= child + 1) throw std::invalid_argument("MPI size < children size"); bench::SynchronousProxyModel* mdl = dynamic_cast <bench::SynchronousProxyModel*>(T::m_children[child].get()); if (!mdl) throw std::invalid_argument("RootMPI without SynchronousProxyModel"); mdl->rank = child + 1; vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child); vle::Common ret(common); return std::move(ret); } }; template <typename T> struct Root : T { Root(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Root() {} virtual vle::Common update_common(const vle::Common& common, const typename Root::vertices& v, const typename Root::edges& e, int child) override { vle::Common ret(common); auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); ret["id"] = child; ret["name"] = vle::stringf("S%d", child); ret["neighbour_number"] = nb; ret["tgf-filesource"] = vle::stringf("S%d.tgf", child); ret["tgf-format"] = (int)1; return std::move(ret); } }; using RootThread = Root <GenericCoupledModelThread>; using RootMono = Root <GenericCoupledModelMono>; using RootMPIThread = RootMPI <GenericCoupledModelThread>; using RootMPIMono = RootMPI <GenericCoupledModelMono>; using CoupledThread = Coupled <GenericCoupledModelThread>; using CoupledMono = Coupled <GenericCoupledModelMono>; } #endif <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file conti_radar_message_manager.h * @brief The class of ContiRadarMessageManager */ #include "modules/drivers/conti_radar/conti_radar_message_manager.h" #include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h" #include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h" #include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h" #include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h" #include "modules/drivers/conti_radar/protocol/object_general_info_60b.h" #include "modules/drivers/conti_radar/protocol/object_list_status_60a.h" #include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h" #include "modules/drivers/conti_radar/protocol/radar_state_201.h" namespace apollo { namespace drivers { namespace conti_radar { using ::apollo::common::adapter::AdapterManager; ContiRadarMessageManager::ContiRadarMessageManager() { AddRecvProtocolData<RadarState201, true>(); AddRecvProtocolData<ClusterListStatus600, true>(); AddRecvProtocolData<ClusterGeneralInfo701, true>(); AddRecvProtocolData<ClusterQualityInfo702, true>(); AddRecvProtocolData<ObjectExtendedInfo60D, true>(); AddRecvProtocolData<ObjectGeneralInfo60B, true>(); AddRecvProtocolData<ObjectListStatus60A, true>(); AddRecvProtocolData<ObjectQualityInfo60C, true>(); } void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) { radar_config_.set_radar_conf(radar_conf); } void ContiRadarMessageManager::set_can_client( std::shared_ptr<CanClient> can_client) { can_client_ = can_client; } ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById( const uint32_t message_id) { uint32_t converted_message_id = message_id; if (protocol_data_map_.find(converted_message_id) == protocol_data_map_.end()) { ADEBUG << "Unable to get protocol data because of invalid message_id:" << message_id; return nullptr; } return protocol_data_map_[converted_message_id]; } void ContiRadarMessageManager::Parse(const uint32_t message_id, const uint8_t *data, int32_t length) { if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) { AERROR << "Incorrect ContiRadar message length, length:" << length << " required length: " << ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH; return; } ProtocolData<ContiRadar> *sensor_protocol_data = GetMutableProtocolDataById(message_id); if (sensor_protocol_data == nullptr) { return; } std::lock_guard<std::mutex> lock(sensor_data_mutex_); if (!is_configured_ && message_id != 0x201) { // read radar state message first return; } // trigger publishment if (message_id == 0x600 || message_id == 0x60A) { ADEBUG << sensor_data_.ShortDebugString(); if (sensor_data_.contiobs_size() <= sensor_data_.object_list_status().nof_objects()) { // maybe lost a object_list_status msg AdapterManager::PublishContiRadar(sensor_data_); } sensor_data_.Clear(); // fill header when recieve the general info message AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_); } sensor_protocol_data->Parse(data, length, &sensor_data_); if (message_id == 0x201) { ADEBUG << sensor_data_.ShortDebugString(); if (sensor_data_.radar_state().send_quality() == radar_config_.radar_conf().send_quality() && sensor_data_.radar_state().send_ext_info() == radar_config_.radar_conf().send_ext_info() && sensor_data_.radar_state().max_distance() == radar_config_.radar_conf().max_distance() && sensor_data_.radar_state().output_type() == radar_config_.radar_conf().output_type() && sensor_data_.radar_state().rcs_threshold() == radar_config_.radar_conf().rcs_threshold() && sensor_data_.radar_state().radar_power() == radar_config_.radar_conf().radar_power()) { is_configured_ = true; } else { AINFO << "configure radar again"; SenderMessage<ContiRadar> sender_message(RadarConfig200::ID, &radar_config_); sender_message.Update(); can_client_->SendSingleFrame({sender_message.CanFrame()}); } } received_ids_.insert(message_id); // check if need to check period const auto it = check_ids_.find(message_id); if (it != check_ids_.end()) { const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now()); it->second.real_period = time - it->second.last_time; // if period 1.5 large than base period, inc error_count const double period_multiplier = 1.5; if (it->second.real_period > (it->second.period * period_multiplier)) { it->second.error_count += 1; } else { it->second.error_count = 0; } it->second.last_time = time; } } } // namespace conti_radar } // namespace drivers } // namespace apollo <commit_msg>conti_radar : temporary disable length check<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file conti_radar_message_manager.h * @brief The class of ContiRadarMessageManager */ #include "modules/drivers/conti_radar/conti_radar_message_manager.h" #include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h" #include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h" #include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h" #include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h" #include "modules/drivers/conti_radar/protocol/object_general_info_60b.h" #include "modules/drivers/conti_radar/protocol/object_list_status_60a.h" #include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h" #include "modules/drivers/conti_radar/protocol/radar_state_201.h" namespace apollo { namespace drivers { namespace conti_radar { using ::apollo::common::adapter::AdapterManager; ContiRadarMessageManager::ContiRadarMessageManager() { AddRecvProtocolData<RadarState201, true>(); AddRecvProtocolData<ClusterListStatus600, true>(); AddRecvProtocolData<ClusterGeneralInfo701, true>(); AddRecvProtocolData<ClusterQualityInfo702, true>(); AddRecvProtocolData<ObjectExtendedInfo60D, true>(); AddRecvProtocolData<ObjectGeneralInfo60B, true>(); AddRecvProtocolData<ObjectListStatus60A, true>(); AddRecvProtocolData<ObjectQualityInfo60C, true>(); } void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) { radar_config_.set_radar_conf(radar_conf); } void ContiRadarMessageManager::set_can_client( std::shared_ptr<CanClient> can_client) { can_client_ = can_client; } ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById( const uint32_t message_id) { uint32_t converted_message_id = message_id; if (protocol_data_map_.find(converted_message_id) == protocol_data_map_.end()) { ADEBUG << "Unable to get protocol data because of invalid message_id:" << message_id; return nullptr; } return protocol_data_map_[converted_message_id]; } void ContiRadarMessageManager::Parse(const uint32_t message_id, const uint8_t *data, int32_t length) { /* if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) { AERROR << "Incorrect ContiRadar message length, length:" << length << " required length: " << ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH; return; } */ ProtocolData<ContiRadar> *sensor_protocol_data = GetMutableProtocolDataById(message_id); if (sensor_protocol_data == nullptr) { return; } std::lock_guard<std::mutex> lock(sensor_data_mutex_); if (!is_configured_ && message_id != 0x201) { // read radar state message first return; } // trigger publishment if (message_id == 0x600 || message_id == 0x60A) { ADEBUG << sensor_data_.ShortDebugString(); if (sensor_data_.contiobs_size() <= sensor_data_.object_list_status().nof_objects()) { // maybe lost a object_list_status msg AdapterManager::PublishContiRadar(sensor_data_); } sensor_data_.Clear(); // fill header when recieve the general info message AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_); } sensor_protocol_data->Parse(data, length, &sensor_data_); if (message_id == 0x201) { ADEBUG << sensor_data_.ShortDebugString(); if (sensor_data_.radar_state().send_quality() == radar_config_.radar_conf().send_quality() && sensor_data_.radar_state().send_ext_info() == radar_config_.radar_conf().send_ext_info() && sensor_data_.radar_state().max_distance() == radar_config_.radar_conf().max_distance() && sensor_data_.radar_state().output_type() == radar_config_.radar_conf().output_type() && sensor_data_.radar_state().rcs_threshold() == radar_config_.radar_conf().rcs_threshold() && sensor_data_.radar_state().radar_power() == radar_config_.radar_conf().radar_power()) { is_configured_ = true; } else { AINFO << "configure radar again"; SenderMessage<ContiRadar> sender_message(RadarConfig200::ID, &radar_config_); sender_message.Update(); can_client_->SendSingleFrame({sender_message.CanFrame()}); } } received_ids_.insert(message_id); // check if need to check period const auto it = check_ids_.find(message_id); if (it != check_ids_.end()) { const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now()); it->second.real_period = time - it->second.last_time; // if period 1.5 large than base period, inc error_count const double period_multiplier = 1.5; if (it->second.real_period > (it->second.period * period_multiplier)) { it->second.error_count += 1; } else { it->second.error_count = 0; } it->second.last_time = time; } } } // namespace conti_radar } // namespace drivers } // namespace apollo <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/account_screen.h" #include "chrome/browser/chromeos/login/language_switch_model.h" #include "chrome/browser/chromeos/login/mock_update_screen.h" #include "chrome/browser/chromeos/login/network_screen.h" #include "chrome/browser/chromeos/login/network_selection_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "unicode/locid.h" namespace { template <class T> class MockOutShowHide : public T { public: template <class P> MockOutShowHide(P p) : T(p) {} template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {} MOCK_METHOD0(Show, void()); MOCK_METHOD0(Hide, void()); }; template <class T> struct CreateMockWizardScreenHelper { static MockOutShowHide<T>* Create(WizardController* wizard); }; template <class T> MockOutShowHide<T>* CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) { return new MockOutShowHide<T>(wizard); } template <> MockOutShowHide<chromeos::NetworkScreen>* CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create( WizardController* wizard) { return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true); } #define MOCK(mock_var, screen_name, mocked_class) \ mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \ controller()->screen_name.reset(mock_var); \ EXPECT_CALL(*mock_var, Show()).Times(0); \ EXPECT_CALL(*mock_var, Hide()).Times(0); } // namespace class WizardControllerTest : public chromeos::WizardInProcessBrowserTest { protected: WizardControllerTest() : chromeos::WizardInProcessBrowserTest( WizardController::kTestNoScreenName) {} virtual ~WizardControllerTest() {} private: DISALLOW_COPY_AND_ASSIGN(WizardControllerTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) { WizardController* const wizard = controller(); ASSERT_TRUE(wizard != NULL); wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName); views::View* current_screen = wizard->contents(); ASSERT_TRUE(current_screen != NULL); // Checking the default locale. Provided that the profile is cleared in SetUp. EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(current_screen->UILayoutIsRightToLeft()); const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); chromeos::LanguageSwitchModel::SwitchLanguage("fr"); EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(current_screen->UILayoutIsRightToLeft()); const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(en_str, fr_str); chromeos::LanguageSwitchModel::SwitchLanguage("ar"); EXPECT_EQ("ar", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage()); EXPECT_TRUE(current_screen->UILayoutIsRightToLeft()); const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(fr_str, ar_str); } class WizardControllerFlowTest : public WizardControllerTest { protected: WizardControllerFlowTest() {} // Overriden from InProcessBrowserTest: virtual Browser* CreateBrowser(Profile* profile) { Browser* ret = WizardControllerTest::CreateBrowser(profile); // Set up the mocks for all screens. MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen); MOCK(mock_login_screen_, login_screen_, LoginScreen); MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen); MOCK(mock_update_screen_, update_screen_, MockUpdateScreen); // Switch to the initial screen. EXPECT_EQ(NULL, controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName); return ret; } MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_; MockOutShowHide<LoginScreen>* mock_login_screen_; MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_; MockOutShowHide<MockUpdateScreen>* mock_update_screen_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11, add_tests_for_new_control_flow_you_just_introduced); <commit_msg>Attempted ChromiumOS compile fix.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/account_screen.h" #include "chrome/browser/chromeos/login/language_switch_model.h" #include "chrome/browser/chromeos/login/mock_update_screen.h" #include "chrome/browser/chromeos/login/network_screen.h" #include "chrome/browser/chromeos/login/network_selection_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "unicode/locid.h" namespace { template <class T> class MockOutShowHide : public T { public: template <class P> MockOutShowHide(P p) : T(p) {} template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {} MOCK_METHOD0(Show, void()); MOCK_METHOD0(Hide, void()); }; template <class T> struct CreateMockWizardScreenHelper { static MockOutShowHide<T>* Create(WizardController* wizard); }; template <class T> MockOutShowHide<T>* CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) { return new MockOutShowHide<T>(wizard); } template <> MockOutShowHide<chromeos::NetworkScreen>* CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create( WizardController* wizard) { return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true); } #define MOCK(mock_var, screen_name, mocked_class) \ mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \ controller()->screen_name.reset(mock_var); \ EXPECT_CALL(*mock_var, Show()).Times(0); \ EXPECT_CALL(*mock_var, Hide()).Times(0); } // namespace class WizardControllerTest : public chromeos::WizardInProcessBrowserTest { protected: WizardControllerTest() : chromeos::WizardInProcessBrowserTest( WizardController::kTestNoScreenName) {} virtual ~WizardControllerTest() {} private: DISALLOW_COPY_AND_ASSIGN(WizardControllerTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) { WizardController* const wizard = controller(); ASSERT_TRUE(wizard != NULL); wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName); views::View* current_screen = wizard->contents(); ASSERT_TRUE(current_screen != NULL); // Checking the default locale. Provided that the profile is cleared in SetUp. EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); chromeos::LanguageSwitchModel::SwitchLanguage("fr"); EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(en_str, fr_str); chromeos::LanguageSwitchModel::SwitchLanguage("ar"); EXPECT_EQ("ar", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage()); EXPECT_TRUE(base::i18n::IsRTL()); const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(fr_str, ar_str); } class WizardControllerFlowTest : public WizardControllerTest { protected: WizardControllerFlowTest() {} // Overriden from InProcessBrowserTest: virtual Browser* CreateBrowser(Profile* profile) { Browser* ret = WizardControllerTest::CreateBrowser(profile); // Set up the mocks for all screens. MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen); MOCK(mock_login_screen_, login_screen_, LoginScreen); MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen); MOCK(mock_update_screen_, update_screen_, MockUpdateScreen); // Switch to the initial screen. EXPECT_EQ(NULL, controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName); return ret; } MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_; MockOutShowHide<LoginScreen>* mock_login_screen_; MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_; MockOutShowHide<MockUpdateScreen>* mock_update_screen_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11, add_tests_for_new_control_flow_you_just_introduced); <|endoftext|>
<commit_before>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci unsigned long long int lociPerThread; if (numLoci == 0) { lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads; } else { lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads; } std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); std::cout << "Joined thread " << i << std::endl; } std::cout << "All threads completed running" << std::endl; // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0)); std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0)); for (int tortoise = 0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { for (int threadVector = 0; threadVector < numThreads; threadVector++) { weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise]; pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise]; } } } std::cout << "Finished summing the threads vectors" << std::endl; // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; std::cout << std::fixed; std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl; std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl; std::cout << std::scientific; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } int coverages[numIndividuals]; long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0); } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0); threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise])); } } } } delete[] majorAlleleFreqs; // Needed to avoid memory leaks } std::cout << "Finished thread ending on locus " << endingLocus << std::endl; return 0; } <commit_msg>Minor changes<commit_after>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci unsigned long long int lociPerThread; if (numLoci == 0) { lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads; } else { lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads; } std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); std::cout << "Joined thread " << i << std::endl; } std::cout << "All threads completed running" << std::endl; // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0)); std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0)); for (int tortoise = 0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { for (int threadVector = 0; threadVector < numThreads; threadVector++) { weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise]; pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise]; } } } std::cout << "Finished summing the threads vectors" << std::endl; // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise < numIndividuals; tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; std::cout << std::fixed; std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl; std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl; std::cout << std::scientific; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } unsigned long long coverages[numIndividuals]; long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = unsigned long long (coverages[tortoise]*(coverages[tortoise]-1)); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0); threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])); //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1) } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0); threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise])); } } } } delete[] majorAlleleFreqs; // Needed to avoid memory leaks } std::cout << "Finished thread ending on locus " << endingLocus << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_prefs.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/updater/extension_updater.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/global_error/global_error.h" #include "chrome/browser/ui/global_error/global_error_service.h" #include "chrome/browser/ui/global_error/global_error_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "content/test/net/url_request_prepackaged_interceptor.h" #include "net/url_request/url_fetcher.h" using extensions::Extension; class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL, "http://localhost/autoupdate/updates.xml"); } virtual void SetUpOnMainThread() OVERRIDE { EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); service_ = browser()->profile()->GetExtensionService(); base::FilePath pem_path = test_data_dir_. AppendASCII("permissions_increase").AppendASCII("permissions.pem"); path_v1_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"), scoped_temp_dir_.path().AppendASCII("permissions1.crx"), pem_path, base::FilePath()); path_v2_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"), scoped_temp_dir_.path().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); path_v3_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"), scoped_temp_dir_.path().AppendASCII("permissions3.crx"), pem_path, base::FilePath()); } // Returns the ExtensionDisabledGlobalError, if present. // Caution: currently only supports one error at a time. GlobalError* GetExtensionDisabledGlobalError() { return GlobalErrorServiceFactory::GetForProfile(browser()->profile())-> GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST); } // Install the initial version, which should happen just fine. const Extension* InstallIncreasingPermissionExtensionV1() { size_t size_before = service_->extensions()->size(); const Extension* extension = InstallExtension(path_v1_, 1); if (!extension) return NULL; if (service_->extensions()->size() != size_before + 1) return NULL; return extension; } // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. const Extension* UpdateIncreasingPermissionExtension( const Extension* extension, const base::FilePath& crx_path, int expected_change) { size_t size_before = service_->extensions()->size(); if (UpdateExtension(extension->id(), crx_path, expected_change)) return NULL; BrowserThread::GetBlockingPool()->FlushForTesting(); EXPECT_EQ(size_before + expected_change, service_->extensions()->size()); if (service_->disabled_extensions()->size() != 1u) return NULL; return *service_->disabled_extensions()->begin(); } // Helper function to install an extension and upgrade it to a version // requiring additional permissions. Returns the new disabled Extension. const Extension* InstallAndUpdateIncreasingPermissionsExtension() { const Extension* extension = InstallIncreasingPermissionExtensionV1(); extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1); return extension; } ExtensionService* service_; base::ScopedTempDir scoped_temp_dir_; base::FilePath path_v1_; base::FilePath path_v2_; base::FilePath path_v3_; }; // Tests the process of updating an extension to one that requires higher // permissions, and accepting the permissions. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); const size_t size_before = service_->extensions()->size(); service_->GrantPermissionsAndEnableExtension(extension); EXPECT_EQ(size_before + 1, service_->extensions()->size()); EXPECT_EQ(0u, service_->disabled_extensions()->size()); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Tests uninstalling an extension that was disabled due to higher permissions. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); const size_t size_before = service_->extensions()->size(); UninstallExtension(extension->id()); EXPECT_EQ(size_before, service_->extensions()->size()); EXPECT_EQ(0u, service_->disabled_extensions()->size()); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Tests that no error appears if the user disabled the extension. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) { const Extension* extension = InstallIncreasingPermissionExtensionV1(); DisableExtension(extension->id()); extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Test that no error appears if the disable reason is unknown // (but probably was by the user). IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UnknownReasonSamePermissions) { const Extension* extension = InstallIncreasingPermissionExtensionV1(); DisableExtension(extension->id()); // Clear disable reason to simulate legacy disables. service_->extension_prefs()->ClearDisableReasons(extension->id()); // Upgrade to version 2. Infer from version 1 having the same permissions // granted by the user that it was disabled by the user. extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0); ASSERT_TRUE(extension); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Test that an error appears if the disable reason is unknown // (but probably was for increased permissions). // Disabled due to http://crbug.com/246431 IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, DISABLED_UnknownReasonHigherPermissions) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); // Clear disable reason to simulate legacy disables. service_->extension_prefs()->ClearDisableReasons(extension->id()); // We now have version 2 but only accepted permissions for version 1. GlobalError* error = GetExtensionDisabledGlobalError(); ASSERT_TRUE(error); // Also, remove the upgrade error for version 2. GlobalErrorServiceFactory::GetForProfile(browser()->profile())-> RemoveGlobalError(error); delete error; // Upgrade to version 3, with even higher permissions. Infer from // version 2 having higher-than-granted permissions that it was disabled // for permissions increase. extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); } // Test that an error appears if the extension gets disabled because a // version with higher permissions was installed by sync. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, HigherPermissionsFromSync) { // Get data for extension v2 (disabled) into sync. const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); std::string extension_id = extension->id(); // service_->GrantPermissionsAndEnableExtension(extension, false); extensions::ExtensionSyncData sync_data = service_->GetExtensionSyncData(*extension); UninstallExtension(extension_id); extension = NULL; // Install extension v1. InstallIncreasingPermissionExtensionV1(); // Note: This interceptor gets requests on the IO thread. content::URLLocalHostRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); interceptor.SetResponseIgnoreQuery( GURL("http://localhost/autoupdate/updates.xml"), test_data_dir_.AppendASCII("permissions_increase") .AppendASCII("updates.xml")); interceptor.SetResponseIgnoreQuery( GURL("http://localhost/autoupdate/v2.crx"), scoped_temp_dir_.path().AppendASCII("permissions2.crx")); extensions::ExtensionUpdater::CheckParams params; params.check_blacklist = false; service_->updater()->set_default_check_params(params); // Sync is replacing an older version, so it pends. EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data)); WaitForExtensionInstall(); BrowserThread::GetBlockingPool()->FlushForTesting(); extension = service_->GetExtensionById(extension_id, true); ASSERT_TRUE(extension); EXPECT_EQ("2", extension->VersionString()); EXPECT_EQ(1u, service_->disabled_extensions()->size()); EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE, service_->extension_prefs()->GetDisableReasons(extension_id)); EXPECT_TRUE(GetExtensionDisabledGlobalError()); } <commit_msg>Actually fix ExtensionDisabledGlobalErrorTest flakiness.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_prefs.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/updater/extension_updater.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/global_error/global_error.h" #include "chrome/browser/ui/global_error/global_error_service.h" #include "chrome/browser/ui/global_error/global_error_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "content/public/test/test_utils.h" #include "content/test/net/url_request_prepackaged_interceptor.h" #include "net/url_request/url_fetcher.h" using extensions::Extension; class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL, "http://localhost/autoupdate/updates.xml"); } virtual void SetUpOnMainThread() OVERRIDE { EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); service_ = browser()->profile()->GetExtensionService(); base::FilePath pem_path = test_data_dir_. AppendASCII("permissions_increase").AppendASCII("permissions.pem"); path_v1_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"), scoped_temp_dir_.path().AppendASCII("permissions1.crx"), pem_path, base::FilePath()); path_v2_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"), scoped_temp_dir_.path().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); path_v3_ = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"), scoped_temp_dir_.path().AppendASCII("permissions3.crx"), pem_path, base::FilePath()); } // Returns the ExtensionDisabledGlobalError, if present. // Caution: currently only supports one error at a time. GlobalError* GetExtensionDisabledGlobalError() { return GlobalErrorServiceFactory::GetForProfile(browser()->profile())-> GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST); } // Install the initial version, which should happen just fine. const Extension* InstallIncreasingPermissionExtensionV1() { size_t size_before = service_->extensions()->size(); const Extension* extension = InstallExtension(path_v1_, 1); if (!extension) return NULL; if (service_->extensions()->size() != size_before + 1) return NULL; return extension; } // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. const Extension* UpdateIncreasingPermissionExtension( const Extension* extension, const base::FilePath& crx_path, int expected_change) { size_t size_before = service_->extensions()->size(); if (UpdateExtension(extension->id(), crx_path, expected_change)) return NULL; BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(size_before + expected_change, service_->extensions()->size()); if (service_->disabled_extensions()->size() != 1u) return NULL; return *service_->disabled_extensions()->begin(); } // Helper function to install an extension and upgrade it to a version // requiring additional permissions. Returns the new disabled Extension. const Extension* InstallAndUpdateIncreasingPermissionsExtension() { const Extension* extension = InstallIncreasingPermissionExtensionV1(); extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1); return extension; } ExtensionService* service_; base::ScopedTempDir scoped_temp_dir_; base::FilePath path_v1_; base::FilePath path_v2_; base::FilePath path_v3_; }; // Tests the process of updating an extension to one that requires higher // permissions, and accepting the permissions. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); const size_t size_before = service_->extensions()->size(); service_->GrantPermissionsAndEnableExtension(extension); EXPECT_EQ(size_before + 1, service_->extensions()->size()); EXPECT_EQ(0u, service_->disabled_extensions()->size()); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Tests uninstalling an extension that was disabled due to higher permissions. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); const size_t size_before = service_->extensions()->size(); UninstallExtension(extension->id()); EXPECT_EQ(size_before, service_->extensions()->size()); EXPECT_EQ(0u, service_->disabled_extensions()->size()); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Tests that no error appears if the user disabled the extension. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) { const Extension* extension = InstallIncreasingPermissionExtensionV1(); DisableExtension(extension->id()); extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Test that no error appears if the disable reason is unknown // (but probably was by the user). IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UnknownReasonSamePermissions) { const Extension* extension = InstallIncreasingPermissionExtensionV1(); DisableExtension(extension->id()); // Clear disable reason to simulate legacy disables. service_->extension_prefs()->ClearDisableReasons(extension->id()); // Upgrade to version 2. Infer from version 1 having the same permissions // granted by the user that it was disabled by the user. extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0); ASSERT_TRUE(extension); ASSERT_FALSE(GetExtensionDisabledGlobalError()); } // Test that an error appears if the disable reason is unknown // (but probably was for increased permissions). IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UnknownReasonHigherPermissions) { const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); // Clear disable reason to simulate legacy disables. service_->extension_prefs()->ClearDisableReasons(extension->id()); // We now have version 2 but only accepted permissions for version 1. GlobalError* error = GetExtensionDisabledGlobalError(); ASSERT_TRUE(error); // Also, remove the upgrade error for version 2. GlobalErrorServiceFactory::GetForProfile(browser()->profile())-> RemoveGlobalError(error); delete error; // Upgrade to version 3, with even higher permissions. Infer from // version 2 having higher-than-granted permissions that it was disabled // for permissions increase. extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0); ASSERT_TRUE(extension); ASSERT_TRUE(GetExtensionDisabledGlobalError()); } // Test that an error appears if the extension gets disabled because a // version with higher permissions was installed by sync. IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, HigherPermissionsFromSync) { // Get data for extension v2 (disabled) into sync. const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension(); std::string extension_id = extension->id(); extensions::ExtensionSyncData sync_data = service_->GetExtensionSyncData(*extension); UninstallExtension(extension_id); extension = NULL; // Install extension v1. InstallIncreasingPermissionExtensionV1(); // Note: This interceptor gets requests on the IO thread. content::URLLocalHostRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); interceptor.SetResponseIgnoreQuery( GURL("http://localhost/autoupdate/updates.xml"), test_data_dir_.AppendASCII("permissions_increase") .AppendASCII("updates.xml")); interceptor.SetResponseIgnoreQuery( GURL("http://localhost/autoupdate/v2.crx"), scoped_temp_dir_.path().AppendASCII("permissions2.crx")); extensions::ExtensionUpdater::CheckParams params; params.check_blacklist = false; service_->updater()->set_default_check_params(params); // Sync is replacing an older version, so it pends. EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data)); WaitForExtensionInstall(); BrowserThread::GetBlockingPool()->FlushForTesting(); base::RunLoop().RunUntilIdle(); extension = service_->GetExtensionById(extension_id, true); ASSERT_TRUE(extension); EXPECT_EQ("2", extension->VersionString()); EXPECT_EQ(1u, service_->disabled_extensions()->size()); EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE, service_->extension_prefs()->GetDisableReasons(extension_id)); EXPECT_TRUE(GetExtensionDisabledGlobalError()); } <|endoftext|>
<commit_before>// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - OpenGL Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP #define NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/DynLib.hpp> #include <Nazara/OpenGLRenderer/Config.hpp> #include <Nazara/OpenGLRenderer/OpenGLVaoCache.hpp> #include <Nazara/OpenGLRenderer/Wrapper/CoreFunctions.hpp> #include <Nazara/OpenGLRenderer/Wrapper/Loader.hpp> #include <Nazara/Renderer/RenderStates.hpp> #include <array> #include <string> #include <unordered_set> namespace Nz { class OpenGLDevice; } namespace Nz::GL { enum class BufferTarget { Array, CopyRead, CopyWrite, ElementArray, PixelPack, PixelUnpack, TransformFeedback, Uniform, Max = Uniform }; enum class ContextType { OpenGL, OpenGL_ES }; enum class Extension { SpirV, TextureFilterAnisotropic, TextureCompressionS3tc, Max = TextureFilterAnisotropic }; enum class ExtensionStatus { NotSupported, ARB, EXT, KHR }; enum class FramebufferTarget { Draw, Read }; enum class TextureTarget { Cubemap, CubemapNegativeX, CubemapNegativeY, CubemapNegativeZ, CubemapPositiveX, CubemapPositiveY, CubemapPositiveZ, Target2D, Target2D_Array, Target3D, Max = Target3D }; struct ContextParams { ContextType type = ContextType::OpenGL_ES; bool doubleBuffering = true; unsigned int bitsPerPixel = 32; unsigned int depthBits = 24; unsigned int glMajorVersion = 0; unsigned int glMinorVersion = 0; unsigned int sampleCount = 1; unsigned int stencilBits = 8; }; class NAZARA_OPENGLRENDERER_API Context { struct SymbolLoader; friend SymbolLoader; public: inline Context(const OpenGLDevice* device); virtual ~Context(); void BindBuffer(BufferTarget target, GLuint buffer, bool force = false) const; void BindFramebuffer(GLuint fbo) const; void BindFramebuffer(FramebufferTarget target, GLuint fbo) const; void BindProgram(GLuint program) const; void BindSampler(UInt32 textureUnit, GLuint sampler) const; void BindTexture(TextureTarget target, GLuint texture) const; void BindTexture(UInt32 textureUnit, TextureTarget target, GLuint texture) const; void BindUniformBuffer(UInt32 uboUnit, GLuint buffer, GLintptr offset, GLsizeiptr size) const; void BindVertexArray(GLuint vertexArray, bool force = false) const; bool ClearErrorStack() const; virtual void EnableVerticalSync(bool enabled) = 0; inline const OpenGLDevice* GetDevice() const; inline ExtensionStatus GetExtensionStatus(Extension extension) const; inline GLFunction GetFunctionByIndex(std::size_t funcIndex) const; inline const OpenGLVaoCache& GetVaoCache() const; inline const ContextParams& GetParams() const; inline bool IsExtensionSupported(Extension extension) const; inline bool IsExtensionSupported(const std::string& extension) const; bool Initialize(const ContextParams& params); inline void NotifyBufferDestruction(GLuint buffer) const; inline void NotifyFramebufferDestruction(GLuint fbo) const; inline void NotifyProgramDestruction(GLuint program) const; inline void NotifySamplerDestruction(GLuint sampler) const; inline void NotifyTextureDestruction(GLuint texture) const; inline void NotifyVertexArrayDestruction(GLuint vao) const; bool ProcessErrorStack() const; inline void ResetColorWriteMasks() const; inline void ResetDepthWriteMasks() const; inline void ResetStencilWriteMasks() const; void SetCurrentTextureUnit(UInt32 textureUnit) const; void SetScissorBox(GLint x, GLint y, GLsizei width, GLsizei height) const; void SetViewport(GLint x, GLint y, GLsizei width, GLsizei height) const; virtual void SwapBuffers() = 0; void UpdateStates(const RenderStates& renderStates, bool isViewportFlipped) const; #define NAZARA_OPENGLRENDERER_FUNC(name, sig) sig name = nullptr; NAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC) #undef NAZARA_OPENGLRENDERER_FUNC static const Context* GetCurrentContext(); static bool SetCurrentContext(const Context* context); protected: virtual bool Activate() const = 0; virtual void Desactivate() const = 0; virtual const Loader& GetLoader() = 0; void OnContextRelease(); virtual bool ImplementFallback(const std::string_view& function); static void NotifyContextDestruction(Context* context); ContextParams m_params; private: void GL_APIENTRY HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message) const; enum class FunctionIndex { #define NAZARA_OPENGLRENDERER_FUNC(name, sig) name, NAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC) #undef NAZARA_OPENGLRENDERER_FUNC Count }; struct State { struct Box { GLint x, y; GLsizei width, height; }; struct TextureUnit { GLuint sampler = 0; std::array<GLuint, UnderlyingCast(TextureTarget::Max) + 1> textureTargets = { 0 }; }; struct UniformBufferUnit { GLuint buffer = 0; GLintptr offset = 0; GLsizeiptr size = 0; }; std::array<GLuint, UnderlyingCast(BufferTarget::Max) + 1> bufferTargets = { 0 }; std::vector<TextureUnit> textureUnits; std::vector<UniformBufferUnit> uboUnits; Box scissorBox; Box viewport; GLuint boundProgram = 0; GLuint boundDrawFBO = 0; GLuint boundReadFBO = 0; GLuint boundVertexArray = 0; UInt32 currentTextureUnit = 0; RenderStates renderStates; }; std::array<ExtensionStatus, UnderlyingCast(Extension::Max) + 1> m_extensionStatus; std::array<GLFunction, UnderlyingCast(FunctionIndex::Count)> m_originalFunctionPointer; std::unordered_set<std::string> m_supportedExtensions; OpenGLVaoCache m_vaoCache; const OpenGLDevice* m_device; mutable State m_state; }; } #include <Nazara/OpenGLRenderer/Wrapper/Context.inl> #endif <commit_msg>Update Context.hpp<commit_after>// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - OpenGL Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP #define NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/DynLib.hpp> #include <Nazara/OpenGLRenderer/Config.hpp> #include <Nazara/OpenGLRenderer/OpenGLVaoCache.hpp> #include <Nazara/OpenGLRenderer/Wrapper/CoreFunctions.hpp> #include <Nazara/OpenGLRenderer/Wrapper/Loader.hpp> #include <Nazara/Renderer/RenderStates.hpp> #include <array> #include <string> #include <unordered_set> namespace Nz { class OpenGLDevice; } namespace Nz::GL { enum class BufferTarget { Array, CopyRead, CopyWrite, ElementArray, PixelPack, PixelUnpack, TransformFeedback, Uniform, Max = Uniform }; enum class ContextType { OpenGL, OpenGL_ES }; enum class Extension { SpirV, TextureCompressionS3tc, TextureFilterAnisotropic, Max = TextureFilterAnisotropic }; enum class ExtensionStatus { NotSupported, ARB, EXT, KHR }; enum class FramebufferTarget { Draw, Read }; enum class TextureTarget { Cubemap, CubemapNegativeX, CubemapNegativeY, CubemapNegativeZ, CubemapPositiveX, CubemapPositiveY, CubemapPositiveZ, Target2D, Target2D_Array, Target3D, Max = Target3D }; struct ContextParams { ContextType type = ContextType::OpenGL_ES; bool doubleBuffering = true; unsigned int bitsPerPixel = 32; unsigned int depthBits = 24; unsigned int glMajorVersion = 0; unsigned int glMinorVersion = 0; unsigned int sampleCount = 1; unsigned int stencilBits = 8; }; class NAZARA_OPENGLRENDERER_API Context { struct SymbolLoader; friend SymbolLoader; public: inline Context(const OpenGLDevice* device); virtual ~Context(); void BindBuffer(BufferTarget target, GLuint buffer, bool force = false) const; void BindFramebuffer(GLuint fbo) const; void BindFramebuffer(FramebufferTarget target, GLuint fbo) const; void BindProgram(GLuint program) const; void BindSampler(UInt32 textureUnit, GLuint sampler) const; void BindTexture(TextureTarget target, GLuint texture) const; void BindTexture(UInt32 textureUnit, TextureTarget target, GLuint texture) const; void BindUniformBuffer(UInt32 uboUnit, GLuint buffer, GLintptr offset, GLsizeiptr size) const; void BindVertexArray(GLuint vertexArray, bool force = false) const; bool ClearErrorStack() const; virtual void EnableVerticalSync(bool enabled) = 0; inline const OpenGLDevice* GetDevice() const; inline ExtensionStatus GetExtensionStatus(Extension extension) const; inline GLFunction GetFunctionByIndex(std::size_t funcIndex) const; inline const OpenGLVaoCache& GetVaoCache() const; inline const ContextParams& GetParams() const; inline bool IsExtensionSupported(Extension extension) const; inline bool IsExtensionSupported(const std::string& extension) const; bool Initialize(const ContextParams& params); inline void NotifyBufferDestruction(GLuint buffer) const; inline void NotifyFramebufferDestruction(GLuint fbo) const; inline void NotifyProgramDestruction(GLuint program) const; inline void NotifySamplerDestruction(GLuint sampler) const; inline void NotifyTextureDestruction(GLuint texture) const; inline void NotifyVertexArrayDestruction(GLuint vao) const; bool ProcessErrorStack() const; inline void ResetColorWriteMasks() const; inline void ResetDepthWriteMasks() const; inline void ResetStencilWriteMasks() const; void SetCurrentTextureUnit(UInt32 textureUnit) const; void SetScissorBox(GLint x, GLint y, GLsizei width, GLsizei height) const; void SetViewport(GLint x, GLint y, GLsizei width, GLsizei height) const; virtual void SwapBuffers() = 0; void UpdateStates(const RenderStates& renderStates, bool isViewportFlipped) const; #define NAZARA_OPENGLRENDERER_FUNC(name, sig) sig name = nullptr; NAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC) #undef NAZARA_OPENGLRENDERER_FUNC static const Context* GetCurrentContext(); static bool SetCurrentContext(const Context* context); protected: virtual bool Activate() const = 0; virtual void Desactivate() const = 0; virtual const Loader& GetLoader() = 0; void OnContextRelease(); virtual bool ImplementFallback(const std::string_view& function); static void NotifyContextDestruction(Context* context); ContextParams m_params; private: void GL_APIENTRY HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message) const; enum class FunctionIndex { #define NAZARA_OPENGLRENDERER_FUNC(name, sig) name, NAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC) #undef NAZARA_OPENGLRENDERER_FUNC Count }; struct State { struct Box { GLint x, y; GLsizei width, height; }; struct TextureUnit { GLuint sampler = 0; std::array<GLuint, UnderlyingCast(TextureTarget::Max) + 1> textureTargets = { 0 }; }; struct UniformBufferUnit { GLuint buffer = 0; GLintptr offset = 0; GLsizeiptr size = 0; }; std::array<GLuint, UnderlyingCast(BufferTarget::Max) + 1> bufferTargets = { 0 }; std::vector<TextureUnit> textureUnits; std::vector<UniformBufferUnit> uboUnits; Box scissorBox; Box viewport; GLuint boundProgram = 0; GLuint boundDrawFBO = 0; GLuint boundReadFBO = 0; GLuint boundVertexArray = 0; UInt32 currentTextureUnit = 0; RenderStates renderStates; }; std::array<ExtensionStatus, UnderlyingCast(Extension::Max) + 1> m_extensionStatus; std::array<GLFunction, UnderlyingCast(FunctionIndex::Count)> m_originalFunctionPointer; std::unordered_set<std::string> m_supportedExtensions; OpenGLVaoCache m_vaoCache; const OpenGLDevice* m_device; mutable State m_state; }; } #include <Nazara/OpenGLRenderer/Wrapper/Context.inl> #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX #define INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX #include <com/sun/star/awt/XWindow2.hpp> #include <com/sun/star/awt/XTopWindow.hpp> #include <com/sun/star/awt/XWindowListener.hpp> #include <canvas/canvastools.hxx> #include <canvas/base/graphicdevicebase.hxx> /* Definition of BufferedGraphicDeviceBase class */ namespace canvas { /** Helper template base class for XGraphicDevice implementations on windows. Use this base class if your target device is a window. Additionally to GraphicDeviceBase, this template provides an implementation of the awt::XWindowListener interface, to receive notifications about state changes of the associated window. @tpl Base Base class to use, most probably one of the WeakComponentImplHelperN templates with the appropriate interfaces. At least XGraphicDevice should be among them (why else would you use this template, then?). Base class must have an Base( const Mutex& ) constructor (like the WeakComponentImplHelperN templates have). As the very least, the base class must be derived from uno::XInterface, as some error reporting mechanisms rely on that. @tpl DeviceHelper Device helper implementation for the backend in question. This object will be held as a member of this template class, and basically gets forwarded all XGraphicDevice API calls that could not be handled generically. @tpl Mutex Lock strategy to use. Defaults to using the OBaseMutex-provided lock. Everytime one of the methods is entered, an object of type Mutex is created with m_aMutex as the sole parameter, and destroyed again when the method scope is left. @tpl UnambiguousBase Optional unambiguous base class for XInterface of Base. It's sometimes necessary to specify this parameter, e.g. if Base derives from multiple UNO interface (were each provides its own version of XInterface, making the conversion ambiguous) */ template< class Base, class DeviceHelper, class Mutex=::osl::MutexGuard, class UnambiguousBase=::com::sun::star::uno::XInterface > class BufferedGraphicDeviceBase : public GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > { public: typedef GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > BaseType; typedef BufferedGraphicDeviceBase OurType; typedef Mutex MutexType; BufferedGraphicDeviceBase() : mxWindow(), maBounds(), mbIsVisible( false ), mbIsTopLevel( false ) { BaseType::maPropHelper.addProperties( PropertySetHelper::MakeMap ("Window", boost::bind(&OurType::getXWindow, this))); } // XGraphicDevice virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBufferController > SAL_CALL getBufferController( ) throw (::com::sun::star::uno::RuntimeException) { return this; } // XBufferController virtual ::sal_Int32 SAL_CALL createBuffers( ::sal_Int32 nBuffers ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException) { tools::verifyRange( nBuffers, (sal_Int32)1 ); MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.createBuffers( nBuffers ); } virtual void SAL_CALL destroyBuffers( ) throw (::com::sun::star::uno::RuntimeException) { MutexType aGuard( BaseType::m_aMutex ); BaseType::maDeviceHelper.destroyBuffers(); } virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException) { MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.showBuffer( mbIsVisible, bUpdateAll ); } virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException) { MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.switchBuffer( mbIsVisible, bUpdateAll ); } /** Set corresponding canvas window Use this method to set the window this canvas displays on. Comes in handy when the canvas needs to adapt size or output position to the changing window. Whenever the bounds of the window change, <code>void notifySizeUpdate( const awt::Rectangle& rBounds )</code> is called, with rBounds the window bound rect relative to the frame window. */ void setWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 >& rWindow ) { if( mxWindow.is() ) mxWindow->removeWindowListener( this ); mxWindow = rWindow; if( mxWindow.is() ) { mbIsVisible = mxWindow->isVisible(); mbIsTopLevel = ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow >( mxWindow, ::com::sun::star::uno::UNO_QUERY ).is(); maBounds = transformBounds( mxWindow->getPosSize() ); mxWindow->addWindowListener( this ); } } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > getWindow() const { return mxWindow; } ::com::sun::star::uno::Any getXWindow() const { return ::com::sun::star::uno::makeAny(mxWindow); } virtual void disposeThis() { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); if( mxWindow.is() ) { mxWindow->removeWindowListener(this); mxWindow.clear(); } // pass on to base class BaseType::disposeThis(); } ::com::sun::star::awt::Rectangle transformBounds( const ::com::sun::star::awt::Rectangle& rBounds ) { // notifySizeUpdate's bounds are relative to the toplevel // window if( !mbIsTopLevel ) return tools::getAbsoluteWindowRect( rBounds, mxWindow ); else return ::com::sun::star::awt::Rectangle( 0,0,rBounds.Width,rBounds.Height ); } void boundsChanged( const ::com::sun::star::awt::WindowEvent& e ) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); const ::com::sun::star::awt::Rectangle& rNewBounds( transformBounds( ::com::sun::star::awt::Rectangle( e.X, e.Y, e.Width, e.Height ))); if( rNewBounds.X != maBounds.X || rNewBounds.Y != maBounds.Y || rNewBounds.Width != maBounds.Width || rNewBounds.Height != maBounds.Height ) { maBounds = rNewBounds; BaseType::maDeviceHelper.notifySizeUpdate( maBounds ); } } // XWindowListener virtual void disposeEventSource( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); if( Source.Source == mxWindow ) mxWindow.clear(); BaseType::disposeEventSource(Source); } virtual void SAL_CALL windowResized( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException) { boundsChanged( e ); } virtual void SAL_CALL windowMoved( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException) { boundsChanged( e ); } virtual void SAL_CALL windowShown( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); mbIsVisible = true; } virtual void SAL_CALL windowHidden( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); mbIsVisible = false; } protected: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > mxWindow; /// Current bounds of the owning Window ::com::sun::star::awt::Rectangle maBounds; /// True, if the window this canvas is contained in, is visible bool mbIsVisible; private: /// True, if the window this canvas is contained in, is a toplevel window bool mbIsTopLevel; }; } #endif // INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#1103730 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX #define INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX #include <com/sun/star/awt/XWindow2.hpp> #include <com/sun/star/awt/XTopWindow.hpp> #include <com/sun/star/awt/XWindowListener.hpp> #include <canvas/canvastools.hxx> #include <canvas/base/graphicdevicebase.hxx> /* Definition of BufferedGraphicDeviceBase class */ namespace canvas { /** Helper template base class for XGraphicDevice implementations on windows. Use this base class if your target device is a window. Additionally to GraphicDeviceBase, this template provides an implementation of the awt::XWindowListener interface, to receive notifications about state changes of the associated window. @tpl Base Base class to use, most probably one of the WeakComponentImplHelperN templates with the appropriate interfaces. At least XGraphicDevice should be among them (why else would you use this template, then?). Base class must have an Base( const Mutex& ) constructor (like the WeakComponentImplHelperN templates have). As the very least, the base class must be derived from uno::XInterface, as some error reporting mechanisms rely on that. @tpl DeviceHelper Device helper implementation for the backend in question. This object will be held as a member of this template class, and basically gets forwarded all XGraphicDevice API calls that could not be handled generically. @tpl Mutex Lock strategy to use. Defaults to using the OBaseMutex-provided lock. Everytime one of the methods is entered, an object of type Mutex is created with m_aMutex as the sole parameter, and destroyed again when the method scope is left. @tpl UnambiguousBase Optional unambiguous base class for XInterface of Base. It's sometimes necessary to specify this parameter, e.g. if Base derives from multiple UNO interface (were each provides its own version of XInterface, making the conversion ambiguous) */ template< class Base, class DeviceHelper, class Mutex=::osl::MutexGuard, class UnambiguousBase=::com::sun::star::uno::XInterface > class BufferedGraphicDeviceBase : public GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > { public: typedef GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > BaseType; typedef BufferedGraphicDeviceBase OurType; typedef Mutex MutexType; BufferedGraphicDeviceBase() : mxWindow(), maBounds(), mbIsVisible( false ), mbIsTopLevel( false ) { BaseType::maPropHelper.addProperties( PropertySetHelper::MakeMap ("Window", boost::bind(&OurType::getXWindow, this))); } // XGraphicDevice virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBufferController > SAL_CALL getBufferController( ) throw (::com::sun::star::uno::RuntimeException) { return this; } // XBufferController virtual ::sal_Int32 SAL_CALL createBuffers( ::sal_Int32 nBuffers ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException) { tools::verifyRange( nBuffers, (sal_Int32)1 ); MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.createBuffers( nBuffers ); } virtual void SAL_CALL destroyBuffers( ) throw (::com::sun::star::uno::RuntimeException) { MutexType aGuard( BaseType::m_aMutex ); BaseType::maDeviceHelper.destroyBuffers(); } virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException, std::exception) { MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.showBuffer( mbIsVisible, bUpdateAll ); } virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException) { MutexType aGuard( BaseType::m_aMutex ); return BaseType::maDeviceHelper.switchBuffer( mbIsVisible, bUpdateAll ); } /** Set corresponding canvas window Use this method to set the window this canvas displays on. Comes in handy when the canvas needs to adapt size or output position to the changing window. Whenever the bounds of the window change, <code>void notifySizeUpdate( const awt::Rectangle& rBounds )</code> is called, with rBounds the window bound rect relative to the frame window. */ void setWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 >& rWindow ) { if( mxWindow.is() ) mxWindow->removeWindowListener( this ); mxWindow = rWindow; if( mxWindow.is() ) { mbIsVisible = mxWindow->isVisible(); mbIsTopLevel = ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow >( mxWindow, ::com::sun::star::uno::UNO_QUERY ).is(); maBounds = transformBounds( mxWindow->getPosSize() ); mxWindow->addWindowListener( this ); } } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > getWindow() const { return mxWindow; } ::com::sun::star::uno::Any getXWindow() const { return ::com::sun::star::uno::makeAny(mxWindow); } virtual void disposeThis() { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); if( mxWindow.is() ) { mxWindow->removeWindowListener(this); mxWindow.clear(); } // pass on to base class BaseType::disposeThis(); } ::com::sun::star::awt::Rectangle transformBounds( const ::com::sun::star::awt::Rectangle& rBounds ) { // notifySizeUpdate's bounds are relative to the toplevel // window if( !mbIsTopLevel ) return tools::getAbsoluteWindowRect( rBounds, mxWindow ); else return ::com::sun::star::awt::Rectangle( 0,0,rBounds.Width,rBounds.Height ); } void boundsChanged( const ::com::sun::star::awt::WindowEvent& e ) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); const ::com::sun::star::awt::Rectangle& rNewBounds( transformBounds( ::com::sun::star::awt::Rectangle( e.X, e.Y, e.Width, e.Height ))); if( rNewBounds.X != maBounds.X || rNewBounds.Y != maBounds.Y || rNewBounds.Width != maBounds.Width || rNewBounds.Height != maBounds.Height ) { maBounds = rNewBounds; BaseType::maDeviceHelper.notifySizeUpdate( maBounds ); } } // XWindowListener virtual void disposeEventSource( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); if( Source.Source == mxWindow ) mxWindow.clear(); BaseType::disposeEventSource(Source); } virtual void SAL_CALL windowResized( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException) { boundsChanged( e ); } virtual void SAL_CALL windowMoved( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException) { boundsChanged( e ); } virtual void SAL_CALL windowShown( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); mbIsVisible = true; } virtual void SAL_CALL windowHidden( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { typename BaseType::MutexType aGuard( BaseType::m_aMutex ); mbIsVisible = false; } protected: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > mxWindow; /// Current bounds of the owning Window ::com::sun::star::awt::Rectangle maBounds; /// True, if the window this canvas is contained in, is visible bool mbIsVisible; private: /// True, if the window this canvas is contained in, is a toplevel window bool mbIsTopLevel; }; } #endif // INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/extension_welcome_notification.h" #include "base/guid.h" #include "base/lazy_instance.h" #include "base/message_loop/message_loop.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/prefs/pref_service_syncable.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/user_prefs/pref_registry_syncable.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_delegate.h" #include "ui/message_center/notification_types.h" const int ExtensionWelcomeNotification::kRequestedShowTimeDays = 14; namespace { class NotificationCallbacks : public message_center::NotificationDelegate { public: NotificationCallbacks( Profile* profile, const message_center::NotifierId notifier_id, const std::string& welcome_notification_id, ExtensionWelcomeNotification::Delegate* delegate) : profile_(profile), notifier_id_(notifier_id.type, notifier_id.id), welcome_notification_id_(welcome_notification_id), delegate_(delegate) { } // Overridden from NotificationDelegate: virtual void Display() OVERRIDE {} virtual void Error() OVERRIDE {} virtual void Close(bool by_user) OVERRIDE { if (by_user) { // Setting the preference here may cause the notification erasing // to reenter. Posting a task avoids this issue. delegate_->PostTask( FROM_HERE, base::Bind(&NotificationCallbacks::MarkAsDismissed, this)); } } virtual void Click() OVERRIDE {} virtual void ButtonClick(int index) OVERRIDE { if (index == 0) { OpenNotificationLearnMoreTab(); } else if (index == 1) { DisableNotificationProvider(); Close(true); } else { NOTREACHED(); } } private: void MarkAsDismissed() { profile_->GetPrefs()->SetBoolean(prefs::kWelcomeNotificationDismissedLocal, true); } void OpenNotificationLearnMoreTab() { chrome::NavigateParams params( profile_, GURL(chrome::kNotificationWelcomeLearnMoreURL), content::PAGE_TRANSITION_LINK); params.disposition = NEW_FOREGROUND_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } void DisableNotificationProvider() { message_center::Notifier notifier(notifier_id_, base::string16(), true); message_center::MessageCenter* message_center = delegate_->GetMessageCenter(); message_center->DisableNotificationsByNotifier(notifier_id_); message_center->RemoveNotification(welcome_notification_id_, true); message_center->GetNotifierSettingsProvider()->SetNotifierEnabled( notifier, false); } virtual ~NotificationCallbacks() {} Profile* const profile_; const message_center::NotifierId notifier_id_; std::string welcome_notification_id_; // Weak ref owned by ExtensionWelcomeNotification. ExtensionWelcomeNotification::Delegate* const delegate_; DISALLOW_COPY_AND_ASSIGN(NotificationCallbacks); }; class DefaultDelegate : public ExtensionWelcomeNotification::Delegate { public: DefaultDelegate() {} virtual message_center::MessageCenter* GetMessageCenter() OVERRIDE { return g_browser_process->message_center(); } virtual base::Time GetCurrentTime() OVERRIDE { return base::Time::Now(); } virtual void PostTask( const tracked_objects::Location& from_here, const base::Closure& task) OVERRIDE { base::MessageLoop::current()->PostTask(from_here, task); } private: DISALLOW_COPY_AND_ASSIGN(DefaultDelegate); }; } // namespace ExtensionWelcomeNotification::ExtensionWelcomeNotification( const std::string& extension_id, Profile* const profile, ExtensionWelcomeNotification::Delegate* const delegate) : notifier_id_(message_center::NotifierId::APPLICATION, extension_id), profile_(profile), delegate_(delegate) { welcome_notification_dismissed_pref_.Init( prefs::kWelcomeNotificationDismissed, profile_->GetPrefs(), base::Bind( &ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged, base::Unretained(this))); welcome_notification_dismissed_local_pref_.Init( prefs::kWelcomeNotificationDismissedLocal, profile_->GetPrefs()); } // static scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create( const std::string& extension_id, Profile* const profile) { return Create(extension_id, profile, new DefaultDelegate()).Pass(); } // static scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create( const std::string& extension_id, Profile* const profile, Delegate* const delegate) { return scoped_ptr<ExtensionWelcomeNotification>( new ExtensionWelcomeNotification(extension_id, profile, delegate)).Pass(); } ExtensionWelcomeNotification::~ExtensionWelcomeNotification() { if (delayed_notification_) { delayed_notification_.reset(); PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this); } else { HideWelcomeNotification(); } } void ExtensionWelcomeNotification::OnIsSyncingChanged() { DCHECK(delayed_notification_); PrefServiceSyncable* const pref_service_syncable = PrefServiceSyncable::FromProfile(profile_); if (pref_service_syncable->IsSyncing()) { pref_service_syncable->RemoveObserver(this); scoped_ptr<Notification> previous_notification( delayed_notification_.release()); ShowWelcomeNotificationIfNecessary(*(previous_notification.get())); } } void ExtensionWelcomeNotification::ShowWelcomeNotificationIfNecessary( const Notification& notification) { if ((notification.notifier_id() == notifier_id_) && !delayed_notification_) { PrefServiceSyncable* const pref_service_syncable = PrefServiceSyncable::FromProfile(profile_); if (pref_service_syncable->IsSyncing()) { PrefService* const pref_service = profile_->GetPrefs(); if (!UserHasDismissedWelcomeNotification()) { const PopUpRequest pop_up_request = pref_service->GetBoolean( prefs::kWelcomeNotificationPreviouslyPoppedUp) ? POP_UP_HIDDEN : POP_UP_SHOWN; if (pop_up_request == POP_UP_SHOWN) { pref_service->SetBoolean( prefs::kWelcomeNotificationPreviouslyPoppedUp, true); } if (IsWelcomeNotificationExpired()) { ExpireWelcomeNotification(); } else { ShowWelcomeNotification( notification.display_source(), pop_up_request); } } } else { delayed_notification_.reset(new Notification(notification)); pref_service_syncable->AddObserver(this); } } } // static void ExtensionWelcomeNotification::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* prefs) { prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissed, false, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissedLocal, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kWelcomeNotificationPreviouslyPoppedUp, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); prefs->RegisterInt64Pref(prefs::kWelcomeNotificationExpirationTimestamp, 0, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } message_center::MessageCenter* ExtensionWelcomeNotification::GetMessageCenter() const { return delegate_->GetMessageCenter(); } void ExtensionWelcomeNotification::ShowWelcomeNotification( const base::string16& display_source, const PopUpRequest pop_up_request) { message_center::ButtonInfo learn_more( l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BUTTON_LEARN_MORE)); learn_more.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFICATION_WELCOME_LEARN_MORE); message_center::ButtonInfo disable( l10n_util::GetStringUTF16(IDS_NOTIFIER_WELCOME_BUTTON)); disable.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFIER_BLOCK_BUTTON); message_center::RichNotificationData rich_notification_data; rich_notification_data.priority = 2; rich_notification_data.buttons.push_back(learn_more); rich_notification_data.buttons.push_back(disable); if (welcome_notification_id_.empty()) welcome_notification_id_ = base::GenerateGUID(); if (!welcome_notification_id_.empty()) { scoped_ptr<message_center::Notification> message_center_notification( new message_center::Notification( message_center::NOTIFICATION_TYPE_BASE_FORMAT, welcome_notification_id_, l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_TITLE), l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BODY), ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFICATION_WELCOME_ICON), display_source, notifier_id_, rich_notification_data, new NotificationCallbacks( profile_, notifier_id_, welcome_notification_id_, delegate_.get()))); if (pop_up_request == POP_UP_HIDDEN) message_center_notification->set_shown_as_popup(true); GetMessageCenter()->AddNotification(message_center_notification.Pass()); StartExpirationTimer(); } } void ExtensionWelcomeNotification::HideWelcomeNotification() { if (!welcome_notification_id_.empty() && GetMessageCenter()->HasNotification(welcome_notification_id_)) { GetMessageCenter()->RemoveNotification(welcome_notification_id_, false); StopExpirationTimer(); } } bool ExtensionWelcomeNotification::UserHasDismissedWelcomeNotification() const { // This was previously a syncable preference; now it's per-machine. // Only the local pref will be written moving forward, but check for both so // users won't be double-toasted. bool shown_synced = profile_->GetPrefs()->GetBoolean( prefs::kWelcomeNotificationDismissed); bool shown_local = profile_->GetPrefs()->GetBoolean( prefs::kWelcomeNotificationDismissedLocal); return (shown_synced || shown_local); } void ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged() { if (UserHasDismissedWelcomeNotification()) { HideWelcomeNotification(); } } void ExtensionWelcomeNotification::StartExpirationTimer() { if (!expiration_timer_ && !IsWelcomeNotificationExpired()) { base::Time expiration_timestamp = GetExpirationTimestamp(); if (expiration_timestamp.is_null()) { SetExpirationTimestampFromNow(); expiration_timestamp = GetExpirationTimestamp(); DCHECK(!expiration_timestamp.is_null()); } expiration_timer_.reset( new base::OneShotTimer<ExtensionWelcomeNotification>()); expiration_timer_->Start( FROM_HERE, expiration_timestamp - delegate_->GetCurrentTime(), this, &ExtensionWelcomeNotification::ExpireWelcomeNotification); } } void ExtensionWelcomeNotification::StopExpirationTimer() { if (expiration_timer_) { expiration_timer_->Stop(); expiration_timer_.reset(); } } void ExtensionWelcomeNotification::ExpireWelcomeNotification() { DCHECK(IsWelcomeNotificationExpired()); profile_->GetPrefs()->SetBoolean( prefs::kWelcomeNotificationDismissedLocal, true); HideWelcomeNotification(); } base::Time ExtensionWelcomeNotification::GetExpirationTimestamp() const { PrefService* const pref_service = profile_->GetPrefs(); const int64 expiration_timestamp = pref_service->GetInt64(prefs::kWelcomeNotificationExpirationTimestamp); return (expiration_timestamp == 0) ? base::Time() : base::Time::FromInternalValue(expiration_timestamp); } void ExtensionWelcomeNotification::SetExpirationTimestampFromNow() { PrefService* const pref_service = profile_->GetPrefs(); pref_service->SetInt64( prefs::kWelcomeNotificationExpirationTimestamp, (delegate_->GetCurrentTime() + base::TimeDelta::FromDays(kRequestedShowTimeDays)).ToInternalValue()); } bool ExtensionWelcomeNotification::IsWelcomeNotificationExpired() const { const base::Time expiration_timestamp = GetExpirationTimestamp(); return !expiration_timestamp.is_null() && (expiration_timestamp <= delegate_->GetCurrentTime()); } <commit_msg>Fix Crash Due to Programmatic Dismissal of a Notification.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/extension_welcome_notification.h" #include "base/guid.h" #include "base/lazy_instance.h" #include "base/message_loop/message_loop.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/prefs/pref_service_syncable.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/user_prefs/pref_registry_syncable.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_delegate.h" #include "ui/message_center/notification_types.h" const int ExtensionWelcomeNotification::kRequestedShowTimeDays = 14; namespace { class NotificationCallbacks : public message_center::NotificationDelegate { public: NotificationCallbacks( Profile* profile, const message_center::NotifierId notifier_id, const std::string& welcome_notification_id, ExtensionWelcomeNotification::Delegate* delegate) : profile_(profile), notifier_id_(notifier_id.type, notifier_id.id), welcome_notification_id_(welcome_notification_id), delegate_(delegate) { } // Overridden from NotificationDelegate: virtual void Display() OVERRIDE {} virtual void Error() OVERRIDE {} virtual void Close(bool by_user) OVERRIDE { if (by_user) { // Setting the preference here may cause the notification erasing // to reenter. Posting a task avoids this issue. delegate_->PostTask( FROM_HERE, base::Bind(&NotificationCallbacks::MarkAsDismissed, this)); } } virtual void Click() OVERRIDE {} virtual void ButtonClick(int index) OVERRIDE { if (index == 0) { OpenNotificationLearnMoreTab(); } else if (index == 1) { DisableNotificationProvider(); Close(true); } else { NOTREACHED(); } } private: void MarkAsDismissed() { profile_->GetPrefs()->SetBoolean(prefs::kWelcomeNotificationDismissedLocal, true); } void OpenNotificationLearnMoreTab() { chrome::NavigateParams params( profile_, GURL(chrome::kNotificationWelcomeLearnMoreURL), content::PAGE_TRANSITION_LINK); params.disposition = NEW_FOREGROUND_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } void DisableNotificationProvider() { message_center::Notifier notifier(notifier_id_, base::string16(), true); message_center::MessageCenter* message_center = delegate_->GetMessageCenter(); message_center->DisableNotificationsByNotifier(notifier_id_); message_center->RemoveNotification(welcome_notification_id_, false); message_center->GetNotifierSettingsProvider()->SetNotifierEnabled( notifier, false); } virtual ~NotificationCallbacks() {} Profile* const profile_; const message_center::NotifierId notifier_id_; std::string welcome_notification_id_; // Weak ref owned by ExtensionWelcomeNotification. ExtensionWelcomeNotification::Delegate* const delegate_; DISALLOW_COPY_AND_ASSIGN(NotificationCallbacks); }; class DefaultDelegate : public ExtensionWelcomeNotification::Delegate { public: DefaultDelegate() {} virtual message_center::MessageCenter* GetMessageCenter() OVERRIDE { return g_browser_process->message_center(); } virtual base::Time GetCurrentTime() OVERRIDE { return base::Time::Now(); } virtual void PostTask( const tracked_objects::Location& from_here, const base::Closure& task) OVERRIDE { base::MessageLoop::current()->PostTask(from_here, task); } private: DISALLOW_COPY_AND_ASSIGN(DefaultDelegate); }; } // namespace ExtensionWelcomeNotification::ExtensionWelcomeNotification( const std::string& extension_id, Profile* const profile, ExtensionWelcomeNotification::Delegate* const delegate) : notifier_id_(message_center::NotifierId::APPLICATION, extension_id), profile_(profile), delegate_(delegate) { welcome_notification_dismissed_pref_.Init( prefs::kWelcomeNotificationDismissed, profile_->GetPrefs(), base::Bind( &ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged, base::Unretained(this))); welcome_notification_dismissed_local_pref_.Init( prefs::kWelcomeNotificationDismissedLocal, profile_->GetPrefs()); } // static scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create( const std::string& extension_id, Profile* const profile) { return Create(extension_id, profile, new DefaultDelegate()).Pass(); } // static scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create( const std::string& extension_id, Profile* const profile, Delegate* const delegate) { return scoped_ptr<ExtensionWelcomeNotification>( new ExtensionWelcomeNotification(extension_id, profile, delegate)).Pass(); } ExtensionWelcomeNotification::~ExtensionWelcomeNotification() { if (delayed_notification_) { delayed_notification_.reset(); PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this); } else { HideWelcomeNotification(); } } void ExtensionWelcomeNotification::OnIsSyncingChanged() { DCHECK(delayed_notification_); PrefServiceSyncable* const pref_service_syncable = PrefServiceSyncable::FromProfile(profile_); if (pref_service_syncable->IsSyncing()) { pref_service_syncable->RemoveObserver(this); scoped_ptr<Notification> previous_notification( delayed_notification_.release()); ShowWelcomeNotificationIfNecessary(*(previous_notification.get())); } } void ExtensionWelcomeNotification::ShowWelcomeNotificationIfNecessary( const Notification& notification) { if ((notification.notifier_id() == notifier_id_) && !delayed_notification_) { PrefServiceSyncable* const pref_service_syncable = PrefServiceSyncable::FromProfile(profile_); if (pref_service_syncable->IsSyncing()) { PrefService* const pref_service = profile_->GetPrefs(); if (!UserHasDismissedWelcomeNotification()) { const PopUpRequest pop_up_request = pref_service->GetBoolean( prefs::kWelcomeNotificationPreviouslyPoppedUp) ? POP_UP_HIDDEN : POP_UP_SHOWN; if (pop_up_request == POP_UP_SHOWN) { pref_service->SetBoolean( prefs::kWelcomeNotificationPreviouslyPoppedUp, true); } if (IsWelcomeNotificationExpired()) { ExpireWelcomeNotification(); } else { ShowWelcomeNotification( notification.display_source(), pop_up_request); } } } else { delayed_notification_.reset(new Notification(notification)); pref_service_syncable->AddObserver(this); } } } // static void ExtensionWelcomeNotification::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* prefs) { prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissed, false, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissedLocal, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kWelcomeNotificationPreviouslyPoppedUp, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); prefs->RegisterInt64Pref(prefs::kWelcomeNotificationExpirationTimestamp, 0, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } message_center::MessageCenter* ExtensionWelcomeNotification::GetMessageCenter() const { return delegate_->GetMessageCenter(); } void ExtensionWelcomeNotification::ShowWelcomeNotification( const base::string16& display_source, const PopUpRequest pop_up_request) { message_center::ButtonInfo learn_more( l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BUTTON_LEARN_MORE)); learn_more.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFICATION_WELCOME_LEARN_MORE); message_center::ButtonInfo disable( l10n_util::GetStringUTF16(IDS_NOTIFIER_WELCOME_BUTTON)); disable.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFIER_BLOCK_BUTTON); message_center::RichNotificationData rich_notification_data; rich_notification_data.priority = 2; rich_notification_data.buttons.push_back(learn_more); rich_notification_data.buttons.push_back(disable); if (welcome_notification_id_.empty()) welcome_notification_id_ = base::GenerateGUID(); if (!welcome_notification_id_.empty()) { scoped_ptr<message_center::Notification> message_center_notification( new message_center::Notification( message_center::NOTIFICATION_TYPE_BASE_FORMAT, welcome_notification_id_, l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_TITLE), l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BODY), ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_NOTIFICATION_WELCOME_ICON), display_source, notifier_id_, rich_notification_data, new NotificationCallbacks( profile_, notifier_id_, welcome_notification_id_, delegate_.get()))); if (pop_up_request == POP_UP_HIDDEN) message_center_notification->set_shown_as_popup(true); GetMessageCenter()->AddNotification(message_center_notification.Pass()); StartExpirationTimer(); } } void ExtensionWelcomeNotification::HideWelcomeNotification() { if (!welcome_notification_id_.empty() && GetMessageCenter()->HasNotification(welcome_notification_id_)) { GetMessageCenter()->RemoveNotification(welcome_notification_id_, false); StopExpirationTimer(); } } bool ExtensionWelcomeNotification::UserHasDismissedWelcomeNotification() const { // This was previously a syncable preference; now it's per-machine. // Only the local pref will be written moving forward, but check for both so // users won't be double-toasted. bool shown_synced = profile_->GetPrefs()->GetBoolean( prefs::kWelcomeNotificationDismissed); bool shown_local = profile_->GetPrefs()->GetBoolean( prefs::kWelcomeNotificationDismissedLocal); return (shown_synced || shown_local); } void ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged() { if (UserHasDismissedWelcomeNotification()) { HideWelcomeNotification(); } } void ExtensionWelcomeNotification::StartExpirationTimer() { if (!expiration_timer_ && !IsWelcomeNotificationExpired()) { base::Time expiration_timestamp = GetExpirationTimestamp(); if (expiration_timestamp.is_null()) { SetExpirationTimestampFromNow(); expiration_timestamp = GetExpirationTimestamp(); DCHECK(!expiration_timestamp.is_null()); } expiration_timer_.reset( new base::OneShotTimer<ExtensionWelcomeNotification>()); expiration_timer_->Start( FROM_HERE, expiration_timestamp - delegate_->GetCurrentTime(), this, &ExtensionWelcomeNotification::ExpireWelcomeNotification); } } void ExtensionWelcomeNotification::StopExpirationTimer() { if (expiration_timer_) { expiration_timer_->Stop(); expiration_timer_.reset(); } } void ExtensionWelcomeNotification::ExpireWelcomeNotification() { DCHECK(IsWelcomeNotificationExpired()); profile_->GetPrefs()->SetBoolean( prefs::kWelcomeNotificationDismissedLocal, true); HideWelcomeNotification(); } base::Time ExtensionWelcomeNotification::GetExpirationTimestamp() const { PrefService* const pref_service = profile_->GetPrefs(); const int64 expiration_timestamp = pref_service->GetInt64(prefs::kWelcomeNotificationExpirationTimestamp); return (expiration_timestamp == 0) ? base::Time() : base::Time::FromInternalValue(expiration_timestamp); } void ExtensionWelcomeNotification::SetExpirationTimestampFromNow() { PrefService* const pref_service = profile_->GetPrefs(); pref_service->SetInt64( prefs::kWelcomeNotificationExpirationTimestamp, (delegate_->GetCurrentTime() + base::TimeDelta::FromDays(kRequestedShowTimeDays)).ToInternalValue()); } bool ExtensionWelcomeNotification::IsWelcomeNotificationExpired() const { const base::Time expiration_timestamp = GetExpirationTimestamp(); return !expiration_timestamp.is_null() && (expiration_timestamp <= delegate_->GetCurrentTime()); } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_domain_isolator.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_graph_dumper.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/types.h" namespace xla { namespace { StatusOr<bool> RunInternal(HloModule* module, HloDomainIsolator::DomainCreator* creator) { int64 added_domains = 0; for (HloComputation* computation : module->computations()) { // Walk in post order and place all the required kDomain instructions. for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kDomain) { continue; } for (HloInstruction* operand : instruction->unique_operands()) { // When applying multiple domains, we could end up stacking more than // one in one edge, so here we want to build the effective // (kDomain-less) instruction->operand edge. HloInstruction* root = operand; while (root->opcode() == HloOpcode::kDomain) { root = root->mutable_operand(0); } // Check whether a kDomain is necessary between instruction and operand. HloInstruction* domain = (*creator)(instruction, root, operand); if (domain != nullptr) { VLOG(4) << "New domain: " << domain->ToString(); TF_RETURN_IF_ERROR(operand->ReplaceUseWith(instruction, domain)); ++added_domains; } } } } VLOG(3) << "Added " << added_domains << " kDomain instructions"; return added_domains > 0; } } // namespace HloDomainIsolator::HloDomainIsolator(DomainCreatorFactory creator_factory) : creator_factory_(std::move(creator_factory)) {} StatusOr<bool> HloDomainIsolator::Run(HloModule* module) { DomainCreator creator = creator_factory_(); return RunInternal(module, &creator); } } // namespace xla <commit_msg>Improve performance of domain isolator<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_domain_isolator.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_graph_dumper.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/types.h" namespace xla { namespace { StatusOr<bool> RunInternal(HloModule* module, HloDomainIsolator::DomainCreator* creator) { int64 added_domains = 0; for (HloComputation* computation : module->computations()) { // Walk in post order and place all the required kDomain instructions. for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kDomain) { continue; } for (HloInstruction* operand : instruction->unique_operands()) { // When applying multiple domains, we could end up stacking more than // one in one edge, so here we want to build the effective // (kDomain-less) instruction->operand edge. HloInstruction* root = operand; while (root->opcode() == HloOpcode::kDomain) { root = root->mutable_operand(0); } // Check whether a kDomain is necessary between instruction and operand. HloInstruction* domain = (*creator)(instruction, root, operand); if (domain != nullptr) { VLOG(4) << "New domain: " << domain->ToString(); // Call ReplaceUseWithDifferentShape even though the shapes are // expected to match to avoid an expensive shape check between the // original and the new instruction. TF_RETURN_IF_ERROR( operand->ReplaceUseWithDifferentShape(instruction, domain)); ++added_domains; } } } } VLOG(3) << "Added " << added_domains << " kDomain instructions"; return added_domains > 0; } } // namespace HloDomainIsolator::HloDomainIsolator(DomainCreatorFactory creator_factory) : creator_factory_(std::move(creator_factory)) {} StatusOr<bool> HloDomainIsolator::Run(HloModule* module) { DomainCreator creator = creator_factory_(); return RunInternal(module, &creator); } } // namespace xla <|endoftext|>
<commit_before>#include <vector> #include <string> #include <iostream> #include <math.h> #include "matrix.h" #include "field2.h" #include "h5out.h" using namespace std; int get_direction(vector<int> p1, vector<int> p2) { if (p1[0] == p2[0]) return 1; else if (p1[1] == p2[1]) return 0; else return 2; } void monitor::set_F(Field2D *newF) { F = newF; } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name,freq,N), p1(p1), p2(p2) { F = nullptr; dir = get_direction(p1, p2); length = p2[dir] - p1[dir] + 1; prevE = new double[length]; rE = matrix<double>(new double[N*length], length, N); iE = matrix<double>(new double[N*length], length, N); rH = matrix<double>(new double[N*length], length, N); iH = matrix<double>(new double[N*length], length, N); for (int i = 0; i != length; i++) { prevE[i] = 0; for (int j = 0; j!= N; j++) { rE[i][j] = 0; iE[i][j] = 0; rH[i][j] = 0; iH[i][j] = 0; } } } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double fmin, double fmax, int N): surface_monitor(name, p1, p2, nullptr, N) { freq = new double[N]; for (int i = 0; i != N; i ++) { freq[i] = fmin + (fmax-fmin)/(N-1.0)*i; } } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double f): surface_monitor(name, p1, p2, nullptr, 1) { freq = new double[1]; freq[0] = f; } void surface_monitor::update() { matrix<double> *Hfield; if (dir == 0) Hfield = &F->Hx; if (dir == 1) Hfield = &F->Hy; int a = p1[0]; int b = p1[1]; double E, H; //this if check could be done outside the for loop somehow for (int i = 0; i != length; i++) { if (dir == 0) { a = p1[0] + i; E = (prevE[i] + F->Ez[a][b])/2; H = ((*Hfield)[a][b] + (*Hfield)[a-1][b-1])/2; } else if (dir == 1) { b = p1[1] + i; E = (prevE[i] + F->Ez[a][b])/2; H = ((*Hfield)[a][b] + (*Hfield)[a][b-1])/2; } prevE[i] = F->Ez[a][b]/2; for (int j = 0; j != N; j++) { rE[i][j] += E*cos(2*M_PI*freq[j]*F->t); iE[i][j] += E*sin(2*M_PI*freq[j]*F->t); rH[i][j] += H*cos(2*M_PI*freq[j]*F->t); iH[i][j] += H*sin(2*M_PI*freq[j]*F->t); } } } void surface_monitor::write(string filename, bool extendable) { double *S = new double[N]; for (int i = 0; i != N; i++) S[i] = 0; for (int j = 0; j != N; j++) { for (int i = 0; i != length; i++) { S[j] += rE[i][j]*rH[i][j] + iE[i][j]*iH[i][j]; } S[j] *= F->dx; } F->write_monitor(filename, name, S, N, extendable); delete[] S; } //none of this below actually works //Consider the following: box_monitor doesn't call surface_monitor, but the code used in surface_monitor // can be externalized so that both can use it //For corners, first study using 4 surface_monitors directly box_monitor::box_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name, freq, N) { monitors = new surface_monitor[4]; monitors[0] = surface_monitor(name + "_1", p1, {p2[0], p1[1]}, freq, N); monitors[1] = surface_monitor(name + "_2", {p2[0], p1[1]}, p2, freq, N); monitors[2] = surface_monitor(name + "_3", {p1[1], p2[0]}, p2, freq, N); monitors[3] = surface_monitor(name + "_4", p1, {p1[1], p2[0]}, freq, N); } box_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double fmin, double fmax, int N): box_monitor(name, p1 p2, nullptr, N) { freq = new double[N]; for (int i = 0; i != N; i ++) { freq[i] = fmin + (fmax-fmin)/(N-1.0)*i; } } box_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double f); box_monitor(name, p1 p2, nullptr, 1) { freq = new double[1]; freq[0] = f; } <commit_msg>fixed another crucial oneline bug in monitor<commit_after>#include <vector> #include <string> #include <iostream> #include <math.h> #include "matrix.h" #include "field2.h" #include "h5out.h" using namespace std; int get_direction(vector<int> p1, vector<int> p2) { if (p1[0] == p2[0]) return 1; else if (p1[1] == p2[1]) return 0; else return 2; } void monitor::set_F(Field2D *newF) { F = newF; } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name,freq,N), p1(p1), p2(p2) { F = nullptr; dir = get_direction(p1, p2); length = p2[dir] - p1[dir] + 1; prevE = new double[length]; rE = matrix<double>(new double[N*length], length, N); iE = matrix<double>(new double[N*length], length, N); rH = matrix<double>(new double[N*length], length, N); iH = matrix<double>(new double[N*length], length, N); for (int i = 0; i != length; i++) { prevE[i] = 0; for (int j = 0; j!= N; j++) { rE[i][j] = 0; iE[i][j] = 0; rH[i][j] = 0; iH[i][j] = 0; } } } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double fmin, double fmax, int N): surface_monitor(name, p1, p2, nullptr, N) { freq = new double[N]; for (int i = 0; i != N; i ++) { freq[i] = fmin + (fmax-fmin)/(N-1.0)*i; } } surface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double f): surface_monitor(name, p1, p2, nullptr, 1) { freq = new double[1]; freq[0] = f; } void surface_monitor::update() { matrix<double> *Hfield; if (dir == 0) Hfield = &F->Hx; if (dir == 1) Hfield = &F->Hy; int a = p1[0]; int b = p1[1]; double E, H; //this if check could be done outside the for loop somehow for (int i = 0; i != length; i++) { if (dir == 0) { a = p1[0] + i; E = (prevE[i] + F->Ez[a][b])/2; H = ((*Hfield)[a][b] + (*Hfield)[a-1][b-1])/2; } else if (dir == 1) { b = p1[1] + i; E = (prevE[i] + F->Ez[a][b])/2; H = ((*Hfield)[a][b] + (*Hfield)[a][b-1])/2; } prevE[i] = F->Ez[a][b]; for (int j = 0; j != N; j++) { rE[i][j] += E*cos(2*M_PI*freq[j]*F->t); iE[i][j] += E*sin(2*M_PI*freq[j]*F->t); rH[i][j] += H*cos(2*M_PI*freq[j]*F->t); iH[i][j] += H*sin(2*M_PI*freq[j]*F->t); } } } void surface_monitor::write(string filename, bool extendable) { double *S = new double[N]; for (int i = 0; i != N; i++) S[i] = 0; for (int j = 0; j != N; j++) { for (int i = 0; i != length; i++) { S[j] += rE[i][j]*rH[i][j] + iE[i][j]*iH[i][j]; } S[j] *= F->dx; } F->write_monitor(filename, name, S, N, extendable); delete[] S; } //none of this below actually works //Consider the following: box_monitor doesn't call surface_monitor, but the code used in surface_monitor // can be externalized so that both can use it //For corners, first study using 4 surface_monitors directly box_monitor::box_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name, freq, N) { monitors = new surface_monitor[4]; monitors[0] = surface_monitor(name + "_1", p1, {p2[0], p1[1]}, freq, N); monitors[1] = surface_monitor(name + "_2", {p2[0], p1[1]}, p2, freq, N); monitors[2] = surface_monitor(name + "_3", {p1[1], p2[0]}, p2, freq, N); monitors[3] = surface_monitor(name + "_4", p1, {p1[1], p2[0]}, freq, N); } box_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double fmin, double fmax, int N): box_monitor(name, p1 p2, nullptr, N) { freq = new double[N]; for (int i = 0; i != N; i ++) { freq[i] = fmin + (fmax-fmin)/(N-1.0)*i; } } box_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double f); box_monitor(name, p1 p2, nullptr, 1) { freq = new double[1]; freq[0] = f; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDER_PATTERN_HPP #define MAPNIK_RENDER_PATTERN_HPP #include <mapnik/image.hpp> #include <mapnik/marker.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/renderer_common.hpp> #include <mapnik/svg/svg_converter.hpp> #include <mapnik/svg/svg_renderer_agg.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/agg_rasterizer.hpp> #include <mapnik/util/const_rendering_buffer.hpp> #include <mapnik/marker_helpers.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_color_rgba.h" #include "agg_color_gray.h" #include "agg_scanline_u.h" #include "agg_image_accessors.h" #include "agg_span_image_filter_rgba.h" #include "agg_rasterizer_scanline_aa.h" #pragma GCC diagnostic pop namespace mapnik { template <typename Symbolizer, typename Rasterizer> struct common_pattern_process_visitor { using image_type = image_rgba8; common_pattern_process_visitor(Rasterizer & ras, renderer_common const & common, Symbolizer const & sym, feature_impl const & feature) : ras_(ras), common_(common), sym_(sym), feature_(feature), spacing_(get<value_double>(sym_, keys::spacing)), lacing_(get<pattern_lacing_mode_enum>(sym_, keys::lacing)) { } image_type operator() (marker_null const &) const { throw std::runtime_error("This should not have been reached."); } template <typename Marker> image_type operator() (Marker const & marker) const { box2d<double> bbox(marker.bounding_box()); agg::trans_affine tr(transform(bbox)); if (bbox.width() < 1.0 || bbox.height() < 1.0) { throw std::runtime_error("Pattern image smaller than one pixel"); } if (lacing_ == PATTERN_LACING_MODE_ALTERNATING_GRID) { return render_pattern_alternating(ras_, marker, bbox, tr); } return render_pattern(ras_, marker, bbox, tr); } private: agg::trans_affine transform(box2d<double> & bbox) const { agg::trans_affine tr = agg::trans_affine_scaling(common_.scale_factor_); auto image_transform = get_optional<transform_type>(sym_, keys::image_transform); if (image_transform) evaluate_transform(tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); bbox *= tr; coord<double, 2> c = bbox.center(); agg::trans_affine mtx = agg::trans_affine_translation( 0.5 * bbox.width() - c.x, 0.5 * bbox.height() - c.y); return tr * mtx; } image_rgba8 render_pattern(rasterizer & ras, marker_svg const & marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::scanline_u8 sl; image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_); agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); svg_storage_type & svg = *marker.get_data(); svg_attribute_type const & svg_attributes = svg.attributes(); svg_attribute_type custom_attributes; bool use_custom_attributes = push_explicit_style( svg_attributes, custom_attributes, sym_, feature_, common_.vars_); svg_attribute_type const & used_attributes = use_custom_attributes ? custom_attributes : svg_attributes; svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source()); svg::svg_path_adapter svg_path(stl_storage); using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter, agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>; renderer_type svg_renderer(svg_path, used_attributes); tr.translate(spacing_ / 2.0, spacing_ / 2.0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); return image; } image_rgba8 render_pattern(rasterizer & ras, marker_rgba8 const& marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer = agg::renderer_scanline_aa_solid<renderer_base>; image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_); agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf_out(buf_out); renderer_base rb(pixf_out); renderer r(rb); using const_rendering_buffer = util::rendering_buffer<image_rgba8>; using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>; image_rgba8 const& src = marker.get_data(); const_rendering_buffer buf_in(src); pixfmt_in pixf(buf_in); tr.translate(spacing_ / 2.0, spacing_ / 2.0); tr.invert(); using interpolator_type = agg::span_interpolator_linear<>; interpolator_type interpolator(tr); agg::span_allocator<agg::rgba8> sa; agg::image_filter_lut filter; filter.calculate(agg::image_filter_bilinear(), true); using img_accessor_type = agg::image_accessor_clone<pixfmt_in>; using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>; img_accessor_type ia(pixf); span_gen_type sg(ia, interpolator, filter); agg::scanline_u8 sl; ras.move_to_d(0, 0); ras.line_to_d(image.width(), 0); ras.line_to_d(image.width(), image.height()); ras.line_to_d(0, image.height()); agg::render_scanlines_aa(ras, sl, rb, sa, sg); return image; } image_rgba8 render_pattern_alternating(rasterizer & ras, marker_svg const & marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::scanline_u8 sl; image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0); agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); svg_storage_type & svg = *marker.get_data(); svg_attribute_type const & svg_attributes = svg.attributes(); svg_attribute_type custom_attributes; bool use_custom_attributes = push_explicit_style( svg_attributes, custom_attributes, sym_, feature_, common_.vars_); svg_attribute_type const & used_attributes = use_custom_attributes ? custom_attributes : svg_attributes; svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source()); svg::svg_path_adapter svg_path(stl_storage); using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter, agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>; renderer_type svg_renderer(svg_path, used_attributes); tr.translate(spacing_ / 2.0, spacing_ / 2.0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); tr.translate(-(bbox.width() / 2.0 + spacing_ / 2.0), bbox.height() + spacing_); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); tr.translate(bbox.width() + spacing_, 0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); return image; } image_rgba8 render_pattern_alternating(rasterizer & ras, marker_rgba8 const& marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer = agg::renderer_scanline_aa_solid<renderer_base>; image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0); agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf_out(buf_out); renderer_base rb(pixf_out); renderer r(rb); using const_rendering_buffer = util::rendering_buffer<image_rgba8>; using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>; image_rgba8 const& src = marker.get_data(); const_rendering_buffer buf_in(src); pixfmt_in pixf(buf_in); tr.translate(spacing_ / 2.0, spacing_ / 2.0); tr.invert(); using interpolator_type = agg::span_interpolator_linear<>; interpolator_type interpolator(tr); agg::span_allocator<agg::rgba8> sa; agg::image_filter_lut filter; filter.calculate(agg::image_filter_bilinear(), true); using img_accessor_type = agg::image_accessor_clone<pixfmt_in>; using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>; img_accessor_type ia(pixf); span_gen_type sg(ia, interpolator, filter); agg::scanline_u8 sl; ras.move_to_d(0, 0); ras.line_to_d(image.width(), 0); ras.line_to_d(image.width(), image.height()); ras.line_to_d(0, image.height()); agg::render_scanlines_aa(ras, sl, rb, sa, sg); tr.invert(); tr.translate(-(bbox.width() / 2.0 + spacing_ / 2.0), bbox.height() + spacing_); tr.invert(); agg::render_scanlines_aa(ras, sl, rb, sa, sg); tr.invert(); tr.translate(bbox.width() + spacing_, 0); tr.invert(); agg::render_scanlines_aa(ras, sl, rb, sa, sg); return image; } Rasterizer & ras_; renderer_common const & common_; Symbolizer const & sym_; feature_impl const & feature_; const value_double spacing_; const pattern_lacing_mode_enum lacing_; }; } // namespace mapnik #endif // MAPNIK_RENDER_PATTERN_HPP <commit_msg>do not throw during rendering<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDER_PATTERN_HPP #define MAPNIK_RENDER_PATTERN_HPP #include <mapnik/image.hpp> #include <mapnik/marker.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/renderer_common.hpp> #include <mapnik/svg/svg_converter.hpp> #include <mapnik/svg/svg_renderer_agg.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/agg_rasterizer.hpp> #include <mapnik/util/const_rendering_buffer.hpp> #include <mapnik/marker_helpers.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_color_rgba.h" #include "agg_color_gray.h" #include "agg_scanline_u.h" #include "agg_image_accessors.h" #include "agg_span_image_filter_rgba.h" #include "agg_rasterizer_scanline_aa.h" #pragma GCC diagnostic pop namespace mapnik { template <typename Symbolizer, typename Rasterizer> struct common_pattern_process_visitor { using image_type = image_rgba8; common_pattern_process_visitor(Rasterizer & ras, renderer_common const & common, Symbolizer const & sym, feature_impl const & feature) : ras_(ras), common_(common), sym_(sym), feature_(feature), spacing_(get<value_double>(sym_, keys::spacing)), lacing_(get<pattern_lacing_mode_enum>(sym_, keys::lacing)) { } image_type operator() (marker_null const &) const { throw std::runtime_error("This should not have been reached."); } template <typename Marker> image_type operator() (Marker const & marker) const { box2d<double> bbox(marker.bounding_box()); agg::trans_affine tr(transform(bbox)); if (bbox.width() < 1.0 || bbox.height() < 1.0) { MAPNIK_LOG_ERROR(common_pattern_process_visitor) << "Pattern image smaller than one pixel"; } if (lacing_ == PATTERN_LACING_MODE_ALTERNATING_GRID) { return render_pattern_alternating(ras_, marker, bbox, tr); } return render_pattern(ras_, marker, bbox, tr); } private: agg::trans_affine transform(box2d<double> & bbox) const { agg::trans_affine tr = agg::trans_affine_scaling(common_.scale_factor_); auto image_transform = get_optional<transform_type>(sym_, keys::image_transform); if (image_transform) evaluate_transform(tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); bbox *= tr; coord<double, 2> c = bbox.center(); agg::trans_affine mtx = agg::trans_affine_translation( 0.5 * bbox.width() - c.x, 0.5 * bbox.height() - c.y); return tr * mtx; } image_rgba8 render_pattern(rasterizer & ras, marker_svg const & marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::scanline_u8 sl; image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_); agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); svg_storage_type & svg = *marker.get_data(); svg_attribute_type const & svg_attributes = svg.attributes(); svg_attribute_type custom_attributes; bool use_custom_attributes = push_explicit_style( svg_attributes, custom_attributes, sym_, feature_, common_.vars_); svg_attribute_type const & used_attributes = use_custom_attributes ? custom_attributes : svg_attributes; svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source()); svg::svg_path_adapter svg_path(stl_storage); using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter, agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>; renderer_type svg_renderer(svg_path, used_attributes); tr.translate(spacing_ / 2.0, spacing_ / 2.0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); return image; } image_rgba8 render_pattern(rasterizer & ras, marker_rgba8 const& marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer = agg::renderer_scanline_aa_solid<renderer_base>; image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_); agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf_out(buf_out); renderer_base rb(pixf_out); renderer r(rb); using const_rendering_buffer = util::rendering_buffer<image_rgba8>; using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>; image_rgba8 const& src = marker.get_data(); const_rendering_buffer buf_in(src); pixfmt_in pixf(buf_in); tr.translate(spacing_ / 2.0, spacing_ / 2.0); tr.invert(); using interpolator_type = agg::span_interpolator_linear<>; interpolator_type interpolator(tr); agg::span_allocator<agg::rgba8> sa; agg::image_filter_lut filter; filter.calculate(agg::image_filter_bilinear(), true); using img_accessor_type = agg::image_accessor_clone<pixfmt_in>; using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>; img_accessor_type ia(pixf); span_gen_type sg(ia, interpolator, filter); agg::scanline_u8 sl; ras.move_to_d(0, 0); ras.line_to_d(image.width(), 0); ras.line_to_d(image.width(), image.height()); ras.line_to_d(0, image.height()); agg::render_scanlines_aa(ras, sl, rb, sa, sg); return image; } image_rgba8 render_pattern_alternating(rasterizer & ras, marker_svg const & marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::scanline_u8 sl; image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0); agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); svg_storage_type & svg = *marker.get_data(); svg_attribute_type const & svg_attributes = svg.attributes(); svg_attribute_type custom_attributes; bool use_custom_attributes = push_explicit_style( svg_attributes, custom_attributes, sym_, feature_, common_.vars_); svg_attribute_type const & used_attributes = use_custom_attributes ? custom_attributes : svg_attributes; svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source()); svg::svg_path_adapter svg_path(stl_storage); using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter, agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>; renderer_type svg_renderer(svg_path, used_attributes); tr.translate(spacing_ / 2.0, spacing_ / 2.0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); tr.translate(-(bbox.width() / 2.0 + spacing_ / 2.0), bbox.height() + spacing_); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); tr.translate(bbox.width() + spacing_, 0); svg_renderer.render(ras, sl, renb, tr, 1.0, bbox); return image; } image_rgba8 render_pattern_alternating(rasterizer & ras, marker_rgba8 const& marker, box2d<double> const & bbox, agg::trans_affine tr) const { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer = agg::renderer_scanline_aa_solid<renderer_base>; image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0); agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size()); pixfmt pixf_out(buf_out); renderer_base rb(pixf_out); renderer r(rb); using const_rendering_buffer = util::rendering_buffer<image_rgba8>; using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>; image_rgba8 const& src = marker.get_data(); const_rendering_buffer buf_in(src); pixfmt_in pixf(buf_in); tr.translate(spacing_ / 2.0, spacing_ / 2.0); tr.invert(); using interpolator_type = agg::span_interpolator_linear<>; interpolator_type interpolator(tr); agg::span_allocator<agg::rgba8> sa; agg::image_filter_lut filter; filter.calculate(agg::image_filter_bilinear(), true); using img_accessor_type = agg::image_accessor_clone<pixfmt_in>; using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>; img_accessor_type ia(pixf); span_gen_type sg(ia, interpolator, filter); agg::scanline_u8 sl; ras.move_to_d(0, 0); ras.line_to_d(image.width(), 0); ras.line_to_d(image.width(), image.height()); ras.line_to_d(0, image.height()); agg::render_scanlines_aa(ras, sl, rb, sa, sg); tr.invert(); tr.translate(-(bbox.width() / 2.0 + spacing_ / 2.0), bbox.height() + spacing_); tr.invert(); agg::render_scanlines_aa(ras, sl, rb, sa, sg); tr.invert(); tr.translate(bbox.width() + spacing_, 0); tr.invert(); agg::render_scanlines_aa(ras, sl, rb, sa, sg); return image; } Rasterizer & ras_; renderer_common const & common_; Symbolizer const & sym_; feature_impl const & feature_; const value_double spacing_; const pattern_lacing_mode_enum lacing_; }; } // namespace mapnik #endif // MAPNIK_RENDER_PATTERN_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "LDAPDAICachePolicyModule.h" //--- standard modules used ---------------------------------------------------- #include "Dbg.h" #include "System.h" #include "SysLog.h" #include "DataAccess.h" #include "Action.h" //--- c-modules used ----------------------------------------------------------- //---- LDAPDAICachePolicyModule ----------------------------------------------------------- RegisterModule(LDAPDAICachePolicyModule); LDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0; LDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name) { StartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule); } LDAPDAICachePolicyModule::~LDAPDAICachePolicyModule() { StartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule); } bool LDAPDAICachePolicyModule::Init(const ROAnything config) { StartTrace(LDAPDAICachePolicyModule.Init); ROAnything LDAPDAICachePolicyModuleConfig; config.LookupPath(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule"); TraceAny(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule:"); ROAnything dataAccesses(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccess"]); ROAnything dataAccessActions(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccessAction"]); if ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) { SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\n"); return false; } if ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) == false || InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) == false ) { return false; } String failedDataAccesses; CheckContractIsFulfilled(failedDataAccesses, dataAccesses); CheckContractIsFulfilled(failedDataAccesses, dataAccessActions); if (failedDataAccesses.Length() != 0 ) { SysLog::WriteToStderr(String("\tLDAPDAICachePolicyModule::LDAP Query: ") << failedDataAccesses << String(" returned no data.\n")); return false; } SysLog::WriteToStderr("\tLDAPDAICachePolicyModule done\n"); return true; } bool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config ) { StartTrace(LDAPDAICachePolicyModule.InitialLoad); CacheHandler *cache = CacheHandler::Get(); bool ret(true); if (cache) { LDAPDAIDataAcccessLoader ldl(config); LDAPDAIActionLoader lal(config); Anything tmp; for (int i = 0; i < dataAccesses.GetSize(); i++) { String toDo(dataAccesses[i].AsString()); if ( daType == dataaccess ) { Trace("Loading ldl with: " << toDo); cache->Load("LdapDAIGetter", toDo, &ldl); } if ( daType == action ) { Trace("Loading lal with: " << toDo); cache->Load("LdapDAIGetter", toDo, &lal); } } } else { SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\n"); ret = false; } return ret; } bool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses) { StartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled); bool ret(true); for (int i = 0; i < dataAccesses.GetSize(); i++) { String daToDo(dataAccesses[i].AsString()); Trace("Checking with: " << daToDo); ROAnything result(LDAPDAICacheGetter::GetAll(daToDo)); // broke contract: specified LDAP-query must return data if (result.IsNull()) { failedDataAccesses.Append(daToDo); failedDataAccesses.Append(" "); ret = false; } } return ret; } bool LDAPDAICachePolicyModule::Finis() { StartTrace(LDAPDAICachePolicyModule.Finis); SysLog::WriteToStderr("\tTerminating LDAPDAICachePolicyModule done\n"); return true; } //--- LDAPDAIDataAcccessLoader ----------------------------------------------- LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { } LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { } LDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { } Anything LDAPDAIDataAcccessLoader::Load(const char *ldapDa) { StartTrace(LDAPDAIDataAcccessLoader.Load); Anything theResult(Storage::Global()); Context ctx; Context::PushPopEntry aEntry(ctx, "LdapLoader", fConfig); if (ldapDa != "") { DataAccess da(ldapDa); bool retCode = da.StdExec(ctx); Anything tmpStore(ctx.GetTmpStore()); if (retCode && tmpStore["LDAPResult"][ldapDa]["NumberOfEntries"].AsLong() > 0) { theResult = tmpStore["LDAPResult"][ldapDa]["Entries"]; } else { String msg; msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDa << "\n"; SysLog::WriteToStderr(msg); } } TraceAny(theResult, "LDAP-Result for " << ldapDa << " cache."); return theResult; } //--- LDAPDAIDataAcccessLoader ----------------------------------------------- LDAPDAIActionLoader::LDAPDAIActionLoader() { } LDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { } LDAPDAIActionLoader::~LDAPDAIActionLoader() { } Anything LDAPDAIActionLoader::Load(const char *ldapDaAction) { StartTrace(LDAPDAIActionLoader.Load); Anything theResult(Storage::Global()); Context ctx; Context::PushPopEntry aEntry(ctx, "LdapLoader", fConfig); if (ldapDaAction != "") { Anything tmpStore = ctx.GetTmpStore(); String transition; Anything config; // Default constructs an action config containing the name of the LDAPDAIDataAccess to execute // This may be overridden by the action implementing the DataAccess(es). config[ldapDaAction]["DataAccess"] = ldapDaAction; bool retCode = Action::ExecAction(transition, ctx, config); Trace("Result of DataAccess " << ldapDaAction << " is: " << retCode); // Called Action *must* return results in slot ["LDAPResult"][ldapDaAction] TraceAny(tmpStore["LDAPResult"][ldapDaAction], "Returned: " << ldapDaAction); if (retCode && tmpStore["LDAPResult"][ldapDaAction]["NumberOfEntries"].AsLong() > 0) { theResult = tmpStore["LDAPResult"][ldapDaAction]["Entries"]; TraceAny(theResult, "Result of Load()"); } else { String msg; msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDaAction << "\n"; SysLog::WriteToStderr(msg); } } return (theResult); } //---- LDAPDAICacheGetter --------------------------------------------------------- LDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess) : fDA(dataAccess) { StartTrace("LDAPDAICacheGetter.LDAPDAICacheGetter"); } LDAPDAICacheGetter::~LDAPDAICacheGetter() { StartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter); } bool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const { StartTrace(LDAPDAICacheGetter.DoLookup); return Get(result, fDA, key, delim, indexdelim); } ROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess) { StartTrace1(LDAPDAICacheGetter.GetAll, dataAccess); CacheHandler *cache = CacheHandler::Get(); return cache->Get("LdapDAIGetter", dataAccess); } bool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI) { StartTrace1(LDAPDAICacheGetter.Get, key); bool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI); TraceAny(result, "Result:"); return ret; } <commit_msg>changed PushPopEntry signature<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "LDAPDAICachePolicyModule.h" //--- standard modules used ---------------------------------------------------- #include "Dbg.h" #include "System.h" #include "SysLog.h" #include "DataAccess.h" #include "Action.h" //--- c-modules used ----------------------------------------------------------- //---- LDAPDAICachePolicyModule ----------------------------------------------------------- RegisterModule(LDAPDAICachePolicyModule); LDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0; LDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name) { StartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule); } LDAPDAICachePolicyModule::~LDAPDAICachePolicyModule() { StartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule); } bool LDAPDAICachePolicyModule::Init(const ROAnything config) { StartTrace(LDAPDAICachePolicyModule.Init); ROAnything LDAPDAICachePolicyModuleConfig; config.LookupPath(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule"); TraceAny(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule:"); ROAnything dataAccesses(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccess"]); ROAnything dataAccessActions(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccessAction"]); if ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) { SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\n"); return false; } if ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) == false || InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) == false ) { return false; } String failedDataAccesses; CheckContractIsFulfilled(failedDataAccesses, dataAccesses); CheckContractIsFulfilled(failedDataAccesses, dataAccessActions); if (failedDataAccesses.Length() != 0 ) { SysLog::WriteToStderr(String("\tLDAPDAICachePolicyModule::LDAP Query: ") << failedDataAccesses << String(" returned no data.\n")); return false; } SysLog::WriteToStderr("\tLDAPDAICachePolicyModule done\n"); return true; } bool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config ) { StartTrace(LDAPDAICachePolicyModule.InitialLoad); CacheHandler *cache = CacheHandler::Get(); bool ret(true); if (cache) { LDAPDAIDataAcccessLoader ldl(config); LDAPDAIActionLoader lal(config); Anything tmp; for (int i = 0; i < dataAccesses.GetSize(); i++) { String toDo(dataAccesses[i].AsString()); if ( daType == dataaccess ) { Trace("Loading ldl with: " << toDo); cache->Load("LdapDAIGetter", toDo, &ldl); } if ( daType == action ) { Trace("Loading lal with: " << toDo); cache->Load("LdapDAIGetter", toDo, &lal); } } } else { SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\n"); ret = false; } return ret; } bool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses) { StartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled); bool ret(true); for (int i = 0; i < dataAccesses.GetSize(); i++) { String daToDo(dataAccesses[i].AsString()); Trace("Checking with: " << daToDo); ROAnything result(LDAPDAICacheGetter::GetAll(daToDo)); // broke contract: specified LDAP-query must return data if (result.IsNull()) { failedDataAccesses.Append(daToDo); failedDataAccesses.Append(" "); ret = false; } } return ret; } bool LDAPDAICachePolicyModule::Finis() { StartTrace(LDAPDAICachePolicyModule.Finis); SysLog::WriteToStderr("\tTerminating LDAPDAICachePolicyModule done\n"); return true; } //--- LDAPDAIDataAcccessLoader ----------------------------------------------- LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { } LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { } LDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { } Anything LDAPDAIDataAcccessLoader::Load(const char *ldapDa) { StartTrace(LDAPDAIDataAcccessLoader.Load); Anything theResult(Storage::Global()); Context ctx; Context::PushPopEntry<Anything> aEntry(ctx, "LdapLoader", fConfig); if (ldapDa != "") { DataAccess da(ldapDa); bool retCode = da.StdExec(ctx); Anything tmpStore(ctx.GetTmpStore()); if (retCode && tmpStore["LDAPResult"][ldapDa]["NumberOfEntries"].AsLong() > 0) { theResult = tmpStore["LDAPResult"][ldapDa]["Entries"]; } else { String msg; msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDa << "\n"; SysLog::WriteToStderr(msg); } } TraceAny(theResult, "LDAP-Result for " << ldapDa << " cache."); return theResult; } //--- LDAPDAIDataAcccessLoader ----------------------------------------------- LDAPDAIActionLoader::LDAPDAIActionLoader() { } LDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { } LDAPDAIActionLoader::~LDAPDAIActionLoader() { } Anything LDAPDAIActionLoader::Load(const char *ldapDaAction) { StartTrace(LDAPDAIActionLoader.Load); Anything theResult(Storage::Global()); Context ctx; Context::PushPopEntry<Anything> aEntry(ctx, "LdapLoader", fConfig); if (ldapDaAction != "") { Anything tmpStore = ctx.GetTmpStore(); String transition; Anything config; // Default constructs an action config containing the name of the LDAPDAIDataAccess to execute // This may be overridden by the action implementing the DataAccess(es). config[ldapDaAction]["DataAccess"] = ldapDaAction; bool retCode = Action::ExecAction(transition, ctx, config); Trace("Result of DataAccess " << ldapDaAction << " is: " << retCode); // Called Action *must* return results in slot ["LDAPResult"][ldapDaAction] TraceAny(tmpStore["LDAPResult"][ldapDaAction], "Returned: " << ldapDaAction); if (retCode && tmpStore["LDAPResult"][ldapDaAction]["NumberOfEntries"].AsLong() > 0) { theResult = tmpStore["LDAPResult"][ldapDaAction]["Entries"]; TraceAny(theResult, "Result of Load()"); } else { String msg; msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDaAction << "\n"; SysLog::WriteToStderr(msg); } } return (theResult); } //---- LDAPDAICacheGetter --------------------------------------------------------- LDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess) : fDA(dataAccess) { StartTrace("LDAPDAICacheGetter.LDAPDAICacheGetter"); } LDAPDAICacheGetter::~LDAPDAICacheGetter() { StartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter); } bool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const { StartTrace(LDAPDAICacheGetter.DoLookup); return Get(result, fDA, key, delim, indexdelim); } ROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess) { StartTrace1(LDAPDAICacheGetter.GetAll, dataAccess); CacheHandler *cache = CacheHandler::Get(); return cache->Get("LdapDAIGetter", dataAccess); } bool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI) { StartTrace1(LDAPDAICacheGetter.Get, key); bool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI); TraceAny(result, "Result:"); return ret; } <|endoftext|>
<commit_before>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC # namespace hmLib { namespace odeint { template<typename state_type_> struct sigmoid_boundary_diff{ template<typename functor> double sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) { if (boundary_error < x)return dx(x); double v = dx(boundary_error); double dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) / (2 * abs_error); double vk = v * 2; double va = dv * 4 / (vk + std::numeric_limits<double>::min()); if (v>0) { // double ans = vk / (1 + std::exp(-va*(x - boundary_error))); return vk / (1 + std::exp(-va*(x - boundary_error))); } double ba = std::log(1 / boundary_error + 1) / boundary_error; double bk = -(vk / (1 + std::exp(-va*(0.0 - boundary_error)))) / (0.5 - (1 / (1 + std::exp(ba*(boundary_error))))); double bv = -bk / (1 + std::exp(ba*boundary_error)); // double ans = vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv; return vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv; } }; struct float_lower_boundary { using state_type = double; private: state_type val; bool prev; public: float_lower_boundary(const state_type& val_) :val(val_) {} float_lower_boundary(state_type&& val_) :val(val_) {} public: void ready(const state_type& x) { prev = check(x); } bool valid_step(const state_type& x)const { return prev || !check(x); } bool validate(const state_type& x, state_type& vx) const { if (check(x)) { vx = val; return true; } return false; } private: bool check(const state_type& x) const { return val >= x; } }; template<typename boundary_type_> struct boundary { using state_type = state_type_; using time_type = time_type_; private: boundary_category bcat; public: void ready(const state_type& x) { bcat.ready(x); } bool valid_step(const state_type& x) { return bcat.valid_step(x, t); } bool validate(const state_type& x, state_type& vx) { } bool on_boundary() { } template<typename fn> void operator()(const state_type& x, state_type& dx, fn&& Fn) { } }; } } # #endif <commit_msg>Fix boundary<commit_after>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC # namespace hmLib { namespace odeint { struct bounadry_diff_mode { struct always{}; struct step_base{}; struct never {}; }; template<typename state_type_> struct sigmoid_boundary_diff{ template<typename functor> double sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) { if (boundary_error < x)return dx(x); double v = dx(boundary_error); double dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) / (2 * abs_error); double vk = v * 2; double va = dv * 4 / (vk + std::numeric_limits<double>::min()); if (v>0) { // double ans = vk / (1 + std::exp(-va*(x - boundary_error))); return vk / (1 + std::exp(-va*(x - boundary_error))); } double ba = std::log(1 / boundary_error + 1) / boundary_error; double bk = -(vk / (1 + std::exp(-va*(0.0 - boundary_error)))) / (0.5 - (1 / (1 + std::exp(ba*(boundary_error))))); double bv = -bk / (1 + std::exp(ba*boundary_error)); // double ans = vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv; return vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv; } }; template<typename diff_type_,typename diff_mode_> struct float_lower_boundary { using state_type = double; private: state_type val; bool prev; public: float_lower_boundary(const state_type& val_) :val(val_) {} float_lower_boundary(state_type&& val_) :val(val_) {} public: void ready(const state_type& x) { prev = check(x); } bool valid_step(const state_type& x)const { return prev || !check(x); } bool validate(const state_type& x, state_type& vx) const { if (check(x)) { vx = val; return true; } return false; } private: bool check(const state_type& x) const { return val >= x; } }; template<typename boundary_type_> struct boundary { using state_type = state_type_; using time_type = time_type_; private: boundary_category bcat; public: void ready(const state_type& x) { bcat.ready(x); } bool valid_step(const state_type& x) { return bcat.valid_step(x, t); } bool validate(const state_type& x, state_type& vx) { } bool on_boundary() { } template<typename fn> void operator()(const state_type& x, state_type& dx, fn&& Fn) { } }; } } # #endif <|endoftext|>
<commit_before>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD #define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD #include <string> #include <GL/glut.h> template<typename window_traits> void setWindow(int& argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(window_traits::window_x_size, window_traits::window_y_size); glutCreateWindow(window_traits::window_name); return; } void setBackground() { glutInitDisplayMode(GLUT_RGBA); glClearColor(1.0, 1.0, 1.0, 1.0); return; } #endif /* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD */ <commit_msg>edit to use glutSwapBuffers().<commit_after>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD #define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD #include <string> #include <GL/glut.h> template<typename window_traits> void setWindow(int& argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(window_traits::window_x_size, window_traits::window_y_size); glutCreateWindow(window_traits::window_name); return; } void setBackground() { glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glClearColor(1.0, 1.0, 1.0, 1.0); return; } #endif /* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD */ <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <iostream> #include <algorithm> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> const char game_name[] = "barley-break"; const int screen_width = 640; const int screen_height = 480; const int tile_size = 64; const int font_size = 32; const int pole_size = 4; const int two_pole_size = pole_size * pole_size; const int tile_shift_x = ( screen_width - pole_size * tile_size ) / 2; const int tile_shift_y = ( screen_height - pole_size * tile_size ) / 2; const short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 }; bool quit_flag = false; SDL_Window *window = NULL; SDL_Renderer *render = NULL; SDL_Event event; SDL_Texture *tile = NULL, *font = NULL; short pole[pole_size][pole_size]; void send_error( int code ) { std::cout << SDL_GetError() << std::endl; exit( code ); } void tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p ) { SDL_Rect wnd = { 0, 0, tile_size, tile_size }; SDL_Rect pos = { 0, 0, tile_size, tile_size }; short x = p % pole_size; short y = p / pole_size; id = id != 16 ? 1 : 0; pos.x = x * tile_size + tile_shift_x; pos.y = y * tile_size + tile_shift_y; wnd.x = id * tile_size; SDL_RenderCopy( r, tex, &wnd, &pos ); } void font_color( SDL_Texture *tex, Uint32 color ) { SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF ); } void font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p ) { SDL_Rect wnd = { 0, 0, font_size, font_size }; SDL_Rect pos = { 0, 0, font_size, font_size }; short x = p % pole_size; short y = p / pole_size; if ( text == 16 ) { return; } pos.x = x * tile_size + tile_shift_x + font_size / 2; pos.y = y * tile_size + tile_shift_y + font_size / 2; wnd.x = (text - 1) * font_size; SDL_RenderCopy( r, tex, &wnd, &pos ); } void game_restart( void ) { for ( short i = 0; i < two_pole_size; i++ ) { *( *pole + i ) = i+1; } for ( short i = 0; i < two_pole_size; i++ ) { short rnd_1 = rand() % two_pole_size; short rnd_2 = rand() % two_pole_size; if ( rnd_1 == rnd_2 ) { rnd_2 = (rnd_1 + 1) % two_pole_size; } std::swap( *(*pole + rnd_1), *(*pole + rnd_2) ); } short incorrect = 0; for (short i = 0; i < two_pole_size; i++) { for (short j = i+1; j < two_pole_size; j++) { if (*(*pole + i) > *(*pole + j)) { incorrect ^= 1; } } } if (incorrect) { std::cout << "OMG!!!" << std::endl; game_restart(); } } void game_event( SDL_Event *event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_MOUSEBUTTONDOWN: switch ( event->button.button ) { case SDL_BUTTON_LEFT: short x = ( event->button.x - tile_shift_x ) / tile_size; short y = ( event->button.y - tile_shift_y ) / tile_size; for ( short i = 0; i < 8; i += 2 ) { short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 && x + moves[i+0] < pole_size && x + moves[i+0] >= 0 && y + moves[i+1] < pole_size && y + moves[i+1] >= 0; if ( it_move ) { pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x]; pole[y][x] = 16; } } break; } break; case SDL_KEYDOWN: short id = 0; for ( int i = 0; i < two_pole_size; i++ ) { if ( *(*pole + i) == 16 ) { id = i; } } short x = id % pole_size; short y = id / pole_size; switch ( event->key.keysym.sym ) { case SDLK_UP: case SDLK_w: if (y < 3) { pole[y][x] = pole[y+1][x]; pole[y+1][x] = 16; } break; case SDLK_DOWN: case SDLK_s: if (y > 0) { pole[y][x] = pole[y-1][x]; pole[y-1][x] = 16; } break; case SDLK_LEFT: case SDLK_a: if (x < 3) { pole[y][x] = pole[y][x+1]; pole[y][x+1] = 16; } break; case SDLK_RIGHT: case SDLK_d: if (x > 0) { pole[y][x] = pole[y][x-1]; pole[y][x-1] = 16; } break; case SDLK_r: game_restart(); break; } break; } event->button.button = 0; event->key.keysym.sym = 0; } void game_loop( void ) { short count = 0; for ( short i = 0; i < two_pole_size; i++ ) { if ( *( *pole + i ) == i+1 ) { count++; } } if ( count == two_pole_size ) { std::cout << "GAME OVER: WIN!\n"; game_restart(); } } void game_render( void ) { SDL_RenderClear( render ); for ( short i = 0; i < two_pole_size; i++ ) { tile_draw( render, tile, *( *pole + i ), i ); font_draw( render, font, *( *pole + i ), i ); } SDL_RenderPresent( render ); } void game_destroy( void ) { SDL_DestroyTexture( tile ); SDL_DestroyTexture( font ); SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN ); if ( window == NULL ) { send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if ( render == NULL ) { send_error( EXIT_FAILURE ); } tile = IMG_LoadTexture( render, "./images/tiles.png" ); font = IMG_LoadTexture( render, "./images/font.png" ); font_color( font, 0xf0c090 ); srand( time( NULL ) ); game_restart(); } int main( int argc, char *argv[] ) { Uint32 FPS_MAX = 1000 / 31; // 30 fps game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); SDL_Delay( FPS_MAX ); } game_destroy(); return EXIT_SUCCESS; }<commit_msg>[add] exit key<commit_after>#include <cstdlib> #include <ctime> #include <iostream> #include <algorithm> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> const char game_name[] = "barley-break"; const int screen_width = 640; const int screen_height = 480; const int tile_size = 64; const int font_size = 32; const int pole_size = 4; const int two_pole_size = pole_size * pole_size; const int tile_shift_x = ( screen_width - pole_size * tile_size ) / 2; const int tile_shift_y = ( screen_height - pole_size * tile_size ) / 2; const short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 }; bool quit_flag = false; SDL_Window *window = NULL; SDL_Renderer *render = NULL; SDL_Event event; SDL_Texture *tile = NULL, *font = NULL; short pole[pole_size][pole_size]; void send_error( int code ) { std::cout << SDL_GetError() << std::endl; exit( code ); } void tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p ) { SDL_Rect wnd = { 0, 0, tile_size, tile_size }; SDL_Rect pos = { 0, 0, tile_size, tile_size }; short x = p % pole_size; short y = p / pole_size; id = id != 16 ? 1 : 0; pos.x = x * tile_size + tile_shift_x; pos.y = y * tile_size + tile_shift_y; wnd.x = id * tile_size; SDL_RenderCopy( r, tex, &wnd, &pos ); } void font_color( SDL_Texture *tex, Uint32 color ) { SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF ); } void font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p ) { SDL_Rect wnd = { 0, 0, font_size, font_size }; SDL_Rect pos = { 0, 0, font_size, font_size }; short x = p % pole_size; short y = p / pole_size; if ( text == 16 ) { return; } pos.x = x * tile_size + tile_shift_x + font_size / 2; pos.y = y * tile_size + tile_shift_y + font_size / 2; wnd.x = (text - 1) * font_size; SDL_RenderCopy( r, tex, &wnd, &pos ); } void game_restart( void ) { for ( short i = 0; i < two_pole_size; i++ ) { *( *pole + i ) = i+1; } for ( short i = 0; i < two_pole_size; i++ ) { short rnd_1 = rand() % two_pole_size; short rnd_2 = rand() % two_pole_size; if ( rnd_1 == rnd_2 ) { rnd_2 = (rnd_1 + 1) % two_pole_size; } std::swap( *(*pole + rnd_1), *(*pole + rnd_2) ); } short incorrect = 0; for (short i = 0; i < two_pole_size; i++) { for (short j = i+1; j < two_pole_size; j++) { if (*(*pole + i) > *(*pole + j)) { incorrect ^= 1; } } } if (incorrect) { std::cout << "OMG!!!" << std::endl; game_restart(); } } void game_event( SDL_Event *event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_MOUSEBUTTONDOWN: switch ( event->button.button ) { case SDL_BUTTON_LEFT: short x = ( event->button.x - tile_shift_x ) / tile_size; short y = ( event->button.y - tile_shift_y ) / tile_size; for ( short i = 0; i < 8; i += 2 ) { short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 && x + moves[i+0] < pole_size && x + moves[i+0] >= 0 && y + moves[i+1] < pole_size && y + moves[i+1] >= 0; if ( it_move ) { pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x]; pole[y][x] = 16; } } break; } break; case SDL_KEYDOWN: short id = 0; for ( int i = 0; i < two_pole_size; i++ ) { if ( *(*pole + i) == 16 ) { id = i; } } short x = id % pole_size; short y = id / pole_size; switch ( event->key.keysym.sym ) { case SDLK_ESCAPE: case SDLK_q: quit_flag = true; break; case SDLK_UP: case SDLK_w: if (y < 3) { pole[y][x] = pole[y+1][x]; pole[y+1][x] = 16; } break; case SDLK_DOWN: case SDLK_s: if (y > 0) { pole[y][x] = pole[y-1][x]; pole[y-1][x] = 16; } break; case SDLK_LEFT: case SDLK_a: if (x < 3) { pole[y][x] = pole[y][x+1]; pole[y][x+1] = 16; } break; case SDLK_RIGHT: case SDLK_d: if (x > 0) { pole[y][x] = pole[y][x-1]; pole[y][x-1] = 16; } break; case SDLK_r: game_restart(); break; } break; } event->button.button = 0; event->key.keysym.sym = 0; } void game_loop( void ) { short count = 0; for ( short i = 0; i < two_pole_size; i++ ) { if ( *( *pole + i ) == i+1 ) { count++; } } if ( count == two_pole_size ) { std::cout << "GAME OVER: WIN!\n"; game_restart(); } } void game_render( void ) { SDL_RenderClear( render ); for ( short i = 0; i < two_pole_size; i++ ) { tile_draw( render, tile, *( *pole + i ), i ); font_draw( render, font, *( *pole + i ), i ); } SDL_RenderPresent( render ); } void game_destroy( void ) { SDL_DestroyTexture( tile ); SDL_DestroyTexture( font ); SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN ); if ( window == NULL ) { send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if ( render == NULL ) { send_error( EXIT_FAILURE ); } tile = IMG_LoadTexture( render, "./images/tiles.png" ); font = IMG_LoadTexture( render, "./images/font.png" ); font_color( font, 0xf0c090 ); srand( time( NULL ) ); game_restart(); } int main( int argc, char *argv[] ) { Uint32 FPS_MAX = 1000 / 31; // 30 fps game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); SDL_Delay( FPS_MAX ); } game_destroy(); return EXIT_SUCCESS; }<|endoftext|>
<commit_before>#include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; using std::cin; int main() { vector<int> ivec; for (int i; cin >> i; ivec.push_back(i)); if (ivec.empty()) { cout << "input at least one integer." << endl; return -1; } if (ivec.size() == 1) { cout << "only one integer " << ivec[0] << ", it doesn't have any adjacent elements." << endl; return -1; } for (int i = 0; i != ivec.size() - 1; ++i) cout << ivec[i] + ivec[i + 1] << " "; cout << endl; return 0; } <commit_msg>Changed condition for clarity<commit_after>#include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; using std::cin; int main() { vector<int> ivec; for (int i; cin >> i; ivec.push_back(i)); if (ivec.empty()) { cout << "input at least one integer." << endl; return -1; } if (ivec.size() == 1) { cout << "only one integer " << ivec[0] << ", it doesn't have any adjacent elements." << endl; return -1; } for (int i = 0; i < ivec.size() - 1; ++i) cout << ivec[i] + ivec[i + 1] << " "; cout << endl; return 0; } <|endoftext|>
<commit_before>// // @author @Yue Wang @shbling @Soyn @Yue Wang // // Exercise 10.24: // Use bind and check_size to find the first element in a vector of ints that has a value greater // than the length of a specified string value. // // Discussion over this exercise on StackOverflow // http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return // #include <iostream> #include <vector> #include <algorithm> #include <functional> using std::cout; using std::endl; using std::string; using std::vector; using std::find_if; using std::bind; using std::size_t; auto check_size(string const& str, size_t sz) { return str.size() < sz; } auto find_first_greater(vector<int> const& v, string const& str) { auto predicate = [&](int i){ return bind(check_size, str, i)(); }; return find_if(v.cbegin(), v.cend(), predicate); } int main() { vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; string str("123456"); auto result = find_first_greater(vec, str); if (result != vec.cend()) cout << *result << endl; else cout << "Not found" << endl; return 0; } <commit_msg>Update ex10_24.cpp<commit_after>// // @author @Yue Wang @shbling @Soyn @Yue Wang // // Exercise 10.24: // Use bind and check_size to find the first element in a vector of ints that has a value greater // than the length of a specified string value. // // Discussion over this exercise on StackOverflow // http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return // #include <iostream> #include <vector> #include <algorithm> #include <functional> using std::cout; using std::endl; using std::string; using std::vector; using std::find_if; using std::bind; using std::size_t; auto check_size(string const& str, size_t sz) { return str.size() < sz; } int main() { vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; string str("123456"); auto result = find_if(vec.begin(), vec.end(), bind(check_size, str, _1)); if (result != vec.cend()) cout << *result << endl; else cout << "Not found" << endl; return 0; } <|endoftext|>
<commit_before>// // ex11_38.cpp // Exercise 11.38 // // Created by pezy on 12/18/14. // Copyright (c) 2014 pezy. All rights reserved. // // Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p. // 440) programs to use an unordered_map. #include <unordered_map> #include <set> #include <string> #include <iostream> #include <fstream> #include <sstream> using std::string; void wordCounting() { std::unordered_map<string, size_t> word_count; for (string word; std::cin >> word; ++word_count[word]) ; for (const auto& w : word_count) std::cout << w.first << " occurs " << w.second << (w.second > 1 ? "times" : "time") << std::endl; } void wordTransformation() { std::ifstream ifs_map("../data/word_transformation.txt"), ifs_content("../data/given_to_transform.txt"); if (!ifs_map || !ifs_content) { std::cerr << "can't find the documents." << std::endl; return; } std::unordered_map<string, string> trans_map; for (string key, value; ifs_map >> key && getline(ifs_map, value);) if (value.size() > 1) trans_map[key] = value.substr(1).substr(0, value.find_last_not_of(' ')); for (string text, word; getline(ifs_content, text); std::cout << std::endl) for (std::istringstream iss(text); iss >> word;) { auto map_it = trans_map.find(word); std::cout << (map_it == trans_map.cend() ? word : map_it->second) << " "; } } int main() { // wordCounting(); wordTransformation(); }<commit_msg>Update ex11_38.cpp<commit_after>// // ex11_38.cpp // Exercise 11.38 // // Created by pezy on 12/18/14. // Copyright (c) 2014 pezy. All rights reserved. // // Rewrite the word counting (11.1, p. 421) and word transformation (11.3.6, p. 440) programs to use an unordered_map. #include <iostream> #include <string> #include <cstddef> #include <fstream> #include <sstream> #include <unordered_map> using namespace std; void wordCounting() { unordered_map<string, size_t> word_count; for(string word; cin>>word; ++word_count[word]) ; for(const auto &w:word_count) cout<<w.first<<" occurs "<<w.second<<((w.second>1)?" times":" time")<<endl; } void wordTransformation() { ifstream ifs_map("E:\\1.txt"), ifs_content("E:\\2.txt"); if(!ifs_map||!ifs_content) { cerr<<"can't find the documents"<<endl; return; } unordered_map<string, string> trans_map; for(string key, value; ifs_map>>key&&getline(ifs_map, value); ) if(value.size()>1) trans_map[key]=value.substr(1).substr(0, value.find_last_not_of(' ')); for(string text, word; getline(ifs_content, text); cout<<endl) for(istringstream iss(text); iss>>word; ) { auto map_it=trans_map.find(word); cout<<((map_it==trans_map.cend()) ? word : map_it->second)<<" "; } } int main() { //wordCounting(); wordTransformation(); } <|endoftext|>
<commit_before>#include "Arduino.h" #include "mt8880.h" void mt8880_init() { //Prepare chip select and register select pinMode(CS, OUTPUT); digitalWrite(CS, HIGH); pinMode(RS, OUTPUT); digitalWrite(RS, HIGH); //Wait until 100ms after power on while(millis() < 100); //Creepy initialization magic from the datasheet mt8880_read(true); mt8880_write(0b0000, true); mt8880_write(0b0000, true); mt8880_write(0b1000, true); mt8880_write(0b0000, true); mt8880_read(true); } char mt8880_read(bool rs) { //Data pins should be inputs pinMode(D0, INPUT); pinMode(D1, INPUT); pinMode(D2, INPUT); pinMode(D3, INPUT); //Select chip digitalWrite(CS, LOW); //Select status/control registers (based on rs value) digitalWrite(RS, rs); //Read register digitalWrite(RW, HIGH); //Clock pulse (so the chip updates) digitalWrite(O2, HIGH); delay(5); //Storage char data = 0; //Fun bitwise stuff to read and combine the binary values data |= digitalRead(D3); data <<= 1; data |= digitalRead(D2); data <<= 1; data |= digitalRead(D1); data <<= 1; data |= digitalRead(D0); //Clock pulse digitalWrite(O2, LOW); delay(5); //Deselect chip digitalWrite(CS, HIGH); return data; } void mt8880_write(char data, bool rs) { //Data pins should be outputs pinMode(D0, OUTPUT); pinMode(D1, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); //Select chip digitalWrite(CS, LOW); //Select status/control registers (based on rs value) digitalWrite(RS, rs); //Write register digitalWrite(RW, LOW); //Fun bitwise stuff to separate and write the binary values digitalWrite(D0, data & 1); data >>= 1; digitalWrite(D1, data & 1); data >>= 1; digitalWrite(D2, data & 1); data >>= 1; digitalWrite(D3, data & 1); data >>= 1; //Clock pulse (so the chip updates) digitalWrite(O2, HIGH); delay(5); //Clock pulse digitalWrite(O2, LOW); delay(5); //Deselect chip digitalWrite(CS, HIGH); } <commit_msg>fix some initialization values for mt8880<commit_after>#include "Arduino.h" #include "mt8880.h" void mt8880_init() { //Prepare interrupt input with pull-up pinMode(IRQ, INPUT); digitalWrite(IRQ, HIGH); //Prepare chip select, register select, read/write, and clock pinMode(CS, OUTPUT); digitalWrite(CS, HIGH); pinMode(RS, OUTPUT); digitalWrite(RS, HIGH); pinMode(RW, OUTPUT); digitalWrite(RW, HIGH); pinMode(O2, OUTPUT); digitalWrite(O2, LOW); //Wait until 100ms after power on while(millis() < 100); //Creepy initialization magic from the datasheet mt8880_read(true); mt8880_write(0b0000, true); mt8880_write(0b0000, true); mt8880_write(0b1000, true); mt8880_write(0b0000, true); mt8880_read(true); } char mt8880_read(bool rs) { //Data pins should be inputs pinMode(D0, INPUT); pinMode(D1, INPUT); pinMode(D2, INPUT); pinMode(D3, INPUT); //Select chip digitalWrite(CS, LOW); //Select status/control registers (based on rs value) digitalWrite(RS, rs); //Read register digitalWrite(RW, HIGH); //Clock pulse (so the chip updates) digitalWrite(O2, HIGH); delay(5); //Storage char data = 0; //Fun bitwise stuff to read and combine the binary values data |= digitalRead(D3); data <<= 1; data |= digitalRead(D2); data <<= 1; data |= digitalRead(D1); data <<= 1; data |= digitalRead(D0); //Clock pulse digitalWrite(O2, LOW); delay(5); //Deselect chip digitalWrite(CS, HIGH); return data; } void mt8880_write(char data, bool rs) { //Data pins should be outputs pinMode(D0, OUTPUT); pinMode(D1, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); //Select chip digitalWrite(CS, LOW); //Select status/control registers (based on rs value) digitalWrite(RS, rs); //Write register digitalWrite(RW, LOW); //Fun bitwise stuff to separate and write the binary values digitalWrite(D0, data & 1); data >>= 1; digitalWrite(D1, data & 1); data >>= 1; digitalWrite(D2, data & 1); data >>= 1; digitalWrite(D3, data & 1); data >>= 1; //Clock pulse (so the chip updates) digitalWrite(O2, HIGH); delay(5); //Clock pulse digitalWrite(O2, LOW); delay(5); //Deselect chip digitalWrite(CS, HIGH); } <|endoftext|>
<commit_before>#include <fftw3.h> #include <boost/timer/timer.hpp> #include <boost/chrono.hpp> #include <cmath> #include <iostream> #include <complex> #include <Eigen/Dense> #include <vector> #include <unsupported/Eigen/FFT> #include <fstream> #include "chirpz.h" using namespace Eigen; namespace chirpz { void hello(fc32_t c) { std::cout << "Hello World : " << c << std::endl; } template class ChirpZ<c32_t>; template class ChirpZ<c64_t>; template class ChirpZ2d<c32_t>; template class ChirpZ2d<c64_t>; } <commit_msg>unneded dependency<commit_after>#include <fftw3.h> #include <boost/timer/timer.hpp> #include <boost/chrono.hpp> #include <cmath> #include <iostream> #include <complex> #include <Eigen/Dense> #include <vector> #include <fstream> #include "chirpz.h" using namespace Eigen; namespace chirpz { void hello(fc32_t c) { std::cout << "Hello World : " << c << std::endl; } template class ChirpZ<c32_t>; template class ChirpZ<c64_t>; template class ChirpZ2d<c32_t>; template class ChirpZ2d<c64_t>; } <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include <glog/logging.h> #include "osquery/core.h" #include "osquery/flags.h" #include "osquery/filesystem.h" #include "osquery/registry.h" namespace osquery { #define __GFLAGS_NAMESPACE google const std::string kDescription = "your operating system as a high-performance " "relational database"; const std::string kEpilog = "osquery project page <http://osquery.io>."; DEFINE_osquery_flag(bool, debug, false, "Enable debug messages."); DEFINE_osquery_flag(bool, verbose_debug, false, "Enable verbose debug messages.") DEFINE_osquery_flag(bool, disable_logging, false, "Disable ERROR/INFO logging."); DEFINE_osquery_flag(string, osquery_log_dir, "/var/log/osquery/", "Directory to store ERROR/INFO and results logging."); static const char* basename(const char* filename) { const char* sep = strrchr(filename, '/'); return sep ? sep + 1 : filename; } void initOsquery(int argc, char* argv[], int tool) { std::string binary(basename(argv[0])); std::string first_arg = (argc > 1) ? std::string(argv[1]) : ""; if ((first_arg == "--help" || first_arg == "-h" || first_arg == "-help") && tool != OSQUERY_TOOL_TEST) { // Parse help options before gflags. Only display osquery-related options. fprintf(stdout, "osquery " OSQUERY_VERSION ", %s\n", kDescription.c_str()); if (tool == OSQUERY_TOOL_SHELL) { // The shell allows a caller to run a single SQL statement and exit. fprintf( stdout, "Usage: %s [OPTION]... [SQL STATEMENT]\n\n", binary.c_str()); } else { fprintf(stdout, "Usage: %s [OPTION]...\n\n", binary.c_str()); } fprintf(stdout, "The following options control the osquery " "daemon and shell.\n\n"); Flag::printFlags(Flag::get().flags()); if (tool == OSQUERY_TOOL_SHELL) { // Print shell flags. fprintf(stdout, "\nThe following options control the osquery shell.\n\n"); Flag::printFlags(Flag::get().shellFlags()); } fprintf(stdout, "\n%s\n", kEpilog.c_str()); ::exit(0); } FLAGS_alsologtostderr = true; FLAGS_logbufsecs = 0; // flush the log buffer immediately FLAGS_stop_logging_if_full_disk = true; FLAGS_max_log_size = 10; // max size for individual log file is 10MB // Set version string from CMake build __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION); // Let gflags parse the non-help options/flags. __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false); // The log dir is used for glogging and the filesystem results logs. if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) { FLAGS_log_dir = FLAGS_osquery_log_dir; } if (FLAGS_verbose_debug) { FLAGS_debug = true; FLAGS_v = 1; } if (!FLAGS_debug) { FLAGS_minloglevel = 1; // WARNING } if (FLAGS_disable_logging) { FLAGS_logtostderr = true; FLAGS_minloglevel = 2; } google::InitGoogleLogging(argv[0]); osquery::InitRegistry::get().run(); } } <commit_msg>More appropriate logging controls<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <glog/logging.h> #include "osquery/core.h" #include "osquery/flags.h" #include "osquery/filesystem.h" #include "osquery/registry.h" namespace osquery { #define __GFLAGS_NAMESPACE google const std::string kDescription = "your operating system as a high-performance " "relational database"; const std::string kEpilog = "osquery project page <http://osquery.io>."; DEFINE_osquery_flag(bool, debug, false, "Enable debug messages."); DEFINE_osquery_flag(bool, verbose_debug, false, "Enable verbose debug messages.") DEFINE_osquery_flag(bool, disable_logging, false, "Disable ERROR/INFO logging."); DEFINE_osquery_flag(string, osquery_log_dir, "/var/log/osquery/", "Directory to store ERROR/INFO and results logging."); static const char* basename(const char* filename) { const char* sep = strrchr(filename, '/'); return sep ? sep + 1 : filename; } void initOsquery(int argc, char* argv[], int tool) { std::string binary(basename(argv[0])); std::string first_arg = (argc > 1) ? std::string(argv[1]) : ""; if ((first_arg == "--help" || first_arg == "-h" || first_arg == "-help") && tool != OSQUERY_TOOL_TEST) { // Parse help options before gflags. Only display osquery-related options. fprintf(stdout, "osquery " OSQUERY_VERSION ", %s\n", kDescription.c_str()); if (tool == OSQUERY_TOOL_SHELL) { // The shell allows a caller to run a single SQL statement and exit. fprintf( stdout, "Usage: %s [OPTION]... [SQL STATEMENT]\n\n", binary.c_str()); } else { fprintf(stdout, "Usage: %s [OPTION]...\n\n", binary.c_str()); } fprintf(stdout, "The following options control the osquery " "daemon and shell.\n\n"); Flag::printFlags(Flag::get().flags()); if (tool == OSQUERY_TOOL_SHELL) { // Print shell flags. fprintf(stdout, "\nThe following options control the osquery shell.\n\n"); Flag::printFlags(Flag::get().shellFlags()); } fprintf(stdout, "\n%s\n", kEpilog.c_str()); ::exit(0); } FLAGS_alsologtostderr = true; FLAGS_logbufsecs = 0; // flush the log buffer immediately FLAGS_stop_logging_if_full_disk = true; FLAGS_max_log_size = 10; // max size for individual log file is 10MB // Set version string from CMake build __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION); // Let gflags parse the non-help options/flags. __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false); // The log dir is used for glogging and the filesystem results logs. if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) { FLAGS_log_dir = FLAGS_osquery_log_dir; } if (FLAGS_verbose_debug) { // Turn verbosity up to 1. // Do log DEBUG, INFO, WARNING, ERROR to their log files. // Do log the above and verbose=1 to stderr. FLAGS_debug = true; FLAGS_v = 1; } if (!FLAGS_debug) { // Do NOT log INFO, WARNING, ERROR to stderr. // Do log to their log files. FLAGS_minloglevel = 0; // INFO FLAGS_alsologtostderr = false; } if (FLAGS_disable_logging) { // Do log ERROR to stderr. // Do NOT log INFO, WARNING, ERROR to their log files. FLAGS_logtostderr = true; FLAGS_minloglevel = 2; // ERROR } google::InitGoogleLogging(argv[0]); osquery::InitRegistry::get().run(); } } <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <poll.h> #include <osquery/events.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/registry_factory.h> #include "osquery/events/linux/udev.h" namespace osquery { static const int kUdevMLatency = 200; REGISTER(UdevEventPublisher, "event_publisher", "udev"); Status UdevEventPublisher::setUp() { // The Setup and Teardown workflows should be protected against races. // Just in case let's protect the publisher's resources. WriteLock lock(mutex_); // Create the udev object. handle_ = udev_new(); if (handle_ == nullptr) { return Status(1, "Could not create udev object."); } // Set up the udev monitor before scanning/polling. monitor_ = udev_monitor_new_from_netlink(handle_, "udev"); if (monitor_ == nullptr) { udev_unref(handle_); handle_ = nullptr; return Status(1, "Could not create udev monitor."); } udev_monitor_enable_receiving(monitor_); return Status(0, "OK"); } void UdevEventPublisher::tearDown() { WriteLock lock(mutex_); if (monitor_ != nullptr) { udev_monitor_unref(monitor_); monitor_ = nullptr; } if (handle_ != nullptr) { udev_unref(handle_); handle_ = nullptr; } } Status UdevEventPublisher::run() { int fd = 0; { WriteLock lock(mutex_); if (monitor_ == nullptr) { return Status(1); } fd = udev_monitor_get_fd(monitor_); } struct pollfd fds[1]; fds[0].fd = fd; fds[0].events = POLLIN; int selector = ::poll(fds, 1, 1000); if (selector == -1 && errno != EINTR && errno != EAGAIN) { LOG(ERROR) << "Could not read udev monitor"; return Status(1, "udev monitor failed."); } if (selector == 0 || !(fds[0].revents & POLLIN)) { // Read timeout. return Status(0, "Finished"); } { WriteLock lock(mutex_); struct udev_device* device = udev_monitor_receive_device(monitor_); if (device == nullptr) { LOG(ERROR) << "udev monitor returned invalid device"; return Status(1, "udev monitor failed."); } auto ec = createEventContextFrom(device); fire(ec); udev_device_unref(device); } pauseMilli(kUdevMLatency); return Status(0, "OK"); } std::string UdevEventPublisher::getValue(struct udev_device* device, const std::string& property) { auto value = udev_device_get_property_value(device, property.c_str()); if (value != nullptr) { return std::string(value); } return ""; } std::string UdevEventPublisher::getAttr(struct udev_device* device, const std::string& attr) { auto value = udev_device_get_sysattr_value(device, attr.c_str()); if (value != nullptr) { return std::string(value); } return ""; } UdevEventContextRef UdevEventPublisher::createEventContextFrom( struct udev_device* device) { auto ec = createEventContext(); ec->device = device; // Map the action string to the eventing enum. ec->action = UDEV_EVENT_ACTION_UNKNOWN; ec->action_string = std::string(udev_device_get_action(device)); if (ec->action_string == "add") { ec->action = UDEV_EVENT_ACTION_ADD; } else if (ec->action_string == "remove") { ec->action = UDEV_EVENT_ACTION_REMOVE; } else if (ec->action_string == "change") { ec->action = UDEV_EVENT_ACTION_CHANGE; } // Set the subscription-aware variables for the event. auto value = udev_device_get_subsystem(device); if (value != nullptr) { ec->subsystem = std::string(value); } value = udev_device_get_devnode(device); if (value != nullptr) { ec->devnode = std::string(value); } value = udev_device_get_devtype(device); if (value != nullptr) { ec->devtype = std::string(value); } value = udev_device_get_driver(device); if (value != nullptr) { ec->driver = std::string(value); } return ec; } bool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc, const UdevEventContextRef& ec) const { if (sc->action != UDEV_EVENT_ACTION_ALL) { if (sc->action != ec->action) { return false; } } if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) { return false; } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) { return false; } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) { return false; } else if (sc->driver.length() != 0 && sc->driver != ec->driver) { return false; } return true; } } <commit_msg>udev resource protection (#4599)<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <poll.h> #include <osquery/events.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/registry_factory.h> #include "osquery/events/linux/udev.h" namespace osquery { static const int kUdevMLatency = 200; REGISTER(UdevEventPublisher, "event_publisher", "udev"); Status UdevEventPublisher::setUp() { // The Setup and Teardown workflows should be protected against races. // Just in case let's protect the publisher's resources. WriteLock lock(mutex_); // Create the udev object. handle_ = udev_new(); if (handle_ == nullptr) { return Status(1, "Could not create udev object."); } // Set up the udev monitor before scanning/polling. monitor_ = udev_monitor_new_from_netlink(handle_, "udev"); if (monitor_ == nullptr) { udev_unref(handle_); handle_ = nullptr; return Status(1, "Could not create udev monitor."); } udev_monitor_enable_receiving(monitor_); return Status(0, "OK"); } void UdevEventPublisher::tearDown() { WriteLock lock(mutex_); if (monitor_ != nullptr) { udev_monitor_unref(monitor_); monitor_ = nullptr; } if (handle_ != nullptr) { udev_unref(handle_); handle_ = nullptr; } } Status UdevEventPublisher::run() { int fd = 0; { WriteLock lock(mutex_); if (monitor_ == nullptr) { return Status(1); } fd = udev_monitor_get_fd(monitor_); struct pollfd fds[1]; fds[0].fd = fd; fds[0].events = POLLIN; int selector = ::poll(fds, 1, 1000); if (selector == -1 && errno != EINTR && errno != EAGAIN) { LOG(ERROR) << "Could not read udev monitor"; return Status(1, "udev monitor failed."); } if (selector == 0 || !(fds[0].revents & POLLIN)) { // Read timeout. return Status(0, "Finished"); } struct udev_device* device = udev_monitor_receive_device(monitor_); if (device == nullptr) { LOG(ERROR) << "udev monitor returned invalid device"; return Status(1, "udev monitor failed."); } auto ec = createEventContextFrom(device); fire(ec); udev_device_unref(device); } pauseMilli(kUdevMLatency); return Status(0, "OK"); } std::string UdevEventPublisher::getValue(struct udev_device* device, const std::string& property) { auto value = udev_device_get_property_value(device, property.c_str()); if (value != nullptr) { return std::string(value); } return ""; } std::string UdevEventPublisher::getAttr(struct udev_device* device, const std::string& attr) { auto value = udev_device_get_sysattr_value(device, attr.c_str()); if (value != nullptr) { return std::string(value); } return ""; } UdevEventContextRef UdevEventPublisher::createEventContextFrom( struct udev_device* device) { auto ec = createEventContext(); ec->device = device; // Map the action string to the eventing enum. ec->action = UDEV_EVENT_ACTION_UNKNOWN; ec->action_string = std::string(udev_device_get_action(device)); if (ec->action_string == "add") { ec->action = UDEV_EVENT_ACTION_ADD; } else if (ec->action_string == "remove") { ec->action = UDEV_EVENT_ACTION_REMOVE; } else if (ec->action_string == "change") { ec->action = UDEV_EVENT_ACTION_CHANGE; } // Set the subscription-aware variables for the event. auto value = udev_device_get_subsystem(device); if (value != nullptr) { ec->subsystem = std::string(value); } value = udev_device_get_devnode(device); if (value != nullptr) { ec->devnode = std::string(value); } value = udev_device_get_devtype(device); if (value != nullptr) { ec->devtype = std::string(value); } value = udev_device_get_driver(device); if (value != nullptr) { ec->driver = std::string(value); } return ec; } bool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc, const UdevEventContextRef& ec) const { if (sc->action != UDEV_EVENT_ACTION_ALL) { if (sc->action != ec->action) { return false; } } if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) { return false; } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) { return false; } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) { return false; } else if (sc->driver.length() != 0 && sc->driver != ec->driver) { return false; } return true; } } // namespace osquery <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing // permissions and limitations under the License. #include <iostream> #include <fstream> #include <iterator> #include <string> #include <freeflow/sys/socket.hpp> #include <freeflow/sys/json.hpp> using namespace std; using namespace freeflow; // Holds a command-line flag. The flag is set when --flag_true is passed, and // reset when --flag_false is passed. When used in CommandParser, the name // and value act as a key-value pair. Upon construction, value will be set to // the default value of the flag. // // Example usage: // // Flag("auto connect","auto-connect","no-auto-connect",true, "Whether to // automatically connect to the network"); // // If the user typed "run --auto-connect", value for "auto connect" would // be true, whereas is they typed "run --no-auto-connect", it would be false struct Flag { string name; string flag_true; string flag_false; bool value; string help_text; Flag(string n,string f_true,string f_false,bool default_val,string help = "") : name(n), flag_true(f_true), flag_false(f_false), value(default_val), help_text(help){} }; int main(){ return 0; } <commit_msg>Added pattern matching functionality and initial framework for parsing command-line arguments<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing // permissions and limitations under the License. #include <iostream> #include <fstream> #include <iterator> #include <string> #include <vector> #include <assert.h> #include <freeflow/sys/socket.hpp> #include <freeflow/sys/json.hpp> using namespace std; using namespace freeflow; struct CLI_parser_exception { CLI_parser_exception(string err); }; CLI_parser_exception::CLI_parser_exception(string err) { cout << "CLI parser exception: " << err << endl; } struct CLI_parser_rule { string format; bool match(string & str,vector<pair<string,string> > args); CLI_parser_rule(string rule); }; CLI_parser_rule::CLI_parser_rule(string rule) : format(rule) { // Make sure all square brackets are closed bool in_bracket = false; for (char c : format) { if (c == '[') { if (not in_bracket) { in_bracket = true; } else { throw CLI_parser_exception("Too many opening square brackets ('[')" " in parser rule: " + format); } } else if (c == ']') { if (in_bracket) { in_bracket = false; } else { throw CLI_parser_exception("Too many closing square brackets (']')" " in parser rule: " + format); } } } if (in_bracket){ throw CLI_parser_exception("Expected closing square bracket (']')" " in parser rule: " + format); } } bool CLI_parser_rule::match(string & str,vector<pair<string,string> > args) { int pos_f = 0; int pos_s = 0; string name; string var_value; bool var = false; while (pos_s < (int)str.length()) { if (!var) { if (format[pos_f] == '[') { pos_f++; name = ""; var_value = ""; var = true; bool matched = false; while (pos_f < (int)format.length()) { if (format[pos_f] == ']') { matched = true; pos_f++; break; } else{ name += format[pos_f++]; } } if (!matched) { throw "CLI_parser_rule Error: unmatched bracket in rule "+format; } cout << "Next: " << format[pos_f] << endl; //pos_f++; } } if (var) { //if(pos_f+1 < format.length()){ if (str[pos_s] == format[pos_f]) { var = false; cout << "Var " << name << " = " << var_value << endl; args.push_back(pair<string,string>(name,var_value)); } else { var_value += str[pos_s++]; } //} } else { if (format[pos_f] != str[pos_s]) { return false; } pos_f++; pos_s++; } } if (var){ cout << "Var " << name << " = " << var_value << endl; args.push_back(pair<string,string>(name,var_value)); } if (pos_f < (int)format.length()) return false; else return true; } struct CLI_parser { vector<CLI_parser_rule> rules; vector<string> args; int arg_pos; void parse(int argc,char *argv[]); string & get_arg(); bool next_arg(); void set_arg_pos(int pos); }; void CLI_parser::parse(int argc,char *argv[]) { // Probably a good idea to clear the args vector if this is called more than once args.clear(); for (int i = 0; i < argc; i++) { args.push_back(argv[i]); } set_arg_pos(0); } // Gets the current argument string & CLI_parser::get_arg() { assert(arg_pos < (int)args.size()); return args[arg_pos]; } // Advances to the next argument // Returns whether there is another argument bool CLI_parser::next_arg() { return ++arg_pos < (int)args.size(); } // Sets the position of the current argument void CLI_parser::set_arg_pos(int pos) { if (pos < (int)args.size()) arg_pos = pos; else arg_pos = args.size(); } int main(int argc,char *argv[]){ CLI_parser parser; CLI_parser_rule("--[flag]=[value"); parser.parse(argc,argv); do{ cout << parser.get_arg() << endl; } while(parser.next_arg()); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL #define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL #include "CenterPointMechanicalMapping.h" #include <sofa/core/componentmodel/topology/BaseMeshTopology.h> namespace sofa { namespace component { namespace mapping { template <class BaseMapping> CenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to) : Inherit(from, to) , inputTopo(NULL) , outputTopo(NULL) { } template <class BaseMapping> CenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping() { } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::init() { inputTopo = this->fromModel->getContext()->getMeshTopology(); outputTopo = this->toModel->getContext()->getMeshTopology(); this->Inherit::init(); } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); if(out.size() < hexas.size()) out.resize(hexas.size()); for(unsigned int i = 0; i < hexas.size(); ++i) { out[i] =(in[ hexas[i][0] ] + in[ hexas[i][1] ] + in[ hexas[i][2] ] + in[ hexas[i][3] ] + in[ hexas[i][4] ] + in[ hexas[i][5] ] + in[ hexas[i][6] ] + in[ hexas[i][7] ]) * 0.125f; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); if(out.size() < hexas.size()) out.resize(hexas.size()); for(unsigned int i = 0; i < hexas.size(); ++i) { out[i] =(in[ hexas[i][0] ] + in[ hexas[i][1] ] + in[ hexas[i][2] ] + in[ hexas[i][3] ] + in[ hexas[i][4] ] + in[ hexas[i][5] ] + in[ hexas[i][6] ] + in[ hexas[i][7] ]) * 0.125f; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); for(unsigned int i = 0; i <hexas.size(); ++i) { typename Out::Deriv val = in[i] * 0.125f; out[ hexas[i][0] ] += val; out[ hexas[i][1] ] += val; out[ hexas[i][2] ] += val; out[ hexas[i][3] ] += val; out[ hexas[i][4] ] += val; out[ hexas[i][5] ] += val; out[ hexas[i][6] ] += val; out[ hexas[i][7] ] += val; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& /*out*/, const typename Out::VecConst& /*in*/ ) { // TODO return; } } // namespace mapping } // namespace component } // namespace sofa #endif <commit_msg>r3533/sofa-dev : FIX: not well understood bug with certain topologies<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL #define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL #include "CenterPointMechanicalMapping.h" #include <sofa/core/componentmodel/topology/BaseMeshTopology.h> namespace sofa { namespace component { namespace mapping { template <class BaseMapping> CenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to) : Inherit(from, to) , inputTopo(NULL) , outputTopo(NULL) { } template <class BaseMapping> CenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping() { } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::init() { inputTopo = this->fromModel->getContext()->getMeshTopology(); outputTopo = this->toModel->getContext()->getMeshTopology(); this->Inherit::init(); } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); if(out.size() < hexas.size()) out.resize(hexas.size()); for(unsigned int i = 0; i < hexas.size(); ++i) { out[i] =(in[ hexas[i][0] ] + in[ hexas[i][1] ] + in[ hexas[i][2] ] + in[ hexas[i][3] ] + in[ hexas[i][4] ] + in[ hexas[i][5] ] + in[ hexas[i][6] ] + in[ hexas[i][7] ]) * 0.125f; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); if(out.size() < hexas.size()) out.resize(hexas.size()); for(unsigned int i = 0; i < hexas.size(); ++i) { out[i] =(in[ hexas[i][0] ] + in[ hexas[i][1] ] + in[ hexas[i][2] ] + in[ hexas[i][3] ] + in[ hexas[i][4] ] + in[ hexas[i][5] ] + in[ hexas[i][6] ] + in[ hexas[i][7] ]) * 0.125f; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in ) { const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas(); for(unsigned int i = 0; i <hexas.size(); ++i) { if( in.size() <= i ) continue; typename Out::Deriv val = in[i] * 0.125f; out[ hexas[i][0] ] += val; out[ hexas[i][1] ] += val; out[ hexas[i][2] ] += val; out[ hexas[i][3] ] += val; out[ hexas[i][4] ] += val; out[ hexas[i][5] ] += val; out[ hexas[i][6] ] += val; out[ hexas[i][7] ] += val; } } template <class BaseMapping> void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& /*out*/, const typename Out::VecConst& /*in*/ ) { // TODO return; } } // namespace mapping } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/websockets/websocket_handshake_stream_create_helper.h" #include <string> #include <vector> #include "net/base/completion_callback.h" #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "net/http/http_request_info.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/socket/client_socket_handle.h" #include "net/socket/socket_test_util.h" #include "net/websockets/websocket_basic_handshake_stream.h" #include "net/websockets/websocket_stream.h" #include "net/websockets/websocket_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace net { namespace { // This class encapsulates the details of creating a mock ClientSocketHandle. class MockClientSocketHandleFactory { public: MockClientSocketHandleFactory() : pool_(1, 1, socket_factory_maker_.factory()) {} // The created socket expects |expect_written| to be written to the socket, // and will respond with |return_to_read|. The test will fail if the expected // text is not written, or if all the bytes are not read. scoped_ptr<ClientSocketHandle> CreateClientSocketHandle( const std::string& expect_written, const std::string& return_to_read) { socket_factory_maker_.SetExpectations(expect_written, return_to_read); scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle); socket_handle->Init( "a", scoped_refptr<MockTransportSocketParams>(), MEDIUM, CompletionCallback(), &pool_, BoundNetLog()); return socket_handle.Pass(); } private: WebSocketMockClientSocketFactoryMaker socket_factory_maker_; MockTransportClientSocketPool pool_; DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory); }; class TestConnectDelegate : public WebSocketStream::ConnectDelegate { public: ~TestConnectDelegate() override {} void OnSuccess(scoped_ptr<WebSocketStream> stream) override {} void OnFailure(const std::string& failure_message) override {} void OnStartOpeningHandshake( scoped_ptr<WebSocketHandshakeRequestInfo> request) override {} void OnFinishOpeningHandshake( scoped_ptr<WebSocketHandshakeResponseInfo> response) override {} void OnSSLCertificateError( scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks> ssl_error_callbacks, const SSLInfo& ssl_info, bool fatal) override {} }; class WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test { protected: scoped_ptr<WebSocketStream> CreateAndInitializeStream( const std::string& socket_url, const std::string& socket_host, const std::string& socket_path, const std::vector<std::string>& sub_protocols, const std::string& origin, const std::string& extra_request_headers, const std::string& extra_response_headers) { WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_, sub_protocols); create_helper.set_failure_message(&failure_message_); scoped_ptr<ClientSocketHandle> socket_handle = socket_handle_factory_.CreateClientSocketHandle( WebSocketStandardRequest(socket_path, socket_host, url::Origin(GURL(origin)), extra_request_headers), WebSocketStandardResponse(extra_response_headers)); scoped_ptr<WebSocketHandshakeStreamBase> handshake( create_helper.CreateBasicStream(socket_handle.Pass(), false)); // If in future the implementation type returned by CreateBasicStream() // changes, this static_cast will be wrong. However, in that case the test // will fail and AddressSanitizer should identify the issue. static_cast<WebSocketBasicHandshakeStream*>(handshake.get()) ->SetWebSocketKeyForTesting("dGhlIHNhbXBsZSBub25jZQ=="); HttpRequestInfo request_info; request_info.url = GURL(socket_url); request_info.method = "GET"; request_info.load_flags = LOAD_DISABLE_CACHE; int rv = handshake->InitializeStream( &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback()); EXPECT_EQ(OK, rv); HttpRequestHeaders headers; headers.SetHeader("Host", "localhost"); headers.SetHeader("Connection", "Upgrade"); headers.SetHeader("Pragma", "no-cache"); headers.SetHeader("Cache-Control", "no-cache"); headers.SetHeader("Upgrade", "websocket"); headers.SetHeader("Origin", origin); headers.SetHeader("Sec-WebSocket-Version", "13"); headers.SetHeader("User-Agent", ""); headers.SetHeader("Accept-Encoding", "gzip, deflate"); headers.SetHeader("Accept-Language", "en-us,fr"); HttpResponseInfo response; TestCompletionCallback dummy; rv = handshake->SendRequest(headers, &response, dummy.callback()); EXPECT_EQ(OK, rv); rv = handshake->ReadResponseHeaders(dummy.callback()); EXPECT_EQ(OK, rv); EXPECT_EQ(101, response.headers->response_code()); EXPECT_TRUE(response.headers->HasHeaderValue("Connection", "Upgrade")); EXPECT_TRUE(response.headers->HasHeaderValue("Upgrade", "websocket")); return handshake->Upgrade(); } MockClientSocketHandleFactory socket_handle_factory_; TestConnectDelegate connect_delegate_; std::string failure_message_; }; // Confirm that the basic case works as expected. TEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( "ws://localhost/", "localhost", "/", std::vector<std::string>(), "http://localhost", "", ""); EXPECT_EQ("", stream->GetExtensions()); EXPECT_EQ("", stream->GetSubProtocol()); } // Verify that the sub-protocols are passed through. TEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) { std::vector<std::string> sub_protocols; sub_protocols.push_back("chat"); sub_protocols.push_back("superchat"); scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( "ws://localhost/", "localhost", "/", sub_protocols, "http://localhost", "Sec-WebSocket-Protocol: chat, superchat\r\n", "Sec-WebSocket-Protocol: superchat\r\n"); EXPECT_EQ("superchat", stream->GetSubProtocol()); } // Verify that extension name is available. Bad extension names are tested in // websocket_stream_test.cc. TEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( "ws://localhost/", "localhost", "/", std::vector<std::string>(), "http://localhost", "", "Sec-WebSocket-Extensions: permessage-deflate\r\n"); EXPECT_EQ("permessage-deflate", stream->GetExtensions()); } // Verify that extension parameters are available. Bad parameters are tested in // websocket_stream_test.cc. TEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( "ws://localhost/", "localhost", "/", std::vector<std::string>(), "http://localhost", "", "Sec-WebSocket-Extensions: permessage-deflate;" " client_max_window_bits=14; server_max_window_bits=14;" " server_no_context_takeover; client_no_context_takeover\r\n"); EXPECT_EQ( "permessage-deflate;" " client_max_window_bits=14; server_max_window_bits=14;" " server_no_context_takeover; client_no_context_takeover", stream->GetExtensions()); } } // namespace } // namespace net <commit_msg>Remove unused params in WebSocketHandshakeStreamCreateHelperTest<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/websockets/websocket_handshake_stream_create_helper.h" #include <string> #include <vector> #include "net/base/completion_callback.h" #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "net/http/http_request_info.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/socket/client_socket_handle.h" #include "net/socket/socket_test_util.h" #include "net/websockets/websocket_basic_handshake_stream.h" #include "net/websockets/websocket_stream.h" #include "net/websockets/websocket_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace net { namespace { // This class encapsulates the details of creating a mock ClientSocketHandle. class MockClientSocketHandleFactory { public: MockClientSocketHandleFactory() : pool_(1, 1, socket_factory_maker_.factory()) {} // The created socket expects |expect_written| to be written to the socket, // and will respond with |return_to_read|. The test will fail if the expected // text is not written, or if all the bytes are not read. scoped_ptr<ClientSocketHandle> CreateClientSocketHandle( const std::string& expect_written, const std::string& return_to_read) { socket_factory_maker_.SetExpectations(expect_written, return_to_read); scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle); socket_handle->Init( "a", scoped_refptr<MockTransportSocketParams>(), MEDIUM, CompletionCallback(), &pool_, BoundNetLog()); return socket_handle.Pass(); } private: WebSocketMockClientSocketFactoryMaker socket_factory_maker_; MockTransportClientSocketPool pool_; DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory); }; class TestConnectDelegate : public WebSocketStream::ConnectDelegate { public: ~TestConnectDelegate() override {} void OnSuccess(scoped_ptr<WebSocketStream> stream) override {} void OnFailure(const std::string& failure_message) override {} void OnStartOpeningHandshake( scoped_ptr<WebSocketHandshakeRequestInfo> request) override {} void OnFinishOpeningHandshake( scoped_ptr<WebSocketHandshakeResponseInfo> response) override {} void OnSSLCertificateError( scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks> ssl_error_callbacks, const SSLInfo& ssl_info, bool fatal) override {} }; class WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test { protected: scoped_ptr<WebSocketStream> CreateAndInitializeStream( const std::vector<std::string>& sub_protocols, const std::string& extra_request_headers, const std::string& extra_response_headers) { static const char kOrigin[] = "http://localhost"; WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_, sub_protocols); create_helper.set_failure_message(&failure_message_); scoped_ptr<ClientSocketHandle> socket_handle = socket_handle_factory_.CreateClientSocketHandle( WebSocketStandardRequest("/", "localhost", url::Origin(GURL(kOrigin)), extra_request_headers), WebSocketStandardResponse(extra_response_headers)); scoped_ptr<WebSocketHandshakeStreamBase> handshake( create_helper.CreateBasicStream(socket_handle.Pass(), false)); // If in future the implementation type returned by CreateBasicStream() // changes, this static_cast will be wrong. However, in that case the test // will fail and AddressSanitizer should identify the issue. static_cast<WebSocketBasicHandshakeStream*>(handshake.get()) ->SetWebSocketKeyForTesting("dGhlIHNhbXBsZSBub25jZQ=="); HttpRequestInfo request_info; request_info.url = GURL("ws://localhost/"); request_info.method = "GET"; request_info.load_flags = LOAD_DISABLE_CACHE; int rv = handshake->InitializeStream( &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback()); EXPECT_EQ(OK, rv); HttpRequestHeaders headers; headers.SetHeader("Host", "localhost"); headers.SetHeader("Connection", "Upgrade"); headers.SetHeader("Pragma", "no-cache"); headers.SetHeader("Cache-Control", "no-cache"); headers.SetHeader("Upgrade", "websocket"); headers.SetHeader("Origin", kOrigin); headers.SetHeader("Sec-WebSocket-Version", "13"); headers.SetHeader("User-Agent", ""); headers.SetHeader("Accept-Encoding", "gzip, deflate"); headers.SetHeader("Accept-Language", "en-us,fr"); HttpResponseInfo response; TestCompletionCallback dummy; rv = handshake->SendRequest(headers, &response, dummy.callback()); EXPECT_EQ(OK, rv); rv = handshake->ReadResponseHeaders(dummy.callback()); EXPECT_EQ(OK, rv); EXPECT_EQ(101, response.headers->response_code()); EXPECT_TRUE(response.headers->HasHeaderValue("Connection", "Upgrade")); EXPECT_TRUE(response.headers->HasHeaderValue("Upgrade", "websocket")); return handshake->Upgrade(); } MockClientSocketHandleFactory socket_handle_factory_; TestConnectDelegate connect_delegate_; std::string failure_message_; }; // Confirm that the basic case works as expected. TEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(std::vector<std::string>(), "", ""); EXPECT_EQ("", stream->GetExtensions()); EXPECT_EQ("", stream->GetSubProtocol()); } // Verify that the sub-protocols are passed through. TEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) { std::vector<std::string> sub_protocols; sub_protocols.push_back("chat"); sub_protocols.push_back("superchat"); scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( sub_protocols, "Sec-WebSocket-Protocol: chat, superchat\r\n", "Sec-WebSocket-Protocol: superchat\r\n"); EXPECT_EQ("superchat", stream->GetSubProtocol()); } // Verify that extension name is available. Bad extension names are tested in // websocket_stream_test.cc. TEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( std::vector<std::string>(), "", "Sec-WebSocket-Extensions: permessage-deflate\r\n"); EXPECT_EQ("permessage-deflate", stream->GetExtensions()); } // Verify that extension parameters are available. Bad parameters are tested in // websocket_stream_test.cc. TEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) { scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream( std::vector<std::string>(), "", "Sec-WebSocket-Extensions: permessage-deflate;" " client_max_window_bits=14; server_max_window_bits=14;" " server_no_context_takeover; client_no_context_takeover\r\n"); EXPECT_EQ( "permessage-deflate;" " client_max_window_bits=14; server_max_window_bits=14;" " server_no_context_takeover; client_no_context_takeover", stream->GetExtensions()); } } // namespace } // namespace net <|endoftext|>
<commit_before>// // Copyright 2014 Team WALL-E // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // /*******************************************************************************************************************//** * @file realsense_request.cpp * @brief C++ example for receiving realsense image frames via a zmq request / response scheme. * @author Team WALL-E & Christopher D. McMurrough ***********************************************************************************************************************/ #include <string> #include <iostream> #include <zmq.hpp> #include <pcl/visualization/cloud_viewer.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/common/common.h> #include <pcl/common/time.h> #include <ncurses.h> // configuration parameters #define NUM_COMNMAND_LINE_ARGUMENTS 1 #define DISPLAY_WINDOW_NAME "Received Image" /*******************************************************************************************************************//** * @brief program entry point * @param[in] argc number of command line arguments * @param[in] argv string array of command line arguments * @return return code (0 for normal termination) * @author Christoper D. McMurrough ***********************************************************************************************************************/ int main(int argc, char **argv) { // character capturing intialization initscr(); int ch; nodelay(stdscr, TRUE); noecho(); // store display parameters bool showFrames = false; // create the cloud viewer object pcl::visualization::CloudViewer m_viewer (DISPLAY_WINDOW_NAME); // validate and parse the command line arguments if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1) { printw("USAGE: %s <display_mode> \n", argv[0]); printw("WARNING: Proceeding with default execution parameters... \n"); showFrames = true; } else { showFrames = atoi(argv[1]) > 0; } // initialize the zmq context and socket zmq::context_t context(1); zmq::socket_t subscriber(context, ZMQ_SUB); // connect to the image server printw("Connecting to server...\n"); subscriber.connect ("tcp://129.107.132.27:5555"); printw("Press S to stream images and C to capture one image...\n"); // create a request object //zmq::message_t request(5); //memcpy(request.data(), "Hello", 5); // get new frames until the user presses the 'q' key bool running = true; bool stream = false; bool capture = false; while(running) { if ((ch = getch()) == int('s')) { // if presses "stream" button if (stream) { // if we were already streaming subscriber.setsockopt(ZMQ_UNSUBSCRIBE, "", 0); // UNSUBSCRIBE printw("S pressed: Stopping stream.\n"); } else { // else subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); //SUBSCRIBE printw("S pressed: Starting stream.\n"); } stream = !(stream); // toggle stream } else if (ch == int('c')) { // else if presses "capture" button subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); capture = true; printw("C pressed: Capturing image.\n"); } if (stream || capture) { //check for subscription // get the reply zmq::message_t reply; subscriber.recv(&reply); //std::vector<uchar> buffer; std::cout << "Received reply: " << reply.size() << " bytes" << std::endl; // store the reply data into an image structure pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); cloud->height = 480; cloud->width = 640; cloud->is_dense = false; cloud->points.resize(640*480); std::memcpy(cloud->points.data(), reply.data(), reply.size()); //std::cout << cloud->points[0] << std::endl; //cv::Mat image(480, 640, CV_8UC3, reply.data()); //cloud->points = reply.data(); // display the result if(showFrames) { m_viewer.showCloud(cloud); } if (capture) { // we've received one image and can stop subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); capture = false; } } // check for program termination if(m_viewer.wasStopped ()) { running = false; } } // close the subscriber subscriber.close(); return 0; } <commit_msg>Added simple UI to client using ncurses<commit_after>// // Copyright 2014 Team WALL-E // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // /*******************************************************************************************************************//** * @file realsense_request.cpp * @brief C++ example for receiving realsense image frames via a zmq request / response scheme. * @author Team WALL-E & Christopher D. McMurrough ***********************************************************************************************************************/ #include <string> #include <iostream> #include <zmq.hpp> #include <pcl/visualization/cloud_viewer.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/common/common.h> #include <pcl/common/time.h> #include <ncurses.h> // configuration parameters #define NUM_COMNMAND_LINE_ARGUMENTS 1 #define DISPLAY_WINDOW_NAME "Received Image" /*******************************************************************************************************************//** * @brief program entry point * @param[in] argc number of command line arguments * @param[in] argv string array of command line arguments * @return return code (0 for normal termination) * @author Christoper D. McMurrough ***********************************************************************************************************************/ int main(int argc, char **argv) { // character capturing intialization initscr(); int ch; nodelay(stdscr, TRUE); noecho(); // store display parameters bool showFrames = false; // create the cloud viewer object pcl::visualization::CloudViewer m_viewer (DISPLAY_WINDOW_NAME); // validate and parse the command line arguments if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1) { printw("USAGE: %s <display_mode> \n", argv[0]); printw("WARNING: Proceeding with default execution parameters... \n"); showFrames = true; } else { showFrames = atoi(argv[1]) > 0; } // initialize the zmq context and socket zmq::context_t context(1); zmq::socket_t subscriber(context, ZMQ_SUB); // connect to the image server printw("Connecting to server...\n"); subscriber.connect ("tcp://129.107.132.27:5555"); printw("Press S to stream images and C to capture one image...\n"); // create a request object //zmq::message_t request(5); //memcpy(request.data(), "Hello", 5); // get new frames until the user presses the 'q' key bool running = true; bool stream = false; bool capture = false; while(running) { if ((ch = getch()) == int('s')) { // if presses "stream" button if (stream) { // if we were already streaming subscriber.setsockopt(ZMQ_UNSUBSCRIBE, "", 0); // UNSUBSCRIBE printw("S pressed: Stopping stream.\n"); } else { // else subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); //SUBSCRIBE printw("S pressed: Starting stream.\n"); } stream = !(stream); // toggle stream } else if (ch == int('c')) { // else if presses "capture" button subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); capture = true; printw("C pressed: Capturing image.\n"); } if (stream || capture) { //check for subscription // get the reply zmq::message_t reply; subscriber.recv(&reply); //std::vector<uchar> buffer; std::cout << "Received reply: " << reply.size() << " bytes" << std::endl; // store the reply data into an image structure pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); cloud->height = 480; cloud->width = 640; cloud->is_dense = false; cloud->points.resize(640*480); std::memcpy(cloud->points.data(), reply.data(), reply.size()); //std::cout << cloud->points[0] << std::endl; //cv::Mat image(480, 640, CV_8UC3, reply.data()); //cloud->points = reply.data(); // display the result if(showFrames) { m_viewer.showCloud(cloud); } if (capture) { // we've received one image and can stop subscriber.setsockopt(ZMQ_UNSUBSCRIBE, "", 0); capture = false; } } // check for program termination if(m_viewer.wasStopped ()) { running = false; } } // close the subscriber subscriber.close(); return 0; } <|endoftext|>
<commit_before>#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; BIGNUM *a; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_KEY_set_public_key(auth_key, EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx)); a = BN_new(); BN_hex2bn(&a, private_key); EC_KEY_set_private_key(auth_key, a); BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); return 0; } ////////////////////////////////////////////////////////////////////////////////////// char* get_request(int fd) { char* message; size_t size = TOKENSIZE; int offset; message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); //?? if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = 0; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != 0); printf("get_request: message at %p: %s\n", message, message); return message; } ////////////////////////////////////////////////////////////////////////////////////// /*int process_mode(int fd, int choice, const char* port_mode1, const char* port_mode2) { int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); char * sub_request; unsigned char response; struct sockaddr_in retAddress; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); sub_request = get_request(fd); } char* message; size_t size = TOKENSIZE; unsigned int offset; // step 1: read request from client, common for both mode1 and mode2 message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("process_mode: Failure to realloc\n"); exit(1); } offset = 0; do { if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); if(!message) { printf("process_mode: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("process_mode: EOF encountered\n"); char c = message[offset]; message[offset] = '\0'; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } offset++; } while (message[offset-1] != '\0'); printf("DEBUG: process_mode: message at %p: %s\n", message, message); // step 2: create token 'd', common for both mode1 and mode2 vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv, dev; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, strlen(pub_key), d.GetAllocator()); dev.SetString(res_add, strlen(res_add), d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); // Step 3: Mode choice dependent // (Mode 1, return token to client) if (choice == 1) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : " << buffer.GetString(); cout << "\n buffer len:" << buffer.GetSize(); if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); } // return 1; } // (Mode 2, return token to resource, token ID to client) else if(choice == 2 ){ cout << "Mode 2\n"; int soc2; uint16_t port = strtol(port_mode2, NULL, 10); char null_string[17]; soc2 = socket(AF_INET, SOCK_STREAM, 0); if(soc2 < 0) { printf("failed to create socket: %s\n", strerror(errno)); } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) { printf("send token to resource: failed to connect to resource: %s\n", strerror(errno)); } // insert code for null string here int i; // add 17 NULLS before sending the json to resource -- one socket for (i = 0; i <=17; i++){ null_string[i] = (char) 0; } if(write(soc2, null_string, 17) < 0) { printf("Failed to write null string to resource socket\n"); } //send token to resource here StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : "<< buffer.GetString() ; cout << "\n buffer len:" << buffer.GetSize() << "\n"; if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to token to resource socket\n"); } //send token ID to client int tokenID = d["ii"].GetInt(); std::string s_ID = std::to_string(tokenID); char const *tokenID_str = s_ID.c_str(); cout << "string token ID: " << tokenID_str << "\n"; if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) { printf("Failed to write to socket\n"); } // return 1; }// end of mode 2 }*/ int bootstrap_network(const char* port_sub){ int soc; uint16_t port = strtol(port_sub, NULL, 10); // from arguments soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } int listen_block(int soc,int choice, const char* port_mode1, const char* port_mode2){ int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); struct sockaddr_in retAddress; char * sub_request; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); sub_request = get_request(fd); } string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; /////////////////////********************************************** Document d; Value ii, nb, na, suv, dev; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, strlen(pub_key), d.GetAllocator()); dev.SetString(res_add, strlen(res_add), d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); // Step 3: Mode choice dependent // (Mode 1, return token to client) if (choice == 1) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : " << buffer.GetString(); cout << "\n buffer len:" << buffer.GetSize(); if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); } // return 1; } // (Mode 2, return token to resource, token ID to client) else if(choice == 2 ){ cout << "Mode 2\n"; int soc2; uint16_t port = strtol(port_mode2, NULL, 10); char null_string[17]; soc2 = socket(AF_INET, SOCK_STREAM, 0); if(soc2 < 0) { printf("failed to create socket: %s\n", strerror(errno)); } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) { printf("send token to resource: failed to connect to resource: %s\n", strerror(errno)); } // insert code for null string here int i; // add 17 NULLS before sending the json to resource -- one socket for (i = 0; i <=17; i++){ null_string[i] = (char) 0; } if(write(soc2, null_string, 17) < 0) { printf("Failed to write null string to resource socket\n"); } //send token to resource here StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : "<< buffer.GetString() ; cout << "\n buffer len:" << buffer.GetSize() << "\n"; if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to token to resource socket\n"); } //send token ID to client int tokenID = d["ii"].GetInt(); std::string s_ID = std::to_string(tokenID); char const *tokenID_str = s_ID.c_str(); cout << "string token ID: " << tokenID_str << "\n"; if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) { printf("Failed to write to socket\n"); } // return 1; }// end of mode 2 /////////////////////********************************************** } int main(int argc, char *argv[]){ if(argc <= 3){ printf("insufficient arguments\n"); printf("sample argument: ./auth <mode> <port_client> <port_resource>\n"); return 1; } int fd1, soc1; soc1 = bootstrap_network(argv[2]); //fd1 = listen_block(soc1); const char* port_client = argv[2]; const char* port_resource = argv[3]; if(!strcmp(argv[1], "1")) listen_block(soc1,1,port_client,port_resource); else if(!strcmp(argv[1], "2")){ listen_block(soc1,2,port_client,port_resource); } else{ printf("Invalid mode: %s", argv[1]); exit(1); } return 1; } <commit_msg>auth.cpp updated<commit_after>#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; BIGNUM *a; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_KEY_set_public_key(auth_key, EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx)); a = BN_new(); BN_hex2bn(&a, private_key); EC_KEY_set_private_key(auth_key, a); BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); return 0; } ////////////////////////////////////////////////////////////////////////////////////// int get_request(int fd, int choice, const char* port_mode) { char* message; size_t size = TOKENSIZE; int offset; // step 1: read request from client, common for both mode1 and mode2 message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = 0; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != 0); printf("get_request: message at %p: %s\n", message, message); vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; // step 2: create token 'd', common for both mode1 and mode2 Document d; Value ii, nb, na, suv, dev; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, strlen(pub_key), d.GetAllocator()); dev.SetString(res_add, strlen(res_add), d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); // Step 3: Mode choice dependent // (Mode 1, return token to client) if (choice == 1) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : " << buffer.GetString(); cout << "\n buffer len:" << buffer.GetSize(); if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); } return 1; } // (Mode 2, return token to resource, token ID to client) else if(choice == 2 ){ cout << "Mode 2\n"; int soc2; uint16_t port = strtol(port_mode, NULL, 10); char null_string[17]; soc2 = socket(AF_INET, SOCK_STREAM, 0); if(soc2 < 0) { printf("failed to create socket: %s\n", strerror(errno)); } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) { printf("send token to resource: failed to connect to resource: %s\n", strerror(errno)); } // insert code for null string here int i; // add 17 NULLS before sending the json to resource -- one socket for (i = 0; i <=17; i++){ null_string[i] = (char) 0; } if(write(soc2, null_string, 17) < 0) { printf("Failed to write null string to resource socket\n"); } //send token to resource here StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : "<< buffer.GetString() ; cout << "\n buffer len:" << buffer.GetSize() << "\n"; if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to token to resource socket\n"); } //send token ID to client int tokenID = d["ii"].GetInt(); std::string s_ID = std::to_string(tokenID); char const *tokenID_str = s_ID.c_str(); cout << "string token ID: " << tokenID_str << "\n"; if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) { printf("Failed to write to socket\n"); } return 1; }// end of mode 2 } int bootstrap_network(const char* port_sub){ int soc; uint16_t port = strtol(port_sub, NULL, 10); // from arguments soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } int listen_block(int soc,int choice, const char* port_mode){ int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); struct sockaddr_in retAddress; int req1; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); printf("fd value: %d\n",fd); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); req1 = get_request(fd,choice,port_mode); close(fd); } } int main(int argc, char *argv[]){ if(argc <= 3){ printf("insufficient arguments\n"); printf("sample argument: ./auth <mode> <port_client> <port_resource>\n {Enter dummy value for port_resource in Mode 1}"); return 1; } int fd1, soc1; soc1 = bootstrap_network(argv[2]); const char* port_client = argv[2]; const char* port_resource = argv[3]; if(!strcmp(argv[1], "1")) listen_block(soc1,1,port_resource); else if(!strcmp(argv[1], "2")) listen_block(soc1,2,port_resource); else{ printf("Invalid mode: %s", argv[1]); exit(1); } return 1; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConfigure.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #ifdef OTB_USE_OPENCV #include "otbNeuralNetworkMachineLearningModel.h" #include "otbSVMMachineLearningModel.h" #include "otbBoostMachineLearningModel.h" #include "otbDecisionTreeMachineLearningModel.h" #include "otbGradientBoostedTreeMachineLearningModel.h" #include "otbKNearestNeighborsMachineLearningModel.h" #include "otbRandomForestsMachineLearningModel.h" #endif #ifdef OTB_USE_LIBSVM #include "otbLibSVMMachineLearningModel.h" #endif typedef float PrecisionType; typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType; typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType; typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType; typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType; typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType; typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType; typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType; typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; const double epsilon = 0.1; typedef struct RegressionTestParamStruct { double vMin; double vMax; size_t count; double eps; } RegressionTestParam; template <typename TPrecision> struct LinearFunctionSampleGenerator { typedef TPrecision PrecisionType; LinearFunctionSampleGenerator(TPrecision a, TPrecision b) : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->Clear(); m_tsl->Clear(); m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); InputSampleRegressionType inputSample; inputSample.SetSize(m_NbInputVars); TargetSampleRegressionType outputSample; TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); TPrecision inputValue = sMin+ x*sampleStep; inputSample[0] = inputValue; outputSample[0] = m_a*inputValue+m_b; m_isl->PushBack(inputSample); m_tsl->PushBack(outputSample); } } TPrecision m_a; TPrecision m_b; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename SampleGeneratorType, typename RegressionType> int testRegression(SampleGeneratorType& sg, RegressionType& rgrsn, RegressionTestParam param) { std::cout << "Generating training samples" << std::endl; sg.GenerateSamples(param.vMin, param.vMax, param.count); rgrsn->SetInputListSample(sg.m_isl); rgrsn->SetTargetListSample(sg.m_tsl); std::cout << "Training" << std::endl; rgrsn->Train(); std::cout << "Generate validation samples"<<std::endl; sg.GenerateSamples(param.vMin, param.vMax, param.count); std::cout << "Validation" << std::endl; //Check the prediction accuracy typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin(); typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin(); typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End(); typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End(); typename SampleGeneratorType::PrecisionType rmse = 0.0; while(sampleIt != sampleLast && resultIt != resultLast) { //typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0]; typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0]; typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0]; rmse += pow(prediction - expected, 2.0); ++sampleIt; ++resultIt; } rmse = sqrt( rmse / static_cast<double>(param.count) ); std::cout << "RMSE = "<< rmse << std::endl; if(rmse > param.eps) return EXIT_FAILURE; return EXIT_SUCCESS; } #ifdef OTB_USE_LIBSVM int otbLibSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::LibSVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> libsvmType; libsvmType::Pointer regression = libsvmType::New(); regression->SetRegressionMode(true); regression->SetSVMType(EPSILON_SVR); regression->SetKernelType(RBF); regression->SetEpsilon(1e-5); regression->SetParameterOptimization(true); return testRegression(lfsg,regression,param); } #endif #ifdef OTB_USE_OPENCV int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 20000; param.eps = 0.1; typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> NeuralNetworkType; NeuralNetworkType::Pointer regression = NeuralNetworkType::New(); regression->SetRegressionMode(1); regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP); std::vector<unsigned int> layerSizes; layerSizes.push_back(1); layerSizes.push_back(5); layerSizes.push_back(1); regression->SetLayerSizes(layerSizes); regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM); regression->SetAlpha(1.0); regression->SetBeta(1.0); regression->SetBackPropDWScale(0.1); regression->SetBackPropMomentScale(0.1); regression->SetRegPropDW0(0.1); regression->SetRegPropDWMin(1e-7); regression->SetTermCriteriaType(CV_TERMCRIT_EPS); regression->SetEpsilon(1e-5); regression->SetMaxIter(1e4); return testRegression(lfsg,regression,param); } int otbSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::SVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> SVMType; SVMType::Pointer regression = SVMType::New(); regression->SetRegressionMode(1); regression->SetNu(0.5); regression->SetKernelType(CvSVM::RBF); regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); regression->SetMaxIter(100000); regression->SetEpsilon(1e-5); regression->SetParameterOptimization(true); return testRegression(lfsg,regression,param); } int otbDecisionTreeRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::DecisionTreeMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> DTreeType; DTreeType::Pointer regression = DTreeType::New(); regression->SetRegressionMode(true); return testRegression(lfsg,regression,param); } int otbGradientBoostedTreeRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::GradientBoostedTreeMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> GBTreeType; GBTreeType::Pointer regression = GBTreeType::New(); regression->SetRegressionMode(true); regression->SetLossFunctionType(CvGBTrees::SQUARED_LOSS); return testRegression(lfsg,regression,param); } int otbKNearestNeighborsRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::KNearestNeighborsMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> KNNType; KNNType::Pointer regression = KNNType::New(); regression->SetRegressionMode(true); regression->SetK(1); return testRegression(lfsg,regression,param); } int otbRandomForestsRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::RandomForestsMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> RFType; RFType::Pointer regression = RFType::New(); regression->SetRegressionMode(true); return testRegression(lfsg,regression,param); } #endif <commit_msg>ENH: added sample generators for bilinear et polynomial cases<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConfigure.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #ifdef OTB_USE_OPENCV #include "otbNeuralNetworkMachineLearningModel.h" #include "otbSVMMachineLearningModel.h" #include "otbBoostMachineLearningModel.h" #include "otbDecisionTreeMachineLearningModel.h" #include "otbGradientBoostedTreeMachineLearningModel.h" #include "otbKNearestNeighborsMachineLearningModel.h" #include "otbRandomForestsMachineLearningModel.h" #endif #ifdef OTB_USE_LIBSVM #include "otbLibSVMMachineLearningModel.h" #endif typedef float PrecisionType; typedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType; typedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType; typedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType; typedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType; typedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType; typedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType; typedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType; typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; const double epsilon = 0.1; typedef struct RegressionTestParamStruct { double vMin; double vMax; size_t count; double eps; } RegressionTestParam; template <typename TPrecision> struct LinearFunctionSampleGenerator { typedef TPrecision PrecisionType; LinearFunctionSampleGenerator(TPrecision a, TPrecision b) : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->Clear(); m_tsl->Clear(); m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); InputSampleRegressionType inputSample; inputSample.SetSize(m_NbInputVars); TargetSampleRegressionType outputSample; TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); TPrecision inputValue = sMin+ x*sampleStep; inputSample[0] = inputValue; outputSample[0] = m_a*inputValue+m_b; m_isl->PushBack(inputSample); m_tsl->PushBack(outputSample); } } TPrecision m_a; TPrecision m_b; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename TPrecision> struct BilinearFunctionSampleGenerator { typedef TPrecision PrecisionType; BilinearFunctionSampleGenerator(TPrecision a, TPrecision b, TPrecision c) : m_a(a), m_b(b), m_c(c), m_NbInputVars(2), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->Clear(); m_tsl->Clear(); m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); InputSampleRegressionType inputSample; inputSample.SetSize(m_NbInputVars); TargetSampleRegressionType outputSample; TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); TPrecision inputValue1 = sMin+ x*sampleStep; x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); TPrecision inputValue2 = sMin+ x*sampleStep; inputSample[0] = inputValue1; inputSample[1] = inputValue2; outputSample[0] = m_a*inputValue1+m_b*inputValue2+m_c; m_isl->PushBack(inputSample); m_tsl->PushBack(outputSample); } } TPrecision m_a; TPrecision m_b; TPrecision m_c; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename TPrecision> struct PolynomialFunctionSampleGenerator { typedef TPrecision PrecisionType; PolynomialFunctionSampleGenerator(std::vector<TPrecision> c) : m_c(c), m_NbInputVars(1), m_NbOutputVars(1) { m_isl = InputListSampleRegressionType::New(); m_tsl = TargetListSampleRegressionType::New(); }; void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples) { m_isl->Clear(); m_tsl->Clear(); m_isl->SetMeasurementVectorSize(m_NbInputVars); m_tsl->SetMeasurementVectorSize(m_NbOutputVars); RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance(); InputSampleRegressionType inputSample; inputSample.SetSize(m_NbInputVars); TargetSampleRegressionType outputSample; TPrecision sampleStep = (sMax-sMin)/nbSamples; for(size_t i=0; i<nbSamples; ++i) { TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples); TPrecision inputValue = sMin+ x*sampleStep; inputSample[0] = inputValue; TPrecision y = 0.0; for (unsigned int j=0; j<m_c.size() ; ++j) { y += m_c[j] * pow(static_cast<double>(inputValue), static_cast<double>(j)); } outputSample[0] = y; m_isl->PushBack(inputSample); m_tsl->PushBack(outputSample); } } std::vector<TPrecision> m_c; const size_t m_NbInputVars; const size_t m_NbOutputVars; InputListSampleRegressionType::Pointer m_isl; TargetListSampleRegressionType::Pointer m_tsl; }; template <typename SampleGeneratorType, typename RegressionType> int testRegression(SampleGeneratorType& sg, RegressionType& rgrsn, RegressionTestParam param) { std::cout << "Generating training samples" << std::endl; sg.GenerateSamples(param.vMin, param.vMax, param.count); rgrsn->SetInputListSample(sg.m_isl); rgrsn->SetTargetListSample(sg.m_tsl); std::cout << "Training" << std::endl; rgrsn->Train(); std::cout << "Generate validation samples"<<std::endl; sg.GenerateSamples(param.vMin, param.vMax, param.count); std::cout << "Validation" << std::endl; //Check the prediction accuracy typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin(); typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin(); typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End(); typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End(); typename SampleGeneratorType::PrecisionType rmse = 0.0; while(sampleIt != sampleLast && resultIt != resultLast) { //typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0]; typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0]; typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0]; rmse += pow(prediction - expected, 2.0); ++sampleIt; ++resultIt; } rmse = sqrt( rmse / static_cast<double>(param.count) ); std::cout << "RMSE = "<< rmse << std::endl; if(rmse > param.eps) return EXIT_FAILURE; return EXIT_SUCCESS; } #ifdef OTB_USE_LIBSVM int otbLibSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::LibSVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> libsvmType; libsvmType::Pointer regression = libsvmType::New(); regression->SetRegressionMode(true); regression->SetSVMType(EPSILON_SVR); regression->SetKernelType(RBF); regression->SetEpsilon(1e-5); regression->SetParameterOptimization(true); return testRegression(lfsg,regression,param); } #endif #ifdef OTB_USE_OPENCV int otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 20000; param.eps = 0.1; typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> NeuralNetworkType; NeuralNetworkType::Pointer regression = NeuralNetworkType::New(); regression->SetRegressionMode(1); regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP); std::vector<unsigned int> layerSizes; layerSizes.push_back(1); layerSizes.push_back(5); layerSizes.push_back(1); regression->SetLayerSizes(layerSizes); regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM); regression->SetAlpha(1.0); regression->SetBeta(1.0); regression->SetBackPropDWScale(0.1); regression->SetBackPropMomentScale(0.1); regression->SetRegPropDW0(0.1); regression->SetRegPropDWMin(1e-7); regression->SetTermCriteriaType(CV_TERMCRIT_EPS); regression->SetEpsilon(1e-5); regression->SetMaxIter(1e4); return testRegression(lfsg,regression,param); } int otbSVMRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::SVMMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> SVMType; SVMType::Pointer regression = SVMType::New(); regression->SetRegressionMode(1); regression->SetNu(0.5); regression->SetKernelType(CvSVM::RBF); regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); regression->SetMaxIter(100000); regression->SetEpsilon(1e-5); regression->SetParameterOptimization(true); return testRegression(lfsg,regression,param); } int otbDecisionTreeRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::DecisionTreeMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> DTreeType; DTreeType::Pointer regression = DTreeType::New(); regression->SetRegressionMode(true); return testRegression(lfsg,regression,param); } int otbGradientBoostedTreeRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::GradientBoostedTreeMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> GBTreeType; GBTreeType::Pointer regression = GBTreeType::New(); regression->SetRegressionMode(true); regression->SetLossFunctionType(CvGBTrees::SQUARED_LOSS); return testRegression(lfsg,regression,param); } int otbKNearestNeighborsRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::KNearestNeighborsMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> KNNType; KNNType::Pointer regression = KNNType::New(); regression->SetRegressionMode(true); regression->SetK(1); return testRegression(lfsg,regression,param); } int otbRandomForestsRegressionLinearMonovariate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0); RegressionTestParam param; param.vMin = -0.5; param.vMax = 0.5; param.count = 200; param.eps = 0.1; typedef otb::RandomForestsMachineLearningModel<InputValueRegressionType, TargetValueRegressionType> RFType; RFType::Pointer regression = RFType::New(); regression->SetRegressionMode(true); return testRegression(lfsg,regression,param); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/FontPlatformData.h" #include "RuntimeEnabledFeatures.h" #include "SkPaint.h" #include "SkTypeface.h" #include "SkTypeface_win.h" #include "core/platform/graphics/FontCache.h" #include "core/platform/graphics/GraphicsContext.h" #include "core/platform/graphics/skia/SkiaFontWin.h" #include "platform/LayoutTestSupport.h" #include "platform/SharedBuffer.h" #include "platform/win/HWndDC.h" #include "public/platform/Platform.h" #include "public/platform/win/WebSandboxSupport.h" #include "wtf/PassOwnPtr.h" #include "wtf/StdLibExtras.h" #include <mlang.h> #include <objidl.h> #include <windows.h> namespace WebCore { void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const { const float ts = m_textSize >= 0 ? m_textSize : 12; paint->setTextSize(SkFloatToScalar(m_textSize)); paint->setTypeface(typeface()); paint->setFakeBoldText(m_fakeBold); paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 / 4 : 0); if (RuntimeEnabledFeatures::subpixelFontScalingEnabled()) paint->setSubpixelText(true); // Only set painting flags when we're actually painting. if (context) { int textFlags = paintTextFlags(); if (!context->couldUseLCDRenderedText()) { textFlags &= ~SkPaint::kLCDRenderText_Flag; // If we *just* clear our request for LCD, then GDI seems to // sometimes give us AA text, and sometimes give us BW text. Since the // original intent was LCD, we want to force AA (rather than BW), so we // add a special bit to tell Skia to do its best to avoid the BW: by // drawing LCD offscreen and downsampling that to AA. textFlags |= SkPaint::kGenA8FromLCD_Flag; } static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag | SkPaint::kGenA8FromLCD_Flag; SkASSERT(!(textFlags & ~textFlagsMask)); uint32_t flags = paint->getFlags(); flags &= ~textFlagsMask; flags |= textFlags; paint->setFlags(flags); } } // Lookup the current system settings for font smoothing. // We cache these values for performance, but if the browser has a way to be // notified when these change, we could re-query them at that time. static uint32_t getDefaultGDITextFlags() { static bool gInited; static uint32_t gFlags; if (!gInited) { BOOL enabled; gFlags = 0; if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) { gFlags |= SkPaint::kAntiAlias_Flag; UINT smoothType; if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) { if (FE_FONTSMOOTHINGCLEARTYPE == smoothType) gFlags |= SkPaint::kLCDRenderText_Flag; } } gInited = true; } return gFlags; } static bool isWebFont(const LOGFONT& lf) { // web-fonts have artifical names constructed to always be // 1. 24 characters, followed by a '\0' // 2. the last two characters are '==' return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\0' == lf.lfFaceName[24]; } static int computePaintTextFlags(const LOGFONT& lf) { int textFlags = 0; switch (lf.lfQuality) { case NONANTIALIASED_QUALITY: textFlags = 0; break; case ANTIALIASED_QUALITY: textFlags = SkPaint::kAntiAlias_Flag; break; case CLEARTYPE_QUALITY: textFlags = (SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag); break; default: textFlags = getDefaultGDITextFlags(); break; } // only allow features that SystemParametersInfo allows textFlags &= getDefaultGDITextFlags(); /* * FontPlatformData(...) will read our logfont, and try to honor the the lfQuality * setting (computing the corresponding SkPaint flags for AA and LCD). However, it * will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean * we end up drawing the text in BW, even though our lfQuality requested antialiasing. * * Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW. * In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA, * even when the System (getDefaultGDITextFlags) tells us to draw only in BW. */ if (isWebFont(lf) && !isRunningLayoutTest()) textFlags |= SkPaint::kAntiAlias_Flag; return textFlags; } PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags) { LOGFONT info; GetObject(hfont, sizeof(info), &info); if (size) { int height = info.lfHeight; if (height < 0) height = -height; *size = height; } if (paintTextFlags) *paintTextFlags = computePaintTextFlags(info); return adoptRef(SkCreateTypefaceFromLOGFONT(info)); } FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType) : m_font(0) , m_textSize(-1) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(SkTypeface::RefDefault()) , m_paintTextFlags(0) , m_isHashTableDeletedValue(true) { } FontPlatformData::FontPlatformData() : m_font(0) , m_textSize(0) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(SkTypeface::RefDefault()) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) { } #if ENABLE(GDI_FONTS_ON_WINDOWS) FontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation) : m_font(RefCountedHFONT::create(font)) , m_textSize(size) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(orientation) , m_scriptCache(0) , m_typeface(CreateTypefaceFromHFont(font, 0, &m_paintTextFlags)) , m_isHashTableDeletedValue(false) { } #endif // FIXME: this constructor is needed for SVG fonts but doesn't seem to do much FontPlatformData::FontPlatformData(float size, bool bold, bool oblique) : m_font(0) , m_textSize(size) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(SkTypeface::RefDefault()) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(const FontPlatformData& data) : m_font(data.m_font) , m_textSize(data.m_textSize) , m_fakeBold(data.m_fakeBold) , m_fakeItalic(data.m_fakeItalic) , m_orientation(data.m_orientation) , m_scriptCache(0) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize) : m_font(data.m_font) , m_textSize(textSize) , m_fakeBold(data.m_fakeBold) , m_fakeItalic(data.m_fakeItalic) , m_orientation(data.m_orientation) , m_scriptCache(0) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation) : m_font(0) , m_textSize(textSize) , m_fakeBold(fakeBold) , m_fakeItalic(fakeItalic) , m_orientation(orientation) , m_scriptCache(0) , m_typeface(tf) , m_isHashTableDeletedValue(false) { // FIXME: This can be removed together with m_font once the last few // uses of hfont() has been eliminated. LOGFONT logFont; SkLOGFONTFromTypeface(m_typeface.get(), &logFont); logFont.lfHeight = -textSize; HFONT hFont = CreateFontIndirect(&logFont); if (hFont) m_font = RefCountedHFONT::create(hFont); m_paintTextFlags = computePaintTextFlags(logFont); } FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data) { if (this != &data) { m_font = data.m_font; m_textSize = data.m_textSize; m_fakeBold = data.m_fakeBold; m_fakeItalic = data.m_fakeItalic; m_orientation = data.m_orientation; m_typeface = data.m_typeface; m_paintTextFlags = data.m_paintTextFlags; // The following fields will get re-computed if necessary. ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; m_scriptFontProperties.clear(); } return *this; } FontPlatformData::~FontPlatformData() { ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; } String FontPlatformData::fontFamilyName() const { HWndDC dc(0); HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont())); WCHAR name[LF_FACESIZE]; unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name); if (resultLength > 0) resultLength--; // ignore the null terminator SelectObject(dc, oldFont); return String(name, resultLength); } bool FontPlatformData::isFixedPitch() const { #if ENABLE(GDI_FONTS_ON_WINDOWS) // TEXTMETRICS have this. Set m_treatAsFixedPitch based off that. HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); // Yes, this looks backwards, but the fixed pitch bit is actually set if the font // is *not* fixed pitch. Unbelievable but true. TEXTMETRIC textMetric = { 0 }; if (!GetTextMetrics(dc, &textMetric)) { if (ensureFontLoaded(hfont())) { // Retry GetTextMetrics. // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. if (!GetTextMetrics(dc, &textMetric)) LOG_ERROR("Unable to get the text metrics after second attempt"); } } bool treatAsFixedPitch = !(textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH); SelectObject(dc, oldFont); return treatAsFixedPitch; #else return typeface() && typeface()->isFixedPitch(); #endif } FontPlatformData::RefCountedHFONT::~RefCountedHFONT() { DeleteObject(m_hfont); } SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const { if (!m_scriptFontProperties) { m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES); memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES)); m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES); HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get()); if (result == E_PENDING) { HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { if (FontPlatformData::ensureFontLoaded(hfont())) { // FIXME: Handle gracefully the error if this call also fails. hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { LOG_ERROR("Unable to get the font properties after second attempt"); } } } SelectObject(dc, oldFont); } } return m_scriptFontProperties.get(); } #ifndef NDEBUG String FontPlatformData::description() const { return String(); } #endif bool FontPlatformData::ensureFontLoaded(HFONT font) { WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport(); // if there is no sandbox, then we can assume the font // was able to be loaded successfully already return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true; } } <commit_msg>Fixing leaked references in FontPlatformData<commit_after>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/FontPlatformData.h" #include "RuntimeEnabledFeatures.h" #include "SkPaint.h" #include "SkTypeface.h" #include "SkTypeface_win.h" #include "core/platform/graphics/FontCache.h" #include "core/platform/graphics/GraphicsContext.h" #include "core/platform/graphics/skia/SkiaFontWin.h" #include "platform/LayoutTestSupport.h" #include "platform/SharedBuffer.h" #include "platform/win/HWndDC.h" #include "public/platform/Platform.h" #include "public/platform/win/WebSandboxSupport.h" #include "wtf/PassOwnPtr.h" #include "wtf/StdLibExtras.h" #include <mlang.h> #include <objidl.h> #include <windows.h> namespace WebCore { void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const { const float ts = m_textSize >= 0 ? m_textSize : 12; paint->setTextSize(SkFloatToScalar(m_textSize)); paint->setTypeface(typeface()); paint->setFakeBoldText(m_fakeBold); paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 / 4 : 0); if (RuntimeEnabledFeatures::subpixelFontScalingEnabled()) paint->setSubpixelText(true); // Only set painting flags when we're actually painting. if (context) { int textFlags = paintTextFlags(); if (!context->couldUseLCDRenderedText()) { textFlags &= ~SkPaint::kLCDRenderText_Flag; // If we *just* clear our request for LCD, then GDI seems to // sometimes give us AA text, and sometimes give us BW text. Since the // original intent was LCD, we want to force AA (rather than BW), so we // add a special bit to tell Skia to do its best to avoid the BW: by // drawing LCD offscreen and downsampling that to AA. textFlags |= SkPaint::kGenA8FromLCD_Flag; } static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag | SkPaint::kGenA8FromLCD_Flag; SkASSERT(!(textFlags & ~textFlagsMask)); uint32_t flags = paint->getFlags(); flags &= ~textFlagsMask; flags |= textFlags; paint->setFlags(flags); } } // Lookup the current system settings for font smoothing. // We cache these values for performance, but if the browser has a way to be // notified when these change, we could re-query them at that time. static uint32_t getDefaultGDITextFlags() { static bool gInited; static uint32_t gFlags; if (!gInited) { BOOL enabled; gFlags = 0; if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) { gFlags |= SkPaint::kAntiAlias_Flag; UINT smoothType; if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) { if (FE_FONTSMOOTHINGCLEARTYPE == smoothType) gFlags |= SkPaint::kLCDRenderText_Flag; } } gInited = true; } return gFlags; } static bool isWebFont(const LOGFONT& lf) { // web-fonts have artifical names constructed to always be // 1. 24 characters, followed by a '\0' // 2. the last two characters are '==' return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\0' == lf.lfFaceName[24]; } static int computePaintTextFlags(const LOGFONT& lf) { int textFlags = 0; switch (lf.lfQuality) { case NONANTIALIASED_QUALITY: textFlags = 0; break; case ANTIALIASED_QUALITY: textFlags = SkPaint::kAntiAlias_Flag; break; case CLEARTYPE_QUALITY: textFlags = (SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag); break; default: textFlags = getDefaultGDITextFlags(); break; } // only allow features that SystemParametersInfo allows textFlags &= getDefaultGDITextFlags(); /* * FontPlatformData(...) will read our logfont, and try to honor the the lfQuality * setting (computing the corresponding SkPaint flags for AA and LCD). However, it * will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean * we end up drawing the text in BW, even though our lfQuality requested antialiasing. * * Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW. * In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA, * even when the System (getDefaultGDITextFlags) tells us to draw only in BW. */ if (isWebFont(lf) && !isRunningLayoutTest()) textFlags |= SkPaint::kAntiAlias_Flag; return textFlags; } PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags) { LOGFONT info; GetObject(hfont, sizeof(info), &info); if (size) { int height = info.lfHeight; if (height < 0) height = -height; *size = height; } if (paintTextFlags) *paintTextFlags = computePaintTextFlags(info); return adoptRef(SkCreateTypefaceFromLOGFONT(info)); } FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType) : m_font(0) , m_textSize(-1) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(true) { } FontPlatformData::FontPlatformData() : m_font(0) , m_textSize(0) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) { } #if ENABLE(GDI_FONTS_ON_WINDOWS) FontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation) : m_font(RefCountedHFONT::create(font)) , m_textSize(size) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(orientation) , m_scriptCache(0) , m_typeface(CreateTypefaceFromHFont(font, 0, &m_paintTextFlags)) , m_isHashTableDeletedValue(false) { } #endif // FIXME: this constructor is needed for SVG fonts but doesn't seem to do much FontPlatformData::FontPlatformData(float size, bool bold, bool oblique) : m_font(0) , m_textSize(size) , m_fakeBold(false) , m_fakeItalic(false) , m_orientation(Horizontal) , m_scriptCache(0) , m_typeface(adoptRef(SkTypeface::RefDefault())) , m_paintTextFlags(0) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(const FontPlatformData& data) : m_font(data.m_font) , m_textSize(data.m_textSize) , m_fakeBold(data.m_fakeBold) , m_fakeItalic(data.m_fakeItalic) , m_orientation(data.m_orientation) , m_scriptCache(0) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize) : m_font(data.m_font) , m_textSize(textSize) , m_fakeBold(data.m_fakeBold) , m_fakeItalic(data.m_fakeItalic) , m_orientation(data.m_orientation) , m_scriptCache(0) , m_typeface(data.m_typeface) , m_paintTextFlags(data.m_paintTextFlags) , m_isHashTableDeletedValue(false) { } FontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation) : m_font(0) , m_textSize(textSize) , m_fakeBold(fakeBold) , m_fakeItalic(fakeItalic) , m_orientation(orientation) , m_scriptCache(0) , m_typeface(tf) , m_isHashTableDeletedValue(false) { // FIXME: This can be removed together with m_font once the last few // uses of hfont() has been eliminated. LOGFONT logFont; SkLOGFONTFromTypeface(m_typeface.get(), &logFont); logFont.lfHeight = -textSize; HFONT hFont = CreateFontIndirect(&logFont); if (hFont) m_font = RefCountedHFONT::create(hFont); m_paintTextFlags = computePaintTextFlags(logFont); } FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data) { if (this != &data) { m_font = data.m_font; m_textSize = data.m_textSize; m_fakeBold = data.m_fakeBold; m_fakeItalic = data.m_fakeItalic; m_orientation = data.m_orientation; m_typeface = data.m_typeface; m_paintTextFlags = data.m_paintTextFlags; // The following fields will get re-computed if necessary. ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; m_scriptFontProperties.clear(); } return *this; } FontPlatformData::~FontPlatformData() { ScriptFreeCache(&m_scriptCache); m_scriptCache = 0; } String FontPlatformData::fontFamilyName() const { HWndDC dc(0); HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont())); WCHAR name[LF_FACESIZE]; unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name); if (resultLength > 0) resultLength--; // ignore the null terminator SelectObject(dc, oldFont); return String(name, resultLength); } bool FontPlatformData::isFixedPitch() const { #if ENABLE(GDI_FONTS_ON_WINDOWS) // TEXTMETRICS have this. Set m_treatAsFixedPitch based off that. HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); // Yes, this looks backwards, but the fixed pitch bit is actually set if the font // is *not* fixed pitch. Unbelievable but true. TEXTMETRIC textMetric = { 0 }; if (!GetTextMetrics(dc, &textMetric)) { if (ensureFontLoaded(hfont())) { // Retry GetTextMetrics. // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. if (!GetTextMetrics(dc, &textMetric)) LOG_ERROR("Unable to get the text metrics after second attempt"); } } bool treatAsFixedPitch = !(textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH); SelectObject(dc, oldFont); return treatAsFixedPitch; #else return typeface() && typeface()->isFixedPitch(); #endif } FontPlatformData::RefCountedHFONT::~RefCountedHFONT() { DeleteObject(m_hfont); } SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const { if (!m_scriptFontProperties) { m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES); memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES)); m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES); HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get()); if (result == E_PENDING) { HWndDC dc(0); HGDIOBJ oldFont = SelectObject(dc, hfont()); HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { if (FontPlatformData::ensureFontLoaded(hfont())) { // FIXME: Handle gracefully the error if this call also fails. hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get()); if (S_OK != hr) { LOG_ERROR("Unable to get the font properties after second attempt"); } } } SelectObject(dc, oldFont); } } return m_scriptFontProperties.get(); } #ifndef NDEBUG String FontPlatformData::description() const { return String(); } #endif bool FontPlatformData::ensureFontLoaded(HFONT font) { WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport(); // if there is no sandbox, then we can assume the font // was able to be loaded successfully already return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true; } } <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #include <algorithm> #include <vector> #include "cuda_runtime.h" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; template <typename Dtype> class PowerLayerTest : public ::testing::Test { protected: PowerLayerTest() : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)), blob_top_(new Blob<Dtype>()) { // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~PowerLayerTest() { delete blob_bottom_; delete blob_top_; } void TestForward(Dtype power, Dtype scale, Dtype shift) { LayerParameter layer_param; layer_param.mutable_power_param()->set_power(power); layer_param.mutable_power_param()->set_scale(scale); layer_param.mutable_power_param()->set_shift(shift); PowerLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const Dtype* bottom_data = this->blob_bottom_->cpu_data(); const Dtype* top_data = this->blob_top_->cpu_data(); const Dtype min_precision = 1e-5; for (int i = 0; i < this->blob_bottom_->count(); ++i) { Dtype expected_value = pow(shift + scale * bottom_data[i], power); if (power == Dtype(0) || power == Dtype(1) || power == Dtype(2)) { EXPECT_FALSE(isnan(top_data[i])); } if (isnan(expected_value)) { EXPECT_TRUE(isnan(top_data[i])); } else { Dtype precision = max(Dtype(abs(expected_value * 0.0001)), min_precision); EXPECT_NEAR(expected_value, top_data[i], precision); } } } void TestBackward(Dtype power, Dtype scale, Dtype shift) { LayerParameter layer_param; layer_param.mutable_power_param()->set_power(power); layer_param.mutable_power_param()->set_scale(scale); layer_param.mutable_power_param()->set_shift(shift); PowerLayer<Dtype> layer(layer_param); if (power != Dtype(0) && power != Dtype(1) && power != Dtype(2)) { // Avoid NaNs by forcing (shift + scale * x) >= 0 Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data(); Dtype min_value = -shift / scale; for (int i = 0; i < this->blob_bottom_->count(); ++i) { if (bottom_data[i] < min_value) { bottom_data[i] = min_value + (min_value - bottom_data[i]); } } } GradientChecker<Dtype> checker(1e-2, 1e-2, 1701, 0., 0.01); checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_), &(this->blob_top_vec_)); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(PowerLayerTest, Dtypes); TYPED_TEST(PowerLayerTest, TestPowerCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = 0.0; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.34; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.5; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = 0.0; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.34; TypeParam shift = -2.4; TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.83; TypeParam shift = -2.4; TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.5; TypeParam shift = -2.4; TestBackward(power, scale, shift); } } // namespace caffe <commit_msg>add using std::isnan and use this-> when calling Test{For,Back}ward<commit_after>// Copyright 2014 BVLC and contributors. #include <algorithm> #include <vector> #include "cuda_runtime.h" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" using std::isnan; namespace caffe { extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; template <typename Dtype> class PowerLayerTest : public ::testing::Test { protected: PowerLayerTest() : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)), blob_top_(new Blob<Dtype>()) { // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~PowerLayerTest() { delete blob_bottom_; delete blob_top_; } void TestForward(Dtype power, Dtype scale, Dtype shift) { LayerParameter layer_param; layer_param.mutable_power_param()->set_power(power); layer_param.mutable_power_param()->set_scale(scale); layer_param.mutable_power_param()->set_shift(shift); PowerLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const Dtype* bottom_data = this->blob_bottom_->cpu_data(); const Dtype* top_data = this->blob_top_->cpu_data(); const Dtype min_precision = 1e-5; for (int i = 0; i < this->blob_bottom_->count(); ++i) { Dtype expected_value = pow(shift + scale * bottom_data[i], power); if (power == Dtype(0) || power == Dtype(1) || power == Dtype(2)) { EXPECT_FALSE(isnan(top_data[i])); } if (isnan(expected_value)) { EXPECT_TRUE(isnan(top_data[i])); } else { Dtype precision = max(Dtype(abs(expected_value * 0.0001)), min_precision); EXPECT_NEAR(expected_value, top_data[i], precision); } } } void TestBackward(Dtype power, Dtype scale, Dtype shift) { LayerParameter layer_param; layer_param.mutable_power_param()->set_power(power); layer_param.mutable_power_param()->set_scale(scale); layer_param.mutable_power_param()->set_shift(shift); PowerLayer<Dtype> layer(layer_param); if (power != Dtype(0) && power != Dtype(1) && power != Dtype(2)) { // Avoid NaNs by forcing (shift + scale * x) >= 0 Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data(); Dtype min_value = -shift / scale; for (int i = 0; i < this->blob_bottom_->count(); ++i) { if (bottom_data[i] < min_value) { bottom_data[i] = min_value + (min_value - bottom_data[i]); } } } GradientChecker<Dtype> checker(1e-2, 1e-2, 1701, 0., 0.01); checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_), &(this->blob_top_vec_)); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(PowerLayerTest, Dtypes); TYPED_TEST(PowerLayerTest, TestPowerCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = 0.0; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.34; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientCPU) { Caffe::set_mode(Caffe::CPU); TypeParam power = 2.0; TypeParam scale = 0.5; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.37; TypeParam scale = 0.83; TypeParam shift = 0.0; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerZeroGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 0.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerOneGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 1.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.34; TypeParam shift = -2.4; this->TestForward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.83; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } TYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientGPU) { Caffe::set_mode(Caffe::GPU); TypeParam power = 2.0; TypeParam scale = 0.5; TypeParam shift = -2.4; this->TestBackward(power, scale, shift); } } // namespace caffe <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2010 VMware, Inc. * Copyright 2011 Intel corporation * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <sstream> #include <string.h> #include <limits.h> // for CHAR_MAX #include <getopt.h> #include <set> #include "cli.hpp" #include "os_string.hpp" #include "trace_analyzer.hpp" #include "trace_callset.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Create a new trace by trimming an existing trace."; static void usage(void) { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show detailed help for trim options and exit\n" " --calls=CALLSET Include specified calls in the trimmed output.\n" " --frames=FRAMESET Include specified frames in the trimmed output.\n" " --deps Include additional calls to satisfy dependencies\n" " --no-deps Do not include calls from dependency analysis\n" " --prune Omit uninteresting calls from the trace output\n" " --no-prune Do not prune uninteresting calls from the trace.\n" " -x, --exact Trim exactly to calls specified in --calls/--frames\n" " Equivalent to both --no-deps and --no-prune\n" " --print-callset Print the final set of calls included in output\n" " --thread=THREAD_ID Only retain calls from specified thread\n" " -o, --output=TRACE_FILE Output trace file\n" ; } static void help() { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show this help message and exit\n" "\n" " --calls=CALLSET Include specified calls in the trimmed output.\n" " --frames=FRAMESET Include specified frames in the trimmed output.\n" " Note that due to dependency analysis and pruning\n" " of uninteresting calls the resulting trace may\n" " include more and less calls than specified.\n" " See --no-deps, --no-prune, and --exact to change\n" " this behavior.\n" "\n" " --deps Perform dependency analysis and include dependent\n" " calls as needed, (even if those calls were not\n" " explicitly requested with --calls or --frames).\n" " This is the default behavior. See --no-deps and\n" " --exact to change the behavior.\n" "\n" " --no-deps Do not perform dependency analysis. In this mode\n" " the trimmed trace will never include calls from\n" " outside what is specified in --calls or --frames.\n" "\n" " --prune Omit calls with no side effects, even if the call\n" " is within the range specified by --calls/--frames.\n" " This is the default behavior. See --no-prune.\n" "\n" " --no-prune Do not prune uninteresting calls from the trace.\n" " In this mode the trimmed trace will never omit\n" " any calls within the user-specified range.\n" "\n" " -x, --exact Trim the trace to exactly the calls specified in\n" " --calls and --frames. This option is equivalent\n" " to passing both --no-deps and --no-prune.\n" "\n" " --print-callset Print to stdout the final set of calls included\n" " in the trim output. This can be useful for\n" " debugging trim operations by using a modified\n" " callset on the command-line along with --exact.\n" " Use --calls=@<file> to read callset from a file.\n" "\n" " --thread=THREAD_ID Only retain calls from specified thread\n" "\n" " -o, --output=TRACE_FILE Output trace file\n" "\n" ; } enum { CALLS_OPT = CHAR_MAX + 1, FRAMES_OPT, DEPS_OPT, NO_DEPS_OPT, PRUNE_OPT, NO_PRUNE_OPT, THREAD_OPT, PRINT_CALLSET_OPT, }; const static char * shortOptions = "ho:x"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"calls", required_argument, 0, CALLS_OPT}, {"frames", required_argument, 0, FRAMES_OPT}, {"deps", no_argument, 0, DEPS_OPT}, {"no-deps", no_argument, 0, NO_DEPS_OPT}, {"prune", no_argument, 0, PRUNE_OPT}, {"no-prune", no_argument, 0, NO_PRUNE_OPT}, {"exact", no_argument, 0, 'x'}, {"thread", required_argument, 0, THREAD_OPT}, {"output", required_argument, 0, 'o'}, {"print-callset", no_argument, 0, PRINT_CALLSET_OPT}, {0, 0, 0, 0} }; struct stringCompare { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; struct trim_options { /* Calls to be included in trace. */ trace::CallSet calls; /* Frames to be included in trace. */ trace::CallSet frames; /* Whether dependency analysis should be performed. */ bool dependency_analysis; /* Whether uninteresting calls should be pruned.. */ bool prune_uninteresting; /* Output filename */ std::string output; /* Emit only calls from this thread (-1 == all threads) */ int thread; /* Print resulting callset */ int print_callset; }; static int trim_trace(const char *filename, struct trim_options *options) { trace::ParseBookmark beginning; trace::Parser p; TraceAnalyzer analyzer; std::set<unsigned> *required; unsigned frame; int call_range_first, call_range_last; if (!p.open(filename)) { std::cerr << "error: failed to open " << filename << "\n"; return 1; } /* Mark the beginning so we can return here for pass 2. */ p.getBookmark(beginning); /* In pass 1, analyze which calls are needed. */ frame = 0; trace::Call *call; while ((call = p.parse_call())) { /* There's no use doing any work past the last call or frame * requested by the user. */ if (call->no > options->calls.getLast() || frame > options->frames.getLast()) { delete call; break; } /* If requested, ignore all calls not belonging to the specified thread. */ if (options->thread != -1 && call->thread_id != options->thread) { goto NEXT; } /* Also, prune if uninteresting (unless the user asked for no pruning. */ if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) { goto NEXT; } /* If this call is included in the user-specified call set, * then require it (and all dependencies) in the trimmed * output. */ if (options->calls.contains(*call) || options->frames.contains(frame, call->flags)) { analyzer.require(call); } /* Regardless of whether we include this call or not, we do * some dependency tracking (unless disabled by the user). We * do this even for calls we have included in the output so * that any state updates get performed. */ if (options->dependency_analysis) { analyzer.analyze(call); } NEXT: if (call->flags & trace::CALL_FLAG_END_FRAME) frame++; delete call; } /* Prepare output file and writer for output. */ if (options->output.empty()) { os::String base(filename); base.trimExtension(); options->output = std::string(base.str()) + std::string("-trim.trace"); } trace::Writer writer; if (!writer.open(options->output.c_str())) { std::cerr << "error: failed to create " << filename << "\n"; return 1; } /* Reset bookmark for pass 2. */ p.setBookmark(beginning); /* In pass 2, emit the calls that are required. */ required = analyzer.get_required(); frame = 0; call_range_first = -1; call_range_last = -1; while ((call = p.parse_call())) { /* There's no use doing any work past the last call or frame * requested by the user. */ if (call->no > options->calls.getLast() || frame > options->frames.getLast()) { break; } if (required->find(call->no) != required->end()) { writer.writeCall(call); if (options->print_callset) { if (call_range_first < 0) { call_range_first = call->no; printf ("%d", call_range_first); } else if (call->no != call_range_last + 1) { if (call_range_last != call_range_first) printf ("-%d", call_range_last); call_range_first = call->no; printf (",%d", call_range_first); } call_range_last = call->no; } } if (call->flags & trace::CALL_FLAG_END_FRAME) { frame++; } delete call; } if (options->print_callset) { if (call_range_last != call_range_first) printf ("-%d\n", call_range_last); } std::cout << "Trimmed trace is available as " << options->output << "\n"; return 0; } static int command(int argc, char *argv[]) { struct trim_options options; options.calls = trace::CallSet(trace::FREQUENCY_NONE); options.frames = trace::CallSet(trace::FREQUENCY_NONE); options.dependency_analysis = true; options.prune_uninteresting = true; options.output = ""; options.thread = -1; options.print_callset = 0; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': help(); return 0; case CALLS_OPT: options.calls = trace::CallSet(optarg); break; case FRAMES_OPT: options.frames = trace::CallSet(optarg); break; case DEPS_OPT: options.dependency_analysis = true; break; case NO_DEPS_OPT: options.dependency_analysis = false; break; case PRUNE_OPT: options.prune_uninteresting = true; break; case NO_PRUNE_OPT: options.prune_uninteresting = false; break; case 'x': options.dependency_analysis = false; options.prune_uninteresting = false; break; case THREAD_OPT: options.thread = atoi(optarg); break; case 'o': options.output = optarg; break; case PRINT_CALLSET_OPT: options.print_callset = 1; break; default: std::cerr << "error: unexpected option `" << opt << "`\n"; usage(); return 1; } } /* If neither of --calls nor --frames was set, default to the * entire set of calls. */ if (options.calls.empty() && options.frames.empty()) { options.calls = trace::CallSet(trace::FREQUENCY_ALL); } if (optind >= argc) { std::cerr << "error: apitrace trim requires a trace file as an argument.\n"; usage(); return 1; } if (argc > optind + 1) { std::cerr << "error: extraneous arguments:"; for (int i = optind + 1; i < argc; i++) { std::cerr << " " << argv[i]; } std::cerr << "\n"; usage(); return 1; } return trim_trace(argv[optind], &options); } const Command trim_command = { "trim", synopsis, help, command }; <commit_msg>trim: Print a warning message when doing dependency analysis.<commit_after>/************************************************************************** * * Copyright 2010 VMware, Inc. * Copyright 2011 Intel corporation * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <sstream> #include <string.h> #include <limits.h> // for CHAR_MAX #include <getopt.h> #include <set> #include "cli.hpp" #include "os_string.hpp" #include "trace_analyzer.hpp" #include "trace_callset.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Create a new trace by trimming an existing trace."; static void usage(void) { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show detailed help for trim options and exit\n" " --calls=CALLSET Include specified calls in the trimmed output.\n" " --frames=FRAMESET Include specified frames in the trimmed output.\n" " --deps Include additional calls to satisfy dependencies\n" " --no-deps Do not include calls from dependency analysis\n" " --prune Omit uninteresting calls from the trace output\n" " --no-prune Do not prune uninteresting calls from the trace.\n" " -x, --exact Trim exactly to calls specified in --calls/--frames\n" " Equivalent to both --no-deps and --no-prune\n" " --print-callset Print the final set of calls included in output\n" " --thread=THREAD_ID Only retain calls from specified thread\n" " -o, --output=TRACE_FILE Output trace file\n" ; } static void help() { std::cout << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show this help message and exit\n" "\n" " --calls=CALLSET Include specified calls in the trimmed output.\n" " --frames=FRAMESET Include specified frames in the trimmed output.\n" " Note that due to dependency analysis and pruning\n" " of uninteresting calls the resulting trace may\n" " include more and less calls than specified.\n" " See --no-deps, --no-prune, and --exact to change\n" " this behavior.\n" "\n" " --deps Perform dependency analysis and include dependent\n" " calls as needed, (even if those calls were not\n" " explicitly requested with --calls or --frames).\n" " This is the default behavior. See --no-deps and\n" " --exact to change the behavior.\n" "\n" " --no-deps Do not perform dependency analysis. In this mode\n" " the trimmed trace will never include calls from\n" " outside what is specified in --calls or --frames.\n" "\n" " --prune Omit calls with no side effects, even if the call\n" " is within the range specified by --calls/--frames.\n" " This is the default behavior. See --no-prune.\n" "\n" " --no-prune Do not prune uninteresting calls from the trace.\n" " In this mode the trimmed trace will never omit\n" " any calls within the user-specified range.\n" "\n" " -x, --exact Trim the trace to exactly the calls specified in\n" " --calls and --frames. This option is equivalent\n" " to passing both --no-deps and --no-prune.\n" "\n" " --print-callset Print to stdout the final set of calls included\n" " in the trim output. This can be useful for\n" " debugging trim operations by using a modified\n" " callset on the command-line along with --exact.\n" " Use --calls=@<file> to read callset from a file.\n" "\n" " --thread=THREAD_ID Only retain calls from specified thread\n" "\n" " -o, --output=TRACE_FILE Output trace file\n" "\n" ; } enum { CALLS_OPT = CHAR_MAX + 1, FRAMES_OPT, DEPS_OPT, NO_DEPS_OPT, PRUNE_OPT, NO_PRUNE_OPT, THREAD_OPT, PRINT_CALLSET_OPT, }; const static char * shortOptions = "ho:x"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"calls", required_argument, 0, CALLS_OPT}, {"frames", required_argument, 0, FRAMES_OPT}, {"deps", no_argument, 0, DEPS_OPT}, {"no-deps", no_argument, 0, NO_DEPS_OPT}, {"prune", no_argument, 0, PRUNE_OPT}, {"no-prune", no_argument, 0, NO_PRUNE_OPT}, {"exact", no_argument, 0, 'x'}, {"thread", required_argument, 0, THREAD_OPT}, {"output", required_argument, 0, 'o'}, {"print-callset", no_argument, 0, PRINT_CALLSET_OPT}, {0, 0, 0, 0} }; struct stringCompare { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; struct trim_options { /* Calls to be included in trace. */ trace::CallSet calls; /* Frames to be included in trace. */ trace::CallSet frames; /* Whether dependency analysis should be performed. */ bool dependency_analysis; /* Whether uninteresting calls should be pruned.. */ bool prune_uninteresting; /* Output filename */ std::string output; /* Emit only calls from this thread (-1 == all threads) */ int thread; /* Print resulting callset */ int print_callset; }; static int trim_trace(const char *filename, struct trim_options *options) { trace::ParseBookmark beginning; trace::Parser p; TraceAnalyzer analyzer; std::set<unsigned> *required; unsigned frame; int call_range_first, call_range_last; if (!p.open(filename)) { std::cerr << "error: failed to open " << filename << "\n"; return 1; } /* Mark the beginning so we can return here for pass 2. */ p.getBookmark(beginning); /* In pass 1, analyze which calls are needed. */ frame = 0; trace::Call *call; while ((call = p.parse_call())) { /* There's no use doing any work past the last call or frame * requested by the user. */ if (call->no > options->calls.getLast() || frame > options->frames.getLast()) { delete call; break; } /* If requested, ignore all calls not belonging to the specified thread. */ if (options->thread != -1 && call->thread_id != options->thread) { goto NEXT; } /* Also, prune if uninteresting (unless the user asked for no pruning. */ if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) { goto NEXT; } /* If this call is included in the user-specified call set, * then require it (and all dependencies) in the trimmed * output. */ if (options->calls.contains(*call) || options->frames.contains(frame, call->flags)) { analyzer.require(call); } /* Regardless of whether we include this call or not, we do * some dependency tracking (unless disabled by the user). We * do this even for calls we have included in the output so * that any state updates get performed. */ if (options->dependency_analysis) { analyzer.analyze(call); } NEXT: if (call->flags & trace::CALL_FLAG_END_FRAME) frame++; delete call; } /* Prepare output file and writer for output. */ if (options->output.empty()) { os::String base(filename); base.trimExtension(); options->output = std::string(base.str()) + std::string("-trim.trace"); } trace::Writer writer; if (!writer.open(options->output.c_str())) { std::cerr << "error: failed to create " << filename << "\n"; return 1; } /* Reset bookmark for pass 2. */ p.setBookmark(beginning); /* In pass 2, emit the calls that are required. */ required = analyzer.get_required(); frame = 0; call_range_first = -1; call_range_last = -1; while ((call = p.parse_call())) { /* There's no use doing any work past the last call or frame * requested by the user. */ if (call->no > options->calls.getLast() || frame > options->frames.getLast()) { break; } if (required->find(call->no) != required->end()) { writer.writeCall(call); if (options->print_callset) { if (call_range_first < 0) { call_range_first = call->no; printf ("%d", call_range_first); } else if (call->no != call_range_last + 1) { if (call_range_last != call_range_first) printf ("-%d", call_range_last); call_range_first = call->no; printf (",%d", call_range_first); } call_range_last = call->no; } } if (call->flags & trace::CALL_FLAG_END_FRAME) { frame++; } delete call; } if (options->print_callset) { if (call_range_last != call_range_first) printf ("-%d\n", call_range_last); } std::cout << "Trimmed trace is available as " << options->output << "\n"; return 0; } static int command(int argc, char *argv[]) { struct trim_options options; options.calls = trace::CallSet(trace::FREQUENCY_NONE); options.frames = trace::CallSet(trace::FREQUENCY_NONE); options.dependency_analysis = true; options.prune_uninteresting = true; options.output = ""; options.thread = -1; options.print_callset = 0; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': help(); return 0; case CALLS_OPT: options.calls = trace::CallSet(optarg); break; case FRAMES_OPT: options.frames = trace::CallSet(optarg); break; case DEPS_OPT: options.dependency_analysis = true; break; case NO_DEPS_OPT: options.dependency_analysis = false; break; case PRUNE_OPT: options.prune_uninteresting = true; break; case NO_PRUNE_OPT: options.prune_uninteresting = false; break; case 'x': options.dependency_analysis = false; options.prune_uninteresting = false; break; case THREAD_OPT: options.thread = atoi(optarg); break; case 'o': options.output = optarg; break; case PRINT_CALLSET_OPT: options.print_callset = 1; break; default: std::cerr << "error: unexpected option `" << opt << "`\n"; usage(); return 1; } } /* If neither of --calls nor --frames was set, default to the * entire set of calls. */ if (options.calls.empty() && options.frames.empty()) { options.calls = trace::CallSet(trace::FREQUENCY_ALL); } if (optind >= argc) { std::cerr << "error: apitrace trim requires a trace file as an argument.\n"; usage(); return 1; } if (argc > optind + 1) { std::cerr << "error: extraneous arguments:"; for (int i = optind + 1; i < argc; i++) { std::cerr << " " << argv[i]; } std::cerr << "\n"; usage(); return 1; } if (options.dependency_analysis) { std::cerr << "Note: The dependency analysis in \"apitrace trim\" is still experimental.\n" " We hope that it will be useful, but it may lead to incorrect results.\n" " If you find a trace that misbehaves while trimming, please share that\n" " by sending email to apitrace@lists.freedesktop.org, cworth@cworth.org\n"; } return trim_trace(argv[optind], &options); } const Command trim_command = { "trim", synopsis, help, command }; <|endoftext|>
<commit_before>// Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp" #include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp" #include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace ::testing; using ::testing::Return; using iox::roudi::IceOryxRouDiApp; namespace iox { namespace test { class IceoryxRoudiApp_Child : public IceOryxRouDiApp { public: IceoryxRoudiApp_Child(const config::CmdLineParser& cmdLineParser, const RouDiConfig_t& roudiConfig):IceOryxRouDiApp(cmdLineParser,roudiConfig) { } bool getVariableMRun() { return m_run; } void setVariableMRun(bool condition) { m_run = condition; } uint8_t callRun() noexcept { return run(); } }; /// @brief Test goal: This file tests class roudi app class IceoryxRoudiApp_test : public Test { public: iox::config::CmdLineParserConfigFileOption cmdLineParser; int argc; char* argv[]; virtual void setUp() { cmdLineParser.parse(argc, argv); } }; TEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull) { IceoryxRoudiApp_Child roudi(cmdLineParser, iox::RouDiConfig_t().setDefaults()); EXPECT_TRUE(roudi.getVariableMRun()); } TEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess) { IceoryxRoudiApp_Child roudi(cmdLineParser, iox::RouDiConfig_t().setDefaults()); roudi.setVariableMRun(false); uint8_t result = roudi.callRun(); EXPECT_EQ(result, EXIT_SUCCESS); } } // namespace test } // namespace iox<commit_msg>iox-#454 improve test for roudi app<commit_after>// Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp" #include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp" #include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace ::testing; using ::testing::Return; using iox::roudi::IceOryxRouDiApp; namespace iox { namespace test { class IceoryxRoudiApp_Child : public IceOryxRouDiApp { public: IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig):IceOryxRouDiApp(cmdLineArgs,roudiConfig) { } bool getVariableMRun() { return m_run; } void setVariableMRun(bool condition) { m_run = condition; } uint8_t callRun() noexcept { return run(); } }; /// @brief Test goal: This file tests class roudi app class IceoryxRoudiApp_test : public Test { public: iox::config::CmdLineParserConfigFileOption cmdLineParser; virtual void setUp() { } }; TEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull) { constexpr uint8_t numberOfArgs{1U}; char* args[numberOfArgs]; char appName[] = "./foo"; args[0] = &appName[0]; auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args); IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); EXPECT_TRUE(roudi.getVariableMRun()); } TEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessfull) { constexpr uint8_t numberOfArgs{1U}; char* args[numberOfArgs]; char appName[] = "./foo"; args[0] = &appName[0]; auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args); IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); EXPECT_TRUE(roudiTest.getVariableMRun()); } TEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess) { constexpr uint8_t numberOfArgs{1U}; char* args[numberOfArgs]; char appName[] = "./foo"; args[0] = &appName[0]; auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args); IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); roudi.setVariableMRun(false); uint8_t result = roudi.callRun(); EXPECT_EQ(result, EXIT_SUCCESS); } TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse) { constexpr uint8_t numberOfArgs{2U}; char* args[numberOfArgs]; char appName[] = "./foo"; char option[] = "-v"; args[0] = &appName[0]; args[1] = &option[0]; auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args); IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); EXPECT_FALSE(roudi.getVariableMRun()); } /*TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdSetRunVariableToFalse) { constexpr uint8_t numberOfArgs{3U}; char* args[numberOfArgs]; char appName[] = "./foo"; char option[] = "-u"; char value[] = "4242"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &value[0]; auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args); iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) { detectedError.emplace(error); EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE)); }); IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults()); ASSERT_THAT(detectedError.has_value(), Eq(true)); EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID)); }*/ } // namespace test } // namespace iox<|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_FUNCTIONS_BITWISE_SHIFT_LEFT_HPP #define BOOST_BRIGAND_FUNCTIONS_BITWISE_SHIFT_LEFT_HPP #include <brigand/types/integral_constant.hpp> namespace brigand { template <typename A, typename B> struct shift_left : brigand::integral_constant<typename A::value_type, (A::value << B::value)> {}; } #endif <commit_msg>Delete shift_left.hpp<commit_after><|endoftext|>
<commit_before>/// ///@Author PEZY ///@Date Aug. 2014 ///@Brief /// read a sequence of strings from cin and /// store those values in a vector. /// #include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> vec; std::string str; while (std::cin >> str) vec.push_back(str); return 0; } <commit_msg>Update ex3_15.cpp<commit_after>/// ///@Author @PEZY @Yue Wang ///@Date Aug. 2014, Jun 2015 ///@Brief /// read a sequence of strings from cin and /// store those values in a vector. /// #include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> vec; for (std::string buffer; std::cin >> buffer; vec.push_back(buffer)); return 0; } <|endoftext|>
<commit_before>// // ex7_07.cpp // Exercise 7.7 // // Created by pezy on 11/8/14. // Copyright (c) 2014 pezy. All rights reserved. // #include "ex7_06.h" int main() { Sales_data total; if (read(std::cin, total)) { Sales_data trans; while (read(std::cin, trans)) { if (total.isbn() == trans.isbn()) total.combine(trans); else { print(std::cout, total) << std::endl; total = trans; } } print(std::cout, total) << std::endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <commit_msg>Update ex7_07.cpp<commit_after>// // ex7_07.cpp // Exercise 7.7 // // Created by pezy on 11/8/14. // Copyright (c) 2014 pezy. All rights reserved. // #include "ex7_06.h" #include <iostream> using std::cin; using std::cout; using std::cerr; using std::endl; int main() { Sales_data total; if (read(cin, total)) { Sales_data trans; while (read(cin, trans)) { if (total.isbn() == trans.isbn()) total.combine(trans); else { print(cout, total) << endl; total = trans; } } print(cout, total) << endl; } else { cerr << "No data?!" << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>//! @file Exercise 9.27 //! @author pezy //! @date 2014-12-03 //! @Brief Write a program to find and remove the odd-valued elements in a forward_list<int>. #include<iostream> #include <forward_list> using namespace std; int main() { forward_list<int> flst{0,1,2,3,4,5,6,7,8,9}; for(auto prev=flst.before_begin(), curr=flst.begin(); curr!=flst.end(); ) if(*curr & 0x1) curr=flst.erase_after(prev); else { prev=curr; ++curr; } for(auto i: flst) cout<<i<<" "; cout<<endl; } <commit_msg>Update ex9_27.cpp<commit_after>//! @file Exercise 9.27 //! @author pezy //! @date 2014-12-03 //! @Brief Write a program to find and remove the odd-valued elements in a forward_list<int>. #include<iostream> #include <forward_list> using namespace std; int main() { forward_list<int> flst{0,1,2,3,4,5,6,7,8,9}; for(auto prev=flst.before_begin(), curr=flst.begin(); curr!=flst.end(); ) if(*curr & 0x1) curr=flst.erase_after(prev); else { prev=curr; ++curr; } for(auto i: flst) cout<<i<<" "; cout<<endl; } <|endoftext|>
<commit_before>/* Ex 6.7: Write a grammar for bitwise logical expressions. A bitwise logical expression is much like an arithmetic expression except that the operators are ! (not), ~ (complement), & (and), | (or), and ^ (exclusive or). Each operator does its operation to each bit of its integer operands (see §25.5). ! and ~ are prefix unary operators. A ^ binds tighter than a | (just as * binds tighter than +) so that x|y^z means x|(y^z) rather than (x|y)^z. The & operator binds tighter than ^ so that x^y&z means x^(y&z).*/ /* // | < ^ < & < ~! Grammar: Expression: Term Expression | Term // Handle | Term: Primary Term ^ Primary Primary Unit Primary & Unit Unit Number(int form) ~Number !Number ( Expression ) ~( Expression ) !( Expression ) */ #include "std_lib_facilities.h" #include <cassert> //------------------------------------------------------------------------------ class Token{ public: char kind; int value; Token(char ch) : kind(ch), value(0) {} Token(char ch, int val) : kind(ch), value(val) {} }; //------------------------------------------------------------------------------ class Token_stream{ public: Token_stream(); Token get(); void putback(Token t); private: bool full; Token buffer; }; Token_stream::Token_stream() : full(false), buffer(0) {} Token Token_stream::get(){ if(full){ full = false; return buffer; } char ch; cin >> ch; switch(ch){ case ';': case 'q': case '~': case '!': case '^': case '|': case '%': case '(' : case ')': return Token(ch); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '9': return Token('8', ch - '0'); default: error("Bad Token"); } } //------------------------------------------------------------------------------ // The putback() member function puts its argument back into the Token_stream's buffer: void Token_stream::putback(Token t) { if (full) error("putback() into a full buffer"); buffer = t; // copy t to buffer full = true; // buffer is now full } int Unit(); int Primary(); int Term(); int Expression(); Token_stream ts; int Expression(){ int left = Term(); Token t = ts.get(); while(true){ if(t.kind == '|'){ left |= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Term(){ int left = Primary(); Token t = ts.get(); while(true){ if(t.kind == '^'){ left ^= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Primary(){ int left = Unit(); Token t = ts.get(); while(true){ if(t.kind == '&'){ left &= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Unit(){ Token t = ts.get(); switch(t.kind){ case '8': return t.value; case '(': { int ret = Expression(); ret = !ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } case '~': { t = ts.get(); if(t.kind == '8') return ~(t.value); if(t.kind == '('){ int ret = Expression(); ret = ~ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } } case '!': { t = ts.get(); if(t.kind == '8') return !(t.value); if(t.kind == '('){ int ret = Expression(); ret = !ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } } } } int main(){ try{ int val = 0; cout << "Please input the logical expression, end with ; " << endl; while(cin){ Token t = ts.get(); if(t.kind == 'q') break; if(t.kind == ';') cout << " = " << val << endl; else ts.putback(t); val = Expression(); } } catch (exception& e) { cerr << "error: " << e.what() << '\n'; keep_window_open(); return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; keep_window_open(); return 2; } } <commit_msg>Fix Ex6.7<commit_after>/* Ex 6.7: Write a grammar for bitwise logical expressions. A bitwise logical expression is much like an arithmetic expression except that the operators are ! (not), ~ (complement), & (and), | (or), and ^ (exclusive or). Each operator does its operation to each bit of its integer operands (see §25.5). ! and ~ are prefix unary operators. A ^ binds tighter than a | (just as * binds tighter than +) so that x|y^z means x|(y^z) rather than (x|y)^z. The & operator binds tighter than ^ so that x^y&z means x^(y&z).*/ /* // | < ^ < & < ~! Grammar: Expression: Term Expression | Term // Handle | Term: Primary Term ^ Primary Primary Unit Primary & Unit Unit Number(int form) ~Number !Number ( Expression ) ~( Expression ) !( Expression ) */ #include "std_lib_facilities.h" #include <cassert> //------------------------------------------------------------------------------ class Token{ public: char kind; int value; Token(char ch) : kind(ch), value(0) {} Token(char ch, int val) : kind(ch), value(val) {} }; //------------------------------------------------------------------------------ class Token_stream{ public: Token_stream(); Token get(); void putback(Token t); private: bool full; Token buffer; }; Token_stream::Token_stream() : full(false), buffer(0) {} Token Token_stream::get(){ if(full){ full = false; return buffer; } char ch; cin >> ch; switch(ch){ case ';': case 'q': case '~': case '!': case '^': case '|': case '&': case '(' : case ')': return Token(ch); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '9': return Token('8', ch - '0'); default: error("Bad Token"); } } //------------------------------------------------------------------------------ // The putback() member function puts its argument back into the Token_stream's buffer: void Token_stream::putback(Token t) { if (full) error("putback() into a full buffer"); buffer = t; // copy t to buffer full = true; // buffer is now full } int Unit(); int Primary(); int Term(); int Expression(); Token_stream ts; int Expression(){ int left = Term(); Token t = ts.get(); while(true){ if(t.kind == '|'){ left |= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Term(){ int left = Primary(); Token t = ts.get(); while(true){ if(t.kind == '^'){ left ^= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Primary(){ int left = Unit(); Token t = ts.get(); while(true){ if(t.kind == '&'){ left &= Expression(); t = ts.get(); }else{ ts.putback(t); return left; } } } int Unit(){ Token t = ts.get(); switch(t.kind){ case '8': return t.value; case '(': { int ret = Expression(); ret = !ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } case '~': { t = ts.get(); if(t.kind == '8') return ~(t.value); if(t.kind == '('){ int ret = Expression(); ret = ~ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } } case '!': { t = ts.get(); if(t.kind == '8') return !(t.value); if(t.kind == '('){ int ret = Expression(); ret = !ret; t = ts.get(); if(t.kind != ')') error("Nead )"); return ret; } } } } int main(){ try{ int val = 0; cout << "Please input the logical expression, end with ; " << endl; while(cin){ Token t = ts.get(); if(t.kind == 'q') break; if(t.kind == ';') cout << " = " << val << endl; else ts.putback(t); val = Expression(); } } catch (exception& e) { cerr << "error: " << e.what() << '\n'; keep_window_open(); return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; keep_window_open(); return 2; } } <|endoftext|>
<commit_before>#include "types.h" #include "amd64.h" #include "kernel.hh" #include "cpu.hh" #include "gc.hh" #include "percpu.hh" #include "spinlock.h" #include "condvar.h" #include "proc.hh" #include "uwq.hh" #include "vm.hh" #include "kalloc.hh" #include "bits.hh" extern "C" { #include "kern_c.h" } bool uwq_trywork(void) { // Returning true means uwq added a thread to the run queue u64 i, k; // A "random" victim CPU k = rdtsc(); for (i = 0; i < NCPU; i++) { u64 j = (i+k) % NCPU; if (j == mycpuid()) continue; struct cpu *c = &cpus[j]; // The gc_epoch is for p and uwq scoped_gc_epoch xgc(); barrier(); struct proc *p = c->proc; if (p == nullptr) continue; uwq* uwq = p->uwq; if (uwq == nullptr) continue; if (uwq->haswork()) { if (uwq->tryworker()) return true; break; } } return false; } long sys_wqwait(void) { uwq_worker* w = myproc()->worker; if (w == nullptr) return -1; return w->wait(); } // // uwq_worker // uwq_worker::uwq_worker(uwq* u, proc* p) : uwq_(u), proc_(p), running_(false) { initlock(&lock_, "worker_lock", 0); initcondvar(&cv_, "worker_cv"); } void uwq_worker::exit(void) { if (--uwq_->uref_ == 0) gc_delayed(uwq_); release(&lock_); delete this; ::exit(); } long uwq_worker::wait(void) { acquire(&lock_); if (!uwq_->valid()) this->exit(); running_ = false; cv_sleep(&cv_, &lock_); if (!uwq_->valid()) this->exit(); release(&lock_); return 0; } // // uwq // uwq* uwq::alloc(vmap* vmap, filetable *ftable) { uwq_ipcbuf* ipc; uwq* u; ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); if (ipc == nullptr) return nullptr; ftable->incref(); vmap->incref(); u = new uwq(vmap, ftable, ipc); if (u == nullptr) { ftable->decref(); vmap->decref(); ksfree(slab_userwq, ipc); return nullptr; } if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) { ftable->decref(); vmap->decref(); ksfree(slab_userwq, ipc); u->dec(); return nullptr; } return u; } uwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) : rcu_freed("uwq"), vmap_(vmap), ftable_(ftable), ipc_(ipc), uentry_(0), ustack_(UWQSTACK), uref_(0) { for (int i = 0; i < NCPU; i++) ipc_->len[i].v_ = 0; initlock(&lock_, "uwq_lock", 0); for (int i = 0; i < NWORKERS; i++) worker_[i].store(nullptr); } uwq::~uwq(void) { if (ipc_ != nullptr) ksfree(slab_userwq, ipc_); vmap_->decref(); ftable_->decref(); } bool uwq::haswork(void) const { if (ipc_ == nullptr) return false; for (int i = 0; i < NCPU; i++) { if (ipc_->len[i].v_ > 0) { return true; } } return false; } bool uwq::tryworker(void) { if (!valid()) return false; // Try to start a worker thread scoped_acquire lock0(&lock_); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] == nullptr) continue; uwq_worker *w = worker_[i]; if (w->running_) continue; else { scoped_acquire lock1(&w->lock_); proc* p = w->proc_; acquire(&p->lock); p->cpuid = mycpuid(); release(&p->lock); w->running_ = true; cv_wakeup(&w->cv_); return true; } } lock0.release(); again: u64 uref = uref_.load(); if (uref < ipc_->maxworkers) { if (!cmpxch(&uref_, uref, uref+1)) goto again; // Guaranteed to have slot in worker_ proc* p = allocworker(); if (p != nullptr) { uwq_worker* w = new uwq_worker(this, p); assert(w != nullptr); ++uref_; p->worker = w; w->running_ = true; acquire(&p->lock); p->cpuid = mycpuid(); addrun(p); release(&p->lock); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] == nullptr) if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w)) return true; } panic("uwq::tryworker: oops"); } } return false; } void uwq::finish(void) { bool gcnow = true; scoped_acquire lock0(&lock_); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] != nullptr) { uwq_worker* w = worker_[i]; gcnow = false; acquire(&w->lock_); cv_wakeup(&w->cv_); release(&w->lock_); } } if (gcnow) gc_delayed(this); } void uwq::onzero() const { uwq *u = (uwq*)this; u->finish(); } void uwq::setuentry(uptr uentry) { uentry_ = uentry; } proc* uwq::allocworker(void) { uptr uentry = uentry_; if (uentry == 0) return nullptr; proc* p = proc::alloc(); if (p == nullptr) return nullptr; safestrcpy(p->name, "uwq_worker", sizeof(p->name)); // finishproc will drop these refs vmap_->incref(); ftable_->incref(); p->vmap = vmap_; p->ftable = ftable_; struct vmnode *vmn; if ((vmn = new vmnode(USTACKPAGES)) == nullptr) { finishproc(p); return nullptr; } // Include a bumper page uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE); uptr stacktop = ustack + (USTACKPAGES*PGSIZE); if (vmap_->insert(vmn, ustack, 1) < 0) { delete vmn; finishproc(p); return nullptr; } p->tf->rsp = stacktop - 8; p->tf->rip = uentry; p->tf->cs = UCSEG | 0x3; p->tf->ds = UDSEG | 0x3; p->tf->ss = p->tf->ds; p->tf->rflags = FL_IF; return p; } <commit_msg>Don't look<commit_after>#include "types.h" #include "amd64.h" #include "kernel.hh" #include "cpu.hh" #include "gc.hh" #include "percpu.hh" #include "spinlock.h" #include "condvar.h" #include "proc.hh" #include "uwq.hh" #include "vm.hh" #include "kalloc.hh" #include "bits.hh" extern "C" { #include "kern_c.h" } bool uwq_trywork(void) { // Returning true means uwq added a thread to the run queue u64 i, k; // A "random" victim CPU k = rdtsc(); for (i = 0; i < NCPU; i++) { u64 j = (i+k) % NCPU; if (j == mycpuid()) continue; struct cpu *c = &cpus[j]; // The gc_epoch is for p and uwq scoped_gc_epoch xgc(); barrier(); struct proc *p = c->proc; if (p == nullptr) continue; uwq* uwq = p->uwq; if (uwq == nullptr) continue; if (uwq->haswork()) { if (uwq->tryworker()) return true; break; } } return false; } long sys_wqwait(void) { uwq_worker* w = myproc()->worker; if (w == nullptr) return -1; return w->wait(); } // // uwq_worker // uwq_worker::uwq_worker(uwq* u, proc* p) : uwq_(u), proc_(p), running_(false) { initlock(&lock_, "worker_lock", 0); initcondvar(&cv_, "worker_cv"); } void uwq_worker::exit(void) { if (--uwq_->uref_ == 0) gc_delayed(uwq_); release(&lock_); delete this; ::exit(); } long uwq_worker::wait(void) { acquire(&lock_); if (!uwq_->valid()) this->exit(); running_ = false; cv_sleep(&cv_, &lock_); if (!uwq_->valid()) this->exit(); release(&lock_); return 0; } // // uwq // uwq* uwq::alloc(vmap* vmap, filetable *ftable) { uwq_ipcbuf* ipc; uwq* u; ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); if (ipc == nullptr) return nullptr; ftable->incref(); vmap->incref(); u = new uwq(vmap, ftable, ipc); if (u == nullptr) { ftable->decref(); vmap->decref(); ksfree(slab_userwq, ipc); return nullptr; } if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) { ftable->decref(); vmap->decref(); ksfree(slab_userwq, ipc); u->dec(); return nullptr; } return u; } uwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) : rcu_freed("uwq"), vmap_(vmap), ftable_(ftable), ipc_(ipc), uentry_(0), ustack_(UWQSTACK), uref_(0) { ftable_->incref(); vmap_->incref(); for (int i = 0; i < NCPU; i++) ipc_->len[i].v_ = 0; initlock(&lock_, "uwq_lock", 0); for (int i = 0; i < NWORKERS; i++) worker_[i].store(nullptr); } uwq::~uwq(void) { if (ipc_ != nullptr) ksfree(slab_userwq, ipc_); vmap_->decref(); ftable_->decref(); } bool uwq::haswork(void) const { if (ipc_ == nullptr) return false; for (int i = 0; i < NCPU; i++) { if (ipc_->len[i].v_ > 0) { return true; } } return false; } bool uwq::tryworker(void) { if (!valid()) return false; // Try to start a worker thread scoped_acquire lock0(&lock_); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] == nullptr) continue; uwq_worker *w = worker_[i]; if (w->running_) continue; else { scoped_acquire lock1(&w->lock_); proc* p = w->proc_; acquire(&p->lock); p->cpuid = mycpuid(); release(&p->lock); w->running_ = true; cv_wakeup(&w->cv_); return true; } } lock0.release(); again: u64 uref = uref_.load(); if (uref < ipc_->maxworkers) { if (!cmpxch(&uref_, uref, uref+1)) goto again; // Guaranteed to have slot in worker_ proc* p = allocworker(); if (p != nullptr) { uwq_worker* w = new uwq_worker(this, p); assert(w != nullptr); ++uref_; p->worker = w; w->running_ = true; acquire(&p->lock); p->cpuid = mycpuid(); addrun(p); release(&p->lock); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] == nullptr) if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w)) return true; } panic("uwq::tryworker: oops"); } } return false; } void uwq::finish(void) { bool gcnow = true; scoped_acquire lock0(&lock_); for (int i = 0; i < NWORKERS; i++) { if (worker_[i] != nullptr) { uwq_worker* w = worker_[i]; gcnow = false; acquire(&w->lock_); cv_wakeup(&w->cv_); release(&w->lock_); } } if (gcnow) gc_delayed(this); } void uwq::onzero() const { uwq *u = (uwq*)this; u->finish(); } void uwq::setuentry(uptr uentry) { uentry_ = uentry; } proc* uwq::allocworker(void) { uptr uentry = uentry_; if (uentry == 0) return nullptr; proc* p = proc::alloc(); if (p == nullptr) return nullptr; safestrcpy(p->name, "uwq_worker", sizeof(p->name)); // finishproc will drop these refs vmap_->incref(); ftable_->incref(); p->vmap = vmap_; p->ftable = ftable_; struct vmnode *vmn; if ((vmn = new vmnode(USTACKPAGES)) == nullptr) { finishproc(p); return nullptr; } // Include a bumper page uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE); uptr stacktop = ustack + (USTACKPAGES*PGSIZE); if (vmap_->insert(vmn, ustack, 1) < 0) { delete vmn; finishproc(p); return nullptr; } p->tf->rsp = stacktop - 8; p->tf->rip = uentry; p->tf->cs = UCSEG | 0x3; p->tf->ds = UDSEG | 0x3; p->tf->ss = p->tf->ds; p->tf->rflags = FL_IF; return p; } <|endoftext|>
<commit_before>#include "spacetyper/scalablesprite.h" #include <cassert> #include <iostream> #include <algorithm> #include "spacetyper/vao.h" #include "spacetyper/rect.h" #include "spacetyper/texture.h" #include "spacetyper/texturecache.h" #include "scalingsprite.pb.h" #include "spacetyper/proto.h" //////////////////////////////////////////////////////////////////////////////// class ScalableSpriteData { public: ScalableSpriteData(const VaoBuilder& avao, const glm::vec2& aworld_size, const glm::vec2& aclient_size, const glm::vec2& aclient_offset) : vao(avao), world_size(aworld_size), client_size(aclient_size), client_offset(aclient_offset) {} Vao vao; glm::vec2 world_size; glm::vec2 client_size; glm::vec2 client_offset; }; //////////////////////////////////////////////////////////////////////////////// ScalableSprite::ScalableSprite(Texture2d* texture, const glm::vec2& min_size, SizeType size_type, const glm::vec2& size) : texture_(texture) , min_size_(min_size) , size_type_(size_type) , size_(size) { } ScalableSprite::~ScalableSprite() { } void ScalableSprite::SetClientSize(const glm::vec2 &new_size) { assert(this); SetSizeSub(new_size, SizeType::CLIENT); } const glm::vec2 ScalableSprite::GetClientSize() const { assert(this); if( size_type_ == SizeType::CLIENT) return size_; PrepareData(); return data_->client_size; } const glm::vec2 ScalableSprite::GetClientOffset() const { assert(this); PrepareData(); return data_->client_offset; } void ScalableSprite::SetSize(const glm::vec2 &new_size) { assert(this); SetSizeSub(new_size, SizeType::WORLD); } const glm::vec2 ScalableSprite::GetSize() const { assert(this); if( size_type_ == SizeType::WORLD) return size_; PrepareData(); return data_->world_size; } const glm::vec2 ScalableSprite::GetMinimumSize() const { assert(this); return min_size_; } const glm::vec2 ScalableSprite::GetMinimumSize(const glm::vec2& extra) const { assert(this); return glm::vec2(min_size_.x + extra.x, min_size_.y + extra.y); } const Texture2d* ScalableSprite::texture_ptr() const { assert(this); return texture_; } const Vao* ScalableSprite::vao_ptr() const { assert(this); PrepareData(); return &data_->vao; } std::pair<ScalableSprite::SizeType, glm::vec2> ScalableSprite::GetSizeData() const { return std::pair<SizeType, glm::vec2>(size_type_, size_); }; void ScalableSprite::PrepareData() const { assert(this); if( data_.get() == nullptr) { data_.reset(BuildData()); } } void ScalableSprite::SetSizeSub(const glm::vec2& new_size, SizeType type) { assert(this); if( data_.get() != nullptr && size_type_ == type && size_ == new_size) { // if we have built the data and the size & type is the same // then there's no need to rebuild it return; } size_ = new_size; size_type_ = type; data_.reset(); } //////////////////////////////////////////////////////////////////////////////// namespace { glm::vec2 DetermineSize(const glm::vec2 real_size, Rect<int> pixel_data) { return glm::vec2( real_size.x - pixel_data.GetWidth() , real_size.y - pixel_data.GetHeight()); } VaoBuilder BuildNinepatchVao(const Texture2d* texture_, const Rect<int> draw, const glm::vec2& inner_size_) { VaoBuilder data; // 00 10 20 30 // +------+-----------------+------+ // | | | | // |01 |11 |21 | 31 // +------+-----------------+------+ // | | | | // | | | | // | | | | // | | | | // | | | | // | | | | // |02 |12 |22 | 32 // +------+-----------------+------+ // | | | | // |03 |13 |23 | 33 // +------+-----------------+------+ // const float width = texture_->width(); const float height = texture_->height(); const float border_left = std::max(0, draw.left); const float border_right = std::max(0.0f, width - draw.right); const float border_top = std::max(0, draw.top); const float border_bottom = std::max(0.0f, height - draw.bottom); const float x0 = 0.0f; const float x1 = border_left; const float x2 = x1 + inner_size_.x; const float x3 = x2 + border_right; const float y0 = 0.0f; const float y1 = border_top; const float y2 = y1 + inner_size_.y; const float y3 = y2 + border_bottom; const float u0 = 0.0f; const float u1 = 0.0f + border_left / width; const float u2 = 1.0f - border_right/width; const float u3 = 1.0f; const float v0 = 0.0f; const float v1 = 0.0f + border_top / height; const float v2 = 1.0f - border_bottom / height; const float v3 = 1.0f; #define P(A, B) Point(x ## A, y ## B, u ## A, v ## B) data.quad(P(0,0), P(1,0), P(0,1), P(1,1)) .quad(P(1,0), P(2,0), P(1,1), P(2,1)) .quad(P(2,0), P(3,0), P(2,1), P(3,1)); data.quad(P(0,1), P(1,1), P(0,2), P(1,2)) .quad(P(1,1), P(2,1), P(1,2), P(2,2)) .quad(P(2,1), P(3,1), P(2,2), P(3,2)); data.quad(P(0,2), P(1,2), P(0,3), P(1,3)) .quad(P(1,2), P(2,2), P(1,3), P(2,3)) .quad(P(2,2), P(3,2), P(2,3), P(3,3)); // basic scale - like a sprite // data.quad(P(0,0), P(3,0), P(0,3), P(3,3)); #undef P return data; } } class ScalableSpriteNinepatch : public ScalableSprite { public: ScalableSpriteNinepatch(Texture2d* texture, SizeType size_type, const glm::vec2& size, const Rect<int>& da, const Rect<int>& ca) : ScalableSprite(texture, glm::vec2(ca.GetWidth(), ca.GetHeight()), size_type, size) , draw_area_(da), client_area_(ca) {} glm::vec2 DetermineRealSize() const { auto data = GetSizeData(); const auto size = data.second; switch (data.first) { case ScalableSprite::SizeType::CLIENT: return glm::vec2(size.x + client_area_.GetWidth(), size.y + client_area_.GetHeight()); case ScalableSprite::SizeType::WORLD: return size; } assert(false && "unhandled SizeType"); } bool ValidateCalculatedSize(const glm::vec2& real_size, const glm::vec2& client_size) const { auto data = GetSizeData(); const auto size = data.second; switch (data.first) { case ScalableSprite::SizeType::CLIENT: return client_size == size; case ScalableSprite::SizeType::WORLD: return real_size == size; } assert(false && "unhandled SizeType"); } ScalableSpriteData* BuildData() const override { const glm::vec2 real_size = DetermineRealSize(); const glm::vec2 draw_size = DetermineSize(real_size, draw_area_); const glm::vec2 client_size = DetermineSize(real_size, client_area_); assert(ValidateCalculatedSize(real_size, client_size)); return new ScalableSpriteData(BuildNinepatchVao(texture_ptr(), draw_area_, draw_size), real_size, client_size, glm::vec2(client_area_.left, client_area_.top)); } Rect<int> draw_area_; Rect<int> client_area_; }; //////////////////////////////////////////////////////////////////////////////// Rect<int> Convert(const scalingsprite::Rect& r) { return Rect<int>::FromLeftRightTopBottom(r.left(), r.right(), r.top(), r.bottom()); } std::shared_ptr<ScalableSprite> LoadScalableNinepatch(Texture2d* tex, ScalableSprite::SizeType size_type, glm::vec2 size, const scalingsprite::Ninepatch& data) { std::shared_ptr<ScalableSprite> ret ( new ScalableSpriteNinepatch(tex, size_type, size, Convert(data.draw()), Convert(data.client())) ); return ret; } std::shared_ptr<ScalableSprite> LoadScalableSprite(const std::string& path, const glm::vec2& size, TextureCache* cache) { std::string json_path = path + ".json"; Texture2d* tex = cache->GetTexture(path); const ScalableSprite::SizeType size_type = ScalableSprite::SizeType::WORLD; scalingsprite::ScalingSprite sprite; SaveProtoJson(sprite, path+".json"); SaveProtoJson(sprite, path+".txt"); // only ninepatch supported... assert(sprite.has_ninepatch()); return LoadScalableNinepatch(tex, size_type, size, sprite.ninepatch()); } <commit_msg>added sprite loading<commit_after>#include "spacetyper/scalablesprite.h" #include <cassert> #include <iostream> #include <algorithm> #include "spacetyper/vao.h" #include "spacetyper/rect.h" #include "spacetyper/texture.h" #include "spacetyper/texturecache.h" #include "scalingsprite.pb.h" #include "spacetyper/proto.h" //////////////////////////////////////////////////////////////////////////////// class ScalableSpriteData { public: ScalableSpriteData(const VaoBuilder& avao, const glm::vec2& aworld_size, const glm::vec2& aclient_size, const glm::vec2& aclient_offset) : vao(avao), world_size(aworld_size), client_size(aclient_size), client_offset(aclient_offset) {} Vao vao; glm::vec2 world_size; glm::vec2 client_size; glm::vec2 client_offset; }; //////////////////////////////////////////////////////////////////////////////// ScalableSprite::ScalableSprite(Texture2d* texture, const glm::vec2& min_size, SizeType size_type, const glm::vec2& size) : texture_(texture) , min_size_(min_size) , size_type_(size_type) , size_(size) { } ScalableSprite::~ScalableSprite() { } void ScalableSprite::SetClientSize(const glm::vec2 &new_size) { assert(this); SetSizeSub(new_size, SizeType::CLIENT); } const glm::vec2 ScalableSprite::GetClientSize() const { assert(this); if( size_type_ == SizeType::CLIENT) return size_; PrepareData(); return data_->client_size; } const glm::vec2 ScalableSprite::GetClientOffset() const { assert(this); PrepareData(); return data_->client_offset; } void ScalableSprite::SetSize(const glm::vec2 &new_size) { assert(this); SetSizeSub(new_size, SizeType::WORLD); } const glm::vec2 ScalableSprite::GetSize() const { assert(this); if( size_type_ == SizeType::WORLD) return size_; PrepareData(); return data_->world_size; } const glm::vec2 ScalableSprite::GetMinimumSize() const { assert(this); return min_size_; } const glm::vec2 ScalableSprite::GetMinimumSize(const glm::vec2& extra) const { assert(this); return glm::vec2(min_size_.x + extra.x, min_size_.y + extra.y); } const Texture2d* ScalableSprite::texture_ptr() const { assert(this); return texture_; } const Vao* ScalableSprite::vao_ptr() const { assert(this); PrepareData(); return &data_->vao; } std::pair<ScalableSprite::SizeType, glm::vec2> ScalableSprite::GetSizeData() const { return std::pair<SizeType, glm::vec2>(size_type_, size_); }; void ScalableSprite::PrepareData() const { assert(this); if( data_.get() == nullptr) { data_.reset(BuildData()); } } void ScalableSprite::SetSizeSub(const glm::vec2& new_size, SizeType type) { assert(this); if( data_.get() != nullptr && size_type_ == type && size_ == new_size) { // if we have built the data and the size & type is the same // then there's no need to rebuild it return; } size_ = new_size; size_type_ = type; data_.reset(); } //////////////////////////////////////////////////////////////////////////////// namespace { glm::vec2 DetermineSize(const glm::vec2 real_size, Rect<int> pixel_data) { return glm::vec2( real_size.x - pixel_data.GetWidth() , real_size.y - pixel_data.GetHeight()); } VaoBuilder BuildNinepatchVao(const Texture2d* texture_, const Rect<int> draw, const glm::vec2& inner_size_) { VaoBuilder data; // 00 10 20 30 // +------+-----------------+------+ // | | | | // |01 |11 |21 | 31 // +------+-----------------+------+ // | | | | // | | | | // | | | | // | | | | // | | | | // | | | | // |02 |12 |22 | 32 // +------+-----------------+------+ // | | | | // |03 |13 |23 | 33 // +------+-----------------+------+ // const float width = texture_->width(); const float height = texture_->height(); const float border_left = std::max(0, draw.left); const float border_right = std::max(0.0f, width - draw.right); const float border_top = std::max(0, draw.top); const float border_bottom = std::max(0.0f, height - draw.bottom); const float x0 = 0.0f; const float x1 = border_left; const float x2 = x1 + inner_size_.x; const float x3 = x2 + border_right; const float y0 = 0.0f; const float y1 = border_top; const float y2 = y1 + inner_size_.y; const float y3 = y2 + border_bottom; const float u0 = 0.0f; const float u1 = 0.0f + border_left / width; const float u2 = 1.0f - border_right/width; const float u3 = 1.0f; const float v0 = 0.0f; const float v1 = 0.0f + border_top / height; const float v2 = 1.0f - border_bottom / height; const float v3 = 1.0f; #define P(A, B) Point(x ## A, y ## B, u ## A, v ## B) data.quad(P(0,0), P(1,0), P(0,1), P(1,1)) .quad(P(1,0), P(2,0), P(1,1), P(2,1)) .quad(P(2,0), P(3,0), P(2,1), P(3,1)); data.quad(P(0,1), P(1,1), P(0,2), P(1,2)) .quad(P(1,1), P(2,1), P(1,2), P(2,2)) .quad(P(2,1), P(3,1), P(2,2), P(3,2)); data.quad(P(0,2), P(1,2), P(0,3), P(1,3)) .quad(P(1,2), P(2,2), P(1,3), P(2,3)) .quad(P(2,2), P(3,2), P(2,3), P(3,3)); // basic scale - like a sprite // data.quad(P(0,0), P(3,0), P(0,3), P(3,3)); #undef P return data; } } class ScalableSpriteNinepatch : public ScalableSprite { public: ScalableSpriteNinepatch(Texture2d* texture, SizeType size_type, const glm::vec2& size, const Rect<int>& da, const Rect<int>& ca) : ScalableSprite(texture, glm::vec2(ca.GetWidth(), ca.GetHeight()), size_type, size) , draw_area_(da), client_area_(ca) {} glm::vec2 DetermineRealSize() const { auto data = GetSizeData(); const auto size = data.second; switch (data.first) { case ScalableSprite::SizeType::CLIENT: return glm::vec2(size.x + client_area_.GetWidth(), size.y + client_area_.GetHeight()); case ScalableSprite::SizeType::WORLD: return size; } assert(false && "unhandled SizeType"); } bool ValidateCalculatedSize(const glm::vec2& real_size, const glm::vec2& client_size) const { auto data = GetSizeData(); const auto size = data.second; switch (data.first) { case ScalableSprite::SizeType::CLIENT: return client_size == size; case ScalableSprite::SizeType::WORLD: return real_size == size; } assert(false && "unhandled SizeType"); } ScalableSpriteData* BuildData() const override { const glm::vec2 real_size = DetermineRealSize(); const glm::vec2 draw_size = DetermineSize(real_size, draw_area_); const glm::vec2 client_size = DetermineSize(real_size, client_area_); assert(ValidateCalculatedSize(real_size, client_size)); return new ScalableSpriteData(BuildNinepatchVao(texture_ptr(), draw_area_, draw_size), real_size, client_size, glm::vec2(client_area_.left, client_area_.top)); } Rect<int> draw_area_; Rect<int> client_area_; }; //////////////////////////////////////////////////////////////////////////////// Rect<int> Convert(const scalingsprite::Rect& r) { return Rect<int>::FromLeftRightTopBottom(r.left(), r.right(), r.top(), r.bottom()); } std::shared_ptr<ScalableSprite> LoadScalableNinepatch(Texture2d* tex, ScalableSprite::SizeType size_type, glm::vec2 size, const scalingsprite::Ninepatch& data) { std::shared_ptr<ScalableSprite> ret ( new ScalableSpriteNinepatch(tex, size_type, size, Convert(data.draw()), Convert(data.client())) ); return ret; } std::shared_ptr<ScalableSprite> LoadScalableSprite(const std::string& path, const glm::vec2& size, TextureCache* cache) { Texture2d* tex = cache->GetTexture(path); const ScalableSprite::SizeType size_type = ScalableSprite::SizeType::WORLD; scalingsprite::ScalingSprite sprite; LoadProtoText(&sprite, path+".txt"); // only ninepatch supported... assert(sprite.has_ninepatch()); return LoadScalableNinepatch(tex, size_type, size, sprite.ninepatch()); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_background_scrub.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>Added p9_mss_memdiag for cronus ipl and modified scrub for step 16<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_background_scrub.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_background_scrub.H /// @brief Begin background scrub /// // *HWP HWP Owner: Matt Hickman <Matthew.Hickman@ibm.com> // *HWP FW Owner: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_BACKGROUND_SCRUB__ #define __P9_MSS_BACKGROUND_SCRUB__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_background_scrub_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>&); extern "C" { /// /// @brief Begin background scrub /// @param[in] i_target, MCBIST /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_background_scrub( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QtTest> #include <QUrl> #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpServer : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testGet_data(); void testGet(); void testPost_data(); void testPost(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoHttpServer *httpServer; }; void tst_QDjangoHttpServer::cleanupTestCase() { httpServer->close(); delete httpServer; } void tst_QDjangoHttpServer::initTestCase() { httpServer = new QDjangoHttpServer; httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); httpServer->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); } void tst_QDjangoHttpServer::testGet_data() { QTest::addColumn<QString>("path"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); const QString errorTemplate = QLatin1String( "<html>" "<head><title>Error</title></head>" "<body><p>%1</p></body>" "</html>"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)) int internalServerError = int(QNetworkReply::InternalServerError); #else int internalServerError = int(QNetworkReply::UnknownContentError); #endif QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/"); QTest::newRow("query-string") << "/?message=bar" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/|get=bar"); QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String("The document you requested was not found.")).toUtf8(); QTest::newRow("internal-server-error") << "/internal-server-error" << internalServerError << errorTemplate.arg(QLatin1String("An internal server error was encountered.")).toUtf8(); } void tst_QDjangoHttpServer::testGet() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String("http://127.0.0.1:8123") + path))); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testPost_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); QTest::newRow("empty") << "/" << QByteArray() << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/"); QTest::newRow("simple") << "/" << QByteArray("message=bar") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); QTest::newRow("multi") << "/" << QByteArray("bob=wiz&message=bar&zoo=wow") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); } void tst_QDjangoHttpServer::testPost() { QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkRequest req(QUrl(QLatin1String("http://127.0.0.1:8123") + path)); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply *reply = network.post(req, data); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoHttpServer) #include "tst_qdjangohttpserver.moc" <commit_msg>test HTTP connection close<commit_after>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QtTest> #include <QUrl> #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpServer : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testCloseConnection(); void testGet_data(); void testGet(); void testPost_data(); void testPost(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoHttpServer *httpServer; }; void tst_QDjangoHttpServer::cleanupTestCase() { httpServer->close(); delete httpServer; } void tst_QDjangoHttpServer::initTestCase() { httpServer = new QDjangoHttpServer; httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); httpServer->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); } void tst_QDjangoHttpServer::testCloseConnection() { QNetworkAccessManager network; QNetworkRequest req(QUrl("http://127.0.0.1:8123/")); req.setRawHeader("Connection", "close"); QNetworkReply *reply = network.get(req); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(reply->error(), QNetworkReply::NoError); //QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testGet_data() { QTest::addColumn<QString>("path"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); const QString errorTemplate = QLatin1String( "<html>" "<head><title>Error</title></head>" "<body><p>%1</p></body>" "</html>"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)) int internalServerError = int(QNetworkReply::InternalServerError); #else int internalServerError = int(QNetworkReply::UnknownContentError); #endif QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/"); QTest::newRow("query-string") << "/?message=bar" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/|get=bar"); QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String("The document you requested was not found.")).toUtf8(); QTest::newRow("internal-server-error") << "/internal-server-error" << internalServerError << errorTemplate.arg(QLatin1String("An internal server error was encountered.")).toUtf8(); } void tst_QDjangoHttpServer::testGet() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String("http://127.0.0.1:8123") + path))); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testPost_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); QTest::newRow("empty") << "/" << QByteArray() << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/"); QTest::newRow("simple") << "/" << QByteArray("message=bar") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); QTest::newRow("multi") << "/" << QByteArray("bob=wiz&message=bar&zoo=wow") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); } void tst_QDjangoHttpServer::testPost() { QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkRequest req(QUrl(QLatin1String("http://127.0.0.1:8123") + path)); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply *reply = network.post(req, data); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoHttpServer) #include "tst_qdjangohttpserver.moc" <|endoftext|>
<commit_before><commit_msg>Update p10152 - ShellSort.cpp<commit_after><|endoftext|>
<commit_before>/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ /*! @file cerrors.hpp * Handling C++ errors from the C API */ #ifndef HARP_CAPI_ERRORS_H #define HARP_CAPI_ERRORS_H #include <string> #include "chemharp/Logger.hpp" namespace harp { //! @brief struct to associate the values of status code to messages. struct CAPIStatus { enum { //! Everythig is OK SUCESS = 0, //! Error in the C++ standard library STD_ERROR, //! Catch all harp::Error errors GENERIC, //! Memory error: wrong pre-allocated arrays, ... MEMORY, //! File error: inexistent, can not open, ... FILE, //! Error in the C++ standard library FORMAT, //! Counter for the number of error codes. LAST, }; CAPIStatus() { messages[SUCESS] = "Operation was sucessfull"; messages[STD_ERROR] = "Error in C++ runtime. Use chrp_last_error for more informations."; messages[GENERIC] = "Error in Chemharp library. Use chrp_last_error for more informations."; messages[MEMORY] = "Memory error."; messages[FILE] = "Error while reading a file."; messages[FORMAT] = "Error while reading a format."; } /// Retrive the message corresponding to an error code. const char* message(int i) const { if (i >= 0 && i < LAST) return messages[i]; else return ""; } std::string last_error; private: const char* messages[LAST]; }; static CAPIStatus status = CAPIStatus(); #define CATCH_AND_RETURN(exception, retval) \ catch(const harp::exception& e) { \ status.last_error = string(e.what()); \ LOG(ERROR) << e.what() << std::endl; \ return retval; \ } #define CATCH_AND_GOTO(exception) \ catch(const harp::exception& e) { \ status.last_error = string(e.what()); \ LOG(ERROR) << e.what() << std::endl; \ goto error; \ } //! Wrap \c instructions in a try/catch bloc automatically, and return a status code #define CHRP_ERROR_WRAP_RETCODE(instructions) \ try { \ instructions \ } \ CATCH_AND_RETURN(FileError, CAPIStatus::FILE) \ CATCH_AND_RETURN(MemoryError, CAPIStatus::MEMORY) \ CATCH_AND_RETURN(FormatError, CAPIStatus::FORMAT) \ CATCH_AND_RETURN(Error, CAPIStatus::GENERIC) \ catch(const std::exception& e) { \ status.last_error = string(e.what()); \ return CAPIStatus::STD_ERROR; \ } \ return CAPIStatus::SUCESS; //! Wrap \c instructions in a try/catch bloc automatically, and goto the \c error //! label in case of error. #define CHRP_ERROR_WRAP(instructions) \ try { \ instructions \ } \ CATCH_AND_GOTO(FileError) \ CATCH_AND_GOTO(MemoryError) \ CATCH_AND_GOTO(FormatError) \ CATCH_AND_GOTO(Error) \ catch(const std::exception& e) { \ status.last_error = string(e.what()); \ goto error; \ } } #endif <commit_msg>Improve naming in chemharp C errors<commit_after>/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ /*! @file cerrors.hpp * Handling C++ errors from the C API */ #ifndef HARP_CAPI_ERRORS_H #define HARP_CAPI_ERRORS_H #include <string> #include "chemharp/Logger.hpp" namespace harp { //! @brief struct to associate the values of status code to messages. struct CAPIStatus { enum { //! Everythig is OK SUCESS = 0, //! Error in the C++ standard library STD_ERROR, //! Catch all harp::Error errors CHEMHARP, //! Memory error: wrong pre-allocated arrays, ... MEMORY, //! File error: inexistent, can not open, ... FILE, //! Error in file formating FORMAT, //! Counter for the number of error codes. LAST, }; CAPIStatus() { messages[SUCESS] = "Operation was sucessfull"; messages[STD_ERROR] = "Error in C++ runtime. Use chrp_last_error for more informations."; messages[CHEMHARP] = "Error in Chemharp library. Use chrp_last_error for more informations."; messages[MEMORY] = "Memory error."; messages[FILE] = "Error while reading a file."; messages[FORMAT] = "Error while reading a format."; } /// Retrive the message corresponding to an error code. const char* message(int i) const { if (i >= 0 && i < LAST) return messages[i]; else return ""; } std::string last_error; private: const char* messages[LAST]; }; static CAPIStatus status = CAPIStatus(); #define CATCH_AND_RETURN(exception, retval) \ catch(const harp::exception& e) { \ status.last_error = string(e.what()); \ LOG(ERROR) << e.what() << std::endl; \ return retval; \ } #define CATCH_AND_GOTO(exception) \ catch(const harp::exception& e) { \ status.last_error = string(e.what()); \ LOG(ERROR) << e.what() << std::endl; \ goto error; \ } //! Wrap \c instructions in a try/catch bloc automatically, and return a status code #define CHRP_ERROR_WRAP_RETCODE(instructions) \ try { \ instructions \ } \ CATCH_AND_RETURN(FileError, CAPIStatus::FILE) \ CATCH_AND_RETURN(MemoryError, CAPIStatus::MEMORY) \ CATCH_AND_RETURN(FormatError, CAPIStatus::FORMAT) \ CATCH_AND_RETURN(Error, CAPIStatus::CHEMHARP) \ catch(const std::exception& e) { \ status.last_error = string(e.what()); \ return CAPIStatus::STD_ERROR; \ } \ return CAPIStatus::SUCESS; //! Wrap \c instructions in a try/catch bloc automatically, and goto the \c error //! label in case of error. #define CHRP_ERROR_WRAP(instructions) \ try { \ instructions \ } \ CATCH_AND_GOTO(FileError) \ CATCH_AND_GOTO(MemoryError) \ CATCH_AND_GOTO(FormatError) \ CATCH_AND_GOTO(Error) \ catch(const std::exception& e) { \ status.last_error = string(e.what()); \ goto error; \ } } #endif <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include <coecntrl.h> // for CCoeControl #include <QApplication> // for QApplication::activeWindow #include <QtCore/private/qcore_symbian_p.h> // for qt_TRect2QRect #include "utils.h" #include "videooutput_dsa.h" #include "videoplayer_dsa.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; // Two-phase constructor idiom is used because construct() calls virtual // functions and therefore cannot be called from the AbstractVideoPlayer // C++ constructor. DsaVideoPlayer* DsaVideoPlayer::create(MediaObject *parent, const AbstractPlayer *player) { QScopedPointer<DsaVideoPlayer> self(new DsaVideoPlayer(parent, player)); self->construct(); return self.take(); } DsaVideoPlayer::DsaVideoPlayer(MediaObject *parent, const AbstractPlayer *player) : AbstractVideoPlayer(parent, player) , m_dsaActive(false) , m_dsaWasActive(false) { } DsaVideoPlayer::~DsaVideoPlayer() { } //----------------------------------------------------------------------------- // Public functions //----------------------------------------------------------------------------- void MMF::DsaVideoPlayer::videoWindowScreenRectChanged() { QRect windowRect = static_cast<DsaVideoOutput *>(m_videoOutput)->videoWindowScreenRect(); // Clip to physical window size // This is due to a defect in the layout when running on S60 3.2, which // results in the rectangle of the video widget extending outside the // screen in certain circumstances. These include the initial startup // of the mediaplayer demo in portrait mode. When this rectangle is // passed to the CVideoPlayerUtility, no video is rendered. const TSize screenSize = m_screenDevice.SizeInPixels(); const QRect screenRect(0, 0, screenSize.iWidth, screenSize.iHeight); windowRect = windowRect.intersected(screenRect); // Recalculate scale factors. Pass 'false' as second parameter in order to // suppress application of the change to the player - this is done at the end // of the function. updateScaleFactors(windowRect.size(), false); m_videoScreenRect = qt_QRect2TRect(windowRect); parametersChanged(WindowScreenRect | ScaleFactors); } void MMF::DsaVideoPlayer::suspendDirectScreenAccess() { m_dsaWasActive = stopDirectScreenAccess(); } void MMF::DsaVideoPlayer::resumeDirectScreenAccess() { if (m_dsaWasActive) { startDirectScreenAccess(); m_dsaWasActive = false; } } //----------------------------------------------------------------------------- // Private functions //----------------------------------------------------------------------------- void MMF::DsaVideoPlayer::createPlayer() { // A window handle must be provided in order to construct // CVideoPlayerUtility. If no VideoOutput has yet been connected to this // player, we temporarily use the top-level application window handle. // No video ever gets rendered into this window; SetDisplayWindowL is // always called before rendering actually begins. if (!m_window) m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow(); const TInt priority = 0; const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone; CVideoPlayerUtility *player = 0; QT_TRAP_THROWING(player = CVideoPlayerUtility::NewL(*this, priority, preference, m_wsSession, m_screenDevice, *m_window, m_videoScreenRect, m_videoScreenRect)); m_player.reset(player); // CVideoPlayerUtility::NewL starts DSA m_dsaActive = true; m_player->RegisterForVideoLoadingNotification(*this); } void MMF::DsaVideoPlayer::initVideoOutput() { bool connected = connect( m_videoOutput, SIGNAL(videoWindowScreenRectChanged()), this, SLOT(videoWindowScreenRectChanged()) ); Q_ASSERT(connected); connected = connect( m_videoOutput, SIGNAL(beginVideoWindowNativePaint()), this, SLOT(suspendDirectScreenAccess()) ); Q_ASSERT(connected); connected = connect( m_videoOutput, SIGNAL(endVideoWindowNativePaint()), this, SLOT(resumeDirectScreenAccess()) ); Q_ASSERT(connected); // Suppress warnings in release builds Q_UNUSED(connected); AbstractVideoPlayer::initVideoOutput(); } void MMF::DsaVideoPlayer::prepareCompleted() { videoWindowScreenRectChanged(); } void MMF::DsaVideoPlayer::handleVideoWindowChanged() { if (!m_window) { m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow(); m_videoScreenRect = TRect(); } parametersChanged(WindowHandle | WindowScreenRect); } #ifndef QT_NO_DEBUG // The following code is for debugging problems related to video visibility. It allows // the VideoPlayer instance to query the window server in order to determine the // DSA drawing region for the video window. class CDummyAO : public CActive { public: CDummyAO() : CActive(CActive::EPriorityStandard) { CActiveScheduler::Add(this); } void RunL() { } void DoCancel() { } TRequestStatus& Status() { return iStatus; } void SetActive() { CActive::SetActive(); } }; void getDsaRegion(RWsSession &session, const RWindowBase &window) { RDirectScreenAccess dsa(session); TInt err = dsa.Construct(); CDummyAO ao; RRegion* region; err = dsa.Request(region, ao.Status(), window); ao.SetActive(); dsa.Close(); ao.Cancel(); if (region) { qDebug() << "Phonon::MMF::getDsaRegion count" << region->Count(); for (int i=0; i<region->Count(); ++i) { const TRect& rect = region->RectangleList()[i]; qDebug() << "Phonon::MMF::getDsaRegion rect" << rect.iTl.iX << rect.iTl.iY << rect.iBr.iX << rect.iBr.iY; } region->Close(); } } #endif // QT_NO_DEBUG void MMF::DsaVideoPlayer::handleParametersChanged(VideoParameters parameters) { TRACE_CONTEXT(DsaVideoPlayer::handleParametersChanged, EVideoInternal); TRACE_ENTRY_0(); #ifndef QT_NO_DEBUG getDsaRegion(m_wsSession, *m_window); #endif static const TBool antialias = ETrue; int err = KErrNone; if (parameters & ScaleFactors) { TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight, antialias)); if(KErrNone != err) { TRACE("SetScaleFactorL (1) err %d", err); setError(tr("Video display error"), err); } } if (KErrNone == err) { if (parameters & WindowHandle || parameters & WindowScreenRect) { TRAP(err, m_player->SetDisplayWindowL(m_wsSession, m_screenDevice, *m_window, m_videoScreenRect, m_videoScreenRect)); } if (KErrNone != err) { TRACE("SetDisplayWindowL err %d", err); setError(tr("Video display error"), err); } else { m_dsaActive = true; if (parameters & ScaleFactors) { TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight, antialias)); if (KErrNone != err) { TRACE("SetScaleFactorL (2) err %d", err); setError(tr("Video display error"), err); } } } } TRACE_EXIT_0(); } void MMF::DsaVideoPlayer::startDirectScreenAccess() { if (!m_dsaActive) { TRAPD(err, m_player->StartDirectScreenAccessL()); if (KErrNone == err) m_dsaActive = true; else setError(tr("Video display error"), err); } } bool MMF::DsaVideoPlayer::stopDirectScreenAccess() { const bool dsaWasActive = m_dsaActive; if (m_dsaActive) { TRAPD(err, m_player->StopDirectScreenAccessL()); if (KErrNone == err) m_dsaActive = false; else setError(tr("Video display error"), err); } return dsaWasActive; } QT_END_NAMESPACE <commit_msg>Fixed crash in Phonon MMF backend during application shutdown<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include <coecntrl.h> // for CCoeControl #include <QApplication> // for QApplication::activeWindow #include <QtCore/private/qcore_symbian_p.h> // for qt_TRect2QRect #include "utils.h" #include "videooutput_dsa.h" #include "videoplayer_dsa.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; // Two-phase constructor idiom is used because construct() calls virtual // functions and therefore cannot be called from the AbstractVideoPlayer // C++ constructor. DsaVideoPlayer* DsaVideoPlayer::create(MediaObject *parent, const AbstractPlayer *player) { QScopedPointer<DsaVideoPlayer> self(new DsaVideoPlayer(parent, player)); self->construct(); return self.take(); } DsaVideoPlayer::DsaVideoPlayer(MediaObject *parent, const AbstractPlayer *player) : AbstractVideoPlayer(parent, player) , m_dsaActive(false) , m_dsaWasActive(false) { } DsaVideoPlayer::~DsaVideoPlayer() { } //----------------------------------------------------------------------------- // Public functions //----------------------------------------------------------------------------- void MMF::DsaVideoPlayer::videoWindowScreenRectChanged() { QRect windowRect = static_cast<DsaVideoOutput *>(m_videoOutput)->videoWindowScreenRect(); // Clip to physical window size // This is due to a defect in the layout when running on S60 3.2, which // results in the rectangle of the video widget extending outside the // screen in certain circumstances. These include the initial startup // of the mediaplayer demo in portrait mode. When this rectangle is // passed to the CVideoPlayerUtility, no video is rendered. const TSize screenSize = m_screenDevice.SizeInPixels(); const QRect screenRect(0, 0, screenSize.iWidth, screenSize.iHeight); windowRect = windowRect.intersected(screenRect); // Recalculate scale factors. Pass 'false' as second parameter in order to // suppress application of the change to the player - this is done at the end // of the function. updateScaleFactors(windowRect.size(), false); m_videoScreenRect = qt_QRect2TRect(windowRect); parametersChanged(WindowScreenRect | ScaleFactors); } void MMF::DsaVideoPlayer::suspendDirectScreenAccess() { m_dsaWasActive = stopDirectScreenAccess(); } void MMF::DsaVideoPlayer::resumeDirectScreenAccess() { if (m_dsaWasActive) { startDirectScreenAccess(); m_dsaWasActive = false; } } //----------------------------------------------------------------------------- // Private functions //----------------------------------------------------------------------------- void MMF::DsaVideoPlayer::createPlayer() { // A window handle must be provided in order to construct // CVideoPlayerUtility. If no VideoOutput has yet been connected to this // player, we temporarily use the top-level application window handle. // No video ever gets rendered into this window; SetDisplayWindowL is // always called before rendering actually begins. if (!m_window) m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow(); const TInt priority = 0; const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone; CVideoPlayerUtility *player = 0; QT_TRAP_THROWING(player = CVideoPlayerUtility::NewL(*this, priority, preference, m_wsSession, m_screenDevice, *m_window, m_videoScreenRect, m_videoScreenRect)); m_player.reset(player); // CVideoPlayerUtility::NewL starts DSA m_dsaActive = true; m_player->RegisterForVideoLoadingNotification(*this); } void MMF::DsaVideoPlayer::initVideoOutput() { bool connected = connect( m_videoOutput, SIGNAL(videoWindowScreenRectChanged()), this, SLOT(videoWindowScreenRectChanged()) ); Q_ASSERT(connected); connected = connect( m_videoOutput, SIGNAL(beginVideoWindowNativePaint()), this, SLOT(suspendDirectScreenAccess()) ); Q_ASSERT(connected); connected = connect( m_videoOutput, SIGNAL(endVideoWindowNativePaint()), this, SLOT(resumeDirectScreenAccess()) ); Q_ASSERT(connected); // Suppress warnings in release builds Q_UNUSED(connected); AbstractVideoPlayer::initVideoOutput(); } void MMF::DsaVideoPlayer::prepareCompleted() { videoWindowScreenRectChanged(); } void MMF::DsaVideoPlayer::handleVideoWindowChanged() { if (!m_window) { if (QWidget *window = QApplication::activeWindow()) m_window = window->effectiveWinId()->DrawableWindow(); else m_window = 0; m_videoScreenRect = TRect(); } parametersChanged(WindowHandle | WindowScreenRect); } #ifndef QT_NO_DEBUG // The following code is for debugging problems related to video visibility. It allows // the VideoPlayer instance to query the window server in order to determine the // DSA drawing region for the video window. class CDummyAO : public CActive { public: CDummyAO() : CActive(CActive::EPriorityStandard) { CActiveScheduler::Add(this); } void RunL() { } void DoCancel() { } TRequestStatus& Status() { return iStatus; } void SetActive() { CActive::SetActive(); } }; void getDsaRegion(RWsSession &session, const RWindowBase &window) { RDirectScreenAccess dsa(session); TInt err = dsa.Construct(); CDummyAO ao; RRegion* region; err = dsa.Request(region, ao.Status(), window); ao.SetActive(); dsa.Close(); ao.Cancel(); if (region) { qDebug() << "Phonon::MMF::getDsaRegion count" << region->Count(); for (int i=0; i<region->Count(); ++i) { const TRect& rect = region->RectangleList()[i]; qDebug() << "Phonon::MMF::getDsaRegion rect" << rect.iTl.iX << rect.iTl.iY << rect.iBr.iX << rect.iBr.iY; } region->Close(); } } #endif // QT_NO_DEBUG void MMF::DsaVideoPlayer::handleParametersChanged(VideoParameters parameters) { TRACE_CONTEXT(DsaVideoPlayer::handleParametersChanged, EVideoInternal); TRACE_ENTRY_0(); if (!m_window) return; #ifndef QT_NO_DEBUG getDsaRegion(m_wsSession, *m_window); #endif static const TBool antialias = ETrue; int err = KErrNone; if (parameters & ScaleFactors) { TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight, antialias)); if(KErrNone != err) { TRACE("SetScaleFactorL (1) err %d", err); setError(tr("Video display error"), err); } } if (KErrNone == err) { if (parameters & WindowHandle || parameters & WindowScreenRect) { TRAP(err, m_player->SetDisplayWindowL(m_wsSession, m_screenDevice, *m_window, m_videoScreenRect, m_videoScreenRect)); } if (KErrNone != err) { TRACE("SetDisplayWindowL err %d", err); setError(tr("Video display error"), err); } else { m_dsaActive = true; if (parameters & ScaleFactors) { TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight, antialias)); if (KErrNone != err) { TRACE("SetScaleFactorL (2) err %d", err); setError(tr("Video display error"), err); } } } } TRACE_EXIT_0(); } void MMF::DsaVideoPlayer::startDirectScreenAccess() { if (!m_dsaActive) { TRAPD(err, m_player->StartDirectScreenAccessL()); if (KErrNone == err) m_dsaActive = true; else setError(tr("Video display error"), err); } } bool MMF::DsaVideoPlayer::stopDirectScreenAccess() { const bool dsaWasActive = m_dsaActive; if (m_dsaActive) { TRAPD(err, m_player->StopDirectScreenAccessL()); if (KErrNone == err) m_dsaActive = false; else setError(tr("Video display error"), err); } return dsaWasActive; } QT_END_NAMESPACE <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/dim4.hpp> #include <af/defines.h> #include <ArrayInfo.hpp> #include <Array.hpp> #include <copy.hpp> #include <fft.hpp> #include <err_opencl.hpp> #include <clFFT.h> #include <math.hpp> #include <string> #include <cstdio> using af::dim4; using std::string; namespace opencl { #define CLFFT_ERROR_CHECK(call) do { \ clfftStatus err = (call); \ if (err!=CLFFT_SUCCESS) \ AF_ERROR("clFFT library call failed", \ AF_ERR_INTERNAL); \ } while(0); // clFFTPlanner will do very basic plan caching. // it looks for required candidate in mHandles array and returns if found one. // otherwise, it will create a plan and set it at the mAvailSlotIndex and increment // the slot index variable in ciruclar fashion 0 to MAX_PLAN_CACHE, then back to zero and repeat. class clFFTPlanner { friend void find_clfft_plan(clfftPlanHandle &plan, clfftDim rank, size_t *clLengths, size_t *istrides, size_t idist, size_t *ostrides, size_t odist, clfftPrecision precision, size_t batch); public: static clFFTPlanner& getInstance() { static clFFTPlanner single_instance; return single_instance; } ~clFFTPlanner() { clfftTeardown(); } private: clFFTPlanner() : mAvailSlotIndex(0) { clfftInitSetupData(&fftSetup); clfftSetup(&fftSetup); for(int p=0; p<MAX_PLAN_CACHE; ++p) mHandles[p] = 0; } clFFTPlanner(clFFTPlanner const&); void operator=(clFFTPlanner const&); static const int MAX_PLAN_CACHE = 5; int mAvailSlotIndex; string mKeys[MAX_PLAN_CACHE]; clfftPlanHandle mHandles[MAX_PLAN_CACHE]; clfftSetupData fftSetup; }; void find_clfft_plan(clfftPlanHandle &plan, clfftDim rank, size_t *clLengths, size_t *istrides, size_t idist, size_t *ostrides, size_t odist, clfftPrecision precision, size_t batch) { clFFTPlanner &planner = clFFTPlanner::getInstance(); // create the key string char key_str_temp[64]; sprintf(key_str_temp, "%d:", rank); string key_string(key_str_temp); for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", clLengths[r]); key_string.append(std::string(key_str_temp)); } if(istrides!=NULL) { for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", istrides[r]); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%zu:", idist); key_string.append(std::string(key_str_temp)); } if (ostrides!=NULL) { for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", ostrides[r]); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%zu:", odist); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%d:%zu", (int)precision, batch); key_string.append(std::string(key_str_temp)); // find the matching plan_index in the array clFFTPlanner::mKeys int plan_index = -1; for (int i=0; i<clFFTPlanner::MAX_PLAN_CACHE; ++i) { if (key_string==planner.mKeys[i]) { plan_index = i; break; } } // return mHandles[plan_index] if plan_index valid if (plan_index!=-1) { plan = planner.mHandles[plan_index]; return; } // otherwise create a new plan and set it at mAvailSlotIndex // and finally set it to output plan variable int slot_index = planner.mAvailSlotIndex; clfftStatus res = CLFFT_SUCCESS; if (planner.mHandles[slot_index]) { res = clfftDestroyPlan(&planner.mHandles[slot_index]); planner.mHandles[slot_index] = 0; } if (res==CLFFT_SUCCESS) { clfftPlanHandle temp; // getContext() returns object of type Context // Context() returns the actual cl_context handle clfftStatus res = clfftCreateDefaultPlan(&temp, getContext()(), rank, clLengths); switch(res) { case CLFFT_INVALID_CONTEXT : AF_ERROR("clFFT: invalid context ", AF_ERR_INTERNAL); case CLFFT_INVALID_PLATFORM : AF_ERROR("clFFT: invalid platform ", AF_ERR_INTERNAL); case CLFFT_OUT_OF_HOST_MEMORY: AF_ERROR("clFFT: out of host memory", AF_ERR_INTERNAL); case CLFFT_OUT_OF_RESOURCES : AF_ERROR("clFFT: out of resources ", AF_ERR_INTERNAL); case CLFFT_MEM_OBJECT_ALLOCATION_FAILURE: AF_ERROR("clFFT: mem object allocation failure", AF_ERR_INTERNAL); case CLFFT_NOTIMPLEMENTED : AF_ERROR("clFFt: feature not implemented", AF_ERR_INTERNAL); case CLFFT_SUCCESS: { res = clfftSetLayout(temp, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED); res = clfftSetPlanBatchSize(temp, batch); res = clfftSetPlanDistance(temp, idist, odist); res = clfftSetPlanInStride(temp, rank, istrides); res = clfftSetPlanOutStride(temp, rank, ostrides); res = clfftSetPlanPrecision(temp, precision); res = clfftSetResultLocation(temp, CLFFT_INPLACE); // getQueue() returns object of type CommandQueue // CommandQueue() returns the actual cl_command_queue handle res = clfftBakePlan(temp, 1, &(getQueue()()), NULL, NULL); plan = temp; planner.mHandles[slot_index] = temp; planner.mKeys[slot_index] = key_string; planner.mAvailSlotIndex = (slot_index + 1)%clFFTPlanner::MAX_PLAN_CACHE; } break; default: AF_ERROR("clFFT: unkown error", AF_ERR_INTERNAL); } } else AF_ERROR("clFFTDestroyPlan call failed", AF_ERR_INTERNAL); } template<typename T> struct Precision; template<> struct Precision<cfloat > { enum {type = CLFFT_SINGLE}; }; template<> struct Precision<cdouble> { enum {type = CLFFT_DOUBLE}; }; template<typename T, int rank, clfftDirection direction> void clfft_common(Array<T> &arr) { const dim4 dims = arr.dims(); const dim4 strides = arr.strides(); size_t io_strides[]= {(size_t)strides[0], (size_t)strides[1], (size_t)strides[2], (size_t)strides[3]}; size_t rank_dims[3] = {(size_t)dims[0], (size_t)dims[1], (size_t)dims[2]}; clfftPlanHandle plan; find_clfft_plan(plan, (clfftDim)rank, rank_dims, io_strides, io_strides[rank], io_strides, io_strides[rank], (clfftPrecision)Precision<T>::type, dims[rank]); CLFFT_ERROR_CHECK( clfftEnqueueTransform(plan, direction, 1, &(getQueue()()), 0, NULL, NULL, &((*arr.get())()), NULL, NULL) ); } template<int rank> void computePaddedDims(dim4 &pdims, dim_type const * const pad) { if (rank==1) { pdims[0] = pad[0]; } else if (rank==2) { pdims[0] = pad[0]; pdims[1] = pad[1]; } else if (rank==3) { pdims[0] = pad[0]; pdims[1] = pad[1]; pdims[2] = pad[2]; } } //(currently) true is in clFFT if length is a power of 2,3,5 inline bool isSupLen(dim_type length) { while( length > 1 ) { if( length % 2 == 0 ) length /= 2; else if( length % 3 == 0 ) length /= 3; else if( length % 5 == 0 ) length /= 5; else return false; } return true; } template<typename inType, typename outType, int rank, bool isR2C> Array<outType> fft(Array<inType> const &in, double norm_factor, dim_type const npad, dim_type const * const pad) { ARG_ASSERT(1, (in.isOwner()==true)); ARG_ASSERT(1, (rank>=1 && rank<=3)); dim4 dims = in.dims(); dim4 pdims(1); computePaddedDims<rank>(pdims, pad); pdims[rank] = in.dims()[rank]; if (npad>0) dims = pdims; switch(rank) { case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break; case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break; case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break; default: AF_ERROR("invalid input dimensions", AF_ERR_SIZE); } Array<outType> ret = padArray<inType, outType>(in, dims, scalar<outType>(0), norm_factor); clfft_common<outType, rank, CLFFT_FORWARD>(ret); return ret; } template<typename T, int rank> Array<T> ifft(Array<T> const &in, double norm_factor, dim_type const npad, dim_type const * const pad) { ARG_ASSERT(1, (in.isOwner()==true)); ARG_ASSERT(1, (rank>=1 && rank<=3)); dim4 dims = in.dims(); dim4 pdims(1); computePaddedDims<rank>(pdims, pad); pdims[rank] = in.dims()[rank]; if (npad>0) dims = pdims; // the input norm_factor is further scaled // based on the input dimensions to match // cuFFT behavior for (int i=0; i<rank; i++) norm_factor *= dims[i]; switch(rank) { case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break; case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break; case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break; default: AF_ERROR("invalid input dimensions", AF_ERR_SIZE); } Array<T> ret = padArray<T, T>(in, dims, scalar<T>(0), norm_factor); clfft_common<T, rank, CLFFT_BACKWARD>(ret); return ret; } #define INSTANTIATE1(T1, T2)\ template Array<T2> fft <T1, T2, 1, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T2> fft <T1, T2, 2, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T2> fft <T1, T2, 3, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); INSTANTIATE1(float , cfloat ) INSTANTIATE1(double , cdouble) #define INSTANTIATE2(T)\ template Array<T> fft <T, T, 1, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> fft <T, T, 2, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> fft <T, T, 3, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 1>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 2>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 3>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); INSTANTIATE2(cfloat ) INSTANTIATE2(cdouble) } <commit_msg>Call garbageCollect() when CLFFT plan creation fails and try again<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/dim4.hpp> #include <af/defines.h> #include <ArrayInfo.hpp> #include <Array.hpp> #include <copy.hpp> #include <fft.hpp> #include <err_opencl.hpp> #include <clFFT.h> #include <math.hpp> #include <string> #include <cstdio> #include <memory.hpp> using af::dim4; using std::string; namespace opencl { static void CLFFT_ERROR(clfftStatus err) { switch(err) { case CLFFT_INVALID_CONTEXT : AF_ERROR("clFFT: invalid context ", AF_ERR_INTERNAL); case CLFFT_INVALID_PLATFORM : AF_ERROR("clFFT: invalid platform ", AF_ERR_INTERNAL); case CLFFT_OUT_OF_HOST_MEMORY: AF_ERROR("clFFT: out of host memory", AF_ERR_INTERNAL); case CLFFT_OUT_OF_RESOURCES : AF_ERROR("clFFT: out of resources ", AF_ERR_INTERNAL); case CLFFT_MEM_OBJECT_ALLOCATION_FAILURE: AF_ERROR("clFFT: mem object allocation failure", AF_ERR_INTERNAL); case CLFFT_NOTIMPLEMENTED : AF_ERROR("clFFt: feature not implemented", AF_ERR_INTERNAL); case CLFFT_SUCCESS: return; default: AF_ERROR("clFFT: unkown error", AF_ERR_INTERNAL); } } #define CLFFT_CHECK(call) do { \ clfftStatus err = (call); \ if (err!=CLFFT_SUCCESS) { \ garbageCollect(); \ err = (call); \ } \ if (err != CLFFT_SUCCESS) CLFFT_ERROR(err); \ } while(0) // clFFTPlanner will do very basic plan caching. // it looks for required candidate in mHandles array and returns if found one. // otherwise, it will create a plan and set it at the mAvailSlotIndex and increment // the slot index variable in ciruclar fashion 0 to MAX_PLAN_CACHE, then back to zero and repeat. class clFFTPlanner { friend void find_clfft_plan(clfftPlanHandle &plan, clfftDim rank, size_t *clLengths, size_t *istrides, size_t idist, size_t *ostrides, size_t odist, clfftPrecision precision, size_t batch); public: static clFFTPlanner& getInstance() { static clFFTPlanner single_instance; return single_instance; } ~clFFTPlanner() { clfftTeardown(); } private: clFFTPlanner() : mAvailSlotIndex(0) { clfftInitSetupData(&fftSetup); clfftSetup(&fftSetup); for(int p=0; p<MAX_PLAN_CACHE; ++p) mHandles[p] = 0; } clFFTPlanner(clFFTPlanner const&); void operator=(clFFTPlanner const&); static const int MAX_PLAN_CACHE = 5; int mAvailSlotIndex; string mKeys[MAX_PLAN_CACHE]; clfftPlanHandle mHandles[MAX_PLAN_CACHE]; clfftSetupData fftSetup; }; void find_clfft_plan(clfftPlanHandle &plan, clfftDim rank, size_t *clLengths, size_t *istrides, size_t idist, size_t *ostrides, size_t odist, clfftPrecision precision, size_t batch) { clFFTPlanner &planner = clFFTPlanner::getInstance(); // create the key string char key_str_temp[64]; sprintf(key_str_temp, "%d:", rank); string key_string(key_str_temp); for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", clLengths[r]); key_string.append(std::string(key_str_temp)); } if(istrides!=NULL) { for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", istrides[r]); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%zu:", idist); key_string.append(std::string(key_str_temp)); } if (ostrides!=NULL) { for(int r=0; r<rank; ++r) { sprintf(key_str_temp, "%zu:", ostrides[r]); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%zu:", odist); key_string.append(std::string(key_str_temp)); } sprintf(key_str_temp, "%d:%zu", (int)precision, batch); key_string.append(std::string(key_str_temp)); // find the matching plan_index in the array clFFTPlanner::mKeys int plan_index = -1; for (int i=0; i<clFFTPlanner::MAX_PLAN_CACHE; ++i) { if (key_string==planner.mKeys[i]) { plan_index = i; break; } } // return mHandles[plan_index] if plan_index valid if (plan_index!=-1) { plan = planner.mHandles[plan_index]; return; } // otherwise create a new plan and set it at mAvailSlotIndex // and finally set it to output plan variable int slot_index = planner.mAvailSlotIndex; if (planner.mHandles[slot_index]) { CLFFT_CHECK(clfftDestroyPlan(&planner.mHandles[slot_index])); planner.mHandles[slot_index] = 0; } clfftPlanHandle temp; // getContext() returns object of type Context // Context() returns the actual cl_context handle CLFFT_CHECK(clfftCreateDefaultPlan(&temp, getContext()(), rank, clLengths)); CLFFT_CHECK(clfftSetLayout(temp, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED)); CLFFT_CHECK(clfftSetPlanBatchSize(temp, batch)); CLFFT_CHECK(clfftSetPlanDistance(temp, idist, odist)); CLFFT_CHECK(clfftSetPlanInStride(temp, rank, istrides)); CLFFT_CHECK(clfftSetPlanOutStride(temp, rank, ostrides)); CLFFT_CHECK(clfftSetPlanPrecision(temp, precision)); CLFFT_CHECK(clfftSetResultLocation(temp, CLFFT_INPLACE)); // getQueue() returns object of type CommandQueue // CommandQueue() returns the actual cl_command_queue handle CLFFT_CHECK(clfftBakePlan(temp, 1, &(getQueue()()), NULL, NULL)); plan = temp; planner.mHandles[slot_index] = temp; planner.mKeys[slot_index] = key_string; planner.mAvailSlotIndex = (slot_index + 1)%clFFTPlanner::MAX_PLAN_CACHE; } template<typename T> struct Precision; template<> struct Precision<cfloat > { enum {type = CLFFT_SINGLE}; }; template<> struct Precision<cdouble> { enum {type = CLFFT_DOUBLE}; }; template<typename T, int rank, clfftDirection direction> void clfft_common(Array<T> &arr) { const dim4 dims = arr.dims(); const dim4 strides = arr.strides(); size_t io_strides[]= {(size_t)strides[0], (size_t)strides[1], (size_t)strides[2], (size_t)strides[3]}; size_t rank_dims[3] = {(size_t)dims[0], (size_t)dims[1], (size_t)dims[2]}; clfftPlanHandle plan; find_clfft_plan(plan, (clfftDim)rank, rank_dims, io_strides, io_strides[rank], io_strides, io_strides[rank], (clfftPrecision)Precision<T>::type, dims[rank]); CLFFT_CHECK( clfftEnqueueTransform(plan, direction, 1, &(getQueue()()), 0, NULL, NULL, &((*arr.get())()), NULL, NULL) ); } template<int rank> void computePaddedDims(dim4 &pdims, dim_type const * const pad) { if (rank==1) { pdims[0] = pad[0]; } else if (rank==2) { pdims[0] = pad[0]; pdims[1] = pad[1]; } else if (rank==3) { pdims[0] = pad[0]; pdims[1] = pad[1]; pdims[2] = pad[2]; } } //(currently) true is in clFFT if length is a power of 2,3,5 inline bool isSupLen(dim_type length) { while( length > 1 ) { if( length % 2 == 0 ) length /= 2; else if( length % 3 == 0 ) length /= 3; else if( length % 5 == 0 ) length /= 5; else return false; } return true; } template<typename inType, typename outType, int rank, bool isR2C> Array<outType> fft(Array<inType> const &in, double norm_factor, dim_type const npad, dim_type const * const pad) { ARG_ASSERT(1, (in.isOwner()==true)); ARG_ASSERT(1, (rank>=1 && rank<=3)); dim4 dims = in.dims(); dim4 pdims(1); computePaddedDims<rank>(pdims, pad); pdims[rank] = in.dims()[rank]; if (npad>0) dims = pdims; switch(rank) { case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break; case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break; case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break; default: AF_ERROR("invalid input dimensions", AF_ERR_SIZE); } Array<outType> ret = padArray<inType, outType>(in, dims, scalar<outType>(0), norm_factor); clfft_common<outType, rank, CLFFT_FORWARD>(ret); return ret; } template<typename T, int rank> Array<T> ifft(Array<T> const &in, double norm_factor, dim_type const npad, dim_type const * const pad) { ARG_ASSERT(1, (in.isOwner()==true)); ARG_ASSERT(1, (rank>=1 && rank<=3)); dim4 dims = in.dims(); dim4 pdims(1); computePaddedDims<rank>(pdims, pad); pdims[rank] = in.dims()[rank]; if (npad>0) dims = pdims; // the input norm_factor is further scaled // based on the input dimensions to match // cuFFT behavior for (int i=0; i<rank; i++) norm_factor *= dims[i]; switch(rank) { case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break; case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break; case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break; default: AF_ERROR("invalid input dimensions", AF_ERR_SIZE); } Array<T> ret = padArray<T, T>(in, dims, scalar<T>(0), norm_factor); clfft_common<T, rank, CLFFT_BACKWARD>(ret); return ret; } #define INSTANTIATE1(T1, T2)\ template Array<T2> fft <T1, T2, 1, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T2> fft <T1, T2, 2, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T2> fft <T1, T2, 3, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); INSTANTIATE1(float , cfloat ) INSTANTIATE1(double , cdouble) #define INSTANTIATE2(T)\ template Array<T> fft <T, T, 1, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> fft <T, T, 2, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> fft <T, T, 3, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 1>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 2>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \ template Array<T> ifft<T, 3>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); INSTANTIATE2(cfloat ) INSTANTIATE2(cdouble) } <|endoftext|>
<commit_before>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <babylon/babylon_stl_util.h> #include <babylon/engines/null_engine.h> #include <babylon/engines/scene.h> #include <babylon/meshes/buffer.h> #include <babylon/meshes/geometry.h> #include <babylon/meshes/vertex_buffer.h> std::unique_ptr<BABYLON::Engine> createSubject() { using namespace BABYLON; NullEngineOptions options; options.renderHeight = 256; options.renderWidth = 256; options.textureSize = 256; options.deterministicLockstep = false; options.lockstepMaxSteps = 1; return NullEngine::New(options); } TEST(TestGeometry, TestVec3FloatColor) { using namespace BABYLON; // vec3 float color tightly packed auto subject = createSubject(); auto scene = Scene::New(subject.get()); Float32Array data{0.4f, 0.4f, 0.4f, 0.6f, 0.6f, 0.6f, 0.8f, 0.8f, 0.8f, 1.f, 1.f, 1.f}; auto buffer = std::make_unique<Buffer>(subject.get(), data, false); auto vertexBuffer = std::make_shared<VertexBuffer>( subject.get(), buffer.get(), VertexBuffer::ColorKind, false, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 3); auto geometry = Geometry::New("geometry1", scene.get()); geometry->setVerticesBuffer(vertexBuffer); IndicesArray indices{0u, 1u, 2u, 3u}; geometry->setIndices(indices, 4); auto result = geometry->getVerticesData(VertexBuffer::ColorKind); EXPECT_THAT(result, ::testing::ContainerEq(data)); } <commit_msg>Updated Geometry unit test name<commit_after>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <babylon/babylon_stl_util.h> #include <babylon/engines/null_engine.h> #include <babylon/engines/scene.h> #include <babylon/meshes/buffer.h> #include <babylon/meshes/geometry.h> #include <babylon/meshes/vertex_buffer.h> /** * @brief Create a new engine subject before each test. */ std::unique_ptr<BABYLON::Engine> createSubject() { using namespace BABYLON; NullEngineOptions options; options.renderHeight = 256; options.renderWidth = 256; options.textureSize = 256; options.deterministicLockstep = false; options.lockstepMaxSteps = 1; return NullEngine::New(options); } TEST(TestGeometry, TestGetVerticesData_Vec3FloatColor) { using namespace BABYLON; // vec3 float color tightly packed auto subject = createSubject(); auto scene = Scene::New(subject.get()); Float32Array data{0.4f, 0.4f, 0.4f, 0.6f, 0.6f, 0.6f, 0.8f, 0.8f, 0.8f, 1.f, 1.f, 1.f}; auto buffer = std::make_unique<Buffer>(subject.get(), data, false); auto vertexBuffer = std::make_shared<VertexBuffer>( subject.get(), buffer.get(), VertexBuffer::ColorKind, false, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 3); auto geometry = Geometry::New("geometry1", scene.get()); geometry->setVerticesBuffer(vertexBuffer); IndicesArray indices{0u, 1u, 2u, 3u}; geometry->setIndices(indices, 4); auto result = geometry->getVerticesData(VertexBuffer::ColorKind); EXPECT_THAT(result, ::testing::ContainerEq(data)); } <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkErrorInternals.h" #include "SkValidatingReadBuffer.h" #include "SkStream.h" #include "SkTypeface.h" SkValidatingReadBuffer::SkValidatingReadBuffer(const void* data, size_t size) : fError(false) { this->setMemory(data, size); this->setFlags(SkReadBuffer::kValidation_Flag); } SkValidatingReadBuffer::~SkValidatingReadBuffer() { } bool SkValidatingReadBuffer::validate(bool isValid) { if (!fError && !isValid) { // When an error is found, send the read cursor to the end of the stream fReader.skip(fReader.available()); fError = true; } return !fError; } bool SkValidatingReadBuffer::isValid() const { return !fError; } void SkValidatingReadBuffer::setMemory(const void* data, size_t size) { this->validate(IsPtrAlign4(data) && (SkAlign4(size) == size)); if (!fError) { fReader.setMemory(data, size); } } const void* SkValidatingReadBuffer::skip(size_t size) { size_t inc = SkAlign4(size); const void* addr = fReader.peek(); this->validate(IsPtrAlign4(addr) && fReader.isAvailable(inc)); if (!fError) { fReader.skip(size); } return addr; } // All the methods in this file funnel down into either readInt(), readScalar() or skip(), // followed by a memcpy. So we've got all our validation in readInt(), readScalar() and skip(); // if they fail they'll return a zero value or skip nothing, respectively, and set fError to // true, which the caller should check to see if an error occurred during the read operation. bool SkValidatingReadBuffer::readBool() { uint32_t value = this->readInt(); // Boolean value should be either 0 or 1 this->validate(!(value & ~1)); return value != 0; } SkColor SkValidatingReadBuffer::readColor() { return this->readInt(); } SkFixed SkValidatingReadBuffer::readFixed() { return this->readInt(); } int32_t SkValidatingReadBuffer::readInt() { const size_t inc = sizeof(int32_t); this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc)); return fError ? 0 : fReader.readInt(); } SkScalar SkValidatingReadBuffer::readScalar() { const size_t inc = sizeof(SkScalar); this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc)); return fError ? 0 : fReader.readScalar(); } uint32_t SkValidatingReadBuffer::readUInt() { return this->readInt(); } int32_t SkValidatingReadBuffer::read32() { return this->readInt(); } void SkValidatingReadBuffer::readString(SkString* string) { const size_t len = this->readUInt(); const void* ptr = fReader.peek(); const char* cptr = (const char*)ptr; // skip over the string + '\0' and then pad to a multiple of 4 const size_t alignedSize = SkAlign4(len + 1); this->skip(alignedSize); if (!fError) { this->validate(cptr[len] == '\0'); } if (!fError) { string->set(cptr, len); } } void* SkValidatingReadBuffer::readEncodedString(size_t* length, SkPaint::TextEncoding encoding) { const int32_t encodingType = this->readInt(); this->validate(encodingType == encoding); *length = this->readInt(); const void* ptr = this->skip(SkAlign4(*length)); void* data = nullptr; if (!fError) { data = sk_malloc_throw(*length); memcpy(data, ptr, *length); } return data; } void SkValidatingReadBuffer::readPoint(SkPoint* point) { point->fX = this->readScalar(); point->fY = this->readScalar(); } void SkValidatingReadBuffer::readMatrix(SkMatrix* matrix) { size_t size = 0; if (!fError) { size = matrix->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } void SkValidatingReadBuffer::readIRect(SkIRect* rect) { const void* ptr = this->skip(sizeof(SkIRect)); if (!fError) { memcpy(rect, ptr, sizeof(SkIRect)); } } void SkValidatingReadBuffer::readRect(SkRect* rect) { const void* ptr = this->skip(sizeof(SkRect)); if (!fError) { memcpy(rect, ptr, sizeof(SkRect)); } } void SkValidatingReadBuffer::readRegion(SkRegion* region) { size_t size = 0; if (!fError) { size = region->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } void SkValidatingReadBuffer::readPath(SkPath* path) { size_t size = 0; if (!fError) { size = path->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } bool SkValidatingReadBuffer::readArray(void* value, size_t size, size_t elementSize) { const uint32_t count = this->getArrayCount(); this->validate(size == count); (void)this->skip(sizeof(uint32_t)); // Skip array count const uint64_t byteLength64 = sk_64_mul(count, elementSize); const size_t byteLength = count * elementSize; this->validate(byteLength == byteLength64); const void* ptr = this->skip(SkAlign4(byteLength)); if (!fError) { memcpy(value, ptr, byteLength); return true; } return false; } bool SkValidatingReadBuffer::readByteArray(void* value, size_t size) { return readArray(static_cast<unsigned char*>(value), size, sizeof(unsigned char)); } bool SkValidatingReadBuffer::readColorArray(SkColor* colors, size_t size) { return readArray(colors, size, sizeof(SkColor)); } bool SkValidatingReadBuffer::readIntArray(int32_t* values, size_t size) { return readArray(values, size, sizeof(int32_t)); } bool SkValidatingReadBuffer::readPointArray(SkPoint* points, size_t size) { return readArray(points, size, sizeof(SkPoint)); } bool SkValidatingReadBuffer::readScalarArray(SkScalar* values, size_t size) { return readArray(values, size, sizeof(SkScalar)); } uint32_t SkValidatingReadBuffer::getArrayCount() { const size_t inc = sizeof(uint32_t); fError = fError || !IsPtrAlign4(fReader.peek()) || !fReader.isAvailable(inc); return fError ? 0 : *(uint32_t*)fReader.peek(); } SkTypeface* SkValidatingReadBuffer::readTypeface() { // TODO: Implement this (securely) when needed return nullptr; } bool SkValidatingReadBuffer::validateAvailable(size_t size) { return this->validate((size <= SK_MaxU32) && fReader.isAvailable(static_cast<uint32_t>(size))); } SkFlattenable* SkValidatingReadBuffer::readFlattenable(SkFlattenable::Type type) { SkString name; this->readString(&name); if (fError) { return nullptr; } // Is this the type we wanted ? const char* cname = name.c_str(); SkFlattenable::Type baseType; if (!SkFlattenable::NameToType(cname, &baseType) || (baseType != type)) { return nullptr; } SkFlattenable::Factory factory = SkFlattenable::NameToFactory(cname); if (nullptr == factory) { return nullptr; // writer failed to give us the flattenable } // if we get here, factory may still be null, but if that is the case, the // failure was ours, not the writer. SkFlattenable* obj = nullptr; uint32_t sizeRecorded = this->readUInt(); if (factory) { size_t offset = fReader.offset(); obj = (*factory)(*this); // check that we read the amount we expected size_t sizeRead = fReader.offset() - offset; this->validate(sizeRecorded == sizeRead); if (fError) { // we could try to fix up the offset... SkSafeUnref(obj); obj = nullptr; } } else { // we must skip the remaining data this->skip(sizeRecorded); SkASSERT(false); } return obj; } void SkValidatingReadBuffer::skipFlattenable() { SkString name; this->readString(&name); if (fError) { return; } uint32_t sizeRecorded = this->readUInt(); this->skip(sizeRecorded); } <commit_msg>SkValidatingReadBuffer: make sure we don't call readTypeface().<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkErrorInternals.h" #include "SkValidatingReadBuffer.h" #include "SkStream.h" #include "SkTypeface.h" SkValidatingReadBuffer::SkValidatingReadBuffer(const void* data, size_t size) : fError(false) { this->setMemory(data, size); this->setFlags(SkReadBuffer::kValidation_Flag); } SkValidatingReadBuffer::~SkValidatingReadBuffer() { } bool SkValidatingReadBuffer::validate(bool isValid) { if (!fError && !isValid) { // When an error is found, send the read cursor to the end of the stream fReader.skip(fReader.available()); fError = true; } return !fError; } bool SkValidatingReadBuffer::isValid() const { return !fError; } void SkValidatingReadBuffer::setMemory(const void* data, size_t size) { this->validate(IsPtrAlign4(data) && (SkAlign4(size) == size)); if (!fError) { fReader.setMemory(data, size); } } const void* SkValidatingReadBuffer::skip(size_t size) { size_t inc = SkAlign4(size); const void* addr = fReader.peek(); this->validate(IsPtrAlign4(addr) && fReader.isAvailable(inc)); if (!fError) { fReader.skip(size); } return addr; } // All the methods in this file funnel down into either readInt(), readScalar() or skip(), // followed by a memcpy. So we've got all our validation in readInt(), readScalar() and skip(); // if they fail they'll return a zero value or skip nothing, respectively, and set fError to // true, which the caller should check to see if an error occurred during the read operation. bool SkValidatingReadBuffer::readBool() { uint32_t value = this->readInt(); // Boolean value should be either 0 or 1 this->validate(!(value & ~1)); return value != 0; } SkColor SkValidatingReadBuffer::readColor() { return this->readInt(); } SkFixed SkValidatingReadBuffer::readFixed() { return this->readInt(); } int32_t SkValidatingReadBuffer::readInt() { const size_t inc = sizeof(int32_t); this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc)); return fError ? 0 : fReader.readInt(); } SkScalar SkValidatingReadBuffer::readScalar() { const size_t inc = sizeof(SkScalar); this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc)); return fError ? 0 : fReader.readScalar(); } uint32_t SkValidatingReadBuffer::readUInt() { return this->readInt(); } int32_t SkValidatingReadBuffer::read32() { return this->readInt(); } void SkValidatingReadBuffer::readString(SkString* string) { const size_t len = this->readUInt(); const void* ptr = fReader.peek(); const char* cptr = (const char*)ptr; // skip over the string + '\0' and then pad to a multiple of 4 const size_t alignedSize = SkAlign4(len + 1); this->skip(alignedSize); if (!fError) { this->validate(cptr[len] == '\0'); } if (!fError) { string->set(cptr, len); } } void* SkValidatingReadBuffer::readEncodedString(size_t* length, SkPaint::TextEncoding encoding) { const int32_t encodingType = this->readInt(); this->validate(encodingType == encoding); *length = this->readInt(); const void* ptr = this->skip(SkAlign4(*length)); void* data = nullptr; if (!fError) { data = sk_malloc_throw(*length); memcpy(data, ptr, *length); } return data; } void SkValidatingReadBuffer::readPoint(SkPoint* point) { point->fX = this->readScalar(); point->fY = this->readScalar(); } void SkValidatingReadBuffer::readMatrix(SkMatrix* matrix) { size_t size = 0; if (!fError) { size = matrix->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } void SkValidatingReadBuffer::readIRect(SkIRect* rect) { const void* ptr = this->skip(sizeof(SkIRect)); if (!fError) { memcpy(rect, ptr, sizeof(SkIRect)); } } void SkValidatingReadBuffer::readRect(SkRect* rect) { const void* ptr = this->skip(sizeof(SkRect)); if (!fError) { memcpy(rect, ptr, sizeof(SkRect)); } } void SkValidatingReadBuffer::readRegion(SkRegion* region) { size_t size = 0; if (!fError) { size = region->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } void SkValidatingReadBuffer::readPath(SkPath* path) { size_t size = 0; if (!fError) { size = path->readFromMemory(fReader.peek(), fReader.available()); this->validate((SkAlign4(size) == size) && (0 != size)); } if (!fError) { (void)this->skip(size); } } bool SkValidatingReadBuffer::readArray(void* value, size_t size, size_t elementSize) { const uint32_t count = this->getArrayCount(); this->validate(size == count); (void)this->skip(sizeof(uint32_t)); // Skip array count const uint64_t byteLength64 = sk_64_mul(count, elementSize); const size_t byteLength = count * elementSize; this->validate(byteLength == byteLength64); const void* ptr = this->skip(SkAlign4(byteLength)); if (!fError) { memcpy(value, ptr, byteLength); return true; } return false; } bool SkValidatingReadBuffer::readByteArray(void* value, size_t size) { return readArray(static_cast<unsigned char*>(value), size, sizeof(unsigned char)); } bool SkValidatingReadBuffer::readColorArray(SkColor* colors, size_t size) { return readArray(colors, size, sizeof(SkColor)); } bool SkValidatingReadBuffer::readIntArray(int32_t* values, size_t size) { return readArray(values, size, sizeof(int32_t)); } bool SkValidatingReadBuffer::readPointArray(SkPoint* points, size_t size) { return readArray(points, size, sizeof(SkPoint)); } bool SkValidatingReadBuffer::readScalarArray(SkScalar* values, size_t size) { return readArray(values, size, sizeof(SkScalar)); } uint32_t SkValidatingReadBuffer::getArrayCount() { const size_t inc = sizeof(uint32_t); fError = fError || !IsPtrAlign4(fReader.peek()) || !fReader.isAvailable(inc); return fError ? 0 : *(uint32_t*)fReader.peek(); } SkTypeface* SkValidatingReadBuffer::readTypeface() { SkASSERT(false); // TODO: Implement this (securely) when needed return nullptr; } bool SkValidatingReadBuffer::validateAvailable(size_t size) { return this->validate((size <= SK_MaxU32) && fReader.isAvailable(static_cast<uint32_t>(size))); } SkFlattenable* SkValidatingReadBuffer::readFlattenable(SkFlattenable::Type type) { SkString name; this->readString(&name); if (fError) { return nullptr; } // Is this the type we wanted ? const char* cname = name.c_str(); SkFlattenable::Type baseType; if (!SkFlattenable::NameToType(cname, &baseType) || (baseType != type)) { return nullptr; } SkFlattenable::Factory factory = SkFlattenable::NameToFactory(cname); if (nullptr == factory) { return nullptr; // writer failed to give us the flattenable } // if we get here, factory may still be null, but if that is the case, the // failure was ours, not the writer. SkFlattenable* obj = nullptr; uint32_t sizeRecorded = this->readUInt(); if (factory) { size_t offset = fReader.offset(); obj = (*factory)(*this); // check that we read the amount we expected size_t sizeRead = fReader.offset() - offset; this->validate(sizeRecorded == sizeRead); if (fError) { // we could try to fix up the offset... SkSafeUnref(obj); obj = nullptr; } } else { // we must skip the remaining data this->skip(sizeRecorded); SkASSERT(false); } return obj; } void SkValidatingReadBuffer::skipFlattenable() { SkString name; this->readString(&name); if (fError) { return; } uint32_t sizeRecorded = this->readUInt(); this->skip(sizeRecorded); } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/commandlineparser.h> namespace inviwo { CommandLineParser::CommandLineParser() : CommandLineParser(0, nullptr) {} CommandLineParser::CommandLineParser(int argc, char** argv) : argc_(argc) , argv_(argv) , cmdQuiet_( "Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for " "interactive visualizations", ' ', IVW_VERSION, false) , cmd_( "Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for " "interactive visualizations", ' ', IVW_VERSION) , workspace_("w", "workspace", "Specify workspace to open", false, "", "workspace file") , outputPath_("o", "output", "Specify output path", false, "", "output path") , logfile_("l", "logfile", "Write log messages to file.", false, "", "logfile") , noSplashScreen_("n", "nosplash", "Pass this flag if you do not want to show a splash screen.") , quitAfterStartup_("q", "quit", "Pass this flag if you want to close inviwo after startup.") , wildcard_() , helpQuiet_("h", "help", "") , versionQuiet_("v", "version", "") { cmdQuiet_.add(workspace_); cmdQuiet_.add(outputPath_); cmdQuiet_.add(quitAfterStartup_); cmdQuiet_.add(noSplashScreen_); cmdQuiet_.add(logfile_); cmdQuiet_.add(helpQuiet_); cmdQuiet_.add(versionQuiet_); cmdQuiet_.add(wildcard_); cmd_.add(workspace_); cmd_.add(outputPath_); cmd_.add(quitAfterStartup_); cmd_.add(noSplashScreen_); cmd_.add(logfile_); parse(Mode::Quiet); } CommandLineParser::~CommandLineParser() {} const std::string CommandLineParser::getOutputPath() const { if (outputPath_.isSet()) return (outputPath_.getValue()); return ""; } const std::string CommandLineParser::getWorkspacePath() const { if (workspace_.isSet()) return (workspace_.getValue()); return ""; } void CommandLineParser::parse(int argc, char** argv, Mode mode) { switch (mode) { case inviwo::CommandLineParser::Mode::Normal: { helpQuiet_.reset(); versionQuiet_.reset(); try { if (argc > 0) { cmd_.reset(); cmd_.parse(argc, argv); } } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; // catch exceptions } break; } case inviwo::CommandLineParser::Mode::Quiet: { try { if (argc > 0) { cmdQuiet_.reset(); cmdQuiet_.parse(argc, argv); } } catch (...) { } break; } default: break; } } void CommandLineParser::parse(Mode mode) { parse(argc_, argv_, mode); } const std::string CommandLineParser::getLogToFileFileName() const { if (logfile_.isSet()) return (logfile_.getValue()); else return ""; } bool CommandLineParser::getQuitApplicationAfterStartup() const { return quitAfterStartup_.getValue(); } bool CommandLineParser::getShowSplashScreen() const { if (versionQuiet_.isSet() || helpQuiet_.isSet()) return false; else return !(noSplashScreen_.isSet()); } bool CommandLineParser::getLoadWorkspaceFromArg() const { if (workspace_.isSet()) { std::string values = workspace_.getValue(); assert(values.size() != 0); return true; } return false; } bool CommandLineParser::getLogToFile() const { if (logfile_.isSet()) { std::string values = logfile_.getValue(); assert(values.size() != 0); return true; } return false; } void CommandLineParser::processCallbacks() { std::sort(callbacks_.begin(), callbacks_.end(), [](typename decltype(callbacks_)::value_type& a, typename decltype(callbacks_)::value_type& b) { return std::get<0>(a) < std::get<0>(b); }); for (auto& elem : callbacks_) { if (std::get<1>(elem)->isSet()) { std::get<2>(elem)(); } } } void CommandLineParser::add(TCLAP::Arg* arg) { cmd_.add(arg); } void CommandLineParser::add(TCLAP::Arg* arg, std::function<void()> callback, int priority) { cmd_.add(arg); callbacks_.push_back(std::make_tuple(priority, arg, callback)); } } // namespace <commit_msg>Core: Jenkins fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/commandlineparser.h> namespace inviwo { CommandLineParser::CommandLineParser() : CommandLineParser(0, nullptr) {} CommandLineParser::CommandLineParser(int argc, char** argv) : argc_(argc) , argv_(argv) , cmdQuiet_( "Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for " "interactive visualizations", ' ', IVW_VERSION, false) , cmd_( "Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for " "interactive visualizations", ' ', IVW_VERSION) , workspace_("w", "workspace", "Specify workspace to open", false, "", "workspace file") , outputPath_("o", "output", "Specify output path", false, "", "output path") , logfile_("l", "logfile", "Write log messages to file.", false, "", "logfile") , noSplashScreen_("n", "nosplash", "Pass this flag if you do not want to show a splash screen.") , quitAfterStartup_("q", "quit", "Pass this flag if you want to close inviwo after startup.") , wildcard_() , helpQuiet_("h", "help", "") , versionQuiet_("v", "version", "") { cmdQuiet_.add(workspace_); cmdQuiet_.add(outputPath_); cmdQuiet_.add(quitAfterStartup_); cmdQuiet_.add(noSplashScreen_); cmdQuiet_.add(logfile_); cmdQuiet_.add(helpQuiet_); cmdQuiet_.add(versionQuiet_); cmdQuiet_.add(wildcard_); cmd_.add(workspace_); cmd_.add(outputPath_); cmd_.add(quitAfterStartup_); cmd_.add(noSplashScreen_); cmd_.add(logfile_); parse(Mode::Quiet); } CommandLineParser::~CommandLineParser() {} const std::string CommandLineParser::getOutputPath() const { if (outputPath_.isSet()) return (outputPath_.getValue()); return ""; } const std::string CommandLineParser::getWorkspacePath() const { if (workspace_.isSet()) return (workspace_.getValue()); return ""; } void CommandLineParser::parse(int argc, char** argv, Mode mode) { switch (mode) { case inviwo::CommandLineParser::Mode::Normal: { helpQuiet_.reset(); versionQuiet_.reset(); try { if (argc > 0) { cmd_.reset(); cmd_.parse(argc, argv); } } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; // catch exceptions } break; } case inviwo::CommandLineParser::Mode::Quiet: { try { if (argc > 0) { cmdQuiet_.reset(); cmdQuiet_.parse(argc, argv); } } catch (...) { } break; } default: break; } } void CommandLineParser::parse(Mode mode) { parse(argc_, argv_, mode); } const std::string CommandLineParser::getLogToFileFileName() const { if (logfile_.isSet()) return (logfile_.getValue()); else return ""; } bool CommandLineParser::getQuitApplicationAfterStartup() const { return quitAfterStartup_.getValue(); } bool CommandLineParser::getShowSplashScreen() const { if (versionQuiet_.isSet() || helpQuiet_.isSet()) return false; else return !(noSplashScreen_.isSet()); } bool CommandLineParser::getLoadWorkspaceFromArg() const { if (workspace_.isSet()) { std::string values = workspace_.getValue(); assert(values.size() != 0); return true; } return false; } bool CommandLineParser::getLogToFile() const { if (logfile_.isSet()) { std::string values = logfile_.getValue(); assert(values.size() != 0); return true; } return false; } void CommandLineParser::processCallbacks() { std::sort(callbacks_.begin(), callbacks_.end(), [](const typename decltype(callbacks_)::value_type& a, const typename decltype(callbacks_)::value_type& b) { return std::get<0>(a) < std::get<0>(b); }); for (auto& elem : callbacks_) { if (std::get<1>(elem)->isSet()) { std::get<2>(elem)(); } } } void CommandLineParser::add(TCLAP::Arg* arg) { cmd_.add(arg); } void CommandLineParser::add(TCLAP::Arg* arg, std::function<void()> callback, int priority) { cmd_.add(arg); callbacks_.push_back(std::make_tuple(priority, arg, callback)); } } // namespace <|endoftext|>
<commit_before>#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/portability/CppUnitMap.h> #include <cppunit/TestSuite.h> #include <assert.h> CPPUNIT_NS_BEGIN /*! \brief (INTERNAL) List of all TestFactoryRegistry. */ class TestFactoryRegistryList { private: typedef CppUnitMap<std::string, TestFactoryRegistry *> Registries; Registries m_registries; enum State { doNotChange =0, notCreated, exist, destroyed }; static State stateFlag( State newState = doNotChange ) { static State state = notCreated; if ( newState != doNotChange ) state = newState; return state; } static TestFactoryRegistryList *getInstance() { static TestFactoryRegistryList list; return &list; } TestFactoryRegistry *getInternalRegistry( const std::string &name ) { Registries::const_iterator foundIt = m_registries.find( name ); if ( foundIt == m_registries.end() ) { TestFactoryRegistry *factory = new TestFactoryRegistry( name ); m_registries.insert( std::make_pair( name, factory ) ); return factory; } return foundIt->second; } public: TestFactoryRegistryList() { stateFlag( exist ); } ~TestFactoryRegistryList() { for ( Registries::iterator it = m_registries.begin(); it != m_registries.end(); ++it ) delete it->second; stateFlag( destroyed ); } static TestFactoryRegistry *getRegistry( const std::string &name ) { // If the following assertion failed, then TestFactoryRegistry::getRegistry() // was called during static variable destruction without checking the registry // validity beforehand using TestFactoryRegistry::isValid() beforehand. assert( isValid() ); if ( !isValid() ) // release mode return NULL; // => force CRASH return getInstance()->getInternalRegistry( name ); } static bool isValid() { return stateFlag() != destroyed; } }; TestFactoryRegistry::TestFactoryRegistry( std::string name ) : m_name( name ) { } TestFactoryRegistry::~TestFactoryRegistry() { } TestFactoryRegistry & TestFactoryRegistry::getRegistry( const std::string &name ) { return *TestFactoryRegistryList::getRegistry( name ); } void TestFactoryRegistry::registerFactory( const std::string &name, TestFactory *factory ) { registerFactory( factory ); } void TestFactoryRegistry::registerFactory( TestFactory *factory ) { m_factories.insert( factory ); } void TestFactoryRegistry::unregisterFactory( TestFactory *factory ) { m_factories.erase( factory ); } void TestFactoryRegistry::addRegistry( const std::string &name ) { registerFactory( &getRegistry( name ) ); } Test * TestFactoryRegistry::makeTest() { TestSuite *suite = new TestSuite( m_name ); addTestToSuite( suite ); return suite; } void TestFactoryRegistry::addTestToSuite( TestSuite *suite ) { for ( Factories::iterator it = m_factories.begin(); it != m_factories.end(); ++it ) { TestFactory *factory = *it; suite->addTest( factory->makeTest() ); } } bool TestFactoryRegistry::isValid() { return TestFactoryRegistryList::isValid(); } CPPUNIT_NS_END <commit_msg>map needs comparator, make_pair to pair, and map dereference fix (SUN4)<commit_after>#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/portability/CppUnitMap.h> #include <cppunit/TestSuite.h> #include <assert.h> CPPUNIT_NS_BEGIN /*! \brief (INTERNAL) List of all TestFactoryRegistry. */ class TestFactoryRegistryList { private: typedef CppUnitMap<std::string, TestFactoryRegistry *, std::less<std::string> > Registries; Registries m_registries; enum State { doNotChange =0, notCreated, exist, destroyed }; static State stateFlag( State newState = doNotChange ) { static State state = notCreated; if ( newState != doNotChange ) state = newState; return state; } static TestFactoryRegistryList *getInstance() { static TestFactoryRegistryList list; return &list; } TestFactoryRegistry *getInternalRegistry( const std::string &name ) { Registries::const_iterator foundIt = m_registries.find( name ); if ( foundIt == m_registries.end() ) { TestFactoryRegistry *factory = new TestFactoryRegistry( name ); m_registries.insert( std::pair<const std::string, TestFactoryRegistry*>( name, factory ) ); return factory; } return (*foundIt).second; } public: TestFactoryRegistryList() { stateFlag( exist ); } ~TestFactoryRegistryList() { for ( Registries::iterator it = m_registries.begin(); it != m_registries.end(); ++it ) delete (*it).second; stateFlag( destroyed ); } static TestFactoryRegistry *getRegistry( const std::string &name ) { // If the following assertion failed, then TestFactoryRegistry::getRegistry() // was called during static variable destruction without checking the registry // validity beforehand using TestFactoryRegistry::isValid() beforehand. assert( isValid() ); if ( !isValid() ) // release mode return NULL; // => force CRASH return getInstance()->getInternalRegistry( name ); } static bool isValid() { return stateFlag() != destroyed; } }; TestFactoryRegistry::TestFactoryRegistry( std::string name ) : m_name( name ) { } TestFactoryRegistry::~TestFactoryRegistry() { } TestFactoryRegistry & TestFactoryRegistry::getRegistry( const std::string &name ) { return *TestFactoryRegistryList::getRegistry( name ); } void TestFactoryRegistry::registerFactory( const std::string &name, TestFactory *factory ) { registerFactory( factory ); } void TestFactoryRegistry::registerFactory( TestFactory *factory ) { m_factories.insert( factory ); } void TestFactoryRegistry::unregisterFactory( TestFactory *factory ) { m_factories.erase( factory ); } void TestFactoryRegistry::addRegistry( const std::string &name ) { registerFactory( &getRegistry( name ) ); } Test * TestFactoryRegistry::makeTest() { TestSuite *suite = new TestSuite( m_name ); addTestToSuite( suite ); return suite; } void TestFactoryRegistry::addTestToSuite( TestSuite *suite ) { for ( Factories::iterator it = m_factories.begin(); it != m_factories.end(); ++it ) { TestFactory *factory = *it; suite->addTest( factory->makeTest() ); } } bool TestFactoryRegistry::isValid() { return TestFactoryRegistryList::isValid(); } CPPUNIT_NS_END <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief A/D 変換のサンプル @n P22/ANI2(54)、P23/ANI3(53) を変換して表示 @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/adc_io.hpp" #include "common/task.hpp" namespace { void wait_() { asm("nop"); } typedef utils::fifo<uint8_t, 32> buffer; device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_; device::itimer<uint8_t> itm_; // 最終チャネル番号+1を設定 typedef device::adc_io<4, utils::null_task> adc; adc adc_; } /// 割り込みベクターの定義 const void* ivec_[] __attribute__ ((section (".ivec"))) = { /* 0 */ nullptr, /* 1 */ nullptr, /* 2 */ nullptr, /* 3 */ nullptr, /* 4 */ nullptr, /* 5 */ nullptr, /* 6 */ nullptr, /* 7 */ nullptr, /* 8 */ nullptr, /* 9 */ nullptr, /* 10 */ nullptr, /* 11 */ nullptr, /* 12 */ nullptr, /* 13 */ nullptr, /* 14 */ nullptr, /* 15 */ nullptr, /* 16 */ reinterpret_cast<void*>(uart_.send_task), // UART1-TX /* 17 */ reinterpret_cast<void*>(uart_.recv_task), // UART1-RX /* 18 */ reinterpret_cast<void*>(uart_.error_task), // UART1-ER /* 19 */ nullptr, /* 20 */ nullptr, /* 21 */ nullptr, /* 22 */ nullptr, /* 23 */ nullptr, /* 24 */ reinterpret_cast<void*>(adc_.task), /* 25 */ nullptr, /* 26 */ reinterpret_cast<void*>(itm_.task), }; extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } }; int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { uint8_t intr_level = 1; uart_.start(115200, intr_level); } { uint8_t intr_level = 1; itm_.start(60, intr_level); } { device::PM2.B2 = 1; device::PM2.B3 = 1; uint8_t intr_level = 1; // 割り込み設定 adc_.start(adc::REFP::VDD, adc::REFM::VSS, intr_level); } uart_.puts("Start RL78/G13 A/D Convert sample\n"); uint8_t n = 0; uint8_t t = 0; while(1) { itm_.sync(); adc_.start_scan(2); // スキャン開始チャネル if(t >= 30) { auto val = adc_.get(2); val >>= 6; #if 1 uint32_t vol = static_cast<uint32_t>(val) * 1024 / 310; // Vref: 3.3V とした場合の電圧 utils::format("A/D CH2: %4.2:10y [V] (%d)\n") % vol % val; #else float vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH2: %4.2f [V] (%d)\n") % vol % val; #endif val = adc_.get(3); val >>= 6; #if 1 vol = static_cast<uint32_t>(val) * 1024 / 310; utils::format("A/D CH3: %4.2:10y [V] (%d)\n") % vol % val; #else vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH3: %4.2f [V] (%d)\n") % vol % val; #endif t = 0; } else { ++t; } ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; } } <commit_msg>fix A/D scan sync<commit_after>//=====================================================================// /*! @file @brief A/D 変換のサンプル @n P22/ANI2(54)、P23/ANI3(53) を変換して表示 @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/adc_io.hpp" #include "common/task.hpp" namespace { void wait_() { asm("nop"); } typedef utils::fifo<uint8_t, 32> buffer; device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_; device::itimer<uint8_t> itm_; // 最終チャネル番号+1を設定 typedef device::adc_io<4, utils::null_task> adc; adc adc_; } /// 割り込みベクターの定義 const void* ivec_[] __attribute__ ((section (".ivec"))) = { /* 0 */ nullptr, /* 1 */ nullptr, /* 2 */ nullptr, /* 3 */ nullptr, /* 4 */ nullptr, /* 5 */ nullptr, /* 6 */ nullptr, /* 7 */ nullptr, /* 8 */ nullptr, /* 9 */ nullptr, /* 10 */ nullptr, /* 11 */ nullptr, /* 12 */ nullptr, /* 13 */ nullptr, /* 14 */ nullptr, /* 15 */ nullptr, /* 16 */ reinterpret_cast<void*>(uart_.send_task), // UART1-TX /* 17 */ reinterpret_cast<void*>(uart_.recv_task), // UART1-RX /* 18 */ reinterpret_cast<void*>(uart_.error_task), // UART1-ER /* 19 */ nullptr, /* 20 */ nullptr, /* 21 */ nullptr, /* 22 */ nullptr, /* 23 */ nullptr, /* 24 */ reinterpret_cast<void*>(adc_.task), /* 25 */ nullptr, /* 26 */ reinterpret_cast<void*>(itm_.task), }; extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } }; int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { uint8_t intr_level = 1; uart_.start(115200, intr_level); } { uint8_t intr_level = 1; itm_.start(60, intr_level); } { device::PM2.B2 = 1; device::PM2.B3 = 1; uint8_t intr_level = 1; // 割り込み設定 adc_.start(adc::REFP::VDD, adc::REFM::VSS, intr_level); } uart_.puts("Start RL78/G13 A/D Convert sample\n"); uint8_t n = 0; uint8_t t = 0; while(1) { itm_.sync(); adc_.start_scan(2); // スキャン開始チャネル adc_.sync(); // スキャン終了待ち if(t >= 30) { auto val = adc_.get(2); val >>= 6; #if 1 uint32_t vol = static_cast<uint32_t>(val) * 1024 / 310; // Vref: 3.3V とした場合の電圧 utils::format("A/D CH2: %4.2:10y [V] (%d)\n") % vol % val; #else float vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH2: %4.2f [V] (%d)\n") % vol % val; #endif val = adc_.get(3); val >>= 6; #if 1 vol = static_cast<uint32_t>(val) * 1024 / 310; utils::format("A/D CH3: %4.2:10y [V] (%d)\n") % vol % val; #else vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH3: %4.2f [V] (%d)\n") % vol % val; #endif t = 0; } else { ++t; } ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief A/D 変換のサンプル @n P22/ANI2(54)、P23/ANI3(53) を変換して表示 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RL78/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/renesas.hpp" #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/adc_io.hpp" #include "common/task.hpp" namespace { void wait_() { asm("nop"); } typedef utils::fifo<uint8_t, 32> BUFFER; typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1; UART1 uart_; typedef device::itimer<uint8_t> ITM; ITM itm_; // 最終チャネル番号+1を設定 typedef device::adc_io<4, utils::null_task> ADC; ADC adc_; } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.recv_length(); } void UART1_TX_intr(void) { uart_.send_task(); } void UART1_RX_intr(void) { uart_.recv_task(); } void UART1_ER_intr(void) { uart_.error_task(); } void ADC_intr(void) { adc_.task(); } void ITM_intr(void) { itm_.task(); } }; int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { uint8_t intr_level = 1; uart_.start(115200, intr_level); } { uint8_t intr_level = 1; itm_.start(60, intr_level); } { device::PM2.B2 = 1; device::PM2.B3 = 1; uint8_t intr_level = 1; // 割り込み設定 adc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level); } uart_.puts("Start RL78/G13 A/D Convert sample\n"); uint8_t n = 0; uint8_t t = 0; while(1) { itm_.sync(); adc_.start_scan(2); // スキャン開始チャネル adc_.sync(); // スキャン終了待ち if(t >= 30) { auto val = adc_.get(2); val >>= 6; #if 1 uint32_t vol = static_cast<uint32_t>(val) * 1024 / 310; // Vref: 3.3V とした場合の電圧 utils::format("A/D CH2: %4.2:10y [V] (%d)\n") % vol % val; #else float vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH2: %4.2f [V] (%d)\n") % vol % val; #endif val = adc_.get(3); val >>= 6; #if 1 vol = static_cast<uint32_t>(val) * 1024 / 310; utils::format("A/D CH3: %4.2:10y [V] (%d)\n") % vol % val; #else vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH3: %4.2f [V] (%d)\n") % vol % val; #endif t = 0; } else { ++t; } ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; } } <commit_msg>update interrnal temp<commit_after>//=====================================================================// /*! @file @brief A/D 変換のサンプル @n P22/ANI2(54)、P23/ANI3(53) を変換して表示 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RL78/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/renesas.hpp" #include "common/port_utils.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/itimer.hpp" #include "common/adc_io.hpp" #include "common/task.hpp" namespace { void wait_() { asm("nop"); } typedef utils::fifo<uint8_t, 32> BUFFER; typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1; UART1 uart_; typedef device::itimer<uint8_t> ITM; ITM itm_; // 最終チャネル番号+1を設定 typedef device::adc_io<4, utils::null_task> ADC; ADC adc_; } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } void sci_puts(const char* str) { uart_.puts(str); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.recv_length(); } void UART1_TX_intr(void) { uart_.send_task(); } void UART1_RX_intr(void) { uart_.recv_task(); } void UART1_ER_intr(void) { uart_.error_task(); } void ADC_intr(void) { adc_.task(); } void ITM_intr(void) { itm_.task(); } }; int main(int argc, char* argv[]) { utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ device::PM4.B3 = 0; // output { uint8_t intr_level = 1; uart_.start(115200, intr_level); } { uint8_t intr_level = 1; itm_.start(60, intr_level); } { device::PM2.B2 = 1; device::PM2.B3 = 1; uint8_t intr_level = 1; // 割り込み設定 adc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level); } uart_.puts("Start RL78/G13 A/D Convert sample\n"); uint8_t n = 0; uint8_t t = 0; while(1) { itm_.sync(); adc_.start_scan(2, true); // スキャン開始チャネル、温度取得 adc_.sync(); // スキャン終了待ち if(t >= 30) { auto val = adc_.get(2); val >>= 6; #if 1 uint32_t vol = static_cast<uint32_t>(val) * 1024 / 310; // Vref: 3.3V とした場合の電圧 utils::format("A/D CH2: %4.2:10y [V] (%d)\n") % vol % val; #else float vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH2: %4.2f [V] (%d)\n") % vol % val; #endif val = adc_.get(3); val >>= 6; #if 1 vol = static_cast<uint32_t>(val) * 1024 / 310; utils::format("A/D CH3: %4.2:10y [V] (%d)\n") % vol % val; #else vol = static_cast<float>(val) * 3.3f / 1023.0f; utils::format("A/D CH3: %4.2f [V] (%d)\n") % vol % val; #endif // 温度表示 val = adc_.get_temp(); val >>= 6; // 1.05V: 25.0度, 3.6mV/度 float tv = static_cast<float>(val) * 3.3f / 1023.0f; float temp = (1.05f - tv) / 0.0036f + 25.0f; utils::format("A/D TEMP: %4.2f [K], %4.3f [V]\n") % temp % tv; t = 0; } else { ++t; } ++n; if(n >= 30) n = 0; device::P4.B3 = n < 10 ? false : true; } } <|endoftext|>
<commit_before>// ROS Building Operating System digital temperature and humidity // sensor driver based on: // How to access GPIO registers from C-code on the Raspberry-Pi // Example program // 15-January-2012 // Dom and Gert // // Access from ARM Running Linux #define BCM2708_PERI_BASE 0x20000000 #define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <fcntl.h> #include <assert.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <bcm2835.h> #include <unistd.h> #include "ros/ros.h" #include "std_msgs/Float32.h" #define MAXTIMINGS 100 #define DEBUG #define DHT11 11 #define DHT22 22 #define AM2302 22 int readDHT(int type, int pin, float* t, float* h); int main(int argc, char **argv) { if (!bcm2835_init()) return 1; if (argc < 3) { printf("usage: %s {11|22|2302} GPIOpin# [ROS Parameters]\n", argv[0]); printf("example: %s 2302 4 - Read from an AM2302 connected to GPIO #4\n", argv[0]); return 2; } int type = 0; if (strcmp(argv[1], "11") == 0) type = DHT11; if (strcmp(argv[1], "22") == 0) type = DHT22; if (strcmp(argv[1], "2302") == 0) type = AM2302; if (type == 0) { printf("Select 11, 22, 2302 as type!\n"); return 3; } int dhtpin = atoi(argv[2]); if (dhtpin <= 0) { printf("Please select a valid GPIO pin #\n"); return 3; } printf("Using pin #%d\n", dhtpin); ros::init(argc, argv, "raspi_dht"); ros::NodeHandle n; ros::Publisher temperature_pub = n.advertise<std_msgs::Float32>("temperature", 1); ros::Publisher humidity_pub = n.advertise<std_msgs::Float32>("humidity", 1); ros::Rate loop_rate(0.016); ros::Duration retry_interval(5.0); while (ros::ok()) { std_msgs::Float32 temperature_msg, humidity_msg; float t, h; ros::spinOnce(); if (readDHT(type, dhtpin, &t, &h)) { temperature_msg.data = t; temperature_pub.publish(temperature_msg); humidity_msg.data = h; humidity_pub.publish(humidity_msg); loop_rate.sleep(); } else { #ifdef DEBUG printf("No data, retrying soon\n"); #endif retry_interval.sleep(); } } return 0; } // main int bits[250], data[100]; int bitidx = 0; int readDHT(int type, int pin, float* t, float* h) { int counter = 0; int laststate = HIGH; int j=0; // Set GPIO pin to output bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(pin, HIGH); usleep(500000); // 500 ms bcm2835_gpio_write(pin, LOW); usleep(20000); bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT); data[0] = data[1] = data[2] = data[3] = data[4] = 0; // wait for pin to drop? while (bcm2835_gpio_lev(pin) == 1) { usleep(1); } // read data! for (int i=0; i< MAXTIMINGS; i++) { counter = 0; while ( bcm2835_gpio_lev(pin) == laststate) { counter++; //nanosleep(1); // overclocking might change this? if (counter == 1000) break; } laststate = bcm2835_gpio_lev(pin); if (counter == 1000) break; bits[bitidx++] = counter; if ((i>3) && (i%2 == 0)) { // shove each bit into the storage bytes data[j/8] <<= 1; if (counter > 200) data[j/8] |= 1; j++; } } #ifdef DEBUG for (int i=3; i<bitidx; i+=2) { printf("bit %d: %d\n", i-3, bits[i]); printf("bit %d: %d (%d)\n", i-2, bits[i+1], bits[i+1] > 200); } #endif if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { // yay! if (type == DHT11) { *t = (float)data[2]; *h = (float)data[0]; #ifdef DEBUG printf("Temp = %d *C, Hum = %d \%\n", data[2], data[0]); #endif } if (type == DHT22) { *h = data[0] * 256 + data[1]; *h /= 10; *t = (data[2] & 0x7F)* 256 + data[3]; *t /= 10.0; if (data[2] & 0x80) *t *= -1; #ifdef DEBUG printf("Temp = %.1f *C, Hum = %.1f \%\n", *t, *h); #endif } return 1; } return 0; } <commit_msg>Now working with Avahi enabled on raspberry pi and ROS_HOSTNAME environmental variable set and exported. However there is a buffer overrun bug in the readDHT routine.<commit_after>// ROS Building Operating System digital temperature and humidity // sensor driver based on: // How to access GPIO registers from C-code on the Raspberry-Pi // Example program // 15-January-2012 // Dom and Gert // // Access from ARM Running Linux #define BCM2708_PERI_BASE 0x20000000 #define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <fcntl.h> #include <assert.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <bcm2835.h> #include <unistd.h> #include "ros/ros.h" #include "std_msgs/Float32.h" #define MAXTIMINGS 100 //#define DEBUG #define DHT11 11 #define DHT22 22 #define AM2302 22 int readDHT(int type, int pin, float* t, float* h); int main(int argc, char **argv) { if (!bcm2835_init()) return 1; if (argc < 3) { printf("usage: %s {11|22|2302} GPIOpin# [ROS Parameters]\n", argv[0]); printf("example: %s 2302 4 - Read from an AM2302 connected to GPIO #4\n", argv[0]); return 2; } int type = 0; if (strcmp(argv[1], "11") == 0) type = DHT11; if (strcmp(argv[1], "22") == 0) type = DHT22; if (strcmp(argv[1], "2302") == 0) type = AM2302; if (type == 0) { printf("Select 11, 22, 2302 as type!\n"); return 3; } int dhtpin = atoi(argv[2]); if (dhtpin <= 0) { printf("Please select a valid GPIO pin #\n"); return 3; } printf("Using pin #%d\n", dhtpin); ros::init(argc, argv, "raspi_dht"); ros::NodeHandle n; ros::Publisher temperature_pub = n.advertise<std_msgs::Float32>("temperature", 2); ros::Publisher humidity_pub = n.advertise<std_msgs::Float32>("humidity", 2); ros::Rate loop_rate(0.016); ros::Duration retry_interval(5.0); ros::Duration backoff_interval(200); bool last_had_data = true; while (ros::ok()) { std_msgs::Float32 temperature_msg, humidity_msg; float t, h; if (readDHT(type, dhtpin, &t, &h)) { temperature_msg.data = t; humidity_msg.data = h; #ifdef DEBUG printf("Publishing data: t=%f, h=%f\n", t, h); ROS_INFO("BOS_RASPI_DHT_NODE: %f, %f", t, h); #endif temperature_pub.publish(temperature_msg); humidity_pub.publish(humidity_msg); ros::spinOnce(); loop_rate.sleep(); last_had_data = true; } else { if (last_had_data) { ROS_INFO("BOS_raspi_DHT_node: no data, retrying soon"); retry_interval.sleep(); } else { ROS_INFO("BOS_raspi_DHT_node: no data, waiting a while"); backoff_interval.sleep(); } last_had_data = false; } } return 0; } // main int bits[250], data[100]; int bitidx = 0; int readDHT(int type, int pin, float* t, float* h) { int counter = 0; int laststate = HIGH; int j=0; // Set GPIO pin to output bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(pin, HIGH); usleep(500000); // 500 ms bcm2835_gpio_write(pin, LOW); usleep(20000); bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT); data[0] = data[1] = data[2] = data[3] = data[4] = 0; // wait for pin to drop? while (bcm2835_gpio_lev(pin) == 1) { usleep(1); } // read data! for (int i=0; i< MAXTIMINGS; i++) { counter = 0; while ( bcm2835_gpio_lev(pin) == laststate) { counter++; //nanosleep(1); // overclocking might change this? if (counter == 1000) break; } laststate = bcm2835_gpio_lev(pin); if (counter == 1000) break; bits[bitidx++] = counter; if ((i>3) && (i%2 == 0)) { // shove each bit into the storage bytes data[j/8] <<= 1; if (counter > 200) data[j/8] |= 1; j++; } } #ifdef DEBUG for (int i=3; i<bitidx; i+=2) { printf("bit %d: %d\n", i-3, bits[i]); printf("bit %d: %d (%d)\n", i-2, bits[i+1], bits[i+1] > 200); } #endif if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { // yay! if (type == DHT11) { *t = (float)data[2]; *h = (float)data[0]; #ifdef DEBUG printf("Temp = %d *C, Hum = %d \%\n", data[2], data[0]); #endif } if (type == DHT22) { *h = data[0] * 256 + data[1]; *h /= 10; *t = (data[2] & 0x7F)* 256 + data[3]; *t /= 10.0; if (data[2] & 0x80) *t *= -1; #ifdef DEBUG printf("Temp = %.1f *C, Hum = %.1f \%\n", *t, *h); #endif } return 1; } return 0; } <|endoftext|>
<commit_before>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ #if defined( _MSC_VER) && _MSC_VER <= 1200 #pragma warning( disable: 4786 )// debug symbol truncated #endif // svncpp #include "client_impl.hpp" // Subversion api #include "svn_client.h" #include "svn_path.h" #include "exception.hpp" #include "pool.hpp" #include "status.hpp" #include "svnqt_defines.hpp" namespace svn { /** * a quick way to create error messages */ static void fail (apr_pool_t *pool, apr_status_t status, const char *fmt, ...) { va_list ap; char *msg; svn_error_t * error; va_start (ap, fmt); msg = apr_pvsprintf (pool, fmt, ap); va_end (ap); error = svn_error_create (status, NULL, msg); throw ClientException (error); } /** * closes and deletes temporary files that diff has been using */ static void diffCleanup (apr_file_t * outfile, const char * outfileName, apr_file_t * errfile, const char * errfileName, apr_pool_t *pool) { if (outfile != NULL) apr_file_close (outfile); if (errfile != NULL) apr_file_close (errfile); if (outfileName != NULL) svn_error_clear (svn_io_remove_file (outfileName, pool)); if (errfileName != NULL) svn_error_clear (svn_io_remove_file (errfileName, pool)); } QByteArray Client_impl::diff (const Path & tmpPath, const Path & path, const Revision & revision1, const Revision & revision2, const bool recurse, const bool ignoreAncestry, const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException) { return diff(tmpPath,path,path,revision1,revision2,recurse,ignoreAncestry,noDiffDeleted,ignore_contenttype); } QByteArray Client_impl::diff (const Path & tmpPath, const Path & path1,const Path&path2, const Revision & revision1, const Revision & revision2, const bool recurse, const bool ignoreAncestry, const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException) { Pool pool; svn_error_t * error; apr_status_t status; apr_file_t * outfile = 0L; const char * outfileName = 0L; apr_file_t * errfile = 0L; const char * errfileName = 0L; apr_array_header_t * options; svn_stringbuf_t * stringbuf; bool working_copy_present = false; bool url_is_present = false; Revision r1,r2; r1 = revision1; r2 = revision2; if (svn_path_is_url(path1.cstr())) { url_is_present = true; } else { working_copy_present = true; } if (svn_path_is_url(path2.cstr())) { url_is_present = true; } else { working_copy_present = true; } if (revision1.revision()->kind==svn_opt_revision_unspecified && working_copy_present) { r1 = svn_opt_revision_base; } if (revision2.revision()->kind==svn_opt_revision_unspecified) { r2 = working_copy_present?svn_opt_revision_working : svn_opt_revision_head; } // svn_client_diff needs an options array, even if it is empty options = apr_array_make (pool, 0, 0); // svn_client_diff needs a temporary file to write diff output to error = svn_io_open_unique_file (&outfile, &outfileName, tmpPath.path().TOUTF8(), ".tmp", FALSE, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } // and another one to write errors to error = svn_io_open_unique_file (&errfile, &errfileName, tmpPath.path().TOUTF8(), ".error.tmp", FALSE, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } // run diff error = svn_client_diff2 (options, path1.cstr (), r1.revision (), path2.cstr (), r2.revision (), recurse, ignoreAncestry, noDiffDeleted, ignore_contenttype, outfile, errfile, *m_context, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } // then we reopen outfile for reading status = apr_file_close (outfile); if (status) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); fail (pool, status, "failed to close '%s'", outfileName); } status = apr_file_open (&outfile, outfileName, APR_READ, APR_OS_DEFAULT, pool); if (status) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); fail (pool, status, "failed to open '%s'", outfileName); } // now we can read the diff output from outfile and return that error = svn_stringbuf_from_aprfile (&stringbuf, outfile, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } diffCleanup (outfile, outfileName, errfile, errfileName, pool); #if QT_VERSION < 0x040000 QByteArray res; /// @todo check if realy dup or just assign! res.duplicate(stringbuf->data,stringbuf->len); #else QByteArray res( stringbuf->data, stringbuf->len ); #endif return res; } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <commit_msg>diff reads the result direct into QByteArray instead of copy it from string_buffer<commit_after>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ #if defined( _MSC_VER) && _MSC_VER <= 1200 #pragma warning( disable: 4786 )// debug symbol truncated #endif // svncpp #include "client_impl.hpp" // Subversion api #include "svn_client.h" #include "svn_path.h" #include "exception.hpp" #include "pool.hpp" #include "status.hpp" #include "svnqt_defines.hpp" #include <qfile.h> namespace svn { /** * a quick way to create error messages */ static void fail (apr_pool_t *pool, apr_status_t status, const char *fmt, ...) { va_list ap; char *msg; svn_error_t * error; va_start (ap, fmt); msg = apr_pvsprintf (pool, fmt, ap); va_end (ap); error = svn_error_create (status, NULL, msg); throw ClientException (error); } /** * closes and deletes temporary files that diff has been using */ static void diffCleanup (apr_file_t * outfile, const char * outfileName, apr_file_t * errfile, const char * errfileName, apr_pool_t *pool) { if (outfile != NULL) apr_file_close (outfile); if (errfile != NULL) apr_file_close (errfile); if (outfileName != NULL) svn_error_clear (svn_io_remove_file (outfileName, pool)); if (errfileName != NULL) svn_error_clear (svn_io_remove_file (errfileName, pool)); } QByteArray Client_impl::diff (const Path & tmpPath, const Path & path, const Revision & revision1, const Revision & revision2, const bool recurse, const bool ignoreAncestry, const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException) { return diff(tmpPath,path,path,revision1,revision2,recurse,ignoreAncestry,noDiffDeleted,ignore_contenttype); } QByteArray Client_impl::diff (const Path & tmpPath, const Path & path1,const Path&path2, const Revision & revision1, const Revision & revision2, const bool recurse, const bool ignoreAncestry, const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException) { Pool pool; svn_error_t * error; apr_status_t status; apr_file_t * outfile = 0L; const char * outfileName = 0L; apr_file_t * errfile = 0L; const char * errfileName = 0L; apr_array_header_t * options; bool working_copy_present = false; bool url_is_present = false; Revision r1,r2; r1 = revision1; r2 = revision2; if (svn_path_is_url(path1.cstr())) { url_is_present = true; } else { working_copy_present = true; } if (svn_path_is_url(path2.cstr())) { url_is_present = true; } else { working_copy_present = true; } if (revision1.revision()->kind==svn_opt_revision_unspecified && working_copy_present) { r1 = svn_opt_revision_base; } if (revision2.revision()->kind==svn_opt_revision_unspecified) { r2 = working_copy_present?svn_opt_revision_working : svn_opt_revision_head; } // svn_client_diff needs an options array, even if it is empty options = apr_array_make (pool, 0, 0); // svn_client_diff needs a temporary file to write diff output to error = svn_io_open_unique_file (&outfile, &outfileName, tmpPath.path().TOUTF8(), ".tmp", FALSE, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } // and another one to write errors to error = svn_io_open_unique_file (&errfile, &errfileName, tmpPath.path().TOUTF8(), ".error.tmp", FALSE, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } // run diff error = svn_client_diff2 (options, path1.cstr (), r1.revision (), path2.cstr (), r2.revision (), recurse, ignoreAncestry, noDiffDeleted, ignore_contenttype, outfile, errfile, *m_context, pool); if (error != NULL) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); throw ClientException (error); } status = apr_file_close (outfile); if (status) { diffCleanup (outfile, outfileName, errfile, errfileName, pool); fail (pool, status, "failed to close '%s'", outfileName); } QFile fi(outfileName); #if QT_VERSION < 0x040000 if (!fi.open(IO_ReadOnly|IO_Raw)) { #else if (!fi.open(QIODevice::IO_ReadOnly)) { #endif diffCleanup (outfile, outfileName, errfile, errfileName, pool); fail(pool,0,fi.errorString()+"'%s'",outfileName); } QByteArray res = fi.readAll(); fi.close(); diffCleanup (outfile, outfileName, errfile, errfileName, pool); return res; } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <|endoftext|>
<commit_before>#ifndef CLIENT_WS_HPP #define CLIENT_WS_HPP #include <boost/asio.hpp> #include <unordered_map> #include <iostream> #include <regex> #include <random> namespace SimpleWeb { template <class socket_type> class ClientBase { public: class Response { friend class ClientBase<socket_type>; public: std::string http_version, status_code; std::istream content; std::unordered_map<std::string, std::string> header; private: boost::asio::streambuf content_buffer; Response(): content(&content_buffer) {}; }; //TODO add header parameters std::shared_ptr<Response> request(const std::string& request_type, const std::string& path="/") { std::stringstream empty_ss; return request(request_type, path, empty_ss); } std::shared_ptr<Response> request(const std::string& request_type, const std::string& path, std::ostream& content) { std::string corrected_path=path; if(corrected_path=="") corrected_path="/"; content.seekp(0, std::ios::end); size_t content_length=content.tellp(); content.seekp(0, std::ios::beg); boost::asio::streambuf write_buffer; std::ostream write_stream(&write_buffer); write_stream << request_type << " " << corrected_path << " HTTP/1.1\r\n"; write_stream << "Host: " << host << "\r\n"; if(content_length>0) write_stream << "Content-Length: " << std::to_string(content_length) << "\r\n"; write_stream << "\r\n"; if(content_length>0) write_stream << content.rdbuf(); std::shared_ptr<Response> response(new Response()); try { connect(); boost::asio::write(*socket, write_buffer); size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, "\r\n\r\n"); size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred; parse_response_header(response, response->content); if(response->header.count("Content-Length")>0) { boost::asio::read(*socket, response->content_buffer, boost::asio::transfer_exactly(stoull(response->header["Content-Length"])-num_additional_bytes)); } else if(response->header.count("Transfer-Encoding")>0 && response->header["Transfer-Encoding"]=="chunked") { boost::asio::streambuf streambuf; std::ostream content(&streambuf); size_t length; std::string buffer; do { size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, "\r\n"); std::string line; getline(response->content, line); bytes_transferred-=line.size()+1; line.pop_back(); length=stoull(line, 0, 16); size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred; if((2+length)>num_additional_bytes) { boost::asio::read(*socket, response->content_buffer, boost::asio::transfer_exactly(2+length-num_additional_bytes)); } buffer.resize(length); response->content.read(&buffer[0], length); content.write(&buffer[0], length); //Remove "\r\n" response->content.get(); response->content.get(); } while(length>0); std::ostream response_content_output_stream(&response->content_buffer); response_content_output_stream << content.rdbuf(); } } catch(const std::exception& e) { socket_error=true; throw std::invalid_argument(e.what()); } return response; } protected: boost::asio::io_service asio_io_service; boost::asio::ip::tcp::endpoint asio_endpoint; boost::asio::ip::tcp::resolver asio_resolver; std::shared_ptr<socket_type> socket; bool socket_error; std::string host; unsigned short port; ClientBase(const std::string& host_port, unsigned short default_port) : asio_resolver(asio_io_service), socket_error(false) { std::regex e("^([^:/]+):?([0-9]*)$"); std::smatch sm; if(std::regex_match(host_port, sm, e)) { host=sm[1]; port=default_port; if(sm[2]!="") port=(unsigned short)std::stoul(sm[2]); asio_endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port); } else { throw std::invalid_argument("Error parsing host_port"); } } virtual void connect()=0; void parse_response_header(std::shared_ptr<Response> response, std::istream& stream) const { std::smatch sm; //Parse the first line std::string line; getline(stream, line); line.pop_back(); std::regex e("^HTTP/([^ ]*) (.*)$"); if(std::regex_match(line, sm, e)) { response->http_version=sm[1]; response->status_code=sm[2]; e="^([^:]*): ?(.*)$"; //Parse the rest of the header bool matched; do { getline(stream, line); line.pop_back(); matched=std::regex_match(line, sm, e); if(matched) { response->header[sm[1]]=sm[2]; } } while(matched==true); } } }; template<class socket_type> class Client : public ClientBase<socket_type> {}; typedef boost::asio::ip::tcp::socket HTTP; template<> class Client<HTTP> : public ClientBase<HTTP> { public: Client(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80) { socket=std::make_shared<HTTP>(asio_io_service); }; private: void connect() { if(socket_error || !socket->is_open()) { boost::asio::ip::tcp::resolver::query query(host, std::to_string(port)); boost::asio::connect(*socket, asio_resolver.resolve(query)); socket_error=false; } } }; } #endif /* CLIENT_WS_HPP */<commit_msg>added header parameter to Client::request<commit_after>#ifndef CLIENT_WS_HPP #define CLIENT_WS_HPP #include <boost/asio.hpp> #include <unordered_map> #include <map> #include <iostream> #include <regex> #include <random> namespace SimpleWeb { template <class socket_type> class ClientBase { public: class Response { friend class ClientBase<socket_type>; public: std::string http_version, status_code; std::istream content; std::unordered_map<std::string, std::string> header; private: boost::asio::streambuf content_buffer; Response(): content(&content_buffer) {}; }; //TODO add header parameters std::shared_ptr<Response> request(const std::string& request_type, const std::string& path="/", const std::map<std::string, std::string>& header={{}}) { std::stringstream empty_ss; return request(request_type, path, empty_ss, header); } std::shared_ptr<Response> request(const std::string& request_type, const std::string& path, std::ostream& content, const std::map<std::string, std::string>& header={{}}) { std::string corrected_path=path; if(corrected_path=="") corrected_path="/"; content.seekp(0, std::ios::end); size_t content_length=content.tellp(); content.seekp(0, std::ios::beg); boost::asio::streambuf write_buffer; std::ostream write_stream(&write_buffer); write_stream << request_type << " " << corrected_path << " HTTP/1.1\r\n"; write_stream << "Host: " << host << "\r\n"; for(auto& h: header) { write_stream << h.first << ": " << h.second << "\r\n"; } if(content_length>0) write_stream << "Content-Length: " << std::to_string(content_length) << "\r\n"; write_stream << "\r\n"; if(content_length>0) write_stream << content.rdbuf(); std::shared_ptr<Response> response(new Response()); try { connect(); boost::asio::write(*socket, write_buffer); size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, "\r\n\r\n"); size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred; parse_response_header(response, response->content); if(response->header.count("Content-Length")>0) { boost::asio::read(*socket, response->content_buffer, boost::asio::transfer_exactly(stoull(response->header["Content-Length"])-num_additional_bytes)); } else if(response->header.count("Transfer-Encoding")>0 && response->header["Transfer-Encoding"]=="chunked") { boost::asio::streambuf streambuf; std::ostream content(&streambuf); size_t length; std::string buffer; do { size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, "\r\n"); std::string line; getline(response->content, line); bytes_transferred-=line.size()+1; line.pop_back(); length=stoull(line, 0, 16); size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred; if((2+length)>num_additional_bytes) { boost::asio::read(*socket, response->content_buffer, boost::asio::transfer_exactly(2+length-num_additional_bytes)); } buffer.resize(length); response->content.read(&buffer[0], length); content.write(&buffer[0], length); //Remove "\r\n" response->content.get(); response->content.get(); } while(length>0); std::ostream response_content_output_stream(&response->content_buffer); response_content_output_stream << content.rdbuf(); } } catch(const std::exception& e) { socket_error=true; throw std::invalid_argument(e.what()); } return response; } protected: boost::asio::io_service asio_io_service; boost::asio::ip::tcp::endpoint asio_endpoint; boost::asio::ip::tcp::resolver asio_resolver; std::shared_ptr<socket_type> socket; bool socket_error; std::string host; unsigned short port; ClientBase(const std::string& host_port, unsigned short default_port) : asio_resolver(asio_io_service), socket_error(false) { std::regex e("^([^:/]+):?([0-9]*)$"); std::smatch sm; if(std::regex_match(host_port, sm, e)) { host=sm[1]; port=default_port; if(sm[2]!="") port=(unsigned short)std::stoul(sm[2]); asio_endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port); } else { throw std::invalid_argument("Error parsing host_port"); } } virtual void connect()=0; void parse_response_header(std::shared_ptr<Response> response, std::istream& stream) const { std::smatch sm; //Parse the first line std::string line; getline(stream, line); line.pop_back(); std::regex e("^HTTP/([^ ]*) (.*)$"); if(std::regex_match(line, sm, e)) { response->http_version=sm[1]; response->status_code=sm[2]; e="^([^:]*): ?(.*)$"; //Parse the rest of the header bool matched; do { getline(stream, line); line.pop_back(); matched=std::regex_match(line, sm, e); if(matched) { response->header[sm[1]]=sm[2]; } } while(matched==true); } } }; template<class socket_type> class Client : public ClientBase<socket_type> {}; typedef boost::asio::ip::tcp::socket HTTP; template<> class Client<HTTP> : public ClientBase<HTTP> { public: Client(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80) { socket=std::make_shared<HTTP>(asio_io_service); }; private: void connect() { if(socket_error || !socket->is_open()) { boost::asio::ip::tcp::resolver::query query(host, std::to_string(port)); boost::asio::connect(*socket, asio_resolver.resolve(query)); socket_error=false; } } }; } #endif /* CLIENT_WS_HPP */<|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "TriangulatedMeshGenerator.h" // poly2tri triangulation library #include "poly2tri.h" registerMooseObject("ReactorApp", TriangulatedMeshGenerator); InputParameters TriangulatedMeshGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addRangeCheckedParam<SubdomainID>( "subdomain_id", "subdomain_id>=0", "The subdomain ID given to the TRI3 elements in the triangulation."); params.addRequiredParam<MeshGeneratorName>( "inner_boundary_mesh", "The mesh to use for the inner boundary of the triangulation."); params.addRangeCheckedParam<boundary_id_type>( "inner_boundary_id", "inner_boundary_id>=0", "The boundary ID of the inner mesh outer boundary."); params.addParam<std::string>( "inner_boundary_name", "The boundary name of the inner mesh outer boundary."); params.addRequiredRangeCheckedParam<Real>( "outer_circle_radius", "outer_circle_radius>0", "Radius of outer circle boundary."); params.addRequiredRangeCheckedParam<unsigned int>( "outer_circle_num_segments", "outer_circle_num_segments>0", "Number of radial segments to subdivide outer circle boundary."); params.addRangeCheckedParam<boundary_id_type>( "outer_boundary_id", "outer_boundary_id>=0", "The boundary id for the generated mesh outer boundary."); // params.addParam<std::string>( // "outer_boundary_name", // "The boundary name of the generated mesh outer boundary."); params.addParam<std::vector<Real>>( "extra_circle_radii", "Radii of extra Steiner point circles."); params.addParam<std::vector<unsigned int>>( "extra_circle_num_segments", "Number of segments for extra Steiner point circles."); params.addClassDescription( "This TriangulatedMeshGenerator object is designed to generate " "a triangulated mesh between a generated outer circle boundary " "and a provided inner mesh."); return params; } TriangulatedMeshGenerator::TriangulatedMeshGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _tri_subdomain_id(isParamValid("subdomain_id") ? getParam<SubdomainID>("subdomain_id") : 0), _inner_boundary_mesh(getMesh("inner_boundary_mesh")), _outer_circle_radius(getParam<Real>("outer_circle_radius")), _outer_circle_num_segments(getParam<unsigned int>("outer_circle_num_segments")), _outer_boundary_id(isParamValid("outer_boundary_id") ? getParam<boundary_id_type>("outer_boundary_id") : 0), // _outer_boundary_name(isParamValid("outer_boundary_name") ? getParam<std::string>("outer_boundary_name") : std::string("outside")), _extra_circle_radii(getParam<std::vector<Real>>("extra_circle_radii")), _extra_circle_num_segments(getParam<std::vector<unsigned int>>("extra_circle_num_segments")) { // confirm either id or name (exclusive or) for inner mesh boundary is provided if ((!isParamValid("inner_boundary_id") && !isParamValid("inner_boundary_name")) || (isParamValid("inner_boundary_id") && isParamValid("inner_boundary_name"))) { paramError( "inner_boundary_id", "Either 'inner_boundary_id' or 'inner_boundary_name' must be provided, but not both."); } // confirm Steiner inputs are equal length if (_extra_circle_radii.size() != _extra_circle_num_segments.size()) { paramError( "extra_circle_num_segments", "The size of 'extra_circle_num_segments' must be equal to the size of 'extra_circle_radii'."); } } std::unique_ptr<MeshBase> TriangulatedMeshGenerator::generate() { // // Set up mesh based on input inner mesh // std::unique_ptr<MeshBase> mesh = std::move(_inner_boundary_mesh); BoundaryInfo & boundary_info = mesh->get_boundary_info(); // set inner boundary id based on give input if(isParamValid("inner_boundary_id")) { _inner_boundary_id = getParam<boundary_id_type>("inner_boundary_id"); } if(isParamValid("inner_boundary_name")) { _inner_boundary_id = boundary_info.get_id_by_name(getParam<std::string>("inner_boundary_name")); } // build nodesets and sidesets boundary_info.build_node_list_from_side_list(); boundary_info.build_side_list_from_node_list(); // // extract boundary nodes from input mesh inner boundary // poly2tri requires input boundary nodes be sorted in connected order // std::vector<Node*> inner_boundary_nodes; _create_sorted_boundary_node_list(mesh, inner_boundary_nodes); // // C2T storage // /// Polylines std::vector<p2t::Point*> outer_polyline; std::vector<p2t::Point*> inner_polyline; std::vector<p2t::Point*> steiner_points; // store association map for reference std::map<p2t::Point*, Node*> point_node_map; // // Inner P2T boundary; extract from existing mesh // // POLYLINE NEEDS TO BE DIRECTED // DEBUG // std::cout << "Created Inner Polyline" << std::endl; for (Node* node : inner_boundary_nodes) { // extract (x, y) coords Real x = (*node)(0); Real y = (*node)(1); // create Point p2t::Point *point = new p2t::Point(x, y); // add to inner boundary list inner_polyline.push_back(point); // add to association map point_node_map[point] = node; // DEBUG // std::cout << *node << std::endl; } // // Outer P2T boundary; create circle from input parameters // // DEBUG // std::cout << "Creating Outer Polyline" << std::endl; // radial spacing Real d_theta = 2.0 * M_PI / _outer_circle_num_segments; for (unsigned int i = 0; i < _outer_circle_num_segments; i++) { // rotation angle Real theta = i * d_theta; // calculate (x, y) coords Real x = _outer_circle_radius * std::cos(theta); Real y = _outer_circle_radius * std::sin(theta); // create Point p2t::Point *point = new p2t::Point(x, y); // add to outer boundary list outer_polyline.push_back(point); // create Node and add to mesh Node *node = mesh->add_point(Point(x, y, 0.0)); // add to association map point_node_map[point] = node; // DEBUG // std::cout << *node << std::endl; } // // Additional Steiner points; create additional circles of Steiner points between inner and outer boundaries. // // DEBUG // std::cout << "Creating Steiner points" << std::endl; for (std::vector<unsigned int>::size_type idx = 0; idx < _extra_circle_radii.size(); idx++) { // extract Steiner point circle parameters Real num_segments = _extra_circle_num_segments[idx]; Real radius = _extra_circle_radii[idx]; // radial spacing d_theta = 2.0 * M_PI / num_segments; for (unsigned int i = 0; i < num_segments; i++) { // rotation angle Real theta = i * d_theta; // calculate (x, y) coords Real x = radius * std::cos(theta); Real y = radius * std::sin(theta); // create Point p2t::Point *point = new p2t::Point(x, y); // add to Steiner point list steiner_points.push_back(point); // create Node and add to mesh Node *node = mesh->add_point(Point(x, y, 0.0)); // add to association map point_node_map[point] = node; // DEBUG // std::cout << *node << std::endl; } } // // Create P2T CDT and add primary (outer) polyline // NOTE: polyline must be a simple polygon. The polyline's points constitute constrained edges. No repeat points!!! // p2t::CDT* cdt = new p2t::CDT(outer_polyline); // Add inner boundary cdt->AddHole(inner_polyline); // Add Steiner points for (const auto& point : steiner_points) { cdt->AddPoint(point); } // DEBUG // std::cout << "Triangulating" << std::endl; // Triangulate! cdt->Triangulate(); // DEBUG // std::cout << "Triangulating complete" << std::endl; // // Translate triangulated C2T points/triangles to libMesh nodes/Tri3s // // Extract triangle list from triangulation std::vector<p2t::Triangle*> triangles = cdt->GetTriangles(); // process each P2T triangle into libMesh Tri3 for (p2t::Triangle* triangle : triangles) { // create Tri3 element Tri3* tri_elem = new Tri3(); // process each point on triangle for (const int i : std::vector<int>{0,1,2}) { // extract p2t::point from triangle p2t::Point* point = triangle->GetPoint(i); // check if node has been created for point // if not, create and add to map if (point_node_map.find(point) == point_node_map.end()) { point_node_map[point] = mesh->add_point(Point(point->x, point->y, 0.0)); } // retrieve node and add to element tri_elem->set_node(i) = point_node_map[point]; } // set element subdomain id tri_elem->subdomain_id() = _tri_subdomain_id; // add completed element to mesh mesh->add_elem(tri_elem); } // // add nodesets for boundaries // for (p2t::Point* point : outer_polyline) { boundary_info.add_node(point_node_map[point], _outer_boundary_id); } // boundary_info.sideset_name(_outer_boundary_id) = _outer_boundary_name; // generate sidesets from nodesets // boundary_info.build_side_list_from_node_list(); // // Cleanup P2T objects // delete cdt; _clearPoints(outer_polyline); _clearPoints(inner_polyline); _clearPoints(steiner_points); // // finalize mesh and return // mesh->prepare_for_use(); return dynamic_pointer_cast<MeshBase>(mesh); } void TriangulatedMeshGenerator::_create_sorted_boundary_node_list(std::unique_ptr<MeshBase>& mesh, std::vector<Node*>& inner_boundary_nodes) { BoundaryInfo & boundary_info = mesh->get_boundary_info(); // poly2tri requires input boundary nodes be in connected order // create edge node pairs to sort by connectivity // vector of <element_id, side_id, boundary_id> tuples auto side_list = boundary_info.build_side_list(); std::vector<std::pair<dof_id_type, dof_id_type>> boundary_node_assm; // create edge node pairs for sides on the specified boundary for (const auto entry : side_list) { // select out tuple components dof_id_type element_id = std::get<0>(entry); unsigned short int side_id = std::get<1>(entry); boundary_id_type boundary_id = std::get<2>(entry); // skip sides not in given boundary id if (boundary_id != _inner_boundary_id) { continue; } // select out nodes for given side and add to list auto side = mesh->elem_ptr(element_id)->side_ptr(side_id); boundary_node_assm.push_back( std::make_pair(side->node_id(0), side->node_id(1)) ); } // // sort boundary sides into connected order // std::vector<dof_id_type> boundary_ordered_node_list; bool isFlipped = false; // start sorted node list with nodes from first side in side list, first two nodes are sorted // remove side from side list to be sorted boundary_ordered_node_list.push_back(boundary_node_assm.front().first); boundary_ordered_node_list.push_back(boundary_node_assm.front().second); boundary_node_assm.erase(boundary_node_assm.begin()); // save initial length of the list, size will shrink during loop const unsigned int boundary_node_assm_size_0 = boundary_node_assm.size(); // iterate over all remaining side pairs for (unsigned int i = 0; i < boundary_node_assm_size_0; i++) { // use the last node in the sorted node list for lookup // find the side in the remaining side list that connects to this node dof_id_type end_node_id = boundary_ordered_node_list.back(); // create lambda functions to search remaining side list // lambda to check if current end_node_id is in pair first position auto node_in_first_pos = [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) { return old_id_pair.first == end_node_id; }; // lambda to check if current end_node_id is in pair second position auto node_in_second_pos = [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) { return old_id_pair.second == end_node_id; }; // search for pair with current end_node_id in first position auto result = std::find_if( boundary_node_assm.begin(), boundary_node_assm.end(), node_in_first_pos); // check if first location pair was found // if not, re-search in second position bool match_first; if (result != boundary_node_assm.end()) { match_first = true; } else { match_first = false; result = std::find_if( boundary_node_assm.begin(), boundary_node_assm.end(), node_in_second_pos); } // check that a pair was found in either first or second position if (result != boundary_node_assm.end()) { // based on where the existing node was found // add the correct connected node to sorted node list boundary_ordered_node_list.push_back(match_first ? (*result).second : (*result).first); // remove pair from remaining side list boundary_node_assm.erase(result); } else { // If there are still elements in boundary_node_assm and result == // boundary_node_assm.end(), this means the boundary is not a loop, the // boundary_ordered_node_list is flipped and try the other direction Has not // been tested yet. if (isFlipped) { mooseError("The boundary has more than one segments. This code does not work for that case."); } isFlipped = true; std::reverse(boundary_ordered_node_list.begin(), boundary_ordered_node_list.end()); // As this iteration is wasted, reset the iterator i--; } } // If the boundary is a loop, remove the last node as it should be the same as // the first one if (boundary_ordered_node_list.front() == boundary_ordered_node_list.back()) { boundary_ordered_node_list.erase(boundary_ordered_node_list.end() - 1); } // resolve node_ids to Node pointers for (dof_id_type node_id : boundary_ordered_node_list) { Node *node = mesh->node_ptr(node_id); inner_boundary_nodes.push_back(node); } } void TriangulatedMeshGenerator::_clearPoints(std::vector<p2t::Point*>& point_list) { for (auto point : point_list) { delete point; } point_list.clear(); } <commit_msg>Removed development std::cout debug statements.<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "TriangulatedMeshGenerator.h" // poly2tri triangulation library #include "poly2tri.h" registerMooseObject("ReactorApp", TriangulatedMeshGenerator); InputParameters TriangulatedMeshGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addRangeCheckedParam<SubdomainID>( "subdomain_id", "subdomain_id>=0", "The subdomain ID given to the TRI3 elements in the triangulation."); params.addRequiredParam<MeshGeneratorName>( "inner_boundary_mesh", "The mesh to use for the inner boundary of the triangulation."); params.addRangeCheckedParam<boundary_id_type>( "inner_boundary_id", "inner_boundary_id>=0", "The boundary ID of the inner mesh outer boundary."); params.addParam<std::string>( "inner_boundary_name", "The boundary name of the inner mesh outer boundary."); params.addRequiredRangeCheckedParam<Real>( "outer_circle_radius", "outer_circle_radius>0", "Radius of outer circle boundary."); params.addRequiredRangeCheckedParam<unsigned int>( "outer_circle_num_segments", "outer_circle_num_segments>0", "Number of radial segments to subdivide outer circle boundary."); params.addRangeCheckedParam<boundary_id_type>( "outer_boundary_id", "outer_boundary_id>=0", "The boundary id for the generated mesh outer boundary."); // params.addParam<std::string>( // "outer_boundary_name", // "The boundary name of the generated mesh outer boundary."); params.addParam<std::vector<Real>>( "extra_circle_radii", "Radii of extra Steiner point circles."); params.addParam<std::vector<unsigned int>>( "extra_circle_num_segments", "Number of segments for extra Steiner point circles."); params.addClassDescription( "This TriangulatedMeshGenerator object is designed to generate " "a triangulated mesh between a generated outer circle boundary " "and a provided inner mesh."); return params; } TriangulatedMeshGenerator::TriangulatedMeshGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _tri_subdomain_id(isParamValid("subdomain_id") ? getParam<SubdomainID>("subdomain_id") : 0), _inner_boundary_mesh(getMesh("inner_boundary_mesh")), _outer_circle_radius(getParam<Real>("outer_circle_radius")), _outer_circle_num_segments(getParam<unsigned int>("outer_circle_num_segments")), _outer_boundary_id(isParamValid("outer_boundary_id") ? getParam<boundary_id_type>("outer_boundary_id") : 0), // _outer_boundary_name(isParamValid("outer_boundary_name") ? getParam<std::string>("outer_boundary_name") : std::string("outside")), _extra_circle_radii(getParam<std::vector<Real>>("extra_circle_radii")), _extra_circle_num_segments(getParam<std::vector<unsigned int>>("extra_circle_num_segments")) { // confirm either id or name (exclusive or) for inner mesh boundary is provided if ((!isParamValid("inner_boundary_id") && !isParamValid("inner_boundary_name")) || (isParamValid("inner_boundary_id") && isParamValid("inner_boundary_name"))) { paramError( "inner_boundary_id", "Either 'inner_boundary_id' or 'inner_boundary_name' must be provided, but not both."); } // confirm Steiner inputs are equal length if (_extra_circle_radii.size() != _extra_circle_num_segments.size()) { paramError( "extra_circle_num_segments", "The size of 'extra_circle_num_segments' must be equal to the size of 'extra_circle_radii'."); } } std::unique_ptr<MeshBase> TriangulatedMeshGenerator::generate() { // // Set up mesh based on input inner mesh // std::unique_ptr<MeshBase> mesh = std::move(_inner_boundary_mesh); BoundaryInfo & boundary_info = mesh->get_boundary_info(); // set inner boundary id based on give input if(isParamValid("inner_boundary_id")) { _inner_boundary_id = getParam<boundary_id_type>("inner_boundary_id"); } if(isParamValid("inner_boundary_name")) { _inner_boundary_id = boundary_info.get_id_by_name(getParam<std::string>("inner_boundary_name")); } // build nodesets and sidesets boundary_info.build_node_list_from_side_list(); boundary_info.build_side_list_from_node_list(); // // extract boundary nodes from input mesh inner boundary // poly2tri requires input boundary nodes be sorted in connected order // std::vector<Node*> inner_boundary_nodes; _create_sorted_boundary_node_list(mesh, inner_boundary_nodes); // // C2T storage // /// Polylines std::vector<p2t::Point*> outer_polyline; std::vector<p2t::Point*> inner_polyline; std::vector<p2t::Point*> steiner_points; // store association map for reference std::map<p2t::Point*, Node*> point_node_map; // // Inner P2T boundary; extract from existing mesh // // POLYLINE NEEDS TO BE DIRECTED for (Node* node : inner_boundary_nodes) { // extract (x, y) coords Real x = (*node)(0); Real y = (*node)(1); // create Point p2t::Point *point = new p2t::Point(x, y); // add to inner boundary list inner_polyline.push_back(point); // add to association map point_node_map[point] = node; } // // Outer P2T boundary; create circle from input parameters // // radial spacing Real d_theta = 2.0 * M_PI / _outer_circle_num_segments; for (unsigned int i = 0; i < _outer_circle_num_segments; i++) { // rotation angle Real theta = i * d_theta; // calculate (x, y) coords Real x = _outer_circle_radius * std::cos(theta); Real y = _outer_circle_radius * std::sin(theta); // create Point p2t::Point *point = new p2t::Point(x, y); // add to outer boundary list outer_polyline.push_back(point); // create Node and add to mesh Node *node = mesh->add_point(Point(x, y, 0.0)); // add to association map point_node_map[point] = node; } // // Additional Steiner points; create additional circles of Steiner points between inner and outer boundaries. // for (std::vector<unsigned int>::size_type idx = 0; idx < _extra_circle_radii.size(); idx++) { // extract Steiner point circle parameters Real num_segments = _extra_circle_num_segments[idx]; Real radius = _extra_circle_radii[idx]; // radial spacing d_theta = 2.0 * M_PI / num_segments; for (unsigned int i = 0; i < num_segments; i++) { // rotation angle Real theta = i * d_theta; // calculate (x, y) coords Real x = radius * std::cos(theta); Real y = radius * std::sin(theta); // create Point p2t::Point *point = new p2t::Point(x, y); // add to Steiner point list steiner_points.push_back(point); // create Node and add to mesh Node *node = mesh->add_point(Point(x, y, 0.0)); // add to association map point_node_map[point] = node; } } // // Create P2T CDT and add primary (outer) polyline // NOTE: polyline must be a simple polygon. The polyline's points constitute constrained edges. No repeat points!!! // p2t::CDT* cdt = new p2t::CDT(outer_polyline); // Add inner boundary cdt->AddHole(inner_polyline); // Add Steiner points for (const auto& point : steiner_points) { cdt->AddPoint(point); } // Triangulate! cdt->Triangulate(); // // Translate triangulated C2T points/triangles to libMesh nodes/Tri3s // // Extract triangle list from triangulation std::vector<p2t::Triangle*> triangles = cdt->GetTriangles(); // process each P2T triangle into libMesh Tri3 for (p2t::Triangle* triangle : triangles) { // create Tri3 element Tri3* tri_elem = new Tri3(); // process each point on triangle for (const int i : std::vector<int>{0,1,2}) { // extract p2t::point from triangle p2t::Point* point = triangle->GetPoint(i); // check if node has been created for point // if not, create and add to map if (point_node_map.find(point) == point_node_map.end()) { point_node_map[point] = mesh->add_point(Point(point->x, point->y, 0.0)); } // retrieve node and add to element tri_elem->set_node(i) = point_node_map[point]; } // set element subdomain id tri_elem->subdomain_id() = _tri_subdomain_id; // add completed element to mesh mesh->add_elem(tri_elem); } // // add nodesets for boundaries // for (p2t::Point* point : outer_polyline) { boundary_info.add_node(point_node_map[point], _outer_boundary_id); } // boundary_info.sideset_name(_outer_boundary_id) = _outer_boundary_name; // generate sidesets from nodesets // boundary_info.build_side_list_from_node_list(); // // Cleanup P2T objects // delete cdt; _clearPoints(outer_polyline); _clearPoints(inner_polyline); _clearPoints(steiner_points); // // finalize mesh and return // mesh->prepare_for_use(); return dynamic_pointer_cast<MeshBase>(mesh); } void TriangulatedMeshGenerator::_create_sorted_boundary_node_list(std::unique_ptr<MeshBase>& mesh, std::vector<Node*>& inner_boundary_nodes) { BoundaryInfo & boundary_info = mesh->get_boundary_info(); // poly2tri requires input boundary nodes be in connected order // create edge node pairs to sort by connectivity // vector of <element_id, side_id, boundary_id> tuples auto side_list = boundary_info.build_side_list(); std::vector<std::pair<dof_id_type, dof_id_type>> boundary_node_assm; // create edge node pairs for sides on the specified boundary for (const auto entry : side_list) { // select out tuple components dof_id_type element_id = std::get<0>(entry); unsigned short int side_id = std::get<1>(entry); boundary_id_type boundary_id = std::get<2>(entry); // skip sides not in given boundary id if (boundary_id != _inner_boundary_id) { continue; } // select out nodes for given side and add to list auto side = mesh->elem_ptr(element_id)->side_ptr(side_id); boundary_node_assm.push_back( std::make_pair(side->node_id(0), side->node_id(1)) ); } // // sort boundary sides into connected order // std::vector<dof_id_type> boundary_ordered_node_list; bool isFlipped = false; // start sorted node list with nodes from first side in side list, first two nodes are sorted // remove side from side list to be sorted boundary_ordered_node_list.push_back(boundary_node_assm.front().first); boundary_ordered_node_list.push_back(boundary_node_assm.front().second); boundary_node_assm.erase(boundary_node_assm.begin()); // save initial length of the list, size will shrink during loop const unsigned int boundary_node_assm_size_0 = boundary_node_assm.size(); // iterate over all remaining side pairs for (unsigned int i = 0; i < boundary_node_assm_size_0; i++) { // use the last node in the sorted node list for lookup // find the side in the remaining side list that connects to this node dof_id_type end_node_id = boundary_ordered_node_list.back(); // create lambda functions to search remaining side list // lambda to check if current end_node_id is in pair first position auto node_in_first_pos = [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) { return old_id_pair.first == end_node_id; }; // lambda to check if current end_node_id is in pair second position auto node_in_second_pos = [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) { return old_id_pair.second == end_node_id; }; // search for pair with current end_node_id in first position auto result = std::find_if( boundary_node_assm.begin(), boundary_node_assm.end(), node_in_first_pos); // check if first location pair was found // if not, re-search in second position bool match_first; if (result != boundary_node_assm.end()) { match_first = true; } else { match_first = false; result = std::find_if( boundary_node_assm.begin(), boundary_node_assm.end(), node_in_second_pos); } // check that a pair was found in either first or second position if (result != boundary_node_assm.end()) { // based on where the existing node was found // add the correct connected node to sorted node list boundary_ordered_node_list.push_back(match_first ? (*result).second : (*result).first); // remove pair from remaining side list boundary_node_assm.erase(result); } else { // If there are still elements in boundary_node_assm and result == // boundary_node_assm.end(), this means the boundary is not a loop, the // boundary_ordered_node_list is flipped and try the other direction Has not // been tested yet. if (isFlipped) { mooseError("The boundary has more than one segments. This code does not work for that case."); } isFlipped = true; std::reverse(boundary_ordered_node_list.begin(), boundary_ordered_node_list.end()); // As this iteration is wasted, reset the iterator i--; } } // If the boundary is a loop, remove the last node as it should be the same as // the first one if (boundary_ordered_node_list.front() == boundary_ordered_node_list.back()) { boundary_ordered_node_list.erase(boundary_ordered_node_list.end() - 1); } // resolve node_ids to Node pointers for (dof_id_type node_id : boundary_ordered_node_list) { Node *node = mesh->node_ptr(node_id); inner_boundary_nodes.push_back(node); } } void TriangulatedMeshGenerator::_clearPoints(std::vector<p2t::Point*>& point_list) { for (auto point : point_list) { delete point; } point_list.clear(); } <|endoftext|>
<commit_before>#include "StorageBulkCursor.h" #include "StorageEnvironment.h" #include "StoragePageCache.h" StorageBulkCursor::StorageBulkCursor() : dataPage(NULL, 0) { chunkID = 0; shard = NULL; env = NULL; isLast = false; } StorageBulkCursor::~StorageBulkCursor() { env->numBulkCursors = env->numBulkCursors - 1; } StorageKeyValue* StorageBulkCursor::First() { StorageChunk* chunk; StorageChunk** itChunk; itChunk = shard->chunks.First(); if (itChunk == NULL) return NULL; chunk = *itChunk; assert(chunk != NULL); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); return FromNextBunch(chunk); } StorageKeyValue* StorageBulkCursor::Next(StorageKeyValue* it) { StorageKeyValue* kv; StorageChunk* chunk; StorageChunk** itChunk; kv = dataPage.Next((StorageFileKeyValue*) it); if (kv != NULL) { assert(kv->GetKey().GetBuffer()[0] != 0); return kv; } // TODO: what if shard has been deleted? FOREACH(itChunk, shard->chunks) { if ((*itChunk)->GetChunkID() == chunkID) break; } if (itChunk == NULL) { chunk = shard->GetMemoChunk(); } else { assert(itChunk != NULL); // TODO: what if chunk has been deleted? chunk = *itChunk; } assert(chunk != NULL); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); kv = FromNextBunch(chunk); return kv; } void StorageBulkCursor::SetLast(bool isLast_) { isLast = isLast_; } ReadBuffer StorageBulkCursor::GetNextKey() { return ReadBuffer(nextKey); } void StorageBulkCursor::SetNextKey(ReadBuffer key) { nextKey.Write(key); } void StorageBulkCursor::AppendKeyValue(StorageKeyValue* kv) { dataPage.Append(kv); } void StorageBulkCursor::FinalizeKeyValues() { dataPage.Finalize(); } StorageKeyValue* StorageBulkCursor::FromNextBunch(StorageChunk* chunk) { StorageChunk** itChunk; while (true) { if (!isLast) { dataPage.Reset(); chunk->NextBunch(*this, shard); if (dataPage.First()) return dataPage.First(); else continue; } // go to next chunk FOREACH(itChunk, shard->chunks) { if ((*itChunk)->GetChunkID() == chunkID) { Log_Debug("Cursor next chunk"); itChunk = shard->chunks.Next(itChunk); isLast = false; break; } } if (itChunk) { chunk = *itChunk; chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); } else { if (shard->GetMemoChunk()->GetChunkID() == chunkID) return NULL; // end of iteration // iterate memoChunk chunk = shard->GetMemoChunk(); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); } dataPage.Reset(); } } void StorageBulkCursor::SetEnvironment(StorageEnvironment* env_) { env = env_; } void StorageBulkCursor::SetShard(StorageShard* shard_) { shard = shard_; } <commit_msg>Fixed bug in StorageBulkCursor.<commit_after>#include "StorageBulkCursor.h" #include "StorageEnvironment.h" #include "StoragePageCache.h" StorageBulkCursor::StorageBulkCursor() : dataPage(NULL, 0) { chunkID = 0; shard = NULL; env = NULL; isLast = false; } StorageBulkCursor::~StorageBulkCursor() { env->numBulkCursors = env->numBulkCursors - 1; } StorageKeyValue* StorageBulkCursor::First() { StorageChunk* chunk; StorageChunk** itChunk; itChunk = shard->chunks.First(); if (itChunk == NULL) chunk = shard->GetMemoChunk(); else chunk = *itChunk; assert(chunk != NULL); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); return FromNextBunch(chunk); } StorageKeyValue* StorageBulkCursor::Next(StorageKeyValue* it) { StorageKeyValue* kv; StorageChunk* chunk; StorageChunk** itChunk; kv = dataPage.Next((StorageFileKeyValue*) it); if (kv != NULL) { assert(kv->GetKey().GetBuffer()[0] != 0); return kv; } // TODO: what if shard has been deleted? FOREACH(itChunk, shard->chunks) { if ((*itChunk)->GetChunkID() == chunkID) break; } if (itChunk == NULL) { chunk = shard->GetMemoChunk(); } else { assert(itChunk != NULL); // TODO: what if chunk has been deleted? chunk = *itChunk; } assert(chunk != NULL); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); kv = FromNextBunch(chunk); return kv; } void StorageBulkCursor::SetLast(bool isLast_) { isLast = isLast_; } ReadBuffer StorageBulkCursor::GetNextKey() { return ReadBuffer(nextKey); } void StorageBulkCursor::SetNextKey(ReadBuffer key) { nextKey.Write(key); } void StorageBulkCursor::AppendKeyValue(StorageKeyValue* kv) { dataPage.Append(kv); } void StorageBulkCursor::FinalizeKeyValues() { dataPage.Finalize(); } StorageKeyValue* StorageBulkCursor::FromNextBunch(StorageChunk* chunk) { StorageChunk** itChunk; while (true) { if (!isLast) { dataPage.Reset(); chunk->NextBunch(*this, shard); if (dataPage.First()) return dataPage.First(); else continue; } // go to next chunk FOREACH(itChunk, shard->chunks) { if ((*itChunk)->GetChunkID() == chunkID) { Log_Debug("Cursor next chunk"); itChunk = shard->chunks.Next(itChunk); isLast = false; break; } } if (itChunk) { chunk = *itChunk; chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); } else { if (shard->GetMemoChunk()->GetChunkID() == chunkID) return NULL; // end of iteration // iterate memoChunk chunk = shard->GetMemoChunk(); chunkID = chunk->GetChunkID(); // Log_Message("Iterating chunk %U", chunkID); } dataPage.Reset(); } } void StorageBulkCursor::SetEnvironment(StorageEnvironment* env_) { env = env_; } void StorageBulkCursor::SetShard(StorageShard* shard_) { shard = shard_; } <|endoftext|>
<commit_before>//#define NO_IMPORT_ARRAY //#define PY_ARRAY_UNIQUE_SYMBOL 23847 //#define NPY_ENABLE_SEPARATE_COMPILATION #ifdef LINK_PYTHON_THREADS #include "gil_release.h" #endif #include "boilerplate.h" /*#include <infer_machine/distribution_map.h> #include <infer_machine/hier_infer_machine.h> //#include <dataset_2d/outdoor_2d.h> #include <graph_segment/fh_segmenter.h> #include <region_generic/region_data.h> #include <region_2d/region_2d_level.h> #include <v_regressor/v_random_forest.h> #include <pclassifier/boosted_maxent.h> #include "voc_felz_features.h" */ #include <mymex.h> bool numpy_satisfy_properties(PyArrayObject *ao, int nd, int* dims, int type_num, bool yell) { if (ao->base != NULL) { if (yell) { printf("OH NO! base was %p instead of NULL!\n", ao->base); fflush(stdout); } return false; } if (!(ao->flags | NPY_C_CONTIGUOUS)) { if (yell) { printf("ON NO! NPY_C_CONTIGUOUS FALSE!\n"); fflush(stdout); } return false; } if (!(ao->flags | NPY_OWNDATA)) { if (yell) { printf("ON NO! NPY_OWNDATA FALSE!\n"); fflush(stdout); } return false; } if (!(ao->flags | NPY_ALIGNED)) { if (yell) { printf("ON NO! NPY_ALIGNED FALSE!\n"); fflush(stdout); } return false; } if (nd >= 0) { if (ao->nd != nd) { if (yell) { printf("numpy_satisfy_properties OH NO! nd = %d and desired nd = %d!\n", ao->nd, nd); fflush(stdout); } return false; } if (dims != NULL) { for (int i=0; i<nd; i++) { if (ao->dimensions[i] != dims[i]) { if (yell) { printf("OH NO! dims[%d] = %ld and desired %d!\n", i, ao->dimensions[i], dims[i]); fflush(stdout); } return false; } } } } if (ao->descr->type_num != type_num) { if (yell) { printf("OH NO! type_num is %d and desired %d!\n", ao->descr->type_num, type_num); fflush(stdout); } return false; } return true; } struct mxArray_to_numpy_str { static PyObject *convert(const mxArray &m) { if (m.NDim == 2) { /* fucking column major bitches */ npy_intp dims[] = {m.Dims[0], m.Dims[1]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0]; i++) { for (int j=0; j<dims[1]; j++) { real fake; ((real*)retval->data)[i*dims[1] + j] = m.get2D(i, j, fake); } } return (PyObject*)retval; } else if (m.NDim == 3) { npy_intp dims[] = {m.Dims[0], m.Dims[1], m.Dims[2]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { real fake; ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \ m.get3D(row, col, c, fake); } } } return (PyObject*)retval; } else { printf("OH NO! Tried to convert mxArray of nd %d to numpy!\n", m.NDim); } } }; struct mxArray_from_numpy_str { static void* convertible(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; int cls = npy_real_type(); if (!numpy_satisfy_properties(ao, 2, NULL, cls, true) && !numpy_satisfy_properties(ao, 3, NULL, cls, true)) return 0; return (void*)o; } static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<mxArray>*)data)->storage.bytes; PyArrayObject *ao = (PyArrayObject*)o; new (storage) mxArray(ao->nd, (int*)ao->dimensions, mx_real_type(), mxREAL); mxArray* m = (mxArray*)storage; data->convertible = storage; if (ao->nd == 2) { for (int col=0; col < m->Dims[1]; col++) { for (int row=0; row < m->Dims[0]; row++) { m->set2D(row, col, ((real*)ao->data)[row*m->Dims[1]* + col]); } } } else if (ao->nd == 3) { for (int c=0; c < m->Dims[2]; c++) { for (int col=0; col < m->Dims[1]; col++) { for (int row=0; row < m->Dims[0]; row++) { m->set3D(row, col, c, ((real*)ao->data)[row*m->Dims[1]*m->Dims[2] + col*m->Dims[2] + c]); } } } } } mxArray_from_numpy_str() { converter::registry::push_back(&convertible, &construct, type_id<mxArray>()); } }; // template <typename T, typename U> // struct vec_vec_from_numpy_str { // static void *convertible (PyObject *) // { // PyArrayObject *ao = (PyArrayObject*)o; // if (!numpy_satisfy_properties(ao, 2, NULL, U, true)) // return 0; // return (void*)o; // } // static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) // { // void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes; // PyArrayObject *ao = (PyArrayObject*)o; // new (storage) std::vector<std::vector<T> >(int(ao->dimensions[0]), // std::vector<T>(int(ao->dimensions[1]), 0)); // data->convertible = storage; // } // } struct vec_from_numpy_str { static void* convertible(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) return 0; return (void*)o; } static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes; PyArrayObject *ao = (PyArrayObject*)o; new (storage) vector<real>(ao->dimensions[0]); vector<real> *v = (vector<real>*)storage; data->convertible = storage; for (int i=0; i<ao->dimensions[0]; i++) { (*v)[i] = ((real*)ao->data)[i]; } } vec_from_numpy_str() { converter::registry::push_back(&convertible, &construct, type_id<vector<real> >()); } }; struct vec_to_numpy_str { static PyObject *convert(const vector<real>& v) { npy_intp dims[] = {v.size()}; PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type()); for (int i=0; i<v.size(); i++) { ((real*)ao->data)[i] = v[i]; } return (PyObject*)ao; } }; PyObject *vecvecvec_to_numpy(vector<vector<vector<real> > > v) { npy_intp dims[] = {v.size(), v[0].size(), v[0][0].size()}; PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { for (int k=0; k<dims[2]; k++) { ((real*)retval->data)[i*dims[0]*dims[1] + j*dims[1] + k] = v[i][j][k]; } } } return (PyObject*)retval; } PyObject *vecvec_to_numpy(const vector<const vector<real> *> v) { npy_intp dims[] = {v.size(), v[0]->size()}; PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { ((real*)retval->data)[i*dims[1] + j] = (*v[i])[j]; } } return (PyObject*)retval; } PyObject *vecvec_real_to_numpy(vector<vector<real> > v) { npy_intp dims[] = {v.size(), v[0].size()}; printf("dims[0]: %d, dims[1]: %d\n", dims[0], dims[1]); fflush(stdout); PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { ((real*)retval->data)[i*dims[1] + j] = v[i][j]; } } return (PyObject*)retval; } PyObject* mxarray2d_to_numpy(mxArray* arr) { /* fucking column major bitches */ npy_intp dims[] = {arr->Dims[0], arr->Dims[1]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0]; i++) { for (int j=0; j<dims[1]; j++) { real fake; ((real*)retval->data)[i*dims[1] + j] = arr->get2D(i, j, fake); } } return (PyObject*)retval; } mxArray* numpy_to_mxarray3d(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 3, NULL, npy_real_type(), true)) { return NULL; } int dims[] = {ao->dimensions[0], ao->dimensions[1], ao->dimensions[2]}; mxArray* ret = mxCreateNumericArray(3, dims, mx_real_type(), mxREAL); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { ret->set3D(row, col, c, ((real*)ao->data)[row*dims[1]*dims[2] + col*dims[2] + c]); } } } return ret; } PyObject* mxarray3d_to_numpy(mxArray* arr) { npy_intp dims[] = {arr->Dims[0], arr->Dims[1], arr->Dims[2]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { real fake; ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \ arr->get3D(row, col, c, fake); } } } return (PyObject*)retval; } vector<real> numpy_to_vec(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) { return vector<real>(); } vector<real> ret(ao->dimensions[0]); for (int i=0; i<ao->dimensions[0]; i++) { ret[i] = ((real*)ao->data)[i]; } return ret; } PyObject* vec_to_numpy(vector<real> v) { npy_intp dims[] = {v.size()}; PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type()); for (int i=0; i<v.size(); i++) { ((real*)ao->data)[i] = v[i]; } return (PyObject*)ao; } <commit_msg>Removed annoying print<commit_after>//#define NO_IMPORT_ARRAY //#define PY_ARRAY_UNIQUE_SYMBOL 23847 //#define NPY_ENABLE_SEPARATE_COMPILATION #ifdef LINK_PYTHON_THREADS #include "gil_release.h" #endif #include "boilerplate.h" /*#include <infer_machine/distribution_map.h> #include <infer_machine/hier_infer_machine.h> //#include <dataset_2d/outdoor_2d.h> #include <graph_segment/fh_segmenter.h> #include <region_generic/region_data.h> #include <region_2d/region_2d_level.h> #include <v_regressor/v_random_forest.h> #include <pclassifier/boosted_maxent.h> #include "voc_felz_features.h" */ #include <mymex.h> bool numpy_satisfy_properties(PyArrayObject *ao, int nd, int* dims, int type_num, bool yell) { if (ao->base != NULL) { if (yell) { printf("OH NO! base was %p instead of NULL!\n", ao->base); fflush(stdout); } return false; } if (!(ao->flags | NPY_C_CONTIGUOUS)) { if (yell) { printf("ON NO! NPY_C_CONTIGUOUS FALSE!\n"); fflush(stdout); } return false; } if (!(ao->flags | NPY_OWNDATA)) { if (yell) { printf("ON NO! NPY_OWNDATA FALSE!\n"); fflush(stdout); } return false; } if (!(ao->flags | NPY_ALIGNED)) { if (yell) { printf("ON NO! NPY_ALIGNED FALSE!\n"); fflush(stdout); } return false; } if (nd >= 0) { if (ao->nd != nd) { if (yell) { printf("numpy_satisfy_properties OH NO! nd = %d and desired nd = %d!\n", ao->nd, nd); fflush(stdout); } return false; } if (dims != NULL) { for (int i=0; i<nd; i++) { if (ao->dimensions[i] != dims[i]) { if (yell) { printf("OH NO! dims[%d] = %ld and desired %d!\n", i, ao->dimensions[i], dims[i]); fflush(stdout); } return false; } } } } if (ao->descr->type_num != type_num) { if (yell) { printf("OH NO! type_num is %d and desired %d!\n", ao->descr->type_num, type_num); fflush(stdout); } return false; } return true; } struct mxArray_to_numpy_str { static PyObject *convert(const mxArray &m) { if (m.NDim == 2) { /* fucking column major bitches */ npy_intp dims[] = {m.Dims[0], m.Dims[1]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0]; i++) { for (int j=0; j<dims[1]; j++) { real fake; ((real*)retval->data)[i*dims[1] + j] = m.get2D(i, j, fake); } } return (PyObject*)retval; } else if (m.NDim == 3) { npy_intp dims[] = {m.Dims[0], m.Dims[1], m.Dims[2]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { real fake; ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \ m.get3D(row, col, c, fake); } } } return (PyObject*)retval; } else { printf("OH NO! Tried to convert mxArray of nd %d to numpy!\n", m.NDim); } } }; struct mxArray_from_numpy_str { static void* convertible(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; int cls = npy_real_type(); if (!numpy_satisfy_properties(ao, 2, NULL, cls, true) && !numpy_satisfy_properties(ao, 3, NULL, cls, true)) return 0; return (void*)o; } static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<mxArray>*)data)->storage.bytes; PyArrayObject *ao = (PyArrayObject*)o; new (storage) mxArray(ao->nd, (int*)ao->dimensions, mx_real_type(), mxREAL); mxArray* m = (mxArray*)storage; data->convertible = storage; if (ao->nd == 2) { for (int col=0; col < m->Dims[1]; col++) { for (int row=0; row < m->Dims[0]; row++) { m->set2D(row, col, ((real*)ao->data)[row*m->Dims[1]* + col]); } } } else if (ao->nd == 3) { for (int c=0; c < m->Dims[2]; c++) { for (int col=0; col < m->Dims[1]; col++) { for (int row=0; row < m->Dims[0]; row++) { m->set3D(row, col, c, ((real*)ao->data)[row*m->Dims[1]*m->Dims[2] + col*m->Dims[2] + c]); } } } } } mxArray_from_numpy_str() { converter::registry::push_back(&convertible, &construct, type_id<mxArray>()); } }; // template <typename T, typename U> // struct vec_vec_from_numpy_str { // static void *convertible (PyObject *) // { // PyArrayObject *ao = (PyArrayObject*)o; // if (!numpy_satisfy_properties(ao, 2, NULL, U, true)) // return 0; // return (void*)o; // } // static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) // { // void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes; // PyArrayObject *ao = (PyArrayObject*)o; // new (storage) std::vector<std::vector<T> >(int(ao->dimensions[0]), // std::vector<T>(int(ao->dimensions[1]), 0)); // data->convertible = storage; // } // } struct vec_from_numpy_str { static void* convertible(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) return 0; return (void*)o; } static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data) { void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes; PyArrayObject *ao = (PyArrayObject*)o; new (storage) vector<real>(ao->dimensions[0]); vector<real> *v = (vector<real>*)storage; data->convertible = storage; for (int i=0; i<ao->dimensions[0]; i++) { (*v)[i] = ((real*)ao->data)[i]; } } vec_from_numpy_str() { converter::registry::push_back(&convertible, &construct, type_id<vector<real> >()); } }; struct vec_to_numpy_str { static PyObject *convert(const vector<real>& v) { npy_intp dims[] = {v.size()}; PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type()); for (int i=0; i<v.size(); i++) { ((real*)ao->data)[i] = v[i]; } return (PyObject*)ao; } }; PyObject *vecvecvec_to_numpy(vector<vector<vector<real> > > v) { npy_intp dims[] = {v.size(), v[0].size(), v[0][0].size()}; PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { for (int k=0; k<dims[2]; k++) { ((real*)retval->data)[i*dims[0]*dims[1] + j*dims[1] + k] = v[i][j][k]; } } } return (PyObject*)retval; } PyObject *vecvec_to_numpy(const vector<const vector<real> *> v) { npy_intp dims[] = {v.size(), v[0]->size()}; PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { ((real*)retval->data)[i*dims[1] + j] = (*v[i])[j]; } } return (PyObject*)retval; } PyObject *vecvec_real_to_numpy(vector<vector<real> > v) { npy_intp dims[] = {v.size(), v[0].size()}; PyArrayObject *retval; retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0];i++) { for (int j=0; j<dims[1]; j++) { ((real*)retval->data)[i*dims[1] + j] = v[i][j]; } } return (PyObject*)retval; } PyObject* mxarray2d_to_numpy(mxArray* arr) { /* fucking column major bitches */ npy_intp dims[] = {arr->Dims[0], arr->Dims[1]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type()); for (int i=0; i<dims[0]; i++) { for (int j=0; j<dims[1]; j++) { real fake; ((real*)retval->data)[i*dims[1] + j] = arr->get2D(i, j, fake); } } return (PyObject*)retval; } mxArray* numpy_to_mxarray3d(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 3, NULL, npy_real_type(), true)) { return NULL; } int dims[] = {ao->dimensions[0], ao->dimensions[1], ao->dimensions[2]}; mxArray* ret = mxCreateNumericArray(3, dims, mx_real_type(), mxREAL); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { ret->set3D(row, col, c, ((real*)ao->data)[row*dims[1]*dims[2] + col*dims[2] + c]); } } } return ret; } PyObject* mxarray3d_to_numpy(mxArray* arr) { npy_intp dims[] = {arr->Dims[0], arr->Dims[1], arr->Dims[2]}; PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type()); for (int c=0; c<dims[2]; c++) { for (int col=0; col<dims[1]; col++) { for (int row=0; row<dims[0]; row++) { real fake; ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \ arr->get3D(row, col, c, fake); } } } return (PyObject*)retval; } vector<real> numpy_to_vec(PyObject *o) { PyArrayObject *ao = (PyArrayObject*)o; if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) { return vector<real>(); } vector<real> ret(ao->dimensions[0]); for (int i=0; i<ao->dimensions[0]; i++) { ret[i] = ((real*)ao->data)[i]; } return ret; } PyObject* vec_to_numpy(vector<real> v) { npy_intp dims[] = {v.size()}; PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type()); for (int i=0; i<v.size(); i++) { ((real*)ao->data)[i] = v[i]; } return (PyObject*)ao; } <|endoftext|>
<commit_before><commit_msg>Fixed symlink<commit_after><|endoftext|>
<commit_before>/* * datasetfibers.cpp * * Created on: Dec 12, 2012 * Author: Ralph Schurade */ #include "datasetfibers.h" #include "../../gui/gl/fiberrenderer.h" DatasetFibers::DatasetFibers( QString filename, QVector< QVector< float > > fibs, int numPoints, int numLines ) : Dataset( filename, Fn::DatasetType::FIBERS ), m_fibs( fibs ), m_renderer( 0 ) { m_properties.set( Fn::Property::NUM_POINTS, numPoints ); m_properties.set( Fn::Property::NUM_LINES, numLines ); m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true ); m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true ); } DatasetFibers::DatasetFibers( QVector< QVector< float > > fibs ) : Dataset( QString("new fibers"), Fn::DatasetType::FIBERS ), m_fibs( fibs ), m_renderer( 0 ) { int numPoints = 0; for ( int i = 0; i < fibs.size(); ++i ) { numPoints += fibs[i].size(); } m_properties.set( Fn::Property::NUM_POINTS, numPoints ); m_properties.set( Fn::Property::NUM_LINES, fibs.size() ); m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 1, true ); m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true ); } DatasetFibers::~DatasetFibers() { m_fibs.clear(); } QVector< QVector< float > > DatasetFibers::getFibs() { return m_fibs; } QVector< QVector< float > > DatasetFibers::getSelectedFibs() { if ( m_renderer == 0 ) { return m_fibs; } else { QVector<bool>selected = m_renderer->getSelection(); QVector<QVector<float> >out; for ( int i = 0; i < selected.size(); ++i ) { if ( selected[i] ) { out.push_back( m_fibs[i] ); } } return out; } } void DatasetFibers::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, QAbstractItemModel* globalModel, QAbstractItemModel* roiModel ) { if ( m_renderer == 0 ) { m_renderer = new FiberRenderer( roiModel, m_fibs ); m_renderer->setModel( globalModel ); m_renderer->init(); connect( m_properties.getProperty( Fn::Property::FIBER_COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) ); } m_renderer->setRenderParams( m_properties.get( Fn::Property::FIBER_COLORMODE ).toInt() ); m_renderer->draw( mvpMatrix, mvMatrixInverse ); } QString DatasetFibers::getValueAsString( int x, int y, int z ) { return QString( "" ); } <commit_msg>fix color mode selection for created fibers<commit_after>/* * datasetfibers.cpp * * Created on: Dec 12, 2012 * Author: Ralph Schurade */ #include "datasetfibers.h" #include "../../gui/gl/fiberrenderer.h" DatasetFibers::DatasetFibers( QString filename, QVector< QVector< float > > fibs, int numPoints, int numLines ) : Dataset( filename, Fn::DatasetType::FIBERS ), m_fibs( fibs ), m_renderer( 0 ) { m_properties.set( Fn::Property::NUM_POINTS, numPoints ); m_properties.set( Fn::Property::NUM_LINES, numLines ); m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true ); m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true ); } DatasetFibers::DatasetFibers( QVector< QVector< float > > fibs ) : Dataset( QString("new fibers"), Fn::DatasetType::FIBERS ), m_fibs( fibs ), m_renderer( 0 ) { int numPoints = 0; for ( int i = 0; i < fibs.size(); ++i ) { numPoints += fibs[i].size(); } m_properties.set( Fn::Property::NUM_POINTS, numPoints ); m_properties.set( Fn::Property::NUM_LINES, fibs.size() ); m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true ); m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true ); } DatasetFibers::~DatasetFibers() { m_fibs.clear(); } QVector< QVector< float > > DatasetFibers::getFibs() { return m_fibs; } QVector< QVector< float > > DatasetFibers::getSelectedFibs() { if ( m_renderer == 0 ) { return m_fibs; } else { QVector<bool>selected = m_renderer->getSelection(); QVector<QVector<float> >out; for ( int i = 0; i < selected.size(); ++i ) { if ( selected[i] ) { out.push_back( m_fibs[i] ); } } return out; } } void DatasetFibers::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, QAbstractItemModel* globalModel, QAbstractItemModel* roiModel ) { if ( m_renderer == 0 ) { m_renderer = new FiberRenderer( roiModel, m_fibs ); m_renderer->setModel( globalModel ); m_renderer->init(); connect( m_properties.getProperty( Fn::Property::FIBER_COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) ); } m_renderer->setRenderParams( m_properties.get( Fn::Property::FIBER_COLORMODE ).toInt() ); m_renderer->draw( mvpMatrix, mvMatrixInverse ); } QString DatasetFibers::getValueAsString( int x, int y, int z ) { return QString( "" ); } <|endoftext|>
<commit_before>#include <iostream> #include <set> #include <cassert> template <typename T> struct node { T data; node *left = nullptr, *right = nullptr; node(T data): data(data) {} }; template <typename T> class tree { node<T>* root = nullptr; public: bool contains(const T& data) { auto curr = root; while (curr != nullptr) { if (curr->data == data) return true; curr = data < curr->data ? curr->left : curr->right; } return false; } void insert(T data) { auto ptr = &root; while (auto curr = *ptr) { if (curr->data == data) return; ptr = data < curr->data ? &curr->left : &curr->right; } *ptr = new node<T>(data); } void remove(const T& data) { auto ptr = &root; while (auto curr = *ptr) { if (data == curr->data) { if (curr->left == nullptr) { *ptr = curr->right; } else if (curr->right == nullptr) { *ptr = curr->left; } else { auto l = curr->left, r = l->right; if (r == nullptr) { l->right = curr->right; *ptr = l; } else { while (r->right != nullptr) l = r, r = r->right; l->right = r->left; r->left = curr->left; r->right = curr->right; *ptr = r; } } delete curr; return; } ptr = data < curr->data ? &curr->left : &curr->right; } } }; int main() { tree<int> ours; std::set<int> theirs; int op_counts[] = {0, 0, 0}; for (int i = 0; i < 100000; ++i) { int data = rand() % 100; int op = rand() % 3; ++op_counts[op]; if (op == 0) { assert(ours.contains(data) == theirs.count(data)); } else if (op == 1) { ours.insert(data); theirs.insert(data); } else { assert(op == 2); ours.remove(data); theirs.erase(data); } } for (int n : op_counts) assert(n > 0); std::cout << "All tests passed" << std::endl; return 0; } <commit_msg>Add parent ptrs to bst; implement iterator<commit_after>#include <iostream> #include <set> #include <cassert> template <typename T> class tree { struct node { const T data; node *left = nullptr, *right = nullptr, *parent; node(T data, node* parent): data(data), parent(parent) {} }; struct iterator { node* n; iterator(node* n): n(n) {} bool operator==(iterator o) const { return n == o.n; } bool operator!=(iterator o) const { return n != o.n; } const T& operator*() const { return n->data; } const T* operator->() const { return &n->data; } iterator operator++(int) { auto copy = *this; ++(*this); return copy; } iterator& operator++() { if (n->right != nullptr) { n = n->right; while (n->left != nullptr) { n = n->left; } } else { while (n->parent != nullptr && n == n->parent->right) n = n->parent; n = n->parent; } return *this; } }; node* root = nullptr; public: bool contains(const T& data) const { auto n = root; while (n != nullptr) { if (n->data == data) return true; n = data < n->data ? n->left : n->right; } return false; } void insert(T data) { node* parent = nullptr; auto ptr = &root; while (auto n = *ptr) { if (n->data == data) return; parent = n; ptr = data < n->data ? &n->left : &n->right; } *ptr = new node(data, parent); } void remove(const T& data) { node* parent = nullptr; auto ptr = &root; while (auto n = *ptr) { if (data == n->data) { if (n->left == nullptr && n->right == nullptr) { *ptr = n->right; } else if (n->left == nullptr) { *ptr = n->right; n->right->parent = parent; } else if (n->right == nullptr) { *ptr = n->left; n->left->parent = parent; } else { auto l = n->left, r = l->right; if (r == nullptr) { l->right = n->right; l->parent = parent; n->right->parent = l; *ptr = l; } else { while (r->right != nullptr) l = r, r = r->right; l->right = r->left; if (l->right != nullptr) l->right->parent = l; r->left = n->left; r->right = n->right; r->parent = parent; n->left->parent = r; n->right->parent = r; *ptr = r; } } delete n; return; } parent = n; ptr = data < n->data ? &n->left : &n->right; } } iterator begin() const { if (!root) return end(); auto n = root; while (n->left != nullptr) n = n->left; return iterator(n); } iterator end() const { return iterator(nullptr); } }; int main() { tree<int> ours; std::set<int> theirs; int op_counts[] = {0, 0, 0, 0}; for (int i = 0; i < 1000000; ++i) { int data = rand() % 100; int op = rand() % 4; ++op_counts[op]; if (op == 0) { assert(ours.contains(data) == theirs.count(data)); } else if (op == 1) { ours.insert(data); theirs.insert(data); } else if (op == 2) { ours.remove(data); theirs.erase(data); } else { assert(op == 3); auto our_it = ours.begin(); auto their_it = theirs.begin(); while (our_it != ours.end() && their_it != theirs.end()) assert(*our_it++ == *their_it++); assert(our_it == ours.end() && their_it == theirs.end()); } } for (int n : op_counts) assert(n > 0); std::cout << "All tests passed" << std::endl; return 0; } <|endoftext|>
<commit_before>#include <osmium/visitor.hpp> #include <osmium/index/map/all.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/area/assembler.hpp> #include "generic_writer.hpp" #include "generic_handler.hpp" #include "merged_input.hpp" #include "write_handler.hpp" template <typename T> void apply_reader_simple(osmium::io::Reader &rd, T &h) { osmium::apply(rd, h); } template <typename T> void apply_reader_simple_with_location(osmium::io::Reader &rd, osmium::handler::NodeLocationsForWays<T> &l, BaseHandler &h) { osmium::apply(rd, l, h); } PyObject *invalidLocationExceptionType = NULL; PyObject *notFoundExceptionType = NULL; void translator1(osmium::invalid_location const&) { PyErr_SetString(invalidLocationExceptionType, "Invalid location"); } void translator2(osmium::not_found const&) { PyErr_SetString(notFoundExceptionType, "Element not found in index"); } PyObject* createExceptionClass(const char* name, PyObject* baseTypeObj = PyExc_Exception) { using std::string; namespace bp = boost::python; string scopeName = bp::extract<string>(bp::scope().attr("__name__")); string qualifiedName0 = scopeName + "." + name; char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str()); PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0); if(!typeObj) bp::throw_error_already_set(); bp::scope().attr(name) = bp::handle<>(bp::borrowed(typeObj)); return typeObj; } #include "index.cc" BOOST_PYTHON_MODULE(_osmium) { using namespace boost::python; docstring_options doc_options(true, true, false); invalidLocationExceptionType = createExceptionClass("InvalidLocationError", PyExc_RuntimeError); register_exception_translator<osmium::invalid_location>(&translator1); notFoundExceptionType = createExceptionClass("NotFoundError", PyExc_KeyError); register_exception_translator<osmium::not_found>(&translator2); class_<osmium::handler::NodeLocationsForWays<LocationTable>, boost::noncopyable>("NodeLocationsForWays", init<LocationTable&>()) .def("ignore_errors", &osmium::handler::NodeLocationsForWays<LocationTable>::ignore_errors) ; class_<SimpleHandlerWrap, boost::noncopyable>("SimpleHandler", "The most generic of OSM data handlers. For each data type " "a callback can be implemented where the object is processed. Note that " "all objects that are handed into the handler are only readable and are " "only valid until the end of the callback is reached. Any data that " "should be retained must be copied into other data structures.") .def("apply_file", &SimpleHandlerWrap::apply_file, (arg("self"), arg("filename"), arg("locations")=false, arg("idx")="sparse_mem_array"), "Apply the handler to the given file. If locations is true, then\n" "a location handler will be applied before, which saves the node\n" "positions. In that case, the type of this position index can be\n" "further selected in idx. If an area callback is implemented, then\n" "the file will be scanned twice and a location handler and a\n" "handler for assembling multipolygons and areas from ways will\n" "be executed.") .def("apply_buffer", &SimpleHandlerWrap::apply_buffer, (arg("self"), arg("buffer"), arg("format"), arg("locations")=false, arg("idx")="sparse_mem_array"), "Apply the handler to a string buffer. The buffer must be a\n" "byte string.") ; def("apply", &apply_reader_simple<BaseHandler>, "Apply a chain of handlers."); def("apply", &apply_reader_simple<osmium::handler::NodeLocationsForWays<LocationTable>>); def("apply", &apply_reader_simple_with_location<LocationTable>); class_<SimpleWriterWrap, boost::noncopyable>("SimpleWriter", "The most generic class to write osmium objects into a file. The writer " "takes a file name as its mandatory parameter. The file must not yet " "exist. The file type to output is determined from the file extension. " "The second (optional) parameter is the buffer size. osmium caches the " "output data in an internal memory buffer before writing it on disk. This " "parameter allows changing the default buffer size of 4MB. Larger buffers " "are normally better but you should be aware that there are normally multiple " "buffers in use during the write process.", init<const char*, unsigned long>()) .def(init<const char*>()) .def("add_node", &SimpleWriterWrap::add_node, (arg("self"), arg("node")), "Add a new node to the file. The node may be an ``osmium.osm.Node`` object, " "an ``osmium.osm.mutable.Node`` object or any other Python object that " "implements the same attributes.") .def("add_way", &SimpleWriterWrap::add_way, (arg("self"), arg("way")), "Add a new way to the file. The way may be an ``osmium.osm.Way`` object, " "an ``osmium.osm.mutable.Way`` object or any other Python object that " "implements the same attributes.") .def("add_relation", &SimpleWriterWrap::add_relation, (arg("self"), arg("relation")), "Add a new relation to the file. The relation may be an " "``osmium.osm.Relation`` object, an ``osmium.osm.mutable.Way`` " "object or any other Python object that implements the same attributes.") .def("close", &SimpleWriterWrap::close, args("self"), "Flush the remaining buffers and close the writer. While it is not " "strictly necessary to call this function explicitly, it is still " "strongly recommended to close the writer as soon as possible, so " "that the buffer memory can be freed.") ; class_<WriteHandler, boost::noncopyable>("WriteHandler", "Handler function that writes all data directly to a file." "The handler takes a file name as its mandatory parameter. The file " "must not yet exist. The file type to output is determined from the " "file extension. " "The second (optional) parameter is the buffer size. osmium caches the " "output data in an internal memory buffer before writing it on disk. This " "parameter allows changing the default buffer size of 4MB. Larger buffers " "are normally better but you should be aware that there are normally multiple " "buffers in use during the write process.", init<const char*, unsigned long>()) .def(init<const char*>()) .def("close", &WriteHandler::close, args("self"), "Flush the remaining buffers and close the writer. While it is not " "strictly necessary to call this function explicitly, it is still " "strongly recommended to close the writer as soon as possible, so " "that the buffer memory can be freed.") ; class_<pyosmium::MergeInputReader, boost::noncopyable>("MergeInputReader", "Collects data from multiple input files and sorts and optionally " "deduplicates the data before applying it to a handler.") .def("apply", &pyosmium::MergeInputReader::apply, (arg("self"), arg("handler"), arg("simplify")=true), "Apply collected data to a handler. The data will be sorted first. " "If `simplify` is true (default) then duplicates will be eliminated " "and only the newest version of each object kept. After the data " "has been applied the buffer of the MergeInputReader is empty and " "new data can be added for the next round of application.") .def("apply_to_reader", &pyosmium::MergeInputReader::apply_to_reader, (arg("self"), arg("reader"), arg("writer"), arg("with_history")=false), "Apply the collected data to data from the given `reader` and write " "the result to `writer`. This function can be used to merge the diff " "data together with other OSM data (for example when updating a " "planet file. If `with_history` is true, then the collected data will " "be applied verbatim without removing duplicates. This is important " "when using OSM history files as input.") .def("add_file", &pyosmium::MergeInputReader::add_file, (arg("self"), arg("file")), "Add data from a file to the internal cache. The file type will be " "determined from the file extension.") .def("add_buffer", &pyosmium::MergeInputReader::add_buffer, (arg("self"), arg("buffer"), arg("format")), "Add data from a byte buffer. The format of the input data must " "be given in the `format` argument as a string. The data will be " "copied into internal buffers, so that the input buffer can be " "safely discarded after the function has been called.") ; } <commit_msg>add documentation for SimpleHandler callbacks back<commit_after>#include <osmium/visitor.hpp> #include <osmium/index/map/all.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/area/assembler.hpp> #include "generic_writer.hpp" #include "generic_handler.hpp" #include "merged_input.hpp" #include "write_handler.hpp" template <typename T> void apply_reader_simple(osmium::io::Reader &rd, T &h) { osmium::apply(rd, h); } template <typename T> void apply_reader_simple_with_location(osmium::io::Reader &rd, osmium::handler::NodeLocationsForWays<T> &l, BaseHandler &h) { osmium::apply(rd, l, h); } PyObject *invalidLocationExceptionType = NULL; PyObject *notFoundExceptionType = NULL; void translator1(osmium::invalid_location const&) { PyErr_SetString(invalidLocationExceptionType, "Invalid location"); } void translator2(osmium::not_found const&) { PyErr_SetString(notFoundExceptionType, "Element not found in index"); } PyObject* createExceptionClass(const char* name, PyObject* baseTypeObj = PyExc_Exception) { using std::string; namespace bp = boost::python; string scopeName = bp::extract<string>(bp::scope().attr("__name__")); string qualifiedName0 = scopeName + "." + name; char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str()); PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0); if(!typeObj) bp::throw_error_already_set(); bp::scope().attr(name) = bp::handle<>(bp::borrowed(typeObj)); return typeObj; } #include "index.cc" BOOST_PYTHON_MODULE(_osmium) { using namespace boost::python; docstring_options doc_options(true, true, false); invalidLocationExceptionType = createExceptionClass("InvalidLocationError", PyExc_RuntimeError); register_exception_translator<osmium::invalid_location>(&translator1); notFoundExceptionType = createExceptionClass("NotFoundError", PyExc_KeyError); register_exception_translator<osmium::not_found>(&translator2); class_<osmium::handler::NodeLocationsForWays<LocationTable>, boost::noncopyable>("NodeLocationsForWays", init<LocationTable&>()) .def("ignore_errors", &osmium::handler::NodeLocationsForWays<LocationTable>::ignore_errors) ; class_<SimpleHandlerWrap, boost::noncopyable>("SimpleHandler", "The most generic of OSM data handlers. Derive your data processor " "from this class and implement callbacks for each object type you are " "interested in. The following data types are recognised: \n" " `node`, `way`, `relation`, `area` and `changeset`.\n " "A callback takes exactly one parameter which is the object. Note that " "all objects that are handed into the handler are only readable and are " "only valid until the end of the callback is reached. Any data that " "should be retained must be copied into other data structures.") .def("apply_file", &SimpleHandlerWrap::apply_file, (arg("self"), arg("filename"), arg("locations")=false, arg("idx")="sparse_mem_array"), "Apply the handler to the given file. If locations is true, then\n" "a location handler will be applied before, which saves the node\n" "positions. In that case, the type of this position index can be\n" "further selected in idx. If an area callback is implemented, then\n" "the file will be scanned twice and a location handler and a\n" "handler for assembling multipolygons and areas from ways will\n" "be executed.") .def("apply_buffer", &SimpleHandlerWrap::apply_buffer, (arg("self"), arg("buffer"), arg("format"), arg("locations")=false, arg("idx")="sparse_mem_array"), "Apply the handler to a string buffer. The buffer must be a\n" "byte string.") ; def("apply", &apply_reader_simple<BaseHandler>, "Apply a chain of handlers."); def("apply", &apply_reader_simple<osmium::handler::NodeLocationsForWays<LocationTable>>); def("apply", &apply_reader_simple_with_location<LocationTable>); class_<SimpleWriterWrap, boost::noncopyable>("SimpleWriter", "The most generic class to write osmium objects into a file. The writer " "takes a file name as its mandatory parameter. The file must not yet " "exist. The file type to output is determined from the file extension. " "The second (optional) parameter is the buffer size. osmium caches the " "output data in an internal memory buffer before writing it on disk. This " "parameter allows changing the default buffer size of 4MB. Larger buffers " "are normally better but you should be aware that there are normally multiple " "buffers in use during the write process.", init<const char*, unsigned long>()) .def(init<const char*>()) .def("add_node", &SimpleWriterWrap::add_node, (arg("self"), arg("node")), "Add a new node to the file. The node may be an ``osmium.osm.Node`` object, " "an ``osmium.osm.mutable.Node`` object or any other Python object that " "implements the same attributes.") .def("add_way", &SimpleWriterWrap::add_way, (arg("self"), arg("way")), "Add a new way to the file. The way may be an ``osmium.osm.Way`` object, " "an ``osmium.osm.mutable.Way`` object or any other Python object that " "implements the same attributes.") .def("add_relation", &SimpleWriterWrap::add_relation, (arg("self"), arg("relation")), "Add a new relation to the file. The relation may be an " "``osmium.osm.Relation`` object, an ``osmium.osm.mutable.Way`` " "object or any other Python object that implements the same attributes.") .def("close", &SimpleWriterWrap::close, args("self"), "Flush the remaining buffers and close the writer. While it is not " "strictly necessary to call this function explicitly, it is still " "strongly recommended to close the writer as soon as possible, so " "that the buffer memory can be freed.") ; class_<WriteHandler, boost::noncopyable>("WriteHandler", "Handler function that writes all data directly to a file." "The handler takes a file name as its mandatory parameter. The file " "must not yet exist. The file type to output is determined from the " "file extension. " "The second (optional) parameter is the buffer size. osmium caches the " "output data in an internal memory buffer before writing it on disk. This " "parameter allows changing the default buffer size of 4MB. Larger buffers " "are normally better but you should be aware that there are normally multiple " "buffers in use during the write process.", init<const char*, unsigned long>()) .def(init<const char*>()) .def("close", &WriteHandler::close, args("self"), "Flush the remaining buffers and close the writer. While it is not " "strictly necessary to call this function explicitly, it is still " "strongly recommended to close the writer as soon as possible, so " "that the buffer memory can be freed.") ; class_<pyosmium::MergeInputReader, boost::noncopyable>("MergeInputReader", "Collects data from multiple input files and sorts and optionally " "deduplicates the data before applying it to a handler.") .def("apply", &pyosmium::MergeInputReader::apply, (arg("self"), arg("handler"), arg("simplify")=true), "Apply collected data to a handler. The data will be sorted first. " "If `simplify` is true (default) then duplicates will be eliminated " "and only the newest version of each object kept. After the data " "has been applied the buffer of the MergeInputReader is empty and " "new data can be added for the next round of application.") .def("apply_to_reader", &pyosmium::MergeInputReader::apply_to_reader, (arg("self"), arg("reader"), arg("writer"), arg("with_history")=false), "Apply the collected data to data from the given `reader` and write " "the result to `writer`. This function can be used to merge the diff " "data together with other OSM data (for example when updating a " "planet file. If `with_history` is true, then the collected data will " "be applied verbatim without removing duplicates. This is important " "when using OSM history files as input.") .def("add_file", &pyosmium::MergeInputReader::add_file, (arg("self"), arg("file")), "Add data from a file to the internal cache. The file type will be " "determined from the file extension.") .def("add_buffer", &pyosmium::MergeInputReader::add_buffer, (arg("self"), arg("buffer"), arg("format")), "Add data from a byte buffer. The format of the input data must " "be given in the `format` argument as a string. The data will be " "copied into internal buffers, so that the input buffer can be " "safely discarded after the function has been called.") ; } <|endoftext|>
<commit_before>#include "Scaly.h" namespace scaly { // Some statistics static int oversizedPagesAllocated; static int oversizedBytesAllocated; static int oversizedPagesDeallocated; static int oversizedBytesDeallocated; static int pagesDisposed; static int extensionPagesAllocated; extern __thread _Task* __CurrentTask; _Page::_Page() { reset(); } void _Page::reset() { // Allocate default extension page pointer and initialize it to zero *getLastExtensionPageLocation() = 0; extensions = 0; // Allocate space for the page itself setNextObject(align((char*)this + sizeof(_Page))); currentPage = this; } void _Page::clear() { deallocatePageExtensions(); reset(); } _Page** _Page::getLastExtensionPageLocation() { // Frome where the ordinary extension page is pointed to return ((_Page**) ((char*) this + _pageSize)) - 1; } void* _Page::operator new(size_t size, void* location) { return location; } void* _Page::getNextObject() { return (char*)this + nextObjectOffset; } void _Page::setNextObject(void* object) { nextObjectOffset = (char*)object - (char*)this; } _Page** _Page::getNextExtensionPageLocation() { return getLastExtensionPageLocation() - extensions - 1; } void* _Page::allocateObject(size_t size) { if (this != currentPage) { // We're already known to be full, so we delegate to the current page void* newObject = currentPage->allocateObject(size); // Possibly our current page was also full so we propagate back the new current page _Page* allocatingPage = ((Object*)newObject)->getPage(); if ((allocatingPage != currentPage) && (newObject != allocatingPage)) currentPage = allocatingPage; return newObject; } // Try to allocate from ourselves void* nextLocation = align((char*)getNextObject() + size); if (nextLocation <= (void*) getNextExtensionPageLocation()) { void* location = getNextObject(); setNextObject(nextLocation); return location; } // So the space did not fit. // Calculate gross size to decide whether we're oversized size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment; if (grossSize > _pageSize) { if ((_Page**)getNextObject() == getLastExtensionPageLocation()) { // Allocate an extension page with default size _Page* defaultExtensionPage = allocateExtensionPage(); // Make it our new current currentPage = defaultExtensionPage; // Try again with the new extension page return defaultExtensionPage->allocateObject(size); } // We allocate and free oversized objects directly. void* object; posix_memalign(&object, _pageSize, size); *getNextExtensionPageLocation() = (_Page*)object; extensions++; return object; } // So we're not oversized. Allocate the standard extension page. _Page* extensionPage = allocateExtensionPage(); this->currentPage = extensionPage; // And allocate at last. return extensionPage->allocateObject(size); } _Page* _Page::allocateExtensionPage() { _Page* pageLocation = __CurrentTask->getExtensionPage(); if (!pageLocation) return 0; _Page* extensionPage = new (pageLocation) _Page(); *getLastExtensionPageLocation() = pageLocation; return extensionPage; } _Page* _Page::allocateExclusivePage() { if (this != currentPage) // We're already known to be full, so we delegate to the current page return currentPage->allocateExclusivePage(); // Check first whether we need an ordinary extension if ((_Page**)getNextObject() == getLastExtensionPageLocation()) { // Allocate an extension page with default size _Page* defaultExtensionPage = allocateExtensionPage(); // Make it our new current currentPage = defaultExtensionPage; // Try again with the new extension page return defaultExtensionPage->allocateExclusivePage(); } _Page* pageLocation = __CurrentTask->getExtensionPage(); if (!pageLocation) return 0; _Page* exclusivePage = new (pageLocation) _Page(); *getNextExtensionPageLocation() = pageLocation; extensions++; return exclusivePage; } bool _Page::extend(void* address, size_t size) { if (!size) size = 1; void* nextLocation = align((char*) address + size); // If nextObject would not change because of the alignment, that's it if (nextLocation == (void*)getNextObject()) return true; // If nextObject is already higher, other objects were allocated in the meantime if (nextLocation < getNextObject()) return false; // Now we still have to check whether we still would have space left if (nextLocation >= (void*) getNextExtensionPageLocation()) return false; // Allocate the extension setNextObject(nextLocation); return true; } void _Page::deallocatePageExtensions() { for (_Page* page = this; page;) { _Page* nextExtensionPage = *page->getLastExtensionPageLocation(); deallocateExtensionsOfPage(page); if (page != this) forget(page); page = nextExtensionPage; } } void _Page::deallocateExtensionsOfPage(_Page* page) { // Deallocate the oversized or exclusive pages for (_Page** ppPage = page->getLastExtensionPageLocation() - 1; ppPage > page->getNextExtensionPageLocation(); ppPage--) forget(*ppPage); } void _Page::forget(_Page* page) { __CurrentTask->releaseExtensionPage(page); } bool _Page::reclaimArray(void* address) { if (currentPage->freeExtensionPage((_Page*)address)) return true; for (_Page* page = this; page; page = *getLastExtensionPageLocation()) if (page->freeExtensionPage(page)) return true; } _Page* _Page::getPage(void* address) { return (_Page*) (((intptr_t)address) & ~(intptr_t)(_pageSize - 1)); } bool _Page::freeExtensionPage(_Page* _page) { // Find the extension Page pointer _Page** extensionPosition = getLastExtensionPageLocation() - 1; while (extensionPosition > getNextExtensionPageLocation()) { if (*extensionPosition == _page) break; extensionPosition--; } if (extensionPosition == getNextExtensionPageLocation()) return false; // Shift the remaining array one position up for (_Page** shiftedPosition = extensionPosition; shiftedPosition > getNextExtensionPageLocation(); shiftedPosition--) *shiftedPosition = *(shiftedPosition - 1); // Make room for one more extension extensions--; forget(_page); return true; } } // namespace <commit_msg>some simplifications<commit_after>#include "Scaly.h" namespace scaly { extern __thread _Task* __CurrentTask; _Page::_Page() { reset(); } void _Page::reset() { // Allocate default extension page pointer and initialize it to zero *getLastExtensionPageLocation() = 0; extensions = 0; nextObjectOffset = sizeof(_Page); currentPage = this; } void _Page::clear() { deallocatePageExtensions(); reset(); } _Page** _Page::getLastExtensionPageLocation() { // Frome where the ordinary extension page is pointed to return ((_Page**) ((char*) this + _pageSize)) - 1; } void* _Page::operator new(size_t size, void* location) { return location; } void* _Page::getNextObject() { return (char*)this + nextObjectOffset; } void _Page::setNextObject(void* object) { nextObjectOffset = (char*)object - (char*)this; } _Page** _Page::getNextExtensionPageLocation() { return getLastExtensionPageLocation() - extensions - 1; } void* _Page::allocateObject(size_t size) { if (this != currentPage) { // We're already known to be full, so we delegate to the current page void* newObject = currentPage->allocateObject(size); // Possibly our current page was also full so we propagate back the new current page _Page* allocatingPage = ((Object*)newObject)->getPage(); if ((allocatingPage != currentPage) && (newObject != allocatingPage)) currentPage = allocatingPage; return newObject; } // Try to allocate from ourselves void* nextLocation = align((char*)getNextObject() + size); if (nextLocation <= (void*) getNextExtensionPageLocation()) { void* location = getNextObject(); setNextObject(nextLocation); return location; } // So the space did not fit. // Calculate gross size to decide whether we're oversized size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment; if (grossSize > _pageSize) { if ((_Page**)getNextObject() == getLastExtensionPageLocation()) { // Allocate an extension page with default size _Page* defaultExtensionPage = allocateExtensionPage(); // Make it our new current currentPage = defaultExtensionPage; // Try again with the new extension page return defaultExtensionPage->allocateObject(size); } // We allocate and free oversized objects directly. void* object; posix_memalign(&object, _pageSize, size); *getNextExtensionPageLocation() = (_Page*)object; extensions++; return object; } // So we're not oversized. Allocate the standard extension page. _Page* extensionPage = allocateExtensionPage(); this->currentPage = extensionPage; // And allocate at last. return extensionPage->allocateObject(size); } _Page* _Page::allocateExtensionPage() { _Page* pageLocation = __CurrentTask->getExtensionPage(); if (!pageLocation) return 0; _Page* extensionPage = new (pageLocation) _Page(); *getLastExtensionPageLocation() = pageLocation; return extensionPage; } _Page* _Page::allocateExclusivePage() { if (this != currentPage) // We're already known to be full, so we delegate to the current page return currentPage->allocateExclusivePage(); // Check first whether we need an ordinary extension if ((_Page**)getNextObject() == getLastExtensionPageLocation()) { // Allocate an extension page with default size _Page* defaultExtensionPage = allocateExtensionPage(); // Make it our new current currentPage = defaultExtensionPage; // Try again with the new extension page return defaultExtensionPage->allocateExclusivePage(); } _Page* pageLocation = __CurrentTask->getExtensionPage(); if (!pageLocation) return 0; _Page* exclusivePage = new (pageLocation) _Page(); *getNextExtensionPageLocation() = pageLocation; extensions++; return exclusivePage; } bool _Page::extend(void* address, size_t size) { if (!size) size = 1; void* nextLocation = align((char*) address + size); // If nextObject would not change because of the alignment, that's it if (nextLocation == (void*)getNextObject()) return true; // If nextObject is already higher, other objects were allocated in the meantime if (nextLocation < getNextObject()) return false; // Now we still have to check whether we still would have space left if (nextLocation >= (void*) getNextExtensionPageLocation()) return false; // Allocate the extension setNextObject(nextLocation); return true; } void _Page::deallocatePageExtensions() { for (_Page* page = this; page;) { _Page* nextExtensionPage = *page->getLastExtensionPageLocation(); deallocateExtensionsOfPage(page); if (page != this) forget(page); page = nextExtensionPage; } } void _Page::deallocateExtensionsOfPage(_Page* page) { // Deallocate the oversized or exclusive pages for (_Page** ppPage = page->getLastExtensionPageLocation() - 1; ppPage > page->getNextExtensionPageLocation(); ppPage--) forget(*ppPage); } void _Page::forget(_Page* page) { __CurrentTask->releaseExtensionPage(page); } bool _Page::reclaimArray(void* address) { if (currentPage->freeExtensionPage((_Page*)address)) return true; for (_Page* page = this; page; page = *getLastExtensionPageLocation()) if (page->freeExtensionPage(page)) return true; } _Page* _Page::getPage(void* address) { return (_Page*) (((intptr_t)address) & ~(intptr_t)(_pageSize - 1)); } bool _Page::freeExtensionPage(_Page* _page) { // Find the extension Page pointer _Page** extensionPosition = getLastExtensionPageLocation() - 1; while (extensionPosition > getNextExtensionPageLocation()) { if (*extensionPosition == _page) break; extensionPosition--; } if (extensionPosition == getNextExtensionPageLocation()) return false; // Shift the remaining array one position up for (_Page** shiftedPosition = extensionPosition; shiftedPosition > getNextExtensionPageLocation(); shiftedPosition--) *shiftedPosition = *(shiftedPosition - 1); // Make room for one more extension extensions--; forget(_page); return true; } } // namespace <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" #include "obj_pool.h" void TPool::setDrinkUnits(int n) { setMaxDrinkUnits(n); TBaseCup::setDrinkUnits(n); setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME)); weightChangeObject(0); updateDesc(); obj_flags.decay_time=getDrinkUnits(); } void TPool::addToDrinkUnits(int n) { addToMaxDrinkUnits(n); TBaseCup::addToDrinkUnits(n); setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME)); weightChangeObject(0); updateDesc(); obj_flags.decay_time=getDrinkUnits(); } void TPool::setDrinkType(liqTypeT n) { TBaseCup::setDrinkType(n); updateDesc(); } // the best way to do this would be to explicitly set the proper weight in the // accessors, rather than using weightChangeObject. It is prone to float // rounding errors and some functions don't even bother to use it (ie, pour, // which I fixed). But instead of recoding everything, I'll just put this here // so that pools don't generate errors in weightChangeObject. void TPool::weightChangeObject(float fWeight) { setWeight(obj_index[getItemIndex()].weight); TBaseCup::weightChangeObject(getDrinkUnits() * SIP_WEIGHT); } int TPool::getDrinkIndex() const { int drinkunits=getDrinkUnits(); if(drinkunits<=0){ return 0; } else if(drinkunits<=5){ return 1; } else if(drinkunits<=10){ return 2; } else if(drinkunits<=25){ return 3; } else if(drinkunits<=50){ return 4; } else if(drinkunits<=100){ return 5; } else if(drinkunits<=250){ return 6; } else if(drinkunits<=1000){ return 7; } else if(drinkunits<=10000){ return 8; } else if(drinkunits<=25000){ return 9; } else { return 10; } } void TPool::updateDesc() { int drinkindex=getDrinkIndex(); char buf[256]; const char *liqname=DrinkInfo[getDrinkType()]->name; const char *poolname [] = { "a few drops of %s", "a tiny puddle of %s", "a small puddle of %s", "a puddle of %s", "a fair sized puddle of %s", "a big pool of %s", "a large pool of %s", "a huge pool of %s", "a massive pool of %s", "a tremendously huge pool of %s", "a veritable ocean of %s" }; const char *pooldesc [] = { "A few drops of %s sprinkle the ground here and are fading fast.", "A tiny puddle of %s has gathered here.", "A small puddle of %s is here.", "A puddle of %s is here.", "A fair sized puddle of %s is here.", "A big pool of %s is here.", "A large pool of %s is here.", "A huge pool of %s is here.", "A massive pool of %s is here.", "A tremendously huge pool of %s dominates the area.", "A veritable ocean of %s covers the area." }; if (isObjStat(ITEM_STRUNG)) { delete [] shortDescr; delete [] descr; extraDescription *exd; while ((exd = ex_description)) { ex_description = exd->next; delete exd; } ex_description = NULL; delete [] action_description; action_description = NULL; } else { addObjStat(ITEM_STRUNG); name = mud_str_dup(obj_index[getItemIndex()].name); ex_description = NULL; action_description = NULL; } sprintf(buf, poolname[drinkindex], liqname); shortDescr = mud_str_dup(buf); sprintf(buf, pooldesc[drinkindex], liqname); setDescr(mud_str_dup(buf)); } bool TPool::isPluralItem() const { // a few drops of blood if (getDrinkIndex() == 0) return TRUE; // otherwise, make recursive return TBaseCup::isPluralItem(); } int TBeing::dropPool(int amt, liqTypeT liq) { TPool *pool=NULL; TThing *t; TObj *obj; if(amt==0) return FALSE; /* look for preexisting pool */ for(t=roomp->getStuff();t;t=t->nextThing){ TPool *tp = dynamic_cast<TPool *>(t); if (tp && (tp->getDrinkType() == liq)){ pool=tp; break; } } if(!pool){ // create new pool #if 1 // builder port uses stripped down database which was causing problems // hence this setup instead. int robj = real_object(GENERIC_POOL); if (robj < 0 || robj >= (signed int) obj_index.size()) { vlogf(LOG_BUG, "dropPool(): No object (%d) in database!", GENERIC_POOL); return false; } obj = read_object(robj, REAL); #else obj = read_object(GENERIC_POOL, VIRTUAL); #endif pool = dynamic_cast<TPool *>(obj); if (!pool) return false; pool->initPool(amt, liq); *roomp += *pool; } else { pool->fillMeAmount(amt, liq); } return TRUE; } void TPool::decayMe() { int drinkunits=getDrinkUnits(); // check for non-decaying pools if (isDrinkConFlag(DRINK_PERM)) return; if(drinkunits<=0) setDrinkUnits(0); else if(drinkunits<25) addToDrinkUnits(-1); else // large pools evaporate faster addToDrinkUnits(-(drinkunits/25)); } void TPool::initPool(int amt, liqTypeT liq) { string buf; swapToStrung(); remObjStat(ITEM_TAKE); setDrinkType(liq); canBeSeen = 1; setMaterial(MAT_WATER); ssprintf(buf, "pool puddle %s %s", DrinkInfo[liq]->name, DrinkInfo[liq]->color); delete [] name; name = mud_str_dup(buf.c_str()); fillMeAmount(amt, liq); } TPool::TPool() : TBaseCup() { } TPool::TPool(const TPool &a) : TBaseCup(a) { } TPool & TPool::operator=(const TPool &a) { if (this == &a) return *this; TBaseCup::operator=(a); return *this; } TPool::~TPool() { } void TPool::fillMeAmount(int amt, liqTypeT liq) { setDrinkType(liq); addToDrinkUnits(amt); weightChangeObject(amt * SIP_WEIGHT); } <commit_msg>stripped color codes from pool names<commit_after>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" #include "obj_pool.h" void TPool::setDrinkUnits(int n) { setMaxDrinkUnits(n); TBaseCup::setDrinkUnits(n); setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME)); weightChangeObject(0); updateDesc(); obj_flags.decay_time=getDrinkUnits(); } void TPool::addToDrinkUnits(int n) { addToMaxDrinkUnits(n); TBaseCup::addToDrinkUnits(n); setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME)); weightChangeObject(0); updateDesc(); obj_flags.decay_time=getDrinkUnits(); } void TPool::setDrinkType(liqTypeT n) { TBaseCup::setDrinkType(n); updateDesc(); } // the best way to do this would be to explicitly set the proper weight in the // accessors, rather than using weightChangeObject. It is prone to float // rounding errors and some functions don't even bother to use it (ie, pour, // which I fixed). But instead of recoding everything, I'll just put this here // so that pools don't generate errors in weightChangeObject. void TPool::weightChangeObject(float fWeight) { setWeight(obj_index[getItemIndex()].weight); TBaseCup::weightChangeObject(getDrinkUnits() * SIP_WEIGHT); } int TPool::getDrinkIndex() const { int drinkunits=getDrinkUnits(); if(drinkunits<=0){ return 0; } else if(drinkunits<=5){ return 1; } else if(drinkunits<=10){ return 2; } else if(drinkunits<=25){ return 3; } else if(drinkunits<=50){ return 4; } else if(drinkunits<=100){ return 5; } else if(drinkunits<=250){ return 6; } else if(drinkunits<=1000){ return 7; } else if(drinkunits<=10000){ return 8; } else if(drinkunits<=25000){ return 9; } else { return 10; } } void TPool::updateDesc() { int drinkindex=getDrinkIndex(); char buf[256]; const char *liqname=DrinkInfo[getDrinkType()]->name; const char *poolname [] = { "a few drops of %s", "a tiny puddle of %s", "a small puddle of %s", "a puddle of %s", "a fair sized puddle of %s", "a big pool of %s", "a large pool of %s", "a huge pool of %s", "a massive pool of %s", "a tremendously huge pool of %s", "a veritable ocean of %s" }; const char *pooldesc [] = { "A few drops of %s sprinkle the ground here and are fading fast.", "A tiny puddle of %s has gathered here.", "A small puddle of %s is here.", "A puddle of %s is here.", "A fair sized puddle of %s is here.", "A big pool of %s is here.", "A large pool of %s is here.", "A huge pool of %s is here.", "A massive pool of %s is here.", "A tremendously huge pool of %s dominates the area.", "A veritable ocean of %s covers the area." }; if (isObjStat(ITEM_STRUNG)) { delete [] shortDescr; delete [] descr; extraDescription *exd; while ((exd = ex_description)) { ex_description = exd->next; delete exd; } ex_description = NULL; delete [] action_description; action_description = NULL; } else { addObjStat(ITEM_STRUNG); name=mud_str_dup(obj_index[getItemIndex()].name); ex_description = NULL; action_description = NULL; } sprintf(buf, poolname[drinkindex], liqname); shortDescr = mud_str_dup(buf); sprintf(buf, pooldesc[drinkindex], liqname); setDescr(mud_str_dup(buf)); } bool TPool::isPluralItem() const { // a few drops of blood if (getDrinkIndex() == 0) return TRUE; // otherwise, make recursive return TBaseCup::isPluralItem(); } int TBeing::dropPool(int amt, liqTypeT liq) { TPool *pool=NULL; TThing *t; TObj *obj; if(amt==0) return FALSE; /* look for preexisting pool */ for(t=roomp->getStuff();t;t=t->nextThing){ TPool *tp = dynamic_cast<TPool *>(t); if (tp && (tp->getDrinkType() == liq)){ pool=tp; break; } } if(!pool){ // create new pool #if 1 // builder port uses stripped down database which was causing problems // hence this setup instead. int robj = real_object(GENERIC_POOL); if (robj < 0 || robj >= (signed int) obj_index.size()) { vlogf(LOG_BUG, "dropPool(): No object (%d) in database!", GENERIC_POOL); return false; } obj = read_object(robj, REAL); #else obj = read_object(GENERIC_POOL, VIRTUAL); #endif pool = dynamic_cast<TPool *>(obj); if (!pool) return false; pool->initPool(amt, liq); *roomp += *pool; } else { pool->fillMeAmount(amt, liq); } return TRUE; } void TPool::decayMe() { int drinkunits=getDrinkUnits(); // check for non-decaying pools if (isDrinkConFlag(DRINK_PERM)) return; if(drinkunits<=0) setDrinkUnits(0); else if(drinkunits<25) addToDrinkUnits(-1); else // large pools evaporate faster addToDrinkUnits(-(drinkunits/25)); } void TPool::initPool(int amt, liqTypeT liq) { string buf; swapToStrung(); remObjStat(ITEM_TAKE); setDrinkType(liq); canBeSeen = 1; setMaterial(MAT_WATER); ssprintf(buf, "pool puddle %s %s", stripColorCodes(DrinkInfo[liq]->name).c_str(), stripColorCodes(DrinkInfo[liq]->color).c_str()); delete [] name; name = mud_str_dup(buf.c_str()); fillMeAmount(amt, liq); } TPool::TPool() : TBaseCup() { } TPool::TPool(const TPool &a) : TBaseCup(a) { } TPool & TPool::operator=(const TPool &a) { if (this == &a) return *this; TBaseCup::operator=(a); return *this; } TPool::~TPool() { } void TPool::fillMeAmount(int amt, liqTypeT liq) { setDrinkType(liq); addToDrinkUnits(amt); weightChangeObject(amt * SIP_WEIGHT); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const ll infty = 10000000000000007; struct edge { int to; ll cap; int rev; }; vector<edge> G[100010]; bool used[100010]; void add_edge(int from, int to, ll cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, 0, (int)G[from].size()-1}); } ll dfs(int v, int t, ll f) { if (v == t) return f; used[v] = true; for (auto& e : G[v]) { if (!used[e.to] && e.cap > 0) { ll d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(int s, int t) { ll flow = 0; while (true) { fill(used, used+100010, false); ll f = dfs(s, t, infty); if (f == 0) return flow; flow += f; } } typedef tuple<ll, int> state; // kachi, bit int N; ll x[20]; ll c[20]; ll v[20]; vector<state> V[20]; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[i]; } for (auto i = 0; i < N-1; ++i) { x[i+1] += x[i]; } for (auto i = 0; i < N; ++i) { cin >> c[i]; } for (auto i = 0; i < N; ++i) { cin >> v[i]; } for (auto i = 0; i < (1 << N); ++i) { ll kakaku = 0; ll kachi = 0; for (auto j = 0; j < N; ++j) { if ((i >> j) & 1) { kakaku += c[j]; kachi += v[j]; } } for (auto j = 0; j < N; ++j) { if (kakaku <= x[j]) { V[j].push_back(make_tuple(kachi, i)); break; } } } ll ans = 0; for (auto i = 0; i < N; ++i) { #if DEBUG == 1 cerr << "ban item i+1 = " << i+1 << endl; #endif sort(V[i].begin(), V[i].end()); reverse(V[i].begin(), V[i].end()); for (auto now = 1; now <= (int)V[i].size(); ++now) { // 0 start, 1 goal, 2...N+2 choten, N+2+i i for (auto j = 0; j <= N+2+now; ++j) { G[j].clear(); } for (auto j = 0; j < N; ++j) { add_edge(0, j+2, 1); } for (auto j = 0; j < now; ++j) { int bit = get<1>(V[i][j]); for (auto k = 0; k < N; ++k) { if (((bit >> k) & 1) == 0) { add_edge(k+2, N+2+j, infty); } } add_edge(N+2+j, 1, 1); } ll f = N - max_flow(0, 1); #if DEBUG == 1 cerr << "now = " << now << ", f = " << f << ", bit = " << get<1>(V[i][now-1]) << endl; #endif if (f >= i+1) { // } else { #if DEBUG == 1 cerr << "value = " << get<0>(V[i][now-1]) << endl; #endif ans = max(ans, get<0>(V[i][now-1])); break; } } } cout << ans << endl; } <commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const ll infty = 10000000000000007; struct edge { int to; ll cap; int rev; }; vector<edge> G[100010]; bool used[100010]; void add_edge(int from, int to, ll cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, 0, (int)G[from].size()-1}); } ll dfs(int v, int t, ll f) { if (v == t) return f; used[v] = true; for (auto& e : G[v]) { if (!used[e.to] && e.cap > 0) { ll d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(int s, int t) { ll flow = 0; while (true) { fill(used, used+100010, false); ll f = dfs(s, t, infty); if (f == 0) return flow; flow += f; } } typedef tuple<ll, int> state; // kachi, bit int N; ll x[20]; ll c[20]; ll v[20]; vector<state> V[20]; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[i]; } for (auto i = 0; i < N-1; ++i) { x[i+1] += x[i]; } for (auto i = 0; i < N; ++i) { cin >> c[i]; } for (auto i = 0; i < N; ++i) { cin >> v[i]; } for (auto i = 0; i < (1 << N); ++i) { ll kakaku = 0; ll kachi = 0; for (auto j = 0; j < N; ++j) { if ((i >> j) & 1) { kakaku += c[j]; kachi += v[j]; } } for (auto j = 0; j < N; ++j) { if (kakaku <= x[j]) { V[j].push_back(make_tuple(kachi, i)); break; } } } ll ans = 0; for (auto i = 0; i < N; ++i) { #if DEBUG == 1 cerr << "ban item i+1 = " << i+1 << endl; #endif sort(V[i].begin(), V[i].end()); reverse(V[i].begin(), V[i].end()); for (auto now = 1; now <= (int)V[i].size(); ++now) { // 0 start, 1 goal, 2...N+2 choten, N+2+i i for (auto j = 0; j <= N+2+now; ++j) { G[j].clear(); } for (auto j = 0; j < N; ++j) { add_edge(0, j+2, 1); } for (auto j = 0; j < now; ++j) { int bit = get<1>(V[i][j]); for (auto k = 0; k < N; ++k) { if (((bit >> k) & 1) == 0) { add_edge(k+2, N+2+j, infty); } } add_edge(N+2+j, 1, 1); } ll f = N - max_flow(0, 1); #if DEBUG == 1 cerr << "now = " << now << ", f = " << f << ", bit = " << get<1>(V[i][now-1]) << endl; #endif if (f >= 0) { // } else { #if DEBUG == 1 cerr << "value = " << get<0>(V[i][now-1]) << endl; #endif ans = max(ans, get<0>(V[i][now-1])); break; } } } cout << ans << endl; } <|endoftext|>
<commit_before>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-4-7 14:05:18 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <chrono> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; struct state { int x, y, dir, a, b; }; int A, B; int h, w; string c[100]; stack<state> S; inline bool valid(int x, int y, int a, int b) { return (a <= A && b <= B && c[x][y] == '.'); } int main() { cin >> A >> B >> h >> w; for (auto i = 0; i < h; i++) { cin >> c[i]; } S.push(state{1, 1, 0, 0, 0}); while (!S.empty()) { int now_x = S.top().x; int now_y = S.top().y; int now_dir = S.top().dir; int now_a = S.top().a; int now_b = S.top().b; // #if DEBUG == 1 // cerr << "(" << now_x << ", " << now_y << "), " // << now_dir << ", " // << "(" << now_a << ", " << now_b << ")" << endl; // #endif S.pop(); if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B) { cout << "Yes" << endl; return 0; } else { int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir}; int new_a[3] = {now_a + 1, now_a, now_a}; int new_b[3] = {now_b, now_b + 1, now_b}; for (auto k = 0; k < 3; k++) { int new_x = now_x + dx[new_dir[k]]; int new_y = now_y + dy[new_dir[k]]; if (valid(new_x, new_y, new_a[k], new_b[k])) { S.push(state{new_x, new_y, new_dir[k], new_a[k], new_b[k]}); } } } } cout << "No" << endl; }<commit_msg>submit B.cpp to 'B - 駆け抜けろ!埼大山車部!!' (maximum-cup-2018) [C++14 (GCC 5.4.1)]<commit_after>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-4-7 14:05:18 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <chrono> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; struct state { int x, y, dir, a, b; }; int A, B; int h, w; string c[100]; stack<state> S; inline bool valid(int x, int y, int a, int b) { return (a <= A && b <= B && c[x][y] == '.'); } int main() { auto start = std::chrono::system_clock::now(); cin >> A >> B >> h >> w; for (auto i = 0; i < h; i++) { cin >> c[i]; } S.push(state{1, 1, 0, 0, 0}); while (!S.empty()) { auto end = std::chrono::system_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); if (elapsed > 2950) { cout << ((A < 15) ? "Yes" : "No") << endl; return 0; } int now_x = S.top().x; int now_y = S.top().y; int now_dir = S.top().dir; int now_a = S.top().a; int now_b = S.top().b; // #if DEBUG == 1 // cerr << "(" << now_x << ", " << now_y << "), " // << now_dir << ", " // << "(" << now_a << ", " << now_b << ")" << endl; // #endif S.pop(); if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B) { cout << "Yes" << endl; return 0; } else { int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir}; int new_a[3] = {now_a + 1, now_a, now_a}; int new_b[3] = {now_b, now_b + 1, now_b}; for (auto k = 0; k < 3; k++) { int new_x = now_x + dx[new_dir[k]]; int new_y = now_y + dy[new_dir[k]]; if (valid(new_x, new_y, new_a[k], new_b[k])) { S.push(state{new_x, new_y, new_dir[k], new_a[k], new_b[k]}); } } } } cout << "No" << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 3/10/2019, 2:26:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class UnionFind { public: vector<long long> par; UnionFind(int n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; return true; } long long size(int x) { return -par[root(x)]; } }; int N, M; ll X[100010]; int A[100010]; int B[100010]; ll Y[100010]; typedef tuple<ll, int, int, bool> edge; vector<edge> V; vector<int> W[100010]; bool visited[100010]; typedef tuple<ll, int> task; vector<task> T; void dfs(ll cost, int v) { #if DEBUG == 1 cerr << "dfs(" << cost << ", " << v << ")" << endl; #endif if (visited[v]) { return; } visited[v] = true; for (auto i : W[v]) { edge x = V[i]; ll score = get<0>(x); int a = get<1>(x); int b = get<2>(x); int dst = ((a == v) ? b : a); if (get<3>(x)) { continue; } if (cost >= score) { get<3>(x) = true; if (!W[dst].empty()) { dfs(cost, dst); } } } } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> X[i]; } for (auto i = 0; i < M; i++) { cin >> A[i] >> B[i] >> Y[i]; A[i]--; B[i]--; V.push_back(edge(Y[i], A[i], B[i], false)); } sort(V.begin(), V.end()); for (auto i = 0; i < M; i++) { edge x = V[i]; int a = get<1>(x); int b = get<2>(x); W[a].push_back(i); W[b].push_back(i); } UnionFind UF(N); for (auto i = 0; i < N; i++) { UF.par[i] = -X[i]; } for (auto i = 0; i < M; i++) { edge x = V[i]; ll cost = get<0>(x); int a = get<1>(x); int b = get<2>(x); ll score = 0; if (UF.is_same(a, b)) { score = UF.size(a); } else { score = UF.size(a) + UF.size(b); UF.merge(a, b); } if (score >= cost) { T.push_back(task(cost, a)); } } reverse(T.begin(), T.end()); fill(visited, visited + N, false); for (auto x : T) { #if DEBUG == 1 cerr << get<0>(x) << " " << get<1>(x) << endl; #endif dfs(get<0>(x), get<1>(x)); } int ans = 0; for (auto i = 0; i < M; i++) { if (!get<3>(V[i])) { ans++; } } cout << ans << endl; }<commit_msg>tried E2.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 3/10/2019, 2:26:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class UnionFind { public: vector<long long> par; UnionFind(int n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; return true; } long long size(int x) { return -par[root(x)]; } }; int N, M; ll X[100010]; int A[100010]; int B[100010]; ll Y[100010]; typedef tuple<ll, int, int, bool> edge; vector<edge> V; vector<int> W[100010]; bool visited[100010]; typedef tuple<ll, int> task; vector<task> T; void dfs(ll cost, int v) { #if DEBUG == 1 cerr << "dfs(" << cost << ", " << v << ")" << endl; #endif if (visited[v]) { return; } visited[v] = true; for (auto i : W[v]) { edge x = V[i]; ll score = get<0>(x); int a = get<1>(x); int b = get<2>(x); int dst = ((a == v) ? b : a); if (get<3>(x)) { continue; } if (cost >= score) { get<3>(x) = true; if (!visited[dst]) { dfs(cost, dst); } } } } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> X[i]; } for (auto i = 0; i < M; i++) { cin >> A[i] >> B[i] >> Y[i]; A[i]--; B[i]--; V.push_back(edge(Y[i], A[i], B[i], false)); } sort(V.begin(), V.end()); for (auto i = 0; i < M; i++) { edge x = V[i]; int a = get<1>(x); int b = get<2>(x); W[a].push_back(i); W[b].push_back(i); } UnionFind UF(N); for (auto i = 0; i < N; i++) { UF.par[i] = -X[i]; } for (auto i = 0; i < M; i++) { edge x = V[i]; ll cost = get<0>(x); int a = get<1>(x); int b = get<2>(x); ll score = 0; if (UF.is_same(a, b)) { score = UF.size(a); } else { score = UF.size(a) + UF.size(b); UF.merge(a, b); } if (score >= cost) { T.push_back(task(cost, a)); } } reverse(T.begin(), T.end()); fill(visited, visited + N, false); for (auto x : T) { #if DEBUG == 1 cerr << get<0>(x) << " " << get<1>(x) << endl; #endif dfs(get<0>(x), get<1>(x)); } int ans = 0; for (auto i = 0; i < M; i++) { if (!get<3>(V[i])) { ans++; } } cout << ans << endl; }<|endoftext|>
<commit_before>/* Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5 Credits: Special thanks to @mithmatt for adding this problem and creating all test cases. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <stdio.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void print_list(ListNode *list) { for ( ; list != NULL; list = list->next) { printf("%d->", list->val); } printf("NULL\n"); } class Solution { public: // 1->2->3->4->5->NULL // 1->2->4->5->NULL ListNode* removeElements(ListNode* head, int val) { ListNode* p = head; ListNode* q = head; ListNode* s = head; ListNode* result = NULL; if (head == NULL) { return result; } if (head->next == NULL && head->val == val) { return result; } result = head; for ( ; p != NULL; ) { if (p->val != val ) { break; } result = p->next; p = p->next; } if (result == NULL) { return result; } p = head; for ( ; p->next != NULL; ) { q = p; p = p->next; if (p->val == val) { q->next = p->next; p = q; } } if (p->val == val) { q->next = NULL; } if (head->val == val) { result = head->next; } return result; } }; int main() { ListNode l1(1), l2(2), l3(3); ListNode l4(4), l5(5), l6(6), l7(6), l8(6), l9(9), l10(10), l11(11), l12(12), l13(6); ListNode n1(0), n2(0), n3(0), n4(1); l1.next = &l2; l2.next = &l3; l4.next = &l5; l5.next = &l6; l6.next = &l7; l7.next = &l8; l8.next = &l9; l9.next = &l10; l10.next = &l11; l11.next = &l12; l12.next = &l13; // n1.next = &n2; // n2.next = &n3; //n3.next = &n4; print_list(&l4); Solution s; print_list(s.removeElements(&l4, 6)); return 0; } <commit_msg>add comments<commit_after>/* Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5 Credits: Special thanks to @mithmatt for adding this problem and creating all test cases. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <stdio.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void print_list(ListNode *list) { for ( ; list != NULL; list = list->next) { printf("%d->", list->val); } printf("NULL\n"); } class Solution { public: // 1->2->3->4->5->NULL // 1->2->4->5->NULL ListNode* removeElements(ListNode* head, int val) { ListNode* p = head; ListNode* q = head; ListNode* s = head; ListNode* result = NULL; if (head == NULL) { return result; } if (head->next == NULL && head->val == val) { return result; } result = head; for ( ; p != NULL; ) { if (p->val != val ) { break; } result = p->next; p = p->next; } if (result == NULL) { return result; } p = head; for ( ; p->next != NULL; ) { q = p; p = p->next; if (p->val == val) { q->next = p->next; p = q; } } if (p->val == val) { q->next = NULL; } if (head->val == val) { result = head->next; } return result; } }; int main() { ListNode l1(1), l2(2), l3(3); ListNode l4(4), l5(5), l6(6), l7(6), l8(6), l9(9), l10(10), l11(11), l12(12), l13(6); ListNode n1(0), n2(0), n3(0), n4(1); l1.next = &l2; l2.next = &l3; l4.next = &l5; l5.next = &l6; l6.next = &l7; l7.next = &l8; l8.next = &l9; l9.next = &l10; l10.next = &l11; l11.next = &l12; l12.next = &l13; //n1.next = &n2; //n2.next = &n3; //n3.next = &n4; print_list(&l4); Solution s; print_list(s.removeElements(&l4, 6)); return 0; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // object that creates and contains a spawn position #include "common.h" #include "SpawnPosition.h" #include "FlagInfo.h" #include "TeamBases.h" #include "WorldInfo.h" #include "PlayerInfo.h" #include "PlayerState.h" // FIXME: from bzfs.cxx extern int getCurMaxPlayers(); extern bool areFoes(TeamColor team1, TeamColor team2); extern BasesList bases; extern WorldInfo *world; extern PlayerInfo player[]; extern PlayerState lastState[]; SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) : curMaxPlayers(getCurMaxPlayers()) { team = player[playerId].getTeam(); azimuth = (float)bzfrand() * 2.0f * M_PI; if (player[playerId].shouldRestartAtBase() && (team >= RedTeam) && (team <= PurpleTeam) && (bases.find(team) != bases.end())) { TeamBases &teamBases = bases[team]; const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100)); base.getRandomPosition(pos[0], pos[1], pos[2]); player[playerId].setRestartOnBase(false); } else { const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT); const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS); safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5); safeDistance = tankRadius * 20; // FIXME: is this a good value? const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); const float maxWorldHeight = world->getMaxWorldHeight(); ObstacleLocation *building; // keep track of how much time we spend searching for a location TimeKeeper start = TimeKeeper::getCurrent(); int inAirAttempts = 50; int tries = 0; float minProximity = size / 3.0f; float bestDist = -1.0f; bool foundspot = false; while (!foundspot) { if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) { if (notNearEdges) { // don't spawn close to map edges in CTF mode testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f; testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f; } else { testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius); testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius); } testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight); } tries++; int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, tankHeight); if (onGroundOnly) { if (type == NOT_IN_BUILDING) foundspot = true; } else { if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) { testPos[2] = 0.0f; //Find any intersection regardless of z type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, maxWorldHeight); } // in a building? try climbing on roof until on top int lastType = type; int retriesRemaining = 100; // don't climb forever while (type != NOT_IN_BUILDING) { testPos[2] = building->pos[2] + building->size[2] + 0.0001f; tries++; lastType = type; type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, tankHeight); if (--retriesRemaining <= 0) { DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n"); break; } } // ok, when not on top of pyramid or teleporter if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) { foundspot = true; } // only try up in the sky so many times if (--inAirAttempts <= 0) { onGroundOnly = true; } } // check every now and then if we have already used up 10ms of time if (tries >= 50) { tries = 0; if (TimeKeeper::getCurrent() - start > 0.01f) { if (bestDist < 0.0f) { // haven't found a single spot //Just drop the sucka in, and pray pos[0] = testPos[0]; pos[1] = testPos[1]; pos[2] = maxWorldHeight; DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n"); } break; } } // check if spot is safe enough bool dangerous = isImminentlyDangerous(); if (foundspot && !dangerous) { float enemyAngle; float dist = enemyProximityCheck(enemyAngle); if (dist > bestDist) { // best so far bestDist = dist; pos[0] = testPos[0]; pos[1] = testPos[1]; pos[2] = testPos[2]; azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI); } if (bestDist < minProximity) { // not good enough, keep looking foundspot = false; minProximity *= 0.99f; // relax requirements a little } } else if (dangerous) { foundspot = false; } } delete building; } } SpawnPosition::~SpawnPosition() { } const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, const float deviation) const { // determine angle from source to dest // (X) using only x & y, resultant will be z rotation float dx = testPos[0] - enemyPos[0]; float dy = testPos[1] - enemyPos[1]; float angActual; if (dx == 0) { // avoid divide by zero error angActual = (float)tan(dy / (1 / 1e12f)); } else { angActual = (float)tan(dy / dx); } // see if our heading angle is within the bounds set by deviation // (X) only compare to z-rotation since that's all we're using if (((angActual + deviation / 2) > enemyAzimuth) && ((angActual - deviation / 2) < enemyAzimuth)) { return true; } else { return false; } } const bool SpawnPosition::isImminentlyDangerous() const { for (int i = 0; i < curMaxPlayers; i++) { if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) { const FlagInfo *finfo =&flag[player[i].getFlag()]; const FlagType *ftype = finfo->flag.type; float *enemyPos = lastState[i].pos; float enemyAngle = lastState[i].azimuth; // check for dangerous flags, etc // FIXME: any more? if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point return true; // eek, don't spawn here } } else if (ftype == Flags::ShockWave) { // don't spawn next to a SW if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW return true; // eek, don't spawn here } } // don't spawn in the line of sight of a normal-shot tank within a certain distance if (distanceFrom(enemyPos) < safeDistance) { // within danger zone? if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me return true; } } } } // TODO: should check world weapons also return false; } const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const { float worstDist = 1e12f; // huge number bool noEnemy = true; for (int i = 0; i < curMaxPlayers; i++) { if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) { float *enemyPos = lastState[i].pos; if (fabs(enemyPos[2] - testPos[2]) < 1.0f) { float x = enemyPos[0] - testPos[0]; float y = enemyPos[1] - testPos[1]; float distSq = x * x + y * y; if (distSq < worstDist) { worstDist = distSq; enemyAngle = lastState[i].azimuth; noEnemy = false; } } } } if (noEnemy) enemyAngle = (float)bzfrand() * 2.0f * M_PI; return sqrtf(worstDist); } const float SpawnPosition::distanceFrom(const float* farPos) const { float dx = farPos[0] - testPos[0]; float dy = farPos[1] - testPos[1]; float dz = farPos[2] - testPos[2]; return (float)sqrt(dx*dx + dy*dy + dz*dz); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>and the next one - don't delete building if it was never initialized<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // object that creates and contains a spawn position #include "common.h" #include "SpawnPosition.h" #include "FlagInfo.h" #include "TeamBases.h" #include "WorldInfo.h" #include "PlayerInfo.h" #include "PlayerState.h" // FIXME: from bzfs.cxx extern int getCurMaxPlayers(); extern bool areFoes(TeamColor team1, TeamColor team2); extern BasesList bases; extern WorldInfo *world; extern PlayerInfo player[]; extern PlayerState lastState[]; SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) : curMaxPlayers(getCurMaxPlayers()) { team = player[playerId].getTeam(); azimuth = (float)bzfrand() * 2.0f * M_PI; if (player[playerId].shouldRestartAtBase() && (team >= RedTeam) && (team <= PurpleTeam) && (bases.find(team) != bases.end())) { TeamBases &teamBases = bases[team]; const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100)); base.getRandomPosition(pos[0], pos[1], pos[2]); player[playerId].setRestartOnBase(false); } else { const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT); const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS); safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5); safeDistance = tankRadius * 20; // FIXME: is this a good value? const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); const float maxWorldHeight = world->getMaxWorldHeight(); ObstacleLocation *building = NULL; // keep track of how much time we spend searching for a location TimeKeeper start = TimeKeeper::getCurrent(); int inAirAttempts = 50; int tries = 0; float minProximity = size / 3.0f; float bestDist = -1.0f; bool foundspot = false; while (!foundspot) { if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) { if (notNearEdges) { // don't spawn close to map edges in CTF mode testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f; testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f; } else { testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius); testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius); } testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight); } tries++; int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, tankHeight); if (onGroundOnly) { if (type == NOT_IN_BUILDING) foundspot = true; } else { if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) { testPos[2] = 0.0f; //Find any intersection regardless of z type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, maxWorldHeight); } // in a building? try climbing on roof until on top int lastType = type; int retriesRemaining = 100; // don't climb forever while (type != NOT_IN_BUILDING) { testPos[2] = building->pos[2] + building->size[2] + 0.0001f; tries++; lastType = type; type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2], tankRadius, tankHeight); if (--retriesRemaining <= 0) { DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n"); break; } } // ok, when not on top of pyramid or teleporter if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) { foundspot = true; } // only try up in the sky so many times if (--inAirAttempts <= 0) { onGroundOnly = true; } } // check every now and then if we have already used up 10ms of time if (tries >= 50) { tries = 0; if (TimeKeeper::getCurrent() - start > 0.01f) { if (bestDist < 0.0f) { // haven't found a single spot //Just drop the sucka in, and pray pos[0] = testPos[0]; pos[1] = testPos[1]; pos[2] = maxWorldHeight; DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n"); } break; } } // check if spot is safe enough bool dangerous = isImminentlyDangerous(); if (foundspot && !dangerous) { float enemyAngle; float dist = enemyProximityCheck(enemyAngle); if (dist > bestDist) { // best so far bestDist = dist; pos[0] = testPos[0]; pos[1] = testPos[1]; pos[2] = testPos[2]; azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI); } if (bestDist < minProximity) { // not good enough, keep looking foundspot = false; minProximity *= 0.99f; // relax requirements a little } } else if (dangerous) { foundspot = false; } } if (!(building == NULL)) delete building; } } SpawnPosition::~SpawnPosition() { } const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, const float deviation) const { // determine angle from source to dest // (X) using only x & y, resultant will be z rotation float dx = testPos[0] - enemyPos[0]; float dy = testPos[1] - enemyPos[1]; float angActual; if (dx == 0) { // avoid divide by zero error angActual = (float)tan(dy / (1 / 1e12f)); } else { angActual = (float)tan(dy / dx); } // see if our heading angle is within the bounds set by deviation // (X) only compare to z-rotation since that's all we're using if (((angActual + deviation / 2) > enemyAzimuth) && ((angActual - deviation / 2) < enemyAzimuth)) { return true; } else { return false; } } const bool SpawnPosition::isImminentlyDangerous() const { for (int i = 0; i < curMaxPlayers; i++) { if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) { const FlagInfo *finfo =&flag[player[i].getFlag()]; const FlagType *ftype = finfo->flag.type; float *enemyPos = lastState[i].pos; float enemyAngle = lastState[i].azimuth; // check for dangerous flags, etc // FIXME: any more? if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point return true; // eek, don't spawn here } } else if (ftype == Flags::ShockWave) { // don't spawn next to a SW if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW return true; // eek, don't spawn here } } // don't spawn in the line of sight of a normal-shot tank within a certain distance if (distanceFrom(enemyPos) < safeDistance) { // within danger zone? if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me return true; } } } } // TODO: should check world weapons also return false; } const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const { float worstDist = 1e12f; // huge number bool noEnemy = true; for (int i = 0; i < curMaxPlayers; i++) { if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) { float *enemyPos = lastState[i].pos; if (fabs(enemyPos[2] - testPos[2]) < 1.0f) { float x = enemyPos[0] - testPos[0]; float y = enemyPos[1] - testPos[1]; float distSq = x * x + y * y; if (distSq < worstDist) { worstDist = distSq; enemyAngle = lastState[i].azimuth; noEnemy = false; } } } } if (noEnemy) enemyAngle = (float)bzfrand() * 2.0f * M_PI; return sqrtf(worstDist); } const float SpawnPosition::distanceFrom(const float* farPos) const { float dx = farPos[0] - testPos[0]; float dy = farPos[1] - testPos[1]; float dz = farPos[2] - testPos[2]; return (float)sqrt(dx*dx + dy*dy + dz*dz); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreShaderPrecompiledHeaders.h" namespace Ogre { namespace RTShader { //----------------------------------------------------------------------------- SGScriptTranslator::SGScriptTranslator() : mGeneratedRenderState(NULL) { } //----------------------------------------------------------------------------- void SGScriptTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode* obj = static_cast<ObjectAbstractNode*>(node.get()); ObjectAbstractNode* parent = static_cast<ObjectAbstractNode*>(obj->parent); // Translate section within a pass context. if (parent->id == ID_PASS) { translatePass(compiler, node); } if (parent->id == ID_TEXTURE_UNIT) { translateTextureUnit(compiler, node); } } //----------------------------------------------------------------------------- SubRenderState* SGScriptTranslator::getGeneratedSubRenderState(const String& typeName) { //check if we are in the middle of parsing if (mGeneratedRenderState) { /** Get the list of the template sub render states composing this render state. */ const SubRenderStateList& rsList = mGeneratedRenderState->getTemplateSubRenderStateList(); SubRenderStateList::const_iterator it = rsList.begin(); SubRenderStateList::const_iterator itEnd = rsList.end(); for(; it != itEnd; ++it) { if ((*it)->getType() == typeName) return *it; } } return NULL; } //----------------------------------------------------------------------------- /* note: we can know the texture unit index by getting parent then finding it in the list of children */ void SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); TextureUnitState* texState = any_cast<TextureUnitState*>(obj->parent->context); Pass* pass = texState->getParent(); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; //check if technique already created techniqueCreated = shaderGenerator->hasShaderBasedTechnique(material->getName(), material->getGroup(), technique->getSchemeName(), dstTechniqueSchemeName); if (techniqueCreated == false) { // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); } // Case technique successfully created. if (techniqueCreated) { //Attempt to get the render state which might have been created by the pass parsing mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } } //----------------------------------------------------------------------------- void SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); Pass* pass = any_cast<Pass*>(obj->parent->context); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); // Case technique successfully created. if (techniqueCreated) { // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); // Handle light count property. if (prop->name == "light_count") { if (prop->values.size() != 3) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } else { std::vector<int> lightCount; if (getVector(prop->values.begin(), prop->values.end(), lightCount, 3)) { shaderGenerator->createScheme(dstTechniqueSchemeName); RenderState* renderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); renderState->setLightCount(Vector3i(lightCount.data())); renderState->setLightCountAutoUpdate(false); } else { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } } } // Handle the rest of the custom properties. else { SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } } //----------------------------------------------------------------------------- void SGScriptTranslator::addSubRenderState(SubRenderState* newSubRenderState, const String& dstTechniqueSchemeName, const String& materialName, const String& groupName, unsigned short passIndex) { assert(newSubRenderState); //check if a different sub render state of the same type already exists ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); //create a new scheme if needed shaderGenerator->createScheme(dstTechniqueSchemeName); //update the active render state mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, materialName, groupName, passIndex); //add the new sub render state mGeneratedRenderState->addTemplateSubRenderState(newSubRenderState); } } } <commit_msg>RTSS: ScriptTranslator - log error when encountering unknown parameter<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreShaderPrecompiledHeaders.h" namespace Ogre { namespace RTShader { //----------------------------------------------------------------------------- SGScriptTranslator::SGScriptTranslator() : mGeneratedRenderState(NULL) { } //----------------------------------------------------------------------------- void SGScriptTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode* obj = static_cast<ObjectAbstractNode*>(node.get()); ObjectAbstractNode* parent = static_cast<ObjectAbstractNode*>(obj->parent); // Translate section within a pass context. if (parent->id == ID_PASS) { translatePass(compiler, node); } if (parent->id == ID_TEXTURE_UNIT) { translateTextureUnit(compiler, node); } } //----------------------------------------------------------------------------- SubRenderState* SGScriptTranslator::getGeneratedSubRenderState(const String& typeName) { //check if we are in the middle of parsing if (mGeneratedRenderState) { /** Get the list of the template sub render states composing this render state. */ const SubRenderStateList& rsList = mGeneratedRenderState->getTemplateSubRenderStateList(); SubRenderStateList::const_iterator it = rsList.begin(); SubRenderStateList::const_iterator itEnd = rsList.end(); for(; it != itEnd; ++it) { if ((*it)->getType() == typeName) return *it; } } return NULL; } //----------------------------------------------------------------------------- /* note: we can know the texture unit index by getting parent then finding it in the list of children */ void SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); TextureUnitState* texState = any_cast<TextureUnitState*>(obj->parent->context); Pass* pass = texState->getParent(); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; //check if technique already created techniqueCreated = shaderGenerator->hasShaderBasedTechnique(material->getName(), material->getGroup(), technique->getSchemeName(), dstTechniqueSchemeName); if (techniqueCreated == false) { // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); } // Case technique successfully created. if (techniqueCreated) { //Attempt to get the render state which might have been created by the pass parsing mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } else { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name); } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } } //----------------------------------------------------------------------------- void SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node) { ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); Pass* pass = any_cast<Pass*>(obj->parent->context); Technique* technique = pass->getParent(); Material* material = technique->getParent(); ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); String dstTechniqueSchemeName = obj->name; bool techniqueCreated; // Make sure the scheme name is valid - use default if none exists. if (dstTechniqueSchemeName.empty()) dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; // Create the shader based technique. techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, dstTechniqueSchemeName, shaderGenerator->getCreateShaderOverProgrammablePass()); // Case technique successfully created. if (techniqueCreated) { // Go over all the render state properties. for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get()); // Handle light count property. if (prop->name == "light_count") { if (prop->values.size() != 3) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } else { std::vector<int> lightCount; if (getVector(prop->values.begin(), prop->values.end(), lightCount, 3)) { shaderGenerator->createScheme(dstTechniqueSchemeName); RenderState* renderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); renderState->setLightCount(Vector3i(lightCount.data())); renderState->setLightCountAutoUpdate(false); } else { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } } } // Handle the rest of the custom properties. else { SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this); if (subRenderState) { addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); } else { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name); } } } else { processNode(compiler, *i); } } mGeneratedRenderState = NULL; } } //----------------------------------------------------------------------------- void SGScriptTranslator::addSubRenderState(SubRenderState* newSubRenderState, const String& dstTechniqueSchemeName, const String& materialName, const String& groupName, unsigned short passIndex) { assert(newSubRenderState); //check if a different sub render state of the same type already exists ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); //create a new scheme if needed shaderGenerator->createScheme(dstTechniqueSchemeName); //update the active render state mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, materialName, groupName, passIndex); //add the new sub render state mGeneratedRenderState->addTemplateSubRenderState(newSubRenderState); } } } <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file BoostComponentFinder.cpp * @author Roman Schindlauer * @date Wed Jan 25 14:34:20 CET 2006 * * @brief Strategy class for finding SCCs and WCCs from a given program graph, using * the Boost Graph Library. * * */ #include "dlvhex/BoostComponentFinder.h" #include "dlvhex/globals.h" #include "dlvhex/PrintVisitor.h" #include "dlvhex/Component.h" #include <sstream> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/connected_components.hpp> #include <boost/graph/strong_components.hpp> #include <boost/graph/graphviz.hpp> #include <boost/algorithm/string/replace.hpp> DLVHEX_NAMESPACE_BEGIN void BoostComponentFinder::makeEdges(const std::vector<AtomNodePtr>& nodes, Edges& edges) const { for (std::vector<AtomNodePtr>::const_iterator node = nodes.begin(); node != nodes.end(); ++node) { ComponentFinder::Vertex v1 = (*node)->getId(); // // considering all types of dependencies // for (std::set<Dependency>::const_iterator d = (*node)->getSucceeding().begin(); d != (*node)->getSucceeding().end(); ++d) { ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId(); // // making edge from v2 to v1, because the direction is not relevant // for finding WCCs and SCCs and this is the "traditional" direction // for lp-dependency (head->body), and we want these arrows in the // graphviz output (see below)! // edges.push_back(ComponentFinder::Edge(v2, v1)); } } } void BoostComponentFinder::selectNodes(const Vertices& vertices, const std::vector<AtomNodePtr>& nodes, std::vector<AtomNodePtr>& newnodes) const { newnodes.clear(); for (ComponentFinder::Vertices::const_iterator vi = vertices.begin(); vi != vertices.end(); ++vi) { ///@todo this is too expensive - all the vertices-stuff should /// actually be done in boost, it could handle all these /// properties internally. there shouldn't be any mapping and /// searching here! std::vector<AtomNodePtr>::const_iterator an; for (an = nodes.begin(); an != nodes.end(); ++an) { if ((*an)->getId() == *vi) break; } if (an != nodes.end()) { newnodes.push_back(*an); } } } void BoostComponentFinder::findWeakComponents(const std::vector<AtomNodePtr>& nodes, std::vector<std::vector<AtomNodePtr> >& wccs) { /* std::map<int, Vertex> vmap; Edges contedges; for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { } */ ComponentFinder::Edges edges; makeEdges(nodes, edges); using namespace boost; { typedef adjacency_list <listS, vecS, undirectedS> Graph; Graph G; for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { add_edge(ei->first, ei->second, G); } std::vector<int> component(num_vertices(G)); int num = connected_components(G, &component[0]); // std::cout << "Total number of components: " << num << std::endl; std::vector<AtomNodePtr> wcc; for (int cn = 0; cn < num; ++cn) { Vertices thiscomponent; for (std::vector<int>::size_type i = 0; i != component.size(); ++i) { if (component[i] == cn) { thiscomponent.push_back(Vertex(i)); } } // // hack - remove all single noded-components, as long as we don't know // how to use boost with non-contiguous vertices! // if (thiscomponent.size() > 1) { //.push_back(thiscomponent); wcc.clear(); selectNodes(thiscomponent, nodes, wcc); wccs.push_back(wcc); } } // for (std::vector<int>::size_type i = 0; i != component.size(); ++i) // std::cout << "Vertex " << i <<" is in component " << component[i] << std::endl; // std::cout << std::endl; } } void BoostComponentFinder::findStrongComponents(const std::vector<AtomNodePtr>& nodes, std::vector<std::vector<AtomNodePtr> >& sccs) { ComponentFinder::Edges edges; makeEdges(nodes, edges); using namespace boost; { typedef adjacency_list<vecS, vecS, directedS> Graph; Graph G(0); for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { add_edge(ei->first, ei->second, G); } std::vector<int> component(num_vertices(G)); int num = strong_components(G, &component[0]); //std::cout << "Total number of components: " << num << std::endl; std::vector<AtomNodePtr> scc; for (int cn = 0; cn < num; ++cn) { Vertices thiscomponent; for (std::vector<int>::size_type i = 0; i != component.size(); ++i) { if (component[i] == cn) thiscomponent.push_back(Vertex(i)); } /// @todo boost adds also single components as strong /// components. we avoid that for now (25-01-06), because /// having so many sccs will mean to call dlv a lot, which /// might cost a lot. better to put an effort into the /// graphprocessor strategy of finding big wccs on the /// fly. /// @todo try the other way by using a different /// boostcomponentfinder with a different graphprocessor! // // only add components with more than one vertex: // if (thiscomponent.size() > 1) { //components.push_back(thiscomponent); scc.clear(); selectNodes(thiscomponent, nodes, scc); sccs.push_back(scc); } } if (Globals::Instance()->doVerbose(Globals::DUMP_DEPENDENCY_GRAPH)) { // // create a label table for the graphviz output // std::string nms[3 * nodes.size()]; std::ostringstream oss; RawPrintVisitor rpv(oss); for (unsigned y = 0; y < nodes.size(); ++y) { oss.str(""); nodes[y]->getAtom()->accept(rpv); std::string at(oss.str()); boost::algorithm::replace_all(at, "\"", "\\\""); nms[y] = at; } std::ofstream out; out.open(Globals::Instance()->lpfilename.c_str()); write_graphviz(out, G, make_label_writer(nms)); out.close(); Globals::Instance()->getVerboseStream() << "Graph written to " << Globals::Instance()->lpfilename << std::endl; } } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <commit_msg>applied nice part of clang fix (the one that does not deal with a clang bug)<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file BoostComponentFinder.cpp * @author Roman Schindlauer * @date Wed Jan 25 14:34:20 CET 2006 * * @brief Strategy class for finding SCCs and WCCs from a given program graph, using * the Boost Graph Library. * * */ #include "dlvhex/BoostComponentFinder.h" #include "dlvhex/globals.h" #include "dlvhex/PrintVisitor.h" #include "dlvhex/Component.h" #include <sstream> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/connected_components.hpp> #include <boost/graph/strong_components.hpp> #include <boost/graph/graphviz.hpp> #include <boost/algorithm/string/replace.hpp> DLVHEX_NAMESPACE_BEGIN void BoostComponentFinder::makeEdges(const std::vector<AtomNodePtr>& nodes, Edges& edges) const { for (std::vector<AtomNodePtr>::const_iterator node = nodes.begin(); node != nodes.end(); ++node) { ComponentFinder::Vertex v1 = (*node)->getId(); // // considering all types of dependencies // for (std::set<Dependency>::const_iterator d = (*node)->getSucceeding().begin(); d != (*node)->getSucceeding().end(); ++d) { ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId(); // // making edge from v2 to v1, because the direction is not relevant // for finding WCCs and SCCs and this is the "traditional" direction // for lp-dependency (head->body), and we want these arrows in the // graphviz output (see below)! // edges.push_back(ComponentFinder::Edge(v2, v1)); } } } void BoostComponentFinder::selectNodes(const Vertices& vertices, const std::vector<AtomNodePtr>& nodes, std::vector<AtomNodePtr>& newnodes) const { newnodes.clear(); for (ComponentFinder::Vertices::const_iterator vi = vertices.begin(); vi != vertices.end(); ++vi) { ///@todo this is too expensive - all the vertices-stuff should /// actually be done in boost, it could handle all these /// properties internally. there shouldn't be any mapping and /// searching here! std::vector<AtomNodePtr>::const_iterator an; for (an = nodes.begin(); an != nodes.end(); ++an) { if ((*an)->getId() == *vi) break; } if (an != nodes.end()) { newnodes.push_back(*an); } } } void BoostComponentFinder::findWeakComponents(const std::vector<AtomNodePtr>& nodes, std::vector<std::vector<AtomNodePtr> >& wccs) { /* std::map<int, Vertex> vmap; Edges contedges; for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { } */ ComponentFinder::Edges edges; makeEdges(nodes, edges); using namespace boost; { typedef adjacency_list <listS, vecS, undirectedS> Graph; Graph G; for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { add_edge(ei->first, ei->second, G); } std::vector<int> component(num_vertices(G)); int num = connected_components(G, &component[0]); // std::cout << "Total number of components: " << num << std::endl; std::vector<AtomNodePtr> wcc; for (int cn = 0; cn < num; ++cn) { Vertices thiscomponent; for (std::vector<int>::size_type i = 0; i != component.size(); ++i) { if (component[i] == cn) { thiscomponent.push_back(Vertex(i)); } } // // hack - remove all single noded-components, as long as we don't know // how to use boost with non-contiguous vertices! // if (thiscomponent.size() > 1) { //.push_back(thiscomponent); wcc.clear(); selectNodes(thiscomponent, nodes, wcc); wccs.push_back(wcc); } } // for (std::vector<int>::size_type i = 0; i != component.size(); ++i) // std::cout << "Vertex " << i <<" is in component " << component[i] << std::endl; // std::cout << std::endl; } } void BoostComponentFinder::findStrongComponents(const std::vector<AtomNodePtr>& nodes, std::vector<std::vector<AtomNodePtr> >& sccs) { ComponentFinder::Edges edges; makeEdges(nodes, edges); using namespace boost; { typedef adjacency_list<vecS, vecS, directedS> Graph; Graph G(0); for (Edges::const_iterator ei = edges.begin(); ei != edges.end(); ++ei) { add_edge(ei->first, ei->second, G); } std::vector<int> component(num_vertices(G)); int num = strong_components(G, &component[0]); //std::cout << "Total number of components: " << num << std::endl; std::vector<AtomNodePtr> scc; for (int cn = 0; cn < num; ++cn) { Vertices thiscomponent; for (std::vector<int>::size_type i = 0; i != component.size(); ++i) { if (component[i] == cn) thiscomponent.push_back(Vertex(i)); } /// @todo boost adds also single components as strong /// components. we avoid that for now (25-01-06), because /// having so many sccs will mean to call dlv a lot, which /// might cost a lot. better to put an effort into the /// graphprocessor strategy of finding big wccs on the /// fly. /// @todo try the other way by using a different /// boostcomponentfinder with a different graphprocessor! // // only add components with more than one vertex: // if (thiscomponent.size() > 1) { //components.push_back(thiscomponent); scc.clear(); selectNodes(thiscomponent, nodes, scc); sccs.push_back(scc); } } if (Globals::Instance()->doVerbose(Globals::DUMP_DEPENDENCY_GRAPH)) { // // create a label table for the graphviz output // const int nnames = 3*nodes.size(); std::vector<std::string> nms(nnames); const char* nmsc[nnames]; std::ostringstream oss; RawPrintVisitor rpv(oss); for (unsigned y = 0; y < nodes.size(); ++y) { oss.str(""); nodes[y]->getAtom()->accept(rpv); std::string at(oss.str()); boost::algorithm::replace_all(at, "\"", "\\\""); nms[y] = at; nmsc[y] = nms[y].c_str(); } std::ofstream out; out.open(Globals::Instance()->lpfilename.c_str()); write_graphviz(out, G, make_label_writer(nmsc)); out.close(); Globals::Instance()->getVerboseStream() << "Graph written to " << Globals::Instance()->lpfilename << std::endl; } } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <|endoftext|>
<commit_before>#pragma once #include <Physic/Utils/BtConversion.hpp> #include <Systems/System.h> #include <Components/RigidBody.hpp> #include <Physic/BulletDynamicManager.hpp> #include <Core/Engine.hh> #include <Entities/EntityFlags.hh> #include <future> namespace AGE { class BulletDynamicSystem : public System { public: BulletDynamicSystem(AScene *scene) : System(std::move(scene)) , _manager(nullptr) , _filter(std::move(scene)) { _name = "bullet_dynamic_system"; _manager = dynamic_cast<BulletDynamicManager*>(_scene->getInstance<BulletCollisionManager>()); _filter.requireComponent<RigidBody>(); } virtual ~BulletDynamicSystem(){} private: BulletDynamicManager* _manager; EntityFilter _filter; virtual void updateBegin(float time) { auto scene = _scene; for (auto e : _filter.getCollection()) { if (e.getLink().isUserModified()) { auto rb = e.getComponent<RigidBody>(); if (rb->getMass() == 0) { rb->setTransformation(&e.getLink()); e.getLink().setUserModified(false); } } } _manager->getWorld()->stepSimulation(static_cast<btScalar>(time), 10); } virtual void updateEnd(float time) {} virtual void mainUpdate(float time) { } virtual bool initialize() { return true; } }; }<commit_msg>Physics deactivated when Dt == 0<commit_after>#pragma once #include <Physic/Utils/BtConversion.hpp> #include <Systems/System.h> #include <Components/RigidBody.hpp> #include <Physic/BulletDynamicManager.hpp> #include <Core/Engine.hh> #include <Entities/EntityFlags.hh> #include <future> namespace AGE { class BulletDynamicSystem : public System { public: BulletDynamicSystem(AScene *scene) : System(std::move(scene)) , _manager(nullptr) , _filter(std::move(scene)) { _name = "bullet_dynamic_system"; _manager = dynamic_cast<BulletDynamicManager*>(_scene->getInstance<BulletCollisionManager>()); _filter.requireComponent<RigidBody>(); } virtual ~BulletDynamicSystem(){} private: BulletDynamicManager* _manager; EntityFilter _filter; virtual void updateBegin(float time) { auto scene = _scene; for (auto e : _filter.getCollection()) { if (e.getLink().isUserModified()) { auto rb = e.getComponent<RigidBody>(); if (rb->getMass() == 0) { rb->setTransformation(&e.getLink()); e.getLink().setUserModified(false); } } } if (time == 0.0f) { return; } _manager->getWorld()->stepSimulation(static_cast<btScalar>(time), 10); } virtual void updateEnd(float time) {} virtual void mainUpdate(float time) { } virtual bool initialize() { return true; } }; }<|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* This WRM evaluator evaluates saturation of gas, liquid, and ice from capillary pressures for the ice-liquid and liquid-gas pairs. Authors: Ethan Coon (ecoon@lanl.gov) */ #include "wrm_permafrost_evaluator.hh" #include "wrm_partition.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { /* -------------------------------------------------------------------------------- Constructor from just a ParameterList, reads WRMs and permafrost models from list. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) : SecondaryVariablesFieldEvaluator(plist) { // get the WRMs ASSERT(plist_.isSublist("WRM parameters")); Teuchos::ParameterList wrm_plist = plist_.sublist("WRM parameters"); wrms_ = createWRMPartition(wrm_plist); // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with WRMs. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPartition>& wrms) : SecondaryVariablesFieldEvaluator(plist), wrms_(wrms) { // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with Permafrost models. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPermafrostModelPartition>& models) : SecondaryVariablesFieldEvaluator(plist), permafrost_models_(models) { InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Copy constructor -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) : SecondaryVariablesFieldEvaluator(other), pc_liq_key_(other.pc_liq_key_), pc_ice_key_(other.pc_ice_key_), s_l_key_(other.s_l_key_), permafrost_models_(other.permafrost_models_) {} /* -------------------------------------------------------------------------------- Virtual opy constructor as a FieldEvaluator. -------------------------------------------------------------------------------- */ Teuchos::RCP<FieldEvaluator> WRMPermafrostEvaluator::Clone() const { return Teuchos::rcp(new WRMPermafrostEvaluator(*this)); } /* -------------------------------------------------------------------------------- Initialization of keys. -------------------------------------------------------------------------------- */ void WRMPermafrostEvaluator::InitializeFromPlist_() { // my keys are for saturation -- order matters... gas -> liq -> ice my_keys_.push_back(plist_.get<string>("gas saturation key", "saturation_gas")); s_l_key_ = plist_.get<string>("liquid saturation key", "saturation_liquid"); my_keys_.push_back(s_l_key_); my_keys_.push_back(plist_.get<string>("ice saturation key", "saturation_ice")); // liquid-gas capillary pressure pc_liq_key_ = plist_.get<string>("gas-liquid capillary pressure key", "capillary_pressure_gas_liq"); dependencies_.insert(pc_liq_key_); // liquid-gas capillary pressure pc_ice_key_ = plist_.get<string>("liquid-ice capillary pressure key", "capillary_pressure_liq_ice"); dependencies_.insert(pc_ice_key_); } void WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const std::vector<Teuchos::Ptr<CompositeVector> >& results) { // Initialize the MeshPartition if (!permafrost_models_->first->initialized()) permafrost_models_->first->Initialize(results[0]->Mesh()); // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double sats[3]; int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats); satg_c[0][c] = sats[0]; satl_c[0][c] = sats[1]; sati_c[0][c] = sats[2]; } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); const Epetra_Map& face_map = mesh->face_epetra_map(false); AmanziMesh::Entity_ID_List cells; // calculate boundary face values int nbfaces = satg_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i] ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats); satg_bf[0][bf] = sats[0]; satl_bf[0][bf] = sats[1]; sati_bf[0][bf] = sats[2]; } } } void WRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) { // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double dsats[3]; if (wrt_key == pc_liq_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else { ASSERT(0); } // Potentially do face values as well, though only for saturation_liquid? if (results[1]->HasComponent("boundary_face")) { ASSERT(!results[0]->HasComponent("boundary_face")); ASSERT(!results[2]->HasComponent("boundary_face")); Epetra_MultiVector& sat_bf = *results[1]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& face_map = mesh->face_epetra_map(false); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); AmanziMesh::Entity_ID_List cells; if (wrt_key == pc_liq_key_) { // calculate boundary face values int nbfaces = sat_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); sat_bf[0][bf] = dsats[1]; } } else if (wrt_key == pc_ice_key_) { // calculate boundary face values int nbfaces = sat_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); sat_bf[0][bf] = dsats[1]; } } else { ASSERT(0); } } } } // namespace } // namespace } // namespace <commit_msg>megering stuff<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* This WRM evaluator evaluates saturation of gas, liquid, and ice from capillary pressures for the ice-liquid and liquid-gas pairs. Authors: Ethan Coon (ecoon@lanl.gov) */ #include "wrm_permafrost_evaluator.hh" #include "wrm_partition.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { /* -------------------------------------------------------------------------------- Constructor from just a ParameterList, reads WRMs and permafrost models from list. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) : SecondaryVariablesFieldEvaluator(plist) { // get the WRMs ASSERT(plist_.isSublist("WRM parameters")); Teuchos::ParameterList wrm_plist = plist_.sublist("WRM parameters"); wrms_ = createWRMPartition(wrm_plist); // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with WRMs. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPartition>& wrms) : SecondaryVariablesFieldEvaluator(plist), wrms_(wrms) { // and the permafrost models ASSERT(plist_.isSublist("permafrost model parameters")); Teuchos::ParameterList perm_plist = plist_.sublist("permafrost model parameters"); permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_); InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Constructor with Permafrost models. -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist, const Teuchos::RCP<WRMPermafrostModelPartition>& models) : SecondaryVariablesFieldEvaluator(plist), permafrost_models_(models) { InitializeFromPlist_(); } /* -------------------------------------------------------------------------------- Copy constructor -------------------------------------------------------------------------------- */ WRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) : SecondaryVariablesFieldEvaluator(other), pc_liq_key_(other.pc_liq_key_), pc_ice_key_(other.pc_ice_key_), s_l_key_(other.s_l_key_), permafrost_models_(other.permafrost_models_) {} /* -------------------------------------------------------------------------------- Virtual opy constructor as a FieldEvaluator. -------------------------------------------------------------------------------- */ Teuchos::RCP<FieldEvaluator> WRMPermafrostEvaluator::Clone() const { return Teuchos::rcp(new WRMPermafrostEvaluator(*this)); } /* -------------------------------------------------------------------------------- Initialization of keys. -------------------------------------------------------------------------------- */ void WRMPermafrostEvaluator::InitializeFromPlist_() { // my keys are for saturation -- order matters... gas -> liq -> ice my_keys_.push_back(plist_.get<string>("gas saturation key", "saturation_gas")); s_l_key_ = plist_.get<string>("liquid saturation key", "saturation_liquid"); my_keys_.push_back(s_l_key_); my_keys_.push_back(plist_.get<string>("ice saturation key", "saturation_ice")); // liquid-gas capillary pressure pc_liq_key_ = plist_.get<string>("gas-liquid capillary pressure key", "capillary_pressure_gas_liq"); dependencies_.insert(pc_liq_key_); // liquid-gas capillary pressure pc_ice_key_ = plist_.get<string>("liquid-ice capillary pressure key", "capillary_pressure_liq_ice"); dependencies_.insert(pc_ice_key_); } void WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const std::vector<Teuchos::Ptr<CompositeVector> >& results) { // Initialize the MeshPartition if (!permafrost_models_->first->initialized()) permafrost_models_->first->Initialize(results[0]->Mesh()); // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double sats[3]; int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats); satg_c[0][c] = sats[0]; satl_c[0][c] = sats[1]; sati_c[0][c] = sats[2]; } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); const Epetra_Map& face_map = mesh->face_epetra_map(false); AmanziMesh::Entity_ID_List cells; // calculate boundary face values int nbfaces = satg_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i] ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats); satg_bf[0][bf] = sats[0]; satl_bf[0][bf] = sats[1]; sati_bf[0][bf] = sats[2]; } } } void WRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) { // Cell values Epetra_MultiVector& satg_c = *results[0]->ViewComponent("cell",false); Epetra_MultiVector& satl_c = *results[1]->ViewComponent("cell",false); Epetra_MultiVector& sati_c = *results[2]->ViewComponent("cell",false); const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_) ->ViewComponent("cell",false); const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_) ->ViewComponent("cell",false); double dsats[3]; if (wrt_key == pc_liq_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { int ncells = satg_c.MyLength(); for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) { int i = (*permafrost_models_->first)[c]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_c[0][c], pc_ice_c[0][c], dsats); satg_c[0][c] = dsats[0]; satl_c[0][c] = dsats[1]; sati_c[0][c] = dsats[2]; } } else { ASSERT(0); } // Potentially do face values as well, though only for saturation_liquid? if (results[0]->HasComponent("boundary_face")) { Epetra_MultiVector& satg_bf = *results[0]->ViewComponent("boundary_face",false); Epetra_MultiVector& satl_bf = *results[1]->ViewComponent("boundary_face",false); Epetra_MultiVector& sati_bf = *results[2]->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_) ->ViewComponent("boundary_face",false); const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_) ->ViewComponent("boundary_face",false); // Need to get boundary face's inner cell to specify the WRM. Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh(); const Epetra_Map& face_map = mesh->face_epetra_map(false); const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map(); AmanziMesh::Entity_ID_List cells; if (wrt_key == pc_liq_key_) { // calculate boundary face values int nbfaces = satl_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_liq( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); satg_bf[0][bf] = dsats[0]; satl_bf[0][bf] = dsats[1]; sati_bf[0][bf] = dsats[2]; } } else if (wrt_key == pc_ice_key_) { // calculate boundary face values int nbfaces = satl_bf.MyLength(); for (int bf=0; bf!=nbfaces; ++bf) { // given a boundary face, we need the internal cell to choose the right WRM AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf)); mesh->face_get_cells(f, AmanziMesh::USED, &cells); ASSERT(cells.size() == 1); int i = (*permafrost_models_->first)[cells[0]]; permafrost_models_->second[i]->dsaturations_dpc_ice( pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats); satg_bf[0][bf] = dsats[0]; satl_bf[0][bf] = dsats[1]; sati_bf[0][bf] = dsats[2]; } } else { ASSERT(0); } } } } // namespace } // namespace } // namespace <|endoftext|>
<commit_before>#include <X11/Xlib.h> #include <X11/keysym.h> #include <irrlicht/Keycodes.h> #include <stdio.h> #include <unistd.h> #define RETURN 13 #define BS 8 #define SPACE 32 XKeyEvent createKeyEvent(Display *display, Window &win, Window &winRoot, bool press, int keycode, int modifiers) { // Largely lifted from // http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html XKeyEvent event; event.display = display; event.window = win; event.root = winRoot; event.subwindow = None; event.time = CurrentTime; event.x = 1; event.y = 1; event.x_root = 1; event.y_root = 1; event.same_screen = True; event.keycode = XKeysymToKeycode(display, keycode); event.state = modifiers; if(press) event.type = KeyPress; else event.type = KeyRelease; return event; } class X11Display { public: Display *display; Window winRoot; X11Display(const char* dispName); ~X11Display(); int sendKeyEvent(int keycode, bool keyDown, int mod); }; // TODO: fail out if display doesn't initialize X11Display::X11Display(const char* dispName) { display = XOpenDisplay(dispName); if(NULL == display) { printf("invalid X11 display: %s\n", dispName); throw; } winRoot = XDefaultRootWindow(display); } X11Display::~X11Display() { XCloseDisplay(display); } int X11Display::sendKeyEvent(int keycode, bool keyDown, int mod = 0) { if(-1==keycode) return 0; Window winFocus; int revert; XGetInputFocus(display, &winFocus, &revert); XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, mod); XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event); return 0; } bool IsModKey(int keycode) { switch(keycode){ //shift, control and menu (both left and right) are consecutive case irr::KEY_LSHIFT ... irr::KEY_RMENU : return true; default : return false; } } int mapKeyCode(int irrcode){ switch(irrcode){ //FIXME: only to get rid of arrow spam case 37 ... 40: return -1; case irr::KEY_BACK : return XK_BackSpace; case irr::KEY_TAB : return XK_Tab; //FIXME: Should escape be a modifier too? case irr::KEY_ESCAPE : return XK_Escape; case irr::KEY_RETURN : return XK_Return; case irr::KEY_MINUS : return XK_minus; case irr::KEY_PLUS : return XK_equal; case irr::KEY_OEM_1 : return XK_semicolon; case irr::KEY_OEM_2 : return XK_slash; case irr::KEY_OEM_4 : return XK_bracketleft; case irr::KEY_OEM_6 : return XK_bracketright; case irr::KEY_OEM_7 : return XK_apostrophe; case irr::KEY_PERIOD : return XK_period; case irr::KEY_COMMA : return XK_comma; case irr::KEY_OEM_5 : return XK_backslash; case irr::KEY_LSHIFT : return XK_Shift_L; case irr::KEY_RSHIFT : return XK_Shift_R; case irr::KEY_LCONTROL : return XK_Control_L; case irr::KEY_RCONTROL : return XK_Control_R; default: return irrcode; } } <commit_msg>Lined up prototypes for moving in to header file<commit_after>#include <X11/Xlib.h> #include <X11/keysym.h> #include <irrlicht/Keycodes.h> #include <stdio.h> #include <unistd.h> #define RETURN 13 #define BS 8 #define SPACE 32 XKeyEvent createKeyEvent(Display *display, Window &win, Window &winRoot, bool press, int keycode, int modifiers); class X11Display { public: Display *display; Window winRoot; X11Display(const char* dispName); ~X11Display(); int sendKeyEvent(int keycode, bool keyDown, int mod); }; bool IsModKey(int keycode); int mapKeyCode(int irrcode); XKeyEvent createKeyEvent(Display *display, Window &win, Window &winRoot, bool press, int keycode, int modifiers) { // Largely lifted from // http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html XKeyEvent event; event.display = display; event.window = win; event.root = winRoot; event.subwindow = None; event.time = CurrentTime; event.x = 1; event.y = 1; event.x_root = 1; event.y_root = 1; event.same_screen = True; event.keycode = XKeysymToKeycode(display, keycode); event.state = modifiers; if(press) event.type = KeyPress; else event.type = KeyRelease; return event; } // TODO: fail out if display doesn't initialize X11Display::X11Display(const char* dispName) { display = XOpenDisplay(dispName); if(NULL == display) { printf("invalid X11 display: %s\n", dispName); throw; } winRoot = XDefaultRootWindow(display); } X11Display::~X11Display() { XCloseDisplay(display); } int X11Display::sendKeyEvent(int keycode, bool keyDown, int mod = 0) { if(-1==keycode) return 0; Window winFocus; int revert; XGetInputFocus(display, &winFocus, &revert); XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, mod); XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event); return 0; } bool IsModKey(int keycode) { switch(keycode){ //shift, control and menu (both left and right) are consecutive case irr::KEY_LSHIFT ... irr::KEY_RMENU : return true; default : return false; } } int mapKeyCode(int irrcode){ switch(irrcode){ //FIXME: only to get rid of arrow spam case 37 ... 40: return -1; case irr::KEY_BACK : return XK_BackSpace; case irr::KEY_TAB : return XK_Tab; //FIXME: Should escape be a modifier too? case irr::KEY_ESCAPE : return XK_Escape; case irr::KEY_RETURN : return XK_Return; case irr::KEY_MINUS : return XK_minus; case irr::KEY_PLUS : return XK_equal; case irr::KEY_OEM_1 : return XK_semicolon; case irr::KEY_OEM_2 : return XK_slash; case irr::KEY_OEM_4 : return XK_bracketleft; case irr::KEY_OEM_6 : return XK_bracketright; case irr::KEY_OEM_7 : return XK_apostrophe; case irr::KEY_PERIOD : return XK_period; case irr::KEY_COMMA : return XK_comma; case irr::KEY_OEM_5 : return XK_backslash; case irr::KEY_LSHIFT : return XK_Shift_L; case irr::KEY_RSHIFT : return XK_Shift_R; case irr::KEY_LCONTROL : return XK_Control_L; case irr::KEY_RCONTROL : return XK_Control_R; default: return irrcode; } } <|endoftext|>
<commit_before>/// this file exists to remove C++11 from CUDA, to support outdated nvcc compilers #include "lkt.h" #include <time.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> //#include "mergesort.hh" #include "tbb/tbb.h" #include "quicksort.hh" /* std::ostream& operator<<(std::ostream& s, const lkt_point& p) { s << "{" << p.x << ", " << p.y << ", " << p.key << "}"; return s; } */ /// \todo change these to C++ and use templates. Or Macros. Something. /// finds a heuristic value, using the given sample rate, splitting on the x-axis static ord_t lkt_find_splitpoint_x(lkt_point* begin, lkt_point* end, size_t sample_rate) { double average = 0.0; size_t samples_taken = 0; sample_rate = (end - begin) / sample_rate + 1; for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) { average += i->x; } average /= samples_taken; return average; } /// finds a heuristic value, using the given sample rate, splitting on the y-axis static ord_t lkt_find_splitpoint_y(lkt_point* begin, lkt_point* end, size_t sample_rate) { double average = 0.0; size_t samples_taken = 0; sample_rate = (end - begin) / sample_rate + 1; for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) { average += i->y; } average /= samples_taken; return average; } /// DO NOT change this to use the XOR method. It is slow. static inline void lkt_swap(lkt_point* a, lkt_point* b) { lkt_point old_a = *a; *a = *b; *b = old_a; } static inline size_t get_heap_child_l(const size_t i) {return i * 2 + 1;} static inline size_t get_heap_child_r(const size_t i) {return i * 2 + 2;} static inline size_t get_heap_parent(const size_t i) {return (i - 1) / 2;} static bool point_comparator_x(const lkt_point& a, const lkt_point& b) { return a.x < b.x; } static bool point_comparator_y(const lkt_point& a, const lkt_point& b) { return a.y < b.y; } /// \param sample_rate the rate to sample when finding the split point static void lkt_sort_parallel(lkt_point* points, size_t len, size_t sample_rate, fixlentree<lkt_split_point>& splitpoints, index_t splitpoint_parent, bool splitpoint_thisisleft, bool xaxis, const unsigned short current_depth, const unsigned short max_depth) { const size_t PARALLEL_QUICKSORT_THREADS = 8; /* fprintf(stderr, "lkt_sort called for splitpoint %f\n", splitpoint); fprintf(stderr, "lkt_sort called for points %p, len %lu\n", (void*)points, len); fprintf(stderr, "lkt_sort called for splitpoint_i %lu\n", splitpoint_i); fprintf(stderr, "lkt_sort next splitpoint_is: %lu, %lu\n", get_heap_child_l(splitpoint_i), get_heap_child_r(splitpoint_i)); fprintf(stderr, "sort at splitpoint_i = %lu\n", splitpoint_i); fflush(stdout); */ if(len < 2 || current_depth == max_depth) return; // splitpoint is the value in the points array, by which the points will be partitioned // splitpoint_val is the (local) index in the points array, before which values are less than splitpoint. typedef ord_t (*splitpoint_finder_func_t)(lkt_point* begin, lkt_point* end, size_t sample_rate); typedef bool (*comparator_func_t)(const lkt_point&, const lkt_point&); // avoids conditionals. const splitpoint_finder_func_t find_split_func = (splitpoint_finder_func_t)((intptr_t)lkt_find_splitpoint_x * xaxis + (intptr_t)lkt_find_splitpoint_y * !xaxis); const comparator_func_t comparator_func = (comparator_func_t)((intptr_t)point_comparator_x * xaxis + (intptr_t)point_comparator_y * !xaxis); const ord_t splitpoint = find_split_func(points, points + len, sample_rate); const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; // cheaper to just assign both, than a conditional // cout << "debug len:" << len << " splitpoint: " << splitpoint << endl; // cout << "debug partition started" << endl; const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, points + len, splitpoint_point, PARALLEL_QUICKSORT_THREADS, comparator_func); ///< \todo fix last (?) block bug // cout << "debug partition finished" << endl; const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val}; const index_t splitpoint_next_parent = splitpoints.insert(splitpoint_parent, splitpoint_thisisleft, lkt_splitpoint); if(splitpoint_next_parent == splitpoints.tree_end) return; if(splitpoint_val == 0 || splitpoint_val == len - 1) return; // cout << "splitpoint " << (xaxis ? "x" : "y") << " val: " << splitpoint << " location: " << splitpoint_val << endl; /* lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, true, !xaxis, current_depth + 1, max_depth); lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, false, !xaxis, current_depth + 1, max_depth); */ tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, true, !xaxis, current_depth + 1, max_depth);}, [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, false, !xaxis, current_depth + 1, max_depth);}); } /// returns a heap linear_kdtree lkt_create_parallel(lkt_point* points, size_t len) { const size_t PARALLEL_QUICKSORT_THREADS = 8; fprintf(stderr, "lkt_create called for points %p, true end %p \n", (void*)points, (void*)(points + len)); if(sizeof(mortoncode_t) != 4) { fprintf(stderr, "mortoncode_t NOT 32 BITS! ERROR!ERROR!ERROR!"); /// \todo fix to be static_assert exit(1); } const unsigned short max_depth = sizeof(mortoncode_t) * CHAR_BIT; linear_kdtree tree; tree.points = points; tree.len = len; // fprintf(stderr, "lkt_create depth %lu\n", (size_t)depth); // fprintf(stderr, "lkt_create split_points_len %lu\n", (size_t)tree.split_points_len); // fprintf(stderr, "lkt_create newing split_points size %lu\n", sizeof(lkt_split_point) * tree.split_points_len); // fprintf(stderr, "lkt_create newed split_points\n"); const size_t sample_rate = 100; // fprintf(stderr, "lkt_create sorting\n"); tree.split_points_len = len; fixlentree<lkt_split_point> splitpoints(tree.split_points_len); ///< \todo scope const ord_t splitpoint = lkt_find_splitpoint_x(points, points + len, sample_rate); const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; // cheaper to just assign both, than a conditional const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, &points[len], splitpoint_point, PARALLEL_QUICKSORT_THREADS, point_comparator_x); const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val}; const index_t root = splitpoints.insert_root(lkt_splitpoint); // cout << "first splitpoint x val: " << splitpoint << " location: " << splitpoint_val << endl; cout << "debug 0 parallel invoking" << endl; tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, root, true, false, 1, max_depth);}, [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, root, false, false, 1, max_depth);}); /* lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, root, true, false, 1, max_depth); lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, root, false, false, 1, max_depth); */ cout << "debug 1 splitpoints releasing" << endl; tree.split_points = splitpoints.release(); fprintf(stderr, "lkt_create coding\n"); tree.morton_codes = lkt_create_mortoncodes_parallel(tree.points, tree.len, tree.split_points); // fprintf(stderr, "lkt_create returning\n"); return tree; } /* // x value ALONE is used for comparison, to create an xpack bool operator<(const lkt_point& rhs, const lkt_point& lhs) { return rhs.x < lhs.x; } bool operator<(const lqt_unified_node& rhs, const lqt_unified_node& lhs) { return rhs.location < lhs.location; } linear_quadtree_unified tbb_sortify_unified(linear_quadtree_unified lqt, const size_t threads) { // auto lowxpack = [](const rtree_point& rhs, const rtree_point& lhs) { // return rhs.x < rhs.y; // }; tbb::task_scheduler_init init(threads); tbb::parallel_sort(lqt.nodes, lqt.nodes + lqt.length); return lqt; } /// does not block for GPU memory. Will fail, if GPU memory is insufficient. linear_quadtree_unified lqt_create_heterogeneous(lkt_point* points, size_t len, ord_t xstart, ord_t xend, ord_t ystart, ord_t yend, size_t* depth, const size_t threads) { return tbb_sortify_unified(lqt_nodify_cuda_unified(points, len, xstart, xend, ystart, yend, depth), threads); } /// \param threads the number of threads to use when sorting. ONLY used in the 'sort' part of the algorithm rtree cuda_create_rtree_heterogeneously_mergesort(rtree_point* points, const size_t len, const size_t threads) { rtree_leaf* leaves = cuda_create_leaves_together(parallel_mergesort(points, points + len, threads), len); const size_t leaves_len = DIV_CEIL(len, RTREE_NODE_SIZE); rtree_node* previous_level = (rtree_node*) leaves; size_t previous_len = leaves_len; size_t depth = 1; // leaf level is 0 while(previous_len > RTREE_NODE_SIZE) { previous_level = cuda_create_level(previous_level, previous_len); previous_len = DIV_CEIL(previous_len, RTREE_NODE_SIZE); ++depth; } rtree_node* root = (rtree_node*) malloc(sizeof(rtree_node)); init_boundary(&root->bounding_box); root->num = previous_len; root->children = previous_level; for(size_t i = 0, end = previous_len; i != end; ++i) update_boundary(&root->bounding_box, &root->children[i].bounding_box); ++depth; rtree tree = {depth, root}; return tree; } */ /* /// SISD sort via single CPU core (for benchmarks) rtree cuda_create_rtree_sisd(rtree_point* points, const size_t len) { std::sort(points, points + len); rtree_leaf* leaves = cuda_create_leaves_together(points, len); const size_t leaves_len = DIV_CEIL(len, RTREE_NODE_SIZE); rtree_node* previous_level = (rtree_node*) leaves; size_t previous_len = leaves_len; size_t depth = 1; // leaf level is 0 while(previous_len > RTREE_NODE_SIZE) { previous_level = cuda_create_level(previous_level, previous_len); previous_len = DIV_CEIL(previous_len, RTREE_NODE_SIZE); ++depth; } p rtree_node* root = (rtree_node*) malloc(sizeof(rtree_node)); init_boundary(&root->bounding_box); root->num = previous_len; root->children = previous_level; for(size_t i = 0, end = previous_len; i != end; ++i) update_boundary(&root->bounding_box, &root->children[i].bounding_box); ++depth; rtree tree = {depth, root}; return tree; } */ <commit_msg>removed commented code<commit_after>/// this file exists to remove C++11 from CUDA, to support outdated nvcc compilers #include "lkt.h" #include <time.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> //#include "mergesort.hh" #include "tbb/tbb.h" #include "quicksort.hh" /* std::ostream& operator<<(std::ostream& s, const lkt_point& p) { s << "{" << p.x << ", " << p.y << ", " << p.key << "}"; return s; } */ /// \todo change these to C++ and use templates. Or Macros. Something. /// finds a heuristic value, using the given sample rate, splitting on the x-axis static ord_t lkt_find_splitpoint_x(lkt_point* begin, lkt_point* end, size_t sample_rate) { double average = 0.0; size_t samples_taken = 0; sample_rate = (end - begin) / sample_rate + 1; for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) { average += i->x; } average /= samples_taken; return average; } /// finds a heuristic value, using the given sample rate, splitting on the y-axis static ord_t lkt_find_splitpoint_y(lkt_point* begin, lkt_point* end, size_t sample_rate) { double average = 0.0; size_t samples_taken = 0; sample_rate = (end - begin) / sample_rate + 1; for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) { average += i->y; } average /= samples_taken; return average; } /// DO NOT change this to use the XOR method. It is slow. static inline void lkt_swap(lkt_point* a, lkt_point* b) { lkt_point old_a = *a; *a = *b; *b = old_a; } static inline size_t get_heap_child_l(const size_t i) {return i * 2 + 1;} static inline size_t get_heap_child_r(const size_t i) {return i * 2 + 2;} static inline size_t get_heap_parent(const size_t i) {return (i - 1) / 2;} static bool point_comparator_x(const lkt_point& a, const lkt_point& b) { return a.x < b.x; } static bool point_comparator_y(const lkt_point& a, const lkt_point& b) { return a.y < b.y; } /// \param sample_rate the rate to sample when finding the split point static void lkt_sort_parallel(lkt_point* points, size_t len, size_t sample_rate, fixlentree<lkt_split_point>& splitpoints, index_t splitpoint_parent, bool splitpoint_thisisleft, bool xaxis, const unsigned short current_depth, const unsigned short max_depth) { const size_t PARALLEL_QUICKSORT_THREADS = 8; /* fprintf(stderr, "lkt_sort called for splitpoint %f\n", splitpoint); fprintf(stderr, "lkt_sort called for points %p, len %lu\n", (void*)points, len); fprintf(stderr, "lkt_sort called for splitpoint_i %lu\n", splitpoint_i); fprintf(stderr, "lkt_sort next splitpoint_is: %lu, %lu\n", get_heap_child_l(splitpoint_i), get_heap_child_r(splitpoint_i)); fprintf(stderr, "sort at splitpoint_i = %lu\n", splitpoint_i); fflush(stdout); */ if(len < 2 || current_depth == max_depth) return; // splitpoint is the value in the points array, by which the points will be partitioned // splitpoint_val is the (local) index in the points array, before which values are less than splitpoint. typedef ord_t (*splitpoint_finder_func_t)(lkt_point* begin, lkt_point* end, size_t sample_rate); typedef bool (*comparator_func_t)(const lkt_point&, const lkt_point&); // avoids conditionals. const splitpoint_finder_func_t find_split_func = (splitpoint_finder_func_t)((intptr_t)lkt_find_splitpoint_x * xaxis + (intptr_t)lkt_find_splitpoint_y * !xaxis); const comparator_func_t comparator_func = (comparator_func_t)((intptr_t)point_comparator_x * xaxis + (intptr_t)point_comparator_y * !xaxis); const ord_t splitpoint = find_split_func(points, points + len, sample_rate); const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; // cheaper to just assign both, than a conditional // cout << "debug len:" << len << " splitpoint: " << splitpoint << endl; // cout << "debug partition started" << endl; const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, points + len, splitpoint_point, PARALLEL_QUICKSORT_THREADS, comparator_func); ///< \todo fix last (?) block bug // cout << "debug partition finished" << endl; const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val}; const index_t splitpoint_next_parent = splitpoints.insert(splitpoint_parent, splitpoint_thisisleft, lkt_splitpoint); if(splitpoint_next_parent == splitpoints.tree_end) return; if(splitpoint_val == 0 || splitpoint_val == len - 1) return; // cout << "splitpoint " << (xaxis ? "x" : "y") << " val: " << splitpoint << " location: " << splitpoint_val << endl; /* lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, true, !xaxis, current_depth + 1, max_depth); lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, false, !xaxis, current_depth + 1, max_depth); */ tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, true, !xaxis, current_depth + 1, max_depth);}, [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, splitpoint_next_parent, false, !xaxis, current_depth + 1, max_depth);}); } /// returns a heap linear_kdtree lkt_create_parallel(lkt_point* points, size_t len) { const size_t PARALLEL_QUICKSORT_THREADS = 8; fprintf(stderr, "lkt_create called for points %p, true end %p \n", (void*)points, (void*)(points + len)); if(sizeof(mortoncode_t) != 4) { fprintf(stderr, "mortoncode_t NOT 32 BITS! ERROR!ERROR!ERROR!"); /// \todo fix to be static_assert exit(1); } const unsigned short max_depth = sizeof(mortoncode_t) * CHAR_BIT; linear_kdtree tree; tree.points = points; tree.len = len; // fprintf(stderr, "lkt_create depth %lu\n", (size_t)depth); // fprintf(stderr, "lkt_create split_points_len %lu\n", (size_t)tree.split_points_len); // fprintf(stderr, "lkt_create newing split_points size %lu\n", sizeof(lkt_split_point) * tree.split_points_len); // fprintf(stderr, "lkt_create newed split_points\n"); const size_t sample_rate = 100; // fprintf(stderr, "lkt_create sorting\n"); tree.split_points_len = len; fixlentree<lkt_split_point> splitpoints(tree.split_points_len); ///< \todo scope const ord_t splitpoint = lkt_find_splitpoint_x(points, points + len, sample_rate); const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; // cheaper to just assign both, than a conditional const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, &points[len], splitpoint_point, PARALLEL_QUICKSORT_THREADS, point_comparator_x); const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val}; const index_t root = splitpoints.insert_root(lkt_splitpoint); // cout << "first splitpoint x val: " << splitpoint << " location: " << splitpoint_val << endl; cout << "debug 0 parallel invoking" << endl; tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, root, true, false, 1, max_depth);}, [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, root, false, false, 1, max_depth);}); /* lkt_sort_parallel(points, splitpoint_val, sample_rate, splitpoints, root, true, false, 1, max_depth); lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, splitpoints, root, false, false, 1, max_depth); */ cout << "debug 1 splitpoints releasing" << endl; tree.split_points = splitpoints.release(); fprintf(stderr, "lkt_create coding\n"); tree.morton_codes = lkt_create_mortoncodes_parallel(tree.points, tree.len, tree.split_points); // fprintf(stderr, "lkt_create returning\n"); return tree; } <|endoftext|>
<commit_before><commit_msg>stop uninitialized memory leaking into resource files.<commit_after><|endoftext|>
<commit_before>// Time: O(max(r, c) * wlogw) // Space: O(w^2) class Solution { public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; priority_queue<node, vector<node>, greater<node>> heap; unordered_set<int> visited; heap.emplace(0, start); while (!heap.empty()) { int dist = 0; vector<int> node; tie(dist, node) = heap.top(); heap.pop(); if (visited.count(hash(maze, node))) { continue; } if (node[0] == destination[0] && node[1] == destination[1]) { return dist; } visited.emplace(hash(maze, node)); for (const auto& dir : dirs) { int neighbor_dist = 0; vector<int> neighbor; tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); heap.emplace(dist + neighbor_dist, neighbor); } } return -1; } private: using node = pair<int, vector<int>>; node findNeighbor(const vector<vector<int>>& maze, const vector<int>& node, const vector<int>& dir) { vector<int> cur_node = node; int dist = 0; while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { cur_node[0] += dir[0]; cur_node[1] += dir[1]; ++dist; } return {dist, cur_node}; } int hash(const vector<vector<int>>& maze, const vector<int>& node) { return node[0] * maze[0].size() + node[1]; } }; <commit_msg>Update the-maze-ii.cpp<commit_after>// Time: O(max(r, c) * wlogw) // Space: O(w) class Solution { public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; priority_queue<node, vector<node>, greater<node>> heap; unordered_set<int> visited; heap.emplace(0, start); while (!heap.empty()) { int dist = 0; vector<int> node; tie(dist, node) = heap.top(); heap.pop(); if (visited.count(hash(maze, node))) { continue; } if (node[0] == destination[0] && node[1] == destination[1]) { return dist; } visited.emplace(hash(maze, node)); for (const auto& dir : dirs) { int neighbor_dist = 0; vector<int> neighbor; tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); heap.emplace(dist + neighbor_dist, neighbor); } } return -1; } private: using node = pair<int, vector<int>>; node findNeighbor(const vector<vector<int>>& maze, const vector<int>& node, const vector<int>& dir) { vector<int> cur_node = node; int dist = 0; while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { cur_node[0] += dir[0]; cur_node[1] += dir[1]; ++dist; } return {dist, cur_node}; } int hash(const vector<vector<int>>& maze, const vector<int>& node) { return node[0] * maze[0].size() + node[1]; } }; <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define MAXN 100002 #define X first #define Y second #define PB push_back #define MP make_pair #define INF -1 using namespace std; typedef pair<int, int> P; int N, M, K; vector<P> E[MAXN]; vector<int> S; bool isStorage[MAXN]; int ans = -1; int main() { int i, j, u, v, l, n; cin >> N >> M >> K; for (i = 0; i < M; ++i) { cin >> u >> v >> l; E[u].PB(MP(v, l)); E[v].PB(MP(u, l)); } for (i = 0; i < K; ++i) { cin >> u; S.PB(u); isStorage[u] = true; } for (i = 0; i < K; ++i) { n = E[S[i]].size(); for (j = 0; j < n; ++j) { if (!isStorage[E[S[i]][j].X]) { if (ans == INF) { ans = E[S[i]][j].Y; continue; } ans = min(ans, E[S[i]][j].Y); } } } cout << ans << "\n"; return 0; } <commit_msg>Codeforces - 707-B - Bakery - SOLVED - UPDATED - BEST SOLUTION<commit_after>#include <bits/stdc++.h> #define optimize_ios ios_base::sync_with_stdio(0);cin.tie(0); #define MAXN 100002 #define X first #define Y second #define PB push_back #define MP make_pair #define INF -1 using namespace std; typedef pair<int, int> P; typedef pair<P, int> T; int N, M, K; T E[MAXN]; bool isStorage[MAXN]; int ans = -1; int main() { optimize_ios int i, j, u, v, l, n; cin >> N >> M >> K; for (i = 0; i < M; ++i) { cin >> u >> v >> l; E[i].X.X = u; E[i].X.Y = v; E[i].Y = l; } for (i = 0; i < K; ++i) { cin >> u; isStorage[u] = true; } for (i = 0; i < M; ++i) { if (isStorage[E[i].X.X] ^ isStorage[E[i].X.Y]) { if (ans == INF) { ans = E[i].Y; continue; } ans = min(ans, E[i].Y); } } cout << ans << "\n"; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-05T04:04:14"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc <commit_msg>Update WebRTC code version (2021-01-06T04:02:29).<commit_after>/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-06T04:02:29"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "fstream.hh" #include "align.hh" #include "circular_buffer.hh" #include "semaphore.hh" #include "reactor.hh" #include <malloc.h> #include <string.h> class file_data_source_impl : public data_source_impl { file _file; file_input_stream_options _options; uint64_t _pos; uint64_t _remain; circular_buffer<future<temporary_buffer<char>>> _read_buffers; unsigned _reads_in_progress = 0; std::experimental::optional<promise<>> _done; public: file_data_source_impl(file f, uint64_t offset, uint64_t len, file_input_stream_options options) : _file(std::move(f)), _options(options), _pos(offset), _remain(len) { // prevent wraparounds _remain = std::min(std::numeric_limits<uint64_t>::max() - _pos, _remain); } virtual future<temporary_buffer<char>> get() override { if (_read_buffers.empty()) { issue_read_aheads(1); } auto ret = std::move(_read_buffers.front()); _read_buffers.pop_front(); return ret; } virtual future<> close() { _done.emplace(); if (!_reads_in_progress) { _done->set_value(); } return _done->get_future().then([this] { for (auto&& c : _read_buffers) { c.ignore_ready_future(); } }); } private: void issue_read_aheads(unsigned min_ra = 0) { if (_done) { return; } auto ra = std::max(min_ra, _options.read_ahead); _read_buffers.reserve(ra); // prevent push_back() failure while (_read_buffers.size() < ra) { if (!_remain) { if (_read_buffers.size() >= min_ra) { return; } _read_buffers.push_back(make_ready_future<temporary_buffer<char>>()); continue; } ++_reads_in_progress; // if _pos is not dma-aligned, we'll get a short read. Account for that. // Also avoid reading beyond _remain. uint64_t align = _file.disk_read_dma_alignment(); auto start = align_down(_pos, align); auto end = align_up(std::min(start + _options.buffer_size, _pos + _remain), align); auto len = end - start; _read_buffers.push_back(futurize<future<temporary_buffer<char>>>::apply([&] { return _file.dma_read_bulk<char>(start, len, _options.io_priority_class); }).then_wrapped( [this, start, end, pos = _pos, remain = _remain] (future<temporary_buffer<char>> ret) { issue_read_aheads(); --_reads_in_progress; if (_done && !_reads_in_progress) { _done->set_value(); } if ((pos == start && end <= pos + remain) || ret.failed()) { // no games needed return ret; } else { // first or last buffer, need trimming auto tmp = ret.get0(); auto real_end = start + tmp.size(); if (real_end <= pos) { return make_ready_future<temporary_buffer<char>>(); } if (real_end > pos + remain) { tmp.trim(pos + remain - start); } if (start < pos) { tmp.trim_front(pos - start); } return make_ready_future<temporary_buffer<char>>(std::move(tmp)); } })); auto old_pos = _pos; _pos = end; _remain = std::max(_pos, old_pos + _remain) - _pos; }; } }; class file_data_source : public data_source { public: file_data_source(file f, uint64_t offset, uint64_t len, file_input_stream_options options) : data_source(std::make_unique<file_data_source_impl>( std::move(f), offset, len, options)) {} }; input_stream<char> make_file_input_stream( file f, uint64_t offset, uint64_t len, file_input_stream_options options) { return input_stream<char>(file_data_source(std::move(f), offset, len, std::move(options))); } input_stream<char> make_file_input_stream( file f, uint64_t offset, file_input_stream_options options) { return make_file_input_stream(std::move(f), offset, std::numeric_limits<uint64_t>::max(), std::move(options)); } input_stream<char> make_file_input_stream( file f, file_input_stream_options options) { return make_file_input_stream(std::move(f), 0, std::move(options)); } class file_data_sink_impl : public data_sink_impl { file _file; file_output_stream_options _options; uint64_t _pos = 0; semaphore _write_behind_sem = { _options.write_behind }; future<> _background_writes_done = make_ready_future<>(); bool _failed = false; public: file_data_sink_impl(file f, file_output_stream_options options) : _file(std::move(f)), _options(options) {} future<> put(net::packet data) { abort(); } virtual temporary_buffer<char> allocate_buffer(size_t size) override { return temporary_buffer<char>::aligned(_file.memory_dma_alignment(), size); } virtual future<> put(temporary_buffer<char> buf) override { uint64_t pos = _pos; _pos += buf.size(); if (!_options.write_behind) { return do_put(pos, std::move(buf)); } // Write behind strategy: // // 1. Issue N writes in parallel, using a semaphore to limit to N // 2. Collect results in _background_writes_done, merging exception futures // 3. If we've already seen a failure, don't issue more writes. return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable { if (_failed) { _write_behind_sem.signal(); auto ret = std::move(_background_writes_done); _background_writes_done = make_ready_future<>(); return ret; } auto this_write_done = do_put(pos, std::move(buf)).finally([this] { _write_behind_sem.signal(); }); _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done)) .then([this] (std::tuple<future<>, future<>> possible_errors) { // merge the two errors, preferring the first auto& e1 = std::get<0>(possible_errors); auto& e2 = std::get<1>(possible_errors); if (e1.failed()) { e2.ignore_ready_future(); return std::move(e1); } else { if (e2.failed()) { _failed = true; } return std::move(e2); } }); return make_ready_future<>(); }); } public: future<> do_put(uint64_t pos, temporary_buffer<char> buf) noexcept { try { // put() must usually be of chunks multiple of file::dma_alignment. // Only the last part can have an unaligned length. If put() was // called again with an unaligned pos, we have a bug in the caller. assert(!(pos & (_file.disk_write_dma_alignment() - 1))); bool truncate = false; auto p = static_cast<const char*>(buf.get()); size_t buf_size = buf.size(); if ((buf.size() & (_file.disk_write_dma_alignment() - 1)) != 0) { // If buf size isn't aligned, copy its content into a new aligned buf. // This should only happen when the user calls output_stream::flush(). auto tmp = allocate_buffer(align_up(buf.size(), _file.disk_write_dma_alignment())); ::memcpy(tmp.get_write(), buf.get(), buf.size()); buf = std::move(tmp); p = buf.get(); buf_size = buf.size(); truncate = true; } return _file.dma_write(pos, p, buf_size, _options.io_priority_class).then( [this, buf = std::move(buf), truncate] (size_t size) { if (truncate) { return _file.truncate(_pos); } return make_ready_future<>(); }); } catch (...) { return make_exception_future<>(std::current_exception()); } } future<> wait() { return _write_behind_sem.wait(_options.write_behind).then([this] { return _background_writes_done.then([this] { // restore to pristine state; for flush() + close() sequence // (we allow either flush, or close, or both) _write_behind_sem.signal(_options.write_behind); _background_writes_done = make_ready_future<>(); }); }); } public: virtual future<> flush() override { return wait().then([this] { return _file.flush(); }); } virtual future<> close() { return wait().then([this] { return _file.close(); }); } }; class file_data_sink : public data_sink { public: file_data_sink(file f, file_output_stream_options options) : data_sink(std::make_unique<file_data_sink_impl>( std::move(f), options)) {} }; output_stream<char> make_file_output_stream(file f, size_t buffer_size) { file_output_stream_options options; options.buffer_size = buffer_size; return make_file_output_stream(std::move(f), options); } output_stream<char> make_file_output_stream(file f, file_output_stream_options options) { return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true); } <commit_msg>file_data_sink_impl: Fix hang in close()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "fstream.hh" #include "align.hh" #include "circular_buffer.hh" #include "semaphore.hh" #include "reactor.hh" #include <malloc.h> #include <string.h> class file_data_source_impl : public data_source_impl { file _file; file_input_stream_options _options; uint64_t _pos; uint64_t _remain; circular_buffer<future<temporary_buffer<char>>> _read_buffers; unsigned _reads_in_progress = 0; std::experimental::optional<promise<>> _done; public: file_data_source_impl(file f, uint64_t offset, uint64_t len, file_input_stream_options options) : _file(std::move(f)), _options(options), _pos(offset), _remain(len) { // prevent wraparounds _remain = std::min(std::numeric_limits<uint64_t>::max() - _pos, _remain); } virtual future<temporary_buffer<char>> get() override { if (_read_buffers.empty()) { issue_read_aheads(1); } auto ret = std::move(_read_buffers.front()); _read_buffers.pop_front(); return ret; } virtual future<> close() { _done.emplace(); if (!_reads_in_progress) { _done->set_value(); } return _done->get_future().then([this] { for (auto&& c : _read_buffers) { c.ignore_ready_future(); } }); } private: void issue_read_aheads(unsigned min_ra = 0) { if (_done) { return; } auto ra = std::max(min_ra, _options.read_ahead); _read_buffers.reserve(ra); // prevent push_back() failure while (_read_buffers.size() < ra) { if (!_remain) { if (_read_buffers.size() >= min_ra) { return; } _read_buffers.push_back(make_ready_future<temporary_buffer<char>>()); continue; } ++_reads_in_progress; // if _pos is not dma-aligned, we'll get a short read. Account for that. // Also avoid reading beyond _remain. uint64_t align = _file.disk_read_dma_alignment(); auto start = align_down(_pos, align); auto end = align_up(std::min(start + _options.buffer_size, _pos + _remain), align); auto len = end - start; _read_buffers.push_back(futurize<future<temporary_buffer<char>>>::apply([&] { return _file.dma_read_bulk<char>(start, len, _options.io_priority_class); }).then_wrapped( [this, start, end, pos = _pos, remain = _remain] (future<temporary_buffer<char>> ret) { issue_read_aheads(); --_reads_in_progress; if (_done && !_reads_in_progress) { _done->set_value(); } if ((pos == start && end <= pos + remain) || ret.failed()) { // no games needed return ret; } else { // first or last buffer, need trimming auto tmp = ret.get0(); auto real_end = start + tmp.size(); if (real_end <= pos) { return make_ready_future<temporary_buffer<char>>(); } if (real_end > pos + remain) { tmp.trim(pos + remain - start); } if (start < pos) { tmp.trim_front(pos - start); } return make_ready_future<temporary_buffer<char>>(std::move(tmp)); } })); auto old_pos = _pos; _pos = end; _remain = std::max(_pos, old_pos + _remain) - _pos; }; } }; class file_data_source : public data_source { public: file_data_source(file f, uint64_t offset, uint64_t len, file_input_stream_options options) : data_source(std::make_unique<file_data_source_impl>( std::move(f), offset, len, options)) {} }; input_stream<char> make_file_input_stream( file f, uint64_t offset, uint64_t len, file_input_stream_options options) { return input_stream<char>(file_data_source(std::move(f), offset, len, std::move(options))); } input_stream<char> make_file_input_stream( file f, uint64_t offset, file_input_stream_options options) { return make_file_input_stream(std::move(f), offset, std::numeric_limits<uint64_t>::max(), std::move(options)); } input_stream<char> make_file_input_stream( file f, file_input_stream_options options) { return make_file_input_stream(std::move(f), 0, std::move(options)); } class file_data_sink_impl : public data_sink_impl { file _file; file_output_stream_options _options; uint64_t _pos = 0; semaphore _write_behind_sem = { _options.write_behind }; future<> _background_writes_done = make_ready_future<>(); bool _failed = false; public: file_data_sink_impl(file f, file_output_stream_options options) : _file(std::move(f)), _options(options) {} future<> put(net::packet data) { abort(); } virtual temporary_buffer<char> allocate_buffer(size_t size) override { return temporary_buffer<char>::aligned(_file.memory_dma_alignment(), size); } virtual future<> put(temporary_buffer<char> buf) override { uint64_t pos = _pos; _pos += buf.size(); if (!_options.write_behind) { return do_put(pos, std::move(buf)); } // Write behind strategy: // // 1. Issue N writes in parallel, using a semaphore to limit to N // 2. Collect results in _background_writes_done, merging exception futures // 3. If we've already seen a failure, don't issue more writes. return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable { if (_failed) { _write_behind_sem.signal(); auto ret = std::move(_background_writes_done); _background_writes_done = make_ready_future<>(); return ret; } auto this_write_done = do_put(pos, std::move(buf)).finally([this] { _write_behind_sem.signal(); }); _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done)) .then([this] (std::tuple<future<>, future<>> possible_errors) { // merge the two errors, preferring the first auto& e1 = std::get<0>(possible_errors); auto& e2 = std::get<1>(possible_errors); if (e1.failed()) { e2.ignore_ready_future(); return std::move(e1); } else { if (e2.failed()) { _failed = true; } return std::move(e2); } }); return make_ready_future<>(); }); } public: future<> do_put(uint64_t pos, temporary_buffer<char> buf) noexcept { try { // put() must usually be of chunks multiple of file::dma_alignment. // Only the last part can have an unaligned length. If put() was // called again with an unaligned pos, we have a bug in the caller. assert(!(pos & (_file.disk_write_dma_alignment() - 1))); bool truncate = false; auto p = static_cast<const char*>(buf.get()); size_t buf_size = buf.size(); if ((buf.size() & (_file.disk_write_dma_alignment() - 1)) != 0) { // If buf size isn't aligned, copy its content into a new aligned buf. // This should only happen when the user calls output_stream::flush(). auto tmp = allocate_buffer(align_up(buf.size(), _file.disk_write_dma_alignment())); ::memcpy(tmp.get_write(), buf.get(), buf.size()); buf = std::move(tmp); p = buf.get(); buf_size = buf.size(); truncate = true; } return _file.dma_write(pos, p, buf_size, _options.io_priority_class).then( [this, buf = std::move(buf), truncate] (size_t size) { if (truncate) { return _file.truncate(_pos); } return make_ready_future<>(); }); } catch (...) { return make_exception_future<>(std::current_exception()); } } future<> wait() { // restore to pristine state; for flush() + close() sequence // (we allow either flush, or close, or both) return _write_behind_sem.wait(_options.write_behind).then([this] { return std::exchange(_background_writes_done, make_ready_future<>()); }).finally([this] { _write_behind_sem.signal(_options.write_behind); }); } public: virtual future<> flush() override { return wait().then([this] { return _file.flush(); }); } virtual future<> close() { return wait().then([this] { return _file.close(); }); } }; class file_data_sink : public data_sink { public: file_data_sink(file f, file_output_stream_options options) : data_sink(std::make_unique<file_data_sink_impl>( std::move(f), options)) {} }; output_stream<char> make_file_output_stream(file f, size_t buffer_size) { file_output_stream_options options; options.buffer_size = buffer_size; return make_file_output_stream(std::move(f), options); } output_stream<char> make_file_output_stream(file f, file_output_stream_options options) { return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true); } <|endoftext|>
<commit_before>/** * \file * \brief Semaphore C-API test cases * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/Semaphore.hpp" #include "distortos/C-API/Semaphore.h" namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ void testCommon(distortos_Semaphore& semaphore, const unsigned int value, const unsigned int maxValue = UINT_MAX) { REQUIRE(semaphore.value == std::min(value, maxValue)); REQUIRE(semaphore.maxValue == maxValue); distortos_Semaphore constructed; memcpy(&constructed, &semaphore, sizeof(semaphore)); REQUIRE(distortos_Semaphore_destruct(&semaphore) == 0); struct distortos_Semaphore destructed; memcpy(&destructed, &semaphore, sizeof(semaphore)); memset(&semaphore, 0, sizeof(semaphore)); const auto realSemaphore = new (&semaphore) distortos::Semaphore {value, maxValue}; REQUIRE(realSemaphore->getValue() == std::min(value, maxValue)); REQUIRE(memcmp(&constructed, &semaphore, sizeof(semaphore)) == 0); realSemaphore->~Semaphore(); REQUIRE(memcmp(&destructed, &semaphore, sizeof(semaphore)) == 0); } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global test cases +---------------------------------------------------------------------------------------------------------------------*/ TEST_CASE("Testing DISTORTOS_SEMAPHORE_INITIALIZER()", "[initializer]") { constexpr unsigned int lowRandomValue {0x2c380555}; constexpr unsigned int highRandomValue {0x8d87de63}; { distortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, lowRandomValue, highRandomValue); testCommon(semaphore, lowRandomValue, highRandomValue); } { distortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, highRandomValue, lowRandomValue); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing DISTORTOS_SEMAPHORE_CONSTRUCT_1()", "[construct]") { constexpr unsigned int lowRandomValue {0x0dc449b6}; constexpr unsigned int highRandomValue {0x726030cd}; { DISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, lowRandomValue, highRandomValue); testCommon(semaphore, lowRandomValue, highRandomValue); } { DISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, highRandomValue, lowRandomValue); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing DISTORTOS_SEMAPHORE_CONSTRUCT()", "[construct]") { constexpr unsigned int randomValue {0x5d0051dc}; { DISTORTOS_SEMAPHORE_CONSTRUCT(semaphore, randomValue); testCommon(semaphore, randomValue); } } TEST_CASE("Testing distortos_Semaphore_construct_1()", "[construct]") { constexpr unsigned int lowRandomValue {0x7a78032b}; constexpr unsigned int highRandomValue {0xb24e4367}; { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct_1(&semaphore, lowRandomValue, highRandomValue) == 0); testCommon(semaphore, lowRandomValue, highRandomValue); } { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct_1(&semaphore, highRandomValue, lowRandomValue) == 0); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing distortos_Semaphore_construct()", "[construct]") { constexpr unsigned int randomValue {0xb86c251b}; { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct(&semaphore, randomValue) == 0); testCommon(semaphore, randomValue); } } <commit_msg>Add file comment explaining purpose of C-API-Semaphore-unit-test-1<commit_after>/** * \file * \brief Semaphore C-API test cases * * This test checks whether semaphore objects instantiated with C-API macros and functions are binary identical to * constructed distortos::Semaphore objects. * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/Semaphore.hpp" #include "distortos/C-API/Semaphore.h" namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ void testCommon(distortos_Semaphore& semaphore, const unsigned int value, const unsigned int maxValue = UINT_MAX) { REQUIRE(semaphore.value == std::min(value, maxValue)); REQUIRE(semaphore.maxValue == maxValue); distortos_Semaphore constructed; memcpy(&constructed, &semaphore, sizeof(semaphore)); REQUIRE(distortos_Semaphore_destruct(&semaphore) == 0); struct distortos_Semaphore destructed; memcpy(&destructed, &semaphore, sizeof(semaphore)); memset(&semaphore, 0, sizeof(semaphore)); const auto realSemaphore = new (&semaphore) distortos::Semaphore {value, maxValue}; REQUIRE(realSemaphore->getValue() == std::min(value, maxValue)); REQUIRE(memcmp(&constructed, &semaphore, sizeof(semaphore)) == 0); realSemaphore->~Semaphore(); REQUIRE(memcmp(&destructed, &semaphore, sizeof(semaphore)) == 0); } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global test cases +---------------------------------------------------------------------------------------------------------------------*/ TEST_CASE("Testing DISTORTOS_SEMAPHORE_INITIALIZER()", "[initializer]") { constexpr unsigned int lowRandomValue {0x2c380555}; constexpr unsigned int highRandomValue {0x8d87de63}; { distortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, lowRandomValue, highRandomValue); testCommon(semaphore, lowRandomValue, highRandomValue); } { distortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, highRandomValue, lowRandomValue); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing DISTORTOS_SEMAPHORE_CONSTRUCT_1()", "[construct]") { constexpr unsigned int lowRandomValue {0x0dc449b6}; constexpr unsigned int highRandomValue {0x726030cd}; { DISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, lowRandomValue, highRandomValue); testCommon(semaphore, lowRandomValue, highRandomValue); } { DISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, highRandomValue, lowRandomValue); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing DISTORTOS_SEMAPHORE_CONSTRUCT()", "[construct]") { constexpr unsigned int randomValue {0x5d0051dc}; { DISTORTOS_SEMAPHORE_CONSTRUCT(semaphore, randomValue); testCommon(semaphore, randomValue); } } TEST_CASE("Testing distortos_Semaphore_construct_1()", "[construct]") { constexpr unsigned int lowRandomValue {0x7a78032b}; constexpr unsigned int highRandomValue {0xb24e4367}; { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct_1(&semaphore, lowRandomValue, highRandomValue) == 0); testCommon(semaphore, lowRandomValue, highRandomValue); } { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct_1(&semaphore, highRandomValue, lowRandomValue) == 0); testCommon(semaphore, highRandomValue, lowRandomValue); } } TEST_CASE("Testing distortos_Semaphore_construct()", "[construct]") { constexpr unsigned int randomValue {0xb86c251b}; { distortos_Semaphore semaphore; REQUIRE(distortos_Semaphore_construct(&semaphore, randomValue) == 0); testCommon(semaphore, randomValue); } } <|endoftext|>
<commit_before>#pragma once #include <stdexcept> #include <string> #include <vector> #include <initializer_list> #include <memory> // ---------------------------------------------------------------------- class argc_argv { public: class option_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class argument_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option_has_no_value : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option_value_conversion_failed : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option { public: virtual ~option(); // if option was present in the command line virtual operator bool() const; // argument extraction, throws option_not_found, option_has_no_value, option_value_conversion_failed virtual operator const char*() const; // virtual operator std::string() const; virtual operator double() const; virtual operator int() const; protected: inline option(std::string name, const char* value = nullptr) : mName{name}, mValue{value} {} friend class argc_argv; inline std::string name() const { return mName; } inline void set_value(const char* aValue) { mValue = aValue; } virtual bool really_present() const; private: std::string mName; const char* mValue; }; // class option // options_with_value: list of option names that have values, e.g. {"-o", "--output"} // may throw option_has_no_value if last value in argv is option from options_with_value argc_argv(int argc, const char* const argv[], std::initializer_list<const char*> options_with_value, bool split_single_dash = true); // returns option by name, if option was not in argv, returns ref to special option object const option& operator[](std::string aName) const; // returns option by name, if option was not in argv, returns ref to an option object having aDefault as a value const option& get(std::string aName, std::string aDefault) const; const option& get(std::string aName, double aDefault) const; const option& get(std::string aName, int aDefault) const; // returns number of arguments in the command line that are neither options nor option values inline size_t number_of_arguments() const { return mArguments.size(); } // returns argument (neither option nor option value) by index, throws argument_not_found if aIndex >= number_of_arguments() const char* operator[](size_t aIndex) const; // returns argv[0] inline const char* program() const { return mProgram; } private: const std::vector<const char*> mOptionsWithValue; const char* mProgram; std::vector<const char*> mArguments; mutable std::vector<std::unique_ptr<option>> mOptions; const option& get(std::string aName) const; }; // class argc_argv // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>minor improvement<commit_after>#pragma once #include <stdexcept> #include <string> #include <vector> #include <initializer_list> #include <memory> // ---------------------------------------------------------------------- class argc_argv { public: class option_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class argument_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option_has_no_value : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option_value_conversion_failed : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class option { public: virtual ~option(); // if option was present in the command line virtual operator bool() const; // argument extraction, throws option_not_found, option_has_no_value, option_value_conversion_failed virtual operator const char*() const; inline operator std::string() const { return operator const char*(); } virtual operator double() const; virtual operator int() const; protected: inline option(std::string name, const char* value = nullptr) : mName{name}, mValue{value} {} friend class argc_argv; inline std::string name() const { return mName; } inline void set_value(const char* aValue) { mValue = aValue; } virtual bool really_present() const; private: std::string mName; const char* mValue; }; // class option // options_with_value: list of option names that have values, e.g. {"-o", "--output"} // may throw option_has_no_value if last value in argv is option from options_with_value argc_argv(int argc, const char* const argv[], std::initializer_list<const char*> options_with_value, bool split_single_dash = true); // returns option by name, if option was not in argv, returns ref to special option object const option& operator[](std::string aName) const; // returns option by name, if option was not in argv, returns ref to an option object having aDefault as a value const option& get(std::string aName, std::string aDefault) const; const option& get(std::string aName, double aDefault) const; const option& get(std::string aName, int aDefault) const; // returns number of arguments in the command line that are neither options nor option values inline size_t number_of_arguments() const { return mArguments.size(); } // returns argument (neither option nor option value) by index, throws argument_not_found if aIndex >= number_of_arguments() const char* operator[](size_t aIndex) const; // returns argv[0] inline const char* program() const { return mProgram; } private: const std::vector<const char*> mOptionsWithValue; const char* mProgram; std::vector<const char*> mArguments; mutable std::vector<std::unique_ptr<option>> mOptions; const option& get(std::string aName) const; }; // class argc_argv // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include "ProcessEvent.h" #include <specialized/eventbackend.h> #if defined(__linux__) #include <linux/version.h> #elif !defined(KERNEL_VERSION) #define LINUX_VERSION_CODE 0 #define KERNEL_VERSION(a, b, c) 0 #endif #if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) /* Linux 2.6.15+ */ // Linux #include <linux/netlink.h> #include <linux/connector.h> #include <linux/cn_proc.h> // PDTK #include <cxxutils/posix_helpers.h> #include <cxxutils/socket_helpers.h> #include <cxxutils/vterm.h> #include <specialized/procstat.h> enum { Read = 0, Write = 1, }; struct message_t { union { ProcessEvent::Flags action; uint32_t : 0; }; pid_t pid; }; static_assert(sizeof(message_t) == sizeof(uint64_t), "unexpected struct size"); // process flags static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept { return (flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) | (flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) | (flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ; } /* static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept { return (flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*() (flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited (flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked } */ struct ProcessEvent::platform_dependant // process notification (process events connector) { posix::fd_t fd; struct eventinfo_t { posix::fd_t fd[2]; // two fds for pipe based communication ProcessEvent::Flags_t flags; }; std::unordered_map<pid_t, eventinfo_t> events; platform_dependant(void) noexcept { fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector); flaw(fd == posix::invalid_descriptor, terminal::warning,,, "Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno)) sockaddr_nl sa_nl; sa_nl.nl_family = PF_NETLINK; sa_nl.nl_groups = CN_IDX_PROC; sa_nl.nl_pid = uint32_t(getpid()); flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)), terminal::warning,,, "Process Events Connector requires root level access: %s", std::strerror(errno)); #pragma pack(push, 1) struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment { nlmsghdr header; // 16 bytes cn_msg message; proc_cn_mcast_op operation; } procconn; #pragma pack(pop) static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct"); std::memset(&procconn, 0, sizeof(procconn)); procconn.header.nlmsg_len = sizeof(procconn); procconn.header.nlmsg_pid = uint32_t(getpid()); procconn.header.nlmsg_type = NLMSG_DONE; procconn.message.id.idx = CN_IDX_PROC; procconn.message.id.val = CN_VAL_PROC; procconn.message.len = sizeof(proc_cn_mcast_op); procconn.operation = PROC_CN_MCAST_LISTEN; flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response, terminal::warning,,, "Failed to enable Process Events Connector notifications: %s", std::strerror(errno)); EventBackend::add(fd, EventBackend::SimplePollReadFlags, [this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); }); std::fprintf(stderr, "%s%s\n", terminal::information, "Process Events Connector active"); } ~platform_dependant(void) noexcept { EventBackend::remove(fd, EventBackend::SimplePollReadFlags); posix::close(fd); fd = posix::invalid_descriptor; } posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept { eventinfo_t event; event.flags = flags; if(!posix::pipe(event.fd)) return posix::invalid_descriptor; auto iter = events.emplace(pid, event); // add filter installation code here return event.fd[Read]; } bool remove(pid_t pid) noexcept { auto iter = events.find(pid); if(iter == events.end()) return false; // add filter removal code here posix::close(iter->second.fd[Read]); posix::close(iter->second.fd[Write]); events.erase(iter); return true; } void read(posix::fd_t procfd) noexcept { #pragma pack(push, 1) struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment { nlmsghdr header; // 16 bytes cn_msg message; proc_event event; } procmsg; #pragma pack(pop) static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct"); pollfd fds = { procfd, POLLIN, 0 }; while(posix::poll(&fds, 1, 0) > 0 && // while there are messages AND posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message { auto iter = events.find(procmsg.event.event_data.id.process_pid); // find event info for this PID if(iter != events.end()) // if found... posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); // write process event info into the communications pipe } } } ProcessEvent::s_platform; ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor) { m_fd = s_platform.add(m_pid, m_flags); // add PID to monitor and return communications pipe EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, // connect communications pipe to a lambda function [this](posix::fd_t lambda_fd, native_flags_t) noexcept { proc_event data; pollfd fds = { lambda_fd, POLLIN, 0 }; while(posix::poll(&fds, 1, 0) > 0 && // while there is another event to be read posix::read(lambda_fd, &data, sizeof(data)) > 0) // read the event switch(from_native_flags(data.what)) // find the type of event { case Flags::Exec: // queue exec signal with PID Object::enqueue(execed, data.event_data.exec.process_pid); break; case Flags::Exit: // queue exit signal with PID and exit code if(data.event_data.exit.exit_signal) // if killed by a signal Object::enqueue(killed, data.event_data.exit.process_pid, *reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal)); else // else exited by itself Object::enqueue(exited, data.event_data.exit.process_pid, *reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code)); break; case Flags::Fork: // queue fork signal with PID and child PID Object::enqueue(forked, data.event_data.fork.parent_pid, data.event_data.fork.child_pid); break; } }); } ProcessEvent::~ProcessEvent(void) noexcept { EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags); s_platform.remove(m_pid); } #elif defined(__linux__) //&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) /* Linux X.X.X+ */ # error No process event backend code exists in PDTK for Linux before version 2.6.15! Please submit a patch! #elif (defined(__APPLE__) && defined(__MACH__)) /* Darwin 7+ */ || \ defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \ defined(__DragonFly__) /* DragonFly BSD */ || \ defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \ defined(__NetBSD__) /* NetBSD 2+ */ #include <sys/event.h> // kqueue static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept { return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); } static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset) { return (flags & subset) == subset; } static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept { return (flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) | (flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) | (flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ; } static constexpr ushort extract_filter(native_flags_t flags) noexcept { return (flags >> 16) & 0xFFFF; } static constexpr uint32_t extract_flags(native_flags_t flags) noexcept { return flags >> 32; } ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor) { EventBackend::add(m_pid, to_native_flags(m_flags), // connect PID event to lambda function [this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept { uint32_t data = extract_flags(lambda_fd); // get return value (if any) switch(extract_filter(lambda_fd)) // switch by filtered event type { case Flags::Exec: // queue exec signal with PID Object::enqueue(execed, m_pid); break; case Flags::Exit: // queue exit signal with PID and exit code Object::enqueue(exited, m_pid, *reinterpret_cast<posix::error_t*>(&data)); break; case Flags::Fork: // queue fork signal with PID and child PID Object::enqueue(forked, m_pid, *reinterpret_cast<pid_t*>(&data)); break; } }); } ProcessEvent::~ProcessEvent(void) noexcept { EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect PID with flags } #elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos # error No process event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch! #elif defined(__minix) // MINIX # error No process event backend code exists in PDTK for MINIX! Please submit a patch! #elif defined(__QNX__) // QNX // QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html # error No process event backend code exists in PDTK for QNX! Please submit a patch! #elif defined(__hpux) // HP-UX # error No process event backend code exists in PDTK for HP-UX! Please submit a patch! #elif defined(_AIX) // IBM AIX # error No process event backend code exists in PDTK for IBM AIX! Please submit a patch! #elif defined(BSD) # error Unrecognized BSD derivative! #elif defined(__unix__) || defined(__unix) # error Unrecognized UNIX variant! #else # error This platform is not supported. #endif <commit_msg>use copies for simple types<commit_after>#include "ProcessEvent.h" #include <specialized/eventbackend.h> #if defined(__linux__) #include <linux/version.h> #elif !defined(KERNEL_VERSION) #define LINUX_VERSION_CODE 0 #define KERNEL_VERSION(a, b, c) 0 #endif #if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) /* Linux 2.6.15+ */ // Linux #include <linux/netlink.h> #include <linux/connector.h> #include <linux/cn_proc.h> // PDTK #include <cxxutils/posix_helpers.h> #include <cxxutils/socket_helpers.h> #include <cxxutils/vterm.h> #include <specialized/procstat.h> enum { Read = 0, Write = 1, }; struct message_t { union { ProcessEvent::Flags action; uint32_t : 0; }; pid_t pid; }; static_assert(sizeof(message_t) == sizeof(uint64_t), "unexpected struct size"); // process flags static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept { return (flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) | (flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) | (flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ; } /* static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept { return (flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*() (flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited (flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked } */ struct ProcessEvent::platform_dependant // process notification (process events connector) { posix::fd_t fd; struct eventinfo_t { posix::fd_t fd[2]; // two fds for pipe based communication ProcessEvent::Flags_t flags; }; std::unordered_map<pid_t, eventinfo_t> events; platform_dependant(void) noexcept { fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector); flaw(fd == posix::invalid_descriptor, terminal::warning,,, "Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno)) sockaddr_nl sa_nl; sa_nl.nl_family = PF_NETLINK; sa_nl.nl_groups = CN_IDX_PROC; sa_nl.nl_pid = uint32_t(getpid()); flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)), terminal::warning,,, "Process Events Connector requires root level access: %s", std::strerror(errno)); #pragma pack(push, 1) struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment { nlmsghdr header; // 16 bytes cn_msg message; proc_cn_mcast_op operation; } procconn; #pragma pack(pop) static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct"); std::memset(&procconn, 0, sizeof(procconn)); procconn.header.nlmsg_len = sizeof(procconn); procconn.header.nlmsg_pid = uint32_t(getpid()); procconn.header.nlmsg_type = NLMSG_DONE; procconn.message.id.idx = CN_IDX_PROC; procconn.message.id.val = CN_VAL_PROC; procconn.message.len = sizeof(proc_cn_mcast_op); procconn.operation = PROC_CN_MCAST_LISTEN; flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response, terminal::warning,,, "Failed to enable Process Events Connector notifications: %s", std::strerror(errno)); EventBackend::add(fd, EventBackend::SimplePollReadFlags, [this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); }); std::fprintf(stderr, "%s%s\n", terminal::information, "Process Events Connector active"); } ~platform_dependant(void) noexcept { EventBackend::remove(fd, EventBackend::SimplePollReadFlags); posix::close(fd); fd = posix::invalid_descriptor; } posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept { eventinfo_t event; event.flags = flags; if(!posix::pipe(event.fd)) return posix::invalid_descriptor; auto iter = events.emplace(pid, event); // add filter installation code here return event.fd[Read]; } bool remove(pid_t pid) noexcept { auto iter = events.find(pid); if(iter == events.end()) return false; // add filter removal code here posix::close(iter->second.fd[Read]); posix::close(iter->second.fd[Write]); events.erase(iter); return true; } void read(posix::fd_t procfd) noexcept { #pragma pack(push, 1) struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment { nlmsghdr header; // 16 bytes cn_msg message; proc_event event; } procmsg; #pragma pack(pop) static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct"); pollfd fds = { procfd, POLLIN, 0 }; while(posix::poll(&fds, 1, 0) > 0 && // while there are messages AND posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message { auto iter = events.find(procmsg.event.event_data.id.process_pid); // find event info for this PID if(iter != events.end()) // if found... posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); // write process event info into the communications pipe } } } ProcessEvent::s_platform; ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor) { m_fd = s_platform.add(m_pid, m_flags); // add PID to monitor and return communications pipe EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, // connect communications pipe to a lambda function [this](posix::fd_t lambda_fd, native_flags_t) noexcept { proc_event data; pollfd fds = { lambda_fd, POLLIN, 0 }; while(posix::poll(&fds, 1, 0) > 0 && // while there is another event to be read posix::read(lambda_fd, &data, sizeof(data)) > 0) // read the event switch(from_native_flags(data.what)) // find the type of event { case Flags::Exec: // queue exec signal with PID Object::enqueue(execed, data.event_data.exec.process_pid); break; case Flags::Exit: // queue exit signal with PID and exit code if(data.event_data.exit.exit_signal) // if killed by a signal Object::enqueue(killed, data.event_data.exit.process_pid, *reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal)); else // else exited by itself Object::enqueue(exited, data.event_data.exit.process_pid, *reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code)); break; case Flags::Fork: // queue fork signal with PID and child PID Object::enqueue(forked, data.event_data.fork.parent_pid, data.event_data.fork.child_pid); break; } }); } ProcessEvent::~ProcessEvent(void) noexcept { EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags); s_platform.remove(m_pid); } #elif defined(__linux__) //&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) /* Linux X.X.X+ */ # error No process event backend code exists in PDTK for Linux before version 2.6.15! Please submit a patch! #elif (defined(__APPLE__) && defined(__MACH__)) /* Darwin 7+ */ || \ defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \ defined(__DragonFly__) /* DragonFly BSD */ || \ defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \ defined(__NetBSD__) /* NetBSD 2+ */ #include <sys/event.h> // kqueue static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept { return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); } static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset) { return (flags & subset) == subset; } static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept { return (flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) | (flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) | (flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ; } static constexpr ushort extract_filter(native_flags_t flags) noexcept { return (flags >> 16) & 0xFFFF; } template<typename rtype> static constexpr rtype extract_flags(native_flags_t flags) noexcept { return flags >> 32; } ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor) { EventBackend::add(m_pid, to_native_flags(m_flags), // connect PID event to lambda function [this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept { switch(extract_filter(lambda_fd)) // switch by filtered event type { case Flags::Exec: // queue exec signal with PID Object::enqueue_copy(execed, m_pid); break; case Flags::Exit: // queue exit signal with PID and exit code Object::enqueue_copy(exited, m_pid, extract_flags<posix::error_t>(lambda_fd)); break; case Flags::Fork: // queue fork signal with PID and child PID Object::enqueue_copy(forked, m_pid, extract_flags<pid_t>(lambda_fd)); break; } }); } ProcessEvent::~ProcessEvent(void) noexcept { EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect PID with flags } #elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos # error No process event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch! #elif defined(__minix) // MINIX # error No process event backend code exists in PDTK for MINIX! Please submit a patch! #elif defined(__QNX__) // QNX // QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html # error No process event backend code exists in PDTK for QNX! Please submit a patch! #elif defined(__hpux) // HP-UX # error No process event backend code exists in PDTK for HP-UX! Please submit a patch! #elif defined(_AIX) // IBM AIX # error No process event backend code exists in PDTK for IBM AIX! Please submit a patch! #elif defined(BSD) # error Unrecognized BSD derivative! #elif defined(__unix__) || defined(__unix) # error Unrecognized UNIX variant! #else # error This platform is not supported. #endif <|endoftext|>
<commit_before>#include <chrono> #include "ParallelAndNaive.h" #include "SequentialAnd.h" using Clock = std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::microseconds; void test(const char* info, MultipleAndInterface& ma, const std::vector<bitvector*> input) { assert(input.size() >= 2); printf("%-20s (%lu bitmaps): ", info, input.size()); fflush(stdout); const auto t1 = Clock::now(); auto res = ma.calculate(); const auto t2 = Clock::now(); const auto t_us = duration_cast<microseconds>(t2 - t1).count(); printf("%luus [cardinality=%lu]\n", t_us, res->cardinality()); } int main() { const size_t bitmap_size = 10000000; const size_t count = 20; std::vector<bitvector*> input; srand(0); for (size_t i=0; i < count; i++) { bitvector* bv = new bitvector(bitmap_size); bv->fill_random(50); input.push_back(bv); } SequentialAnd seq(input); test("SequentialAnd", seq, input); ParallelAndNaive par1(input, 8); test("ParallelAndNaive", par1, input); } <commit_msg>Change parameters<commit_after>#include <chrono> #include "ParallelAndNaive.h" #include "SequentialAnd.h" using Clock = std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::microseconds; void test(const char* info, MultipleAndInterface& ma, const std::vector<bitvector*> input) { assert(input.size() >= 2); printf("%-20s (%lu bitmaps): ", info, input.size()); fflush(stdout); const auto t1 = Clock::now(); auto res = ma.calculate(); const auto t2 = Clock::now(); const auto t_us = duration_cast<microseconds>(t2 - t1).count(); printf("%luus [cardinality=%lu]\n", t_us, res->cardinality()); } int main() { const size_t bitmap_size = 2000000; const size_t count = 100; std::vector<bitvector*> input; srand(0); for (size_t i=0; i < count; i++) { bitvector* bv = new bitvector(bitmap_size); bv->fill_random(50); input.push_back(bv); } SequentialAnd seq(input); test("SequentialAnd", seq, input); ParallelAndNaive par1(input, 4); test("ParallelAndNaive", par1, input); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2016 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ /* * Signal * Registers observers. * Notifies registered observers. */ #include <functional> #include <mutex> #include <vector> namespace skui { namespace core { namespace implementation { template<typename... ArgTypes> class signal_base { public: signal_base() = default; signal_base(const signal_base& other) : slots(other.slots) {} signal_base(signal_base&& other) : slots(std::move(other.slots)) {} signal_base& operator=(signal_base other) { swap(other); return *this; } template<typename Callable> void connect(Callable&& slot) { std::lock_guard<decltype(slots_mutex)> lock(slots_mutex); slots.emplace_back(slot); } protected: // mutable here allows to connect to a const object's signals mutable std::vector<std::function<void(ArgTypes...)>> slots; mutable std::mutex slots_mutex; private: void swap(signal_base& other) { std::swap(slots, other.slots); } }; } template<typename... ArgTypes> class signal : public implementation::signal_base<ArgTypes...> { public: signal() = default; void emit(ArgTypes... arguments) const { std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex); for(auto&& slot : this->slots) { slot(arguments...); } } }; // Parameterless specialization template<> class signal<> : public implementation::signal_base<> { public: signal() = default; void emit() const { std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex); for(auto&& slot : this->slots) { slot(); } } }; } } <commit_msg>Make connect a normal function taking a std::function&&.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2016 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ /* * Signal * Registers observers. * Notifies registered observers. */ #include <functional> #include <mutex> #include <vector> namespace skui { namespace core { namespace implementation { template<typename... ArgTypes> class signal_base { public: using slot_type = std::function<void(ArgTypes...)>; signal_base() = default; signal_base(const signal_base& other) : slots(other.slots) {} signal_base(signal_base&& other) : slots(std::move(other.slots)) {} signal_base& operator=(signal_base other) { swap(other); return *this; } void connect(slot_type&& slot) { std::lock_guard<decltype(slots_mutex)> lock(slots_mutex); slots.emplace_back(slot); } protected: // mutable here allows to connect to a const object's signals mutable std::vector<slot_type> slots; mutable std::mutex slots_mutex; private: void swap(signal_base& other) { std::swap(slots, other.slots); } }; } template<typename... ArgTypes> class signal : public implementation::signal_base<ArgTypes...> { public: signal() = default; void emit(ArgTypes... arguments) const { std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex); for(auto&& slot : this->slots) { slot(arguments...); } } }; // Parameterless specialization template<> class signal<> : public implementation::signal_base<> { public: signal() = default; void emit() const { std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex); for(auto&& slot : this->slots) { slot(); } } }; } } <|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "rdf_calculator.h" #include <boost/lexical_cast.hpp> #include <fstream> #include <iomanip> #include <iostream> #include <votca/csg/beadlist.h> #include <votca/csg/imcio.h> #include <votca/csg/nblistgrid.h> #include <votca/tools/constants.h> #include <votca/tools/rangeparser.h> namespace votca { namespace csg { RDFCalculator::RDFCalculator() : _write_every(0), _do_blocks(false), _nblock(0), _subvol_rad(0), _do_vol_corr(false), _processed_some_frames(false) {} RDFCalculator::~RDFCalculator() = default; // begin the coarse graining process // here the data structures are prepared to handle all the data void RDFCalculator::Initialize() { // do some output std::cout << "begin to calculate distribution functions\n"; std::cout << "# of bonded interactions: " << _bonded.size() << std::endl; std::cout << "# of non-bonded interactions: " << _nonbonded.size() << std::endl; if (_bonded.size() + _nonbonded.size() == 0) { throw std::runtime_error( "No interactions defined in options xml-file - nothing to be done"); } // initialize non-bonded structures for (Property *prop : _nonbonded) { interaction_t *i = AddInteraction(prop); i->_is_bonded = false; } } void RDFCalculator::BeginEvaluate(Topology *top, Topology *) { Eigen::Matrix3d box = top->getBox(); Eigen::Vector3d a = box.col(0); Eigen::Vector3d b = box.col(1); Eigen::Vector3d c = box.col(2); _boxc = box.rowwise().sum() / 2.0; std::cout << "Using center of box: " << _boxc << std::endl; // we didn't process any frames so far _nframes = 0; _nblock = 0; _processed_some_frames = false; // initialize non-bonded structures for (Property *prop : _nonbonded) { std::string name = prop->get("name").value(); interaction_t &i = *_interactions[name]; // count total species for ideal densities BeadList allbeads1, allbeads2; allbeads1.Generate(*top, prop->get("type1").value()); allbeads2.Generate(*top, prop->get("type2").value()); if (allbeads1.size() == 0) { throw std::runtime_error("Topology does not have beads of type \"" + prop->get("type1").value() + "\"\n" "This was specified in type1 of interaction \"" + name + "\""); } if (allbeads2.size() == 0) { throw std::runtime_error("Topology does not have beads of type \"" + prop->get("type2").value() + "\"\n" "This was specified in type2 of interaction \"" + name + "\""); } // calculate normalization factor for rdf if (_do_vol_corr) { std::cout << "Volume correction on" << std::endl; i._norm = 1. / (4.0 * votca::tools::conv::Pi * i._step); } else { std::cout << "Volume correction off" << std::endl; i._norm = 1. / (4. * votca::tools::conv::Pi * i._step); } } } // create an entry for interactions RDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) { std::string name = p->get("name").value(); std::string group; group = "none"; interaction_t *i = new interaction_t; i->_index = _interactions.size(); _interactions[name] = i; getGroup(group)->_interactions.push_back(i); i->_step = p->get("step").as<double>(); i->_min = p->get("min").as<double>(); i->_max = p->get("max").as<double>(); i->_norm = 1.0; i->_p = p; // initialize the current and average histogram int n = (int)((i->_max - i->_min) / i->_step + 1.000000001); i->_average.Initialize(i->_min, i->_max + i->_step, n); return i; } // end of trajectory, post processing data void RDFCalculator::EndEvaluate() { if (_nframes > 0) { if (!_do_blocks) { WriteDist(); } } // clear interactions and groups _interactions.clear(); _groups.clear(); if (!_processed_some_frames) { throw std::runtime_error( "no frames were processed. Please check your input"); } } // load options from xml file void RDFCalculator::LoadOptions(const std::string &file) { _options.LoadFromXML(file); _bonded = _options.Select("cg.bonded"); _nonbonded = _options.Select("cg.non-bonded"); } // evaluate current conformation void RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) { _cur_vol = 4.0 / 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad; // process non-bonded interactions DoNonbonded(top); // process bonded interactions DoBonded(top); } void RDFCalculator::ClearAverages() { _nframes = 0; for (auto &_interaction : _interactions) { _interaction.second->_average.Clear(); } for (auto &_group : _groups) { _group.second->_corr.setZero(); } } class IMCNBSearchHandler { public: IMCNBSearchHandler(HistogramNew *hist, double subvol_rad, Eigen::Vector3d boxc, bool do_vol_corr) : _hist(hist), _subvol_rad(subvol_rad), _boxc(boxc), _do_vol_corr(do_vol_corr) {} HistogramNew *_hist; double _subvol_rad; Eigen::Vector3d _boxc; // center of box bool _do_vol_corr; bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) { if (_do_vol_corr) { double dr = (b1->Pos() - _boxc).norm(); if (dist + dr > _subvol_rad) { // 2.0 is because everything is normalized to 4 PI _hist->Process(dist, 2.0 / SurfaceRatio(dist, dr)); } else { _hist->Process(dist); } } else { _hist->Process(dist); } return false; } double SurfaceRatio(double dist, double r) { // r: distance of particle from ex center // dist: distance between particles return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) / (2.0 * dist * r)); } }; // process non-bonded interactions for current frame void RDFCalculator::Worker::DoNonbonded(Topology *top) { for (Property *prop : _rdfcalculator->_nonbonded) { std::string name = prop->get("name").value(); interaction_t &i = *_rdfcalculator->_interactions[name]; // generate the bead lists BeadList beads1, beads2; beads1.GenerateInSphericalSubvolume(*top, prop->get("type1").value(), _rdfcalculator->_boxc, _rdfcalculator->_subvol_rad); beads2.GenerateInSphericalSubvolume(*top, prop->get("type2").value(), _rdfcalculator->_boxc, _rdfcalculator->_subvol_rad); _cur_beadlist_1_count = (double)beads1.size(); _cur_beadlist_2_count = (double)beads2.size(); // same types, so put factor 1/2 because of already counted interactions if (prop->get("type1").value() == prop->get("type2").value()) { _cur_beadlist_2_count /= 2.0; } // generate the neighbour list std::unique_ptr<NBList> nb; bool gridsearch = true; if (_rdfcalculator->_options.exists("cg.nbsearch")) { if (_rdfcalculator->_options.get("cg.nbsearch").as<std::string>() == "grid") { gridsearch = true; } else if (_rdfcalculator->_options.get("cg.nbsearch") .as<std::string>() == "simple") { gridsearch = false; } else { throw std::runtime_error("cg.nbsearch invalid, can be grid or simple"); } } if (gridsearch) { nb = std::make_unique<NBList>(NBListGrid()); } else { nb = std::make_unique<NBList>(NBList()); } nb->setCutoff(i._max + i._step); // clear the current histogram _current_hists[i._index].Clear(); IMCNBSearchHandler h(&(_current_hists[i._index]), _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc, _rdfcalculator->_do_vol_corr); nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair); // is it same types or different types? if (prop->get("type1").value() == prop->get("type2").value()) { nb->Generate(beads1); } else { nb->Generate(beads1, beads2); } // store particle number in subvolume for each interaction i._avg_beadlist_1_count.Process(_cur_beadlist_1_count); i._avg_beadlist_2_count.Process(_cur_beadlist_2_count); } } // process non-bonded interactions for current frame void RDFCalculator::Worker::DoBonded(Topology *top) { for (Property *prop : _rdfcalculator->_bonded) { std::string name = prop->get("name").value(); interaction_t &i = *_rdfcalculator->_interactions[name]; // clear the current histogram _current_hists[i._index].Clear(); // now fill with new data std::list<Interaction *> list = top->InteractionsInGroup(name); for (auto ic : list) { double v = ic->EvaluateVar(*top); _current_hists[i._index].Process(v); } } } // returns a group, creates it if doesn't exist RDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) { std::map<std::string, group_t *>::iterator iter; iter = _groups.find(name); if (iter == _groups.end()) { return _groups[name] = new group_t; } return (*iter).second; } // write the distribution function void RDFCalculator::WriteDist(const std::string &suffix) { // for all interactions for (auto &_interaction : _interactions) { // calculate the rdf Table &t = _interaction.second->_average.data(); Table dist(t); _interaction.second->_norm /= (_interaction.second->_avg_beadlist_1_count.getAvg() * _interaction.second->_avg_beadlist_2_count.getAvg()); dist.y() = _avg_vol.getAvg() * _interaction.second->_norm * dist.y().cwiseQuotient(dist.x().cwiseAbs2()); dist.Save((_interaction.first) + suffix + ".dist.new"); std::cout << "written " << (_interaction.first) + suffix + ".dist.new\n"; std::cout << "Avg. number of particles in subvol for " << (_interaction.first) << std::endl; std::cout << "beadlist 1: " << _interaction.second->_avg_beadlist_1_count.getAvg() << std::endl; std::cout << "beadlist 2: " << _interaction.second->_avg_beadlist_2_count.getAvg() << std::endl; } std::cout << "Volume used for normalization: " << _avg_vol.getAvg() << std::endl; } CsgApplication::Worker *RDFCalculator::ForkWorker() { RDFCalculator::Worker *worker; worker = new RDFCalculator::Worker; worker->_current_hists.resize(_interactions.size()); worker->_rdfcalculator = this; for (auto &_interaction : _interactions) { interaction_t *i = _interaction.second; worker->_current_hists[i->_index].Initialize( i->_average.getMin(), i->_average.getMax(), i->_average.getNBins()); } return worker; } void RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) { _processed_some_frames = true; RDFCalculator::Worker *worker = dynamic_cast<RDFCalculator::Worker *>(worker_); // update the average ++_nframes; _avg_vol.Process(worker->_cur_vol); for (auto &_interaction : _interactions) { interaction_t *i = _interaction.second; i->_average.data().y() = (((double)_nframes - 1.0) * i->_average.data().y() + worker->_current_hists[i->_index].data().y()) / (double)_nframes; } if (_write_every != 0) { if ((_nframes % _write_every) == 0) { _nblock++; std::string suffix = std::string("_") + boost::lexical_cast<std::string>(_nblock); WriteDist(suffix); if (_do_blocks) { ClearAverages(); } } } } } // namespace csg } // namespace votca <commit_msg>Update rdf_calculator.cc<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "rdf_calculator.h" #include <boost/lexical_cast.hpp> #include <fstream> #include <iomanip> #include <iostream> #include <votca/csg/beadlist.h> #include <votca/csg/imcio.h> #include <votca/csg/nblistgrid.h> #include <votca/tools/constants.h> #include <votca/tools/rangeparser.h> namespace votca { namespace csg { RDFCalculator::RDFCalculator() : _write_every(0), _do_blocks(false), _nblock(0), _subvol_rad(0), _do_vol_corr(false), _processed_some_frames(false) {} RDFCalculator::~RDFCalculator() = default; // begin the coarse graining process // here the data structures are prepared to handle all the data void RDFCalculator::Initialize() { // do some output std::cout << "begin to calculate distribution functions\n"; std::cout << "# of bonded interactions: " << _bonded.size() << std::endl; std::cout << "# of non-bonded interactions: " << _nonbonded.size() << std::endl; if (_bonded.size() + _nonbonded.size() == 0) { throw std::runtime_error( "No interactions defined in options xml-file - nothing to be done"); } // initialize non-bonded structures for (Property *prop : _nonbonded) { interaction_t *i = AddInteraction(prop); i->_is_bonded = false; } } void RDFCalculator::BeginEvaluate(Topology *top, Topology *) { Eigen::Matrix3d box = top->getBox(); _boxc = box.rowwise().sum() / 2.0; std::cout << "Using center of box: " << _boxc << std::endl; // we didn't process any frames so far _nframes = 0; _nblock = 0; _processed_some_frames = false; // initialize non-bonded structures for (Property *prop : _nonbonded) { std::string name = prop->get("name").value(); interaction_t &i = *_interactions[name]; // count total species for ideal densities BeadList allbeads1, allbeads2; allbeads1.Generate(*top, prop->get("type1").value()); allbeads2.Generate(*top, prop->get("type2").value()); if (allbeads1.size() == 0) { throw std::runtime_error("Topology does not have beads of type \"" + prop->get("type1").value() + "\"\n" "This was specified in type1 of interaction \"" + name + "\""); } if (allbeads2.size() == 0) { throw std::runtime_error("Topology does not have beads of type \"" + prop->get("type2").value() + "\"\n" "This was specified in type2 of interaction \"" + name + "\""); } // calculate normalization factor for rdf if (_do_vol_corr) { std::cout << "Volume correction on" << std::endl; i._norm = 1. / (4.0 * votca::tools::conv::Pi * i._step); } else { std::cout << "Volume correction off" << std::endl; i._norm = 1. / (4. * votca::tools::conv::Pi * i._step); } } } // create an entry for interactions RDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) { std::string name = p->get("name").value(); std::string group; group = "none"; interaction_t *i = new interaction_t; i->_index = _interactions.size(); _interactions[name] = i; getGroup(group)->_interactions.push_back(i); i->_step = p->get("step").as<double>(); i->_min = p->get("min").as<double>(); i->_max = p->get("max").as<double>(); i->_norm = 1.0; i->_p = p; // initialize the current and average histogram int n = (int)((i->_max - i->_min) / i->_step + 1.000000001); i->_average.Initialize(i->_min, i->_max + i->_step, n); return i; } // end of trajectory, post processing data void RDFCalculator::EndEvaluate() { if (_nframes > 0) { if (!_do_blocks) { WriteDist(); } } // clear interactions and groups _interactions.clear(); _groups.clear(); if (!_processed_some_frames) { throw std::runtime_error( "no frames were processed. Please check your input"); } } // load options from xml file void RDFCalculator::LoadOptions(const std::string &file) { _options.LoadFromXML(file); _bonded = _options.Select("cg.bonded"); _nonbonded = _options.Select("cg.non-bonded"); } // evaluate current conformation void RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) { _cur_vol = 4.0 / 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad; // process non-bonded interactions DoNonbonded(top); // process bonded interactions DoBonded(top); } void RDFCalculator::ClearAverages() { _nframes = 0; for (auto &_interaction : _interactions) { _interaction.second->_average.Clear(); } for (auto &_group : _groups) { _group.second->_corr.setZero(); } } class IMCNBSearchHandler { public: IMCNBSearchHandler(HistogramNew *hist, double subvol_rad, Eigen::Vector3d boxc, bool do_vol_corr) : _hist(hist), _subvol_rad(subvol_rad), _boxc(boxc), _do_vol_corr(do_vol_corr) {} HistogramNew *_hist; double _subvol_rad; Eigen::Vector3d _boxc; // center of box bool _do_vol_corr; bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) { if (_do_vol_corr) { double dr = (b1->Pos() - _boxc).norm(); if (dist + dr > _subvol_rad) { // 2.0 is because everything is normalized to 4 PI _hist->Process(dist, 2.0 / SurfaceRatio(dist, dr)); } else { _hist->Process(dist); } } else { _hist->Process(dist); } return false; } double SurfaceRatio(double dist, double r) { // r: distance of particle from ex center // dist: distance between particles return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) / (2.0 * dist * r)); } }; // process non-bonded interactions for current frame void RDFCalculator::Worker::DoNonbonded(Topology *top) { for (Property *prop : _rdfcalculator->_nonbonded) { std::string name = prop->get("name").value(); interaction_t &i = *_rdfcalculator->_interactions[name]; // generate the bead lists BeadList beads1, beads2; beads1.GenerateInSphericalSubvolume(*top, prop->get("type1").value(), _rdfcalculator->_boxc, _rdfcalculator->_subvol_rad); beads2.GenerateInSphericalSubvolume(*top, prop->get("type2").value(), _rdfcalculator->_boxc, _rdfcalculator->_subvol_rad); _cur_beadlist_1_count = (double)beads1.size(); _cur_beadlist_2_count = (double)beads2.size(); // same types, so put factor 1/2 because of already counted interactions if (prop->get("type1").value() == prop->get("type2").value()) { _cur_beadlist_2_count /= 2.0; } // generate the neighbour list std::unique_ptr<NBList> nb; bool gridsearch = true; if (_rdfcalculator->_options.exists("cg.nbsearch")) { if (_rdfcalculator->_options.get("cg.nbsearch").as<std::string>() == "grid") { gridsearch = true; } else if (_rdfcalculator->_options.get("cg.nbsearch") .as<std::string>() == "simple") { gridsearch = false; } else { throw std::runtime_error("cg.nbsearch invalid, can be grid or simple"); } } if (gridsearch) { nb = std::make_unique<NBList>(NBListGrid()); } else { nb = std::make_unique<NBList>(NBList()); } nb->setCutoff(i._max + i._step); // clear the current histogram _current_hists[i._index].Clear(); IMCNBSearchHandler h(&(_current_hists[i._index]), _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc, _rdfcalculator->_do_vol_corr); nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair); // is it same types or different types? if (prop->get("type1").value() == prop->get("type2").value()) { nb->Generate(beads1); } else { nb->Generate(beads1, beads2); } // store particle number in subvolume for each interaction i._avg_beadlist_1_count.Process(_cur_beadlist_1_count); i._avg_beadlist_2_count.Process(_cur_beadlist_2_count); } } // process non-bonded interactions for current frame void RDFCalculator::Worker::DoBonded(Topology *top) { for (Property *prop : _rdfcalculator->_bonded) { std::string name = prop->get("name").value(); interaction_t &i = *_rdfcalculator->_interactions[name]; // clear the current histogram _current_hists[i._index].Clear(); // now fill with new data std::list<Interaction *> list = top->InteractionsInGroup(name); for (auto ic : list) { double v = ic->EvaluateVar(*top); _current_hists[i._index].Process(v); } } } // returns a group, creates it if doesn't exist RDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) { std::map<std::string, group_t *>::iterator iter; iter = _groups.find(name); if (iter == _groups.end()) { return _groups[name] = new group_t; } return (*iter).second; } // write the distribution function void RDFCalculator::WriteDist(const std::string &suffix) { // for all interactions for (auto &_interaction : _interactions) { // calculate the rdf Table &t = _interaction.second->_average.data(); Table dist(t); _interaction.second->_norm /= (_interaction.second->_avg_beadlist_1_count.getAvg() * _interaction.second->_avg_beadlist_2_count.getAvg()); dist.y() = _avg_vol.getAvg() * _interaction.second->_norm * dist.y().cwiseQuotient(dist.x().cwiseAbs2()); dist.Save((_interaction.first) + suffix + ".dist.new"); std::cout << "written " << (_interaction.first) + suffix + ".dist.new\n"; std::cout << "Avg. number of particles in subvol for " << (_interaction.first) << std::endl; std::cout << "beadlist 1: " << _interaction.second->_avg_beadlist_1_count.getAvg() << std::endl; std::cout << "beadlist 2: " << _interaction.second->_avg_beadlist_2_count.getAvg() << std::endl; } std::cout << "Volume used for normalization: " << _avg_vol.getAvg() << std::endl; } CsgApplication::Worker *RDFCalculator::ForkWorker() { RDFCalculator::Worker *worker; worker = new RDFCalculator::Worker; worker->_current_hists.resize(_interactions.size()); worker->_rdfcalculator = this; for (auto &_interaction : _interactions) { interaction_t *i = _interaction.second; worker->_current_hists[i->_index].Initialize( i->_average.getMin(), i->_average.getMax(), i->_average.getNBins()); } return worker; } void RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) { _processed_some_frames = true; RDFCalculator::Worker *worker = dynamic_cast<RDFCalculator::Worker *>(worker_); // update the average ++_nframes; _avg_vol.Process(worker->_cur_vol); for (auto &_interaction : _interactions) { interaction_t *i = _interaction.second; i->_average.data().y() = (((double)_nframes - 1.0) * i->_average.data().y() + worker->_current_hists[i->_index].data().y()) / (double)_nframes; } if (_write_every != 0) { if ((_nframes % _write_every) == 0) { _nblock++; std::string suffix = std::string("_") + boost::lexical_cast<std::string>(_nblock); WriteDist(suffix); if (_do_blocks) { ClearAverages(); } } } } } // namespace csg } // namespace votca <|endoftext|>
<commit_before>/** * @file py_sql_well.cpp * @brief python wraper for well fracture storage * @author Oleg Borschuk * @version * @date 2011-07-29 */ #include "py_sql_well.h" #include "sql_well.h" #include "bs_serialize.h" #include "bs_prop_base.h" using namespace boost::python; #ifdef BSPY_EXPORTING_PLUGIN namespace blue_sky { namespace python { void py_export_compdat_ident(); ////////////////////////////////////////////////////////////////////////// // helper function to write well_pool to given fname std::string serialize_to_str_fname( smart_ptr< well_pool_iface > wp, const std::string& prj_path, const std::string& prj_name ) { // save project path for serialization code kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type("hdm").td_); //std::string well_pool_filename = prj_name + "_well_pool.db"; p_dt->insert< std::string >(prj_path); // and project name p_dt->insert< std::string >(prj_name); // invoke serializetion std::string res = serialize_to_str< well_pool_iface >(wp); // clear table p_dt->clear< std::string >(); return res; } ////////////////////////////////////////////////////////////////////////// //! export matrices to python void py_export_sql_well () { using namespace boost::python; base_exporter <well_pool_iface, py_sql_well_exporter>::export_class ("well_pool_iface"); class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class ("sql_well"); py_export_compdat_ident(); def("serialize_to_str", &blue_sky::serialize_to_str< well_pool_iface >); def("serialize_from_str", &blue_sky::serialize_from_str< well_pool_iface >); def("serialize_to_str_fname", &serialize_to_str_fname); // register implicit conversion to interface implicitly_convertible< smart_ptr< sql_well >, smart_ptr< well_pool_iface > >(); } } // namespace python } // namespace blue_sky #endif // #ifdef BSPY_EXPORTING_PLUGIN <commit_msg>SQW: export to Python explicit serialization functions for sql_well class<commit_after>/** * @file py_sql_well.cpp * @brief python wraper for well fracture storage * @author Oleg Borschuk * @version * @date 2011-07-29 */ #include "py_sql_well.h" #include "sql_well.h" #include "bs_serialize.h" #include "bs_prop_base.h" using namespace boost::python; #ifdef BSPY_EXPORTING_PLUGIN BLUE_SKY_TYPE_SERIALIZE_GUID(blue_sky::sql_well) BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::sql_well) namespace blue_sky { namespace python { void py_export_compdat_ident(); ////////////////////////////////////////////////////////////////////////// // helper function to write well_pool to given fname std::string serialize_to_str_fname( smart_ptr< well_pool_iface > wp, const std::string& prj_path, const std::string& prj_name ) { // save project path for serialization code kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type("hdm").td_); //std::string well_pool_filename = prj_name + "_well_pool.db"; p_dt->insert< std::string >(prj_path); // and project name p_dt->insert< std::string >(prj_name); // invoke serializetion std::string res = serialize_to_str< well_pool_iface >(wp); // clear table p_dt->clear< std::string >(); return res; } ////////////////////////////////////////////////////////////////////////// //! export matrices to python void py_export_sql_well () { using namespace boost::python; base_exporter <well_pool_iface, py_sql_well_exporter>::export_class ("well_pool_iface"); class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class ("sql_well"); py_export_compdat_ident(); std::string (*s2s_wpi)(smart_ptr< well_pool_iface >&) = &blue_sky::serialize_to_str< well_pool_iface >; std::string (*s2s_sqw)(smart_ptr< sql_well >&) = &blue_sky::serialize_to_str< sql_well >; smart_ptr< well_pool_iface > (*sfs_wpi)(const std::string&) = &blue_sky::serialize_from_str< well_pool_iface >; smart_ptr< sql_well > (*sfs_sqw)(const std::string&) = &blue_sky::serialize_from_str< sql_well >; def("serialize_to_str", s2s_wpi); def("serialize_to_str", s2s_sqw); def("serialize_from_str", sfs_wpi); def("serialize_from_str", sfs_sqw); //def("serialize_to_str", &blue_sky::serialize_to_str< well_pool_iface >); //def("serialize_from_str", &blue_sky::serialize_from_str< well_pool_iface >); def("serialize_to_str_fname", &serialize_to_str_fname); // register implicit conversion to interface implicitly_convertible< smart_ptr< sql_well >, smart_ptr< well_pool_iface > >(); } } // namespace python } // namespace blue_sky #endif // #ifdef BSPY_EXPORTING_PLUGIN <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <Context.h> #include <Filter.h> #include <util.h> #include <text.h> #include <i18n.h> #include <main.h> #include <CmdDelete.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdDelete::CmdDelete () { _keyword = "delete"; _usage = "task <filter> delete <mods>"; _description = STRING_CMD_DELETE_USAGE; _read_only = false; _displays_id = false; _needs_confirm = true; } //////////////////////////////////////////////////////////////////////////////// int CmdDelete::execute (std::string& output) { int rc = 0; int count = 0; // Apply filter. Filter filter; std::vector <Task> filtered; filter.subset (filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // Accumulated project change notifications. std::map <std::string, std::string> projectChanges; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { Task before (*task); if (task->getStatus () != Task::deleted) { // Delete the specified task. std::string question; if (task->id) question = format (STRING_CMD_DELETE_CONFIRM, task->id, task->get ("description")); else question = format (STRING_CMD_DELETE_CONFIRM, task->get ("uuid"), task->get ("description")); task->modify (Task::modAnnotate); task->setStatus (Task::deleted); if (! task->has ("end")) task->setEnd (); if (permission (*task, question, filtered.size ())) { updateRecurrenceMask (*task); ++count; context.tdb2.modify (*task); feedback_affected (STRING_CMD_DELETE_TASK, *task); feedback_unblocked (*task); dependencyChainOnComplete (*task); if (context.verbose ("project")) projectChanges[task->get ("project")] = onProjectChange (*task); // Delete siblings. if (task->has ("parent")) { if (confirm (STRING_CMD_DELETE_CONFIRM_R)) { std::vector <Task> siblings = context.tdb2.siblings (*task); std::vector <Task>::iterator sibling; for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling) { sibling->modify (Task::modAnnotate); sibling->setStatus (Task::deleted); if (! sibling->has ("end")) sibling->setEnd (); updateRecurrenceMask (*sibling); context.tdb2.modify (*sibling); feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling); feedback_unblocked (*sibling); ++count; } // Delete the parent Task parent; context.tdb2.get (task->get ("parent"), parent); parent.setStatus (Task::deleted); if (! parent.has ("end")) parent.setEnd (); context.tdb2.modify (parent); } } // Task potentially has child tasks - optionally delete them. else { std::vector <Task> children = context.tdb2.children (*task); if (children.size () && confirm (STRING_CMD_DELETE_CONFIRM_R)) { std::vector <Task>::iterator child; for (child = children.begin (); child != children.end (); ++child) { child->modify (Task::modAnnotate); child->setStatus (Task::deleted); if (! child->has ("end")) child->setEnd (); updateRecurrenceMask (*child); context.tdb2.modify (*child); feedback_affected (STRING_CMD_DELETE_TASK_R, *child); feedback_unblocked (*child); ++count; } } } } else { std::cout << STRING_CMD_DELETE_NO << "\n"; rc = 1; if (_permission_quit) break; } } else { std::cout << format (STRING_CMD_DELETE_NOT_DEL, task->id, task->get ("description")) << "\n"; rc = 1; } } // Now list the project changes. std::map <std::string, std::string>::iterator i; for (i = projectChanges.begin (); i != projectChanges.end (); ++i) if (i->first != "") context.footnote (i->second); context.tdb2.commit (); feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count); return rc; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>CmdDelete<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <Context.h> #include <Filter.h> #include <util.h> #include <text.h> #include <i18n.h> #include <main.h> #include <CmdDelete.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdDelete::CmdDelete () { _keyword = "delete"; _usage = "task <filter> delete <mods>"; _description = STRING_CMD_DELETE_USAGE; _read_only = false; _displays_id = false; _needs_confirm = true; } //////////////////////////////////////////////////////////////////////////////// int CmdDelete::execute (std::string& output) { int rc = 0; int count = 0; // Apply filter. Filter filter; std::vector <Task> filtered; filter.subset (filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // Accumulated project change notifications. std::map <std::string, std::string> projectChanges; std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { Task before (*task); if (task->getStatus () != Task::deleted) { // Delete the specified task. std::string question; if (task->id) question = format (STRING_CMD_DELETE_CONFIRM, task->id, task->get ("description")); else question = format (STRING_CMD_DELETE_CONFIRM, task->get ("uuid"), task->get ("description")); task->modify (Task::modAnnotate); task->setStatus (Task::deleted); if (! task->has ("end")) task->setEnd (); if (permission (*task, question, filtered.size ())) { updateRecurrenceMask (*task); ++count; context.tdb2.modify (*task); feedback_affected (STRING_CMD_DELETE_TASK, *task); feedback_unblocked (*task); dependencyChainOnComplete (*task); if (context.verbose ("project")) projectChanges[task->get ("project")] = onProjectChange (*task); // Delete siblings. if (task->has ("parent")) { if (confirm (STRING_CMD_DELETE_CONFIRM_R)) { std::vector <Task> siblings = context.tdb2.siblings (*task); std::vector <Task>::iterator sibling; for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling) { sibling->modify (Task::modAnnotate); sibling->setStatus (Task::deleted); if (! sibling->has ("end")) sibling->setEnd (); updateRecurrenceMask (*sibling); context.tdb2.modify (*sibling); feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling); feedback_unblocked (*sibling); ++count; } // Delete the parent Task parent; context.tdb2.get (task->get ("parent"), parent); parent.setStatus (Task::deleted); if (! parent.has ("end")) parent.setEnd (); context.tdb2.modify (parent); } } // Task potentially has child tasks - optionally delete them. else { std::vector <Task> children = context.tdb2.children (*task); if (children.size () && confirm (STRING_CMD_DELETE_CONFIRM_R)) { std::vector <Task>::iterator child; for (child = children.begin (); child != children.end (); ++child) { child->modify (Task::modAnnotate); child->setStatus (Task::deleted); if (! child->has ("end")) child->setEnd (); updateRecurrenceMask (*child); context.tdb2.modify (*child); feedback_affected (STRING_CMD_DELETE_TASK_R, *child); feedback_unblocked (*child); ++count; } } } } else { std::cout << STRING_CMD_DELETE_NO << "\n"; rc = 1; if (_permission_quit) break; } } else { std::cout << format (STRING_CMD_DELETE_NOT_DEL, task->id, task->get ("description")) << "\n"; rc = 1; } } // Now list the project changes. std::map <std::string, std::string>::iterator i; for (i = projectChanges.begin (); i != projectChanges.end (); ++i) if (i->first != "") context.footnote (i->second); feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count); return rc; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/// @author uentity /// @date 01.07.2019 /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/serialize/object_formatter.h> #include <bs/objbase.h> #include <bs/kernel/misc.h> #include <bs/uuid.h> #include <map> #include <unordered_map> #include <set> #include <mutex> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN() /*----------------------------------------------------------------------------- * Formatters manip impl *-----------------------------------------------------------------------------*/ struct fmaster { // obj_type_id -> set of unique object_formatter instances sorted by name // [NOTE] type_id is stored as string view! using fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >; fmt_storage_t fmt_storage; using registry_t = std::unordered_map<const objbase*, const object_formatter*>; registry_t registry; using archive_registry_t = std::unordered_multimap<const object_formatter*, void*>; archive_registry_t archive_registry; // sync access to data above std::mutex fmt_guard, reg_guard, arch_reg_guard; fmaster() {} fmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {} fmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {} static auto self() -> fmaster& { static fmaster& self = []() -> fmaster& { // generate random key auto& kstorage = kernel::idx_key_storage(to_string(gen_uuid())); auto r = kstorage.insert_element(0, fmaster()); if(!r.first) throw error("Failed to make impl of object formatters in kernel storage!"); return *r.first; }(); return self; } auto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool { auto solo = std::lock_guard{ fmt_guard }; return fmt_storage[obj_type.name].insert(std::move(of)).second; } auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool { // deny removing fallback binary formatter if(fmt_name == detail::bin_fmt_name) return false; auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { auto& fmt_set = fmts->second; if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) { // erase format fmt_set.erase(pfmt); return true; } } return false; } auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool { auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) return fmts->second.find(fmt_name) != fmts->second.end(); return false; } auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> { auto solo = std::lock_guard{ fmt_guard }; auto res = std::vector<std::string>{}; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { res.reserve(fmts->second.size()); for(const auto& f : fmts->second) res.emplace_back(f.name); } return res; } auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* { auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { auto& fmt_set = fmts->second; if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) return &const_cast<object_formatter&>(*pfmt); } return nullptr; } auto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void { auto solo = std::lock_guard{ reg_guard }; registry[&obj] = obj_fmt; } auto deregister_formatter(const objbase& obj) -> void { auto solo = std::lock_guard{ reg_guard }; registry.erase(&obj); } auto get_obj_formatter(const objbase* obj) -> const object_formatter* { auto solo = std::lock_guard{ reg_guard }; if(auto r = registry.find(obj); r != registry.end()) return r->second; return nullptr; } auto register_archive(const object_formatter* frm, void* archive) -> void { auto solo = std::lock_guard{ arch_reg_guard }; archive_registry.emplace(frm, archive); } auto deregister_archive(const object_formatter* frm) -> void { auto solo = std::lock_guard{ arch_reg_guard }; archive_registry.erase(frm); } auto deregister_archive(const object_formatter* frm, void* archive) -> void { auto solo = std::lock_guard{ arch_reg_guard }; for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) { if(a->second == archive) { archive_registry.erase(a); break; } } } auto contains_archive(const object_formatter* frm, void* archive) -> bool { auto solo = std::lock_guard{ arch_reg_guard }; for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) { if(a->second == archive) return true; } return false; } }; NAMESPACE_END() /*----------------------------------------------------------------------------- * Formatters manip public API *-----------------------------------------------------------------------------*/ #define FM fmaster::self() auto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool { return FM.install_formatter(obj_type, std::move(of)); } auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool { return FM.uninstall_formatter(obj_type_id, std::move(fmt_name)); } auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool { return FM.formatter_installed(obj_type_id, fmt_name); } auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> { return FM.list_installed_formatters(obj_type_id); } auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* { return FM.get_formatter(obj_type_id, fmt_name); } auto get_obj_formatter(const objbase* obj) -> const object_formatter* { return FM.get_obj_formatter(obj); } /*----------------------------------------------------------------------------- * object_formatter *-----------------------------------------------------------------------------*/ object_formatter::object_formatter( std::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_ ) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_) {} // compare formatters by name auto operator<(const object_formatter& lhs, const object_formatter& rhs) { return lhs.name < rhs.name; } // ... and with arbitrary string key auto operator<(const object_formatter& lhs, std::string_view rhs) { return lhs.name < rhs; } auto operator<(std::string_view lhs, const object_formatter& rhs) { return lhs < rhs.name; } auto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error { // if obj has empty payload, skip save if(obj.empty_payload()) return tree::Error::EmptyData; const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }}; return error::eval_safe([&] { FM.register_formatter(obj, this); first(*this, obj, std::move(obj_fname), name); }); } auto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error { const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }}; return error::eval_safe([&] { FM.register_formatter(obj, this); second(*this, obj, std::move(obj_fname), name); }); } auto object_formatter::bind_archive(void* archive) const -> void { FM.register_archive(this, archive); } auto object_formatter::unbind_archive(void* archive) const -> void { FM.deregister_archive(this, archive); } auto object_formatter::unbind_archive() const -> void { FM.deregister_archive(this); } auto object_formatter::is_archive_binded(void* archive) const -> bool { return FM.contains_archive(this, archive); } NAMESPACE_END(blue_sky) <commit_msg>serial/objformatter: fix loud EmptyData from object_formatter::save()<commit_after>/// @author uentity /// @date 01.07.2019 /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/serialize/object_formatter.h> #include <bs/objbase.h> #include <bs/kernel/misc.h> #include <bs/uuid.h> #include <map> #include <unordered_map> #include <set> #include <mutex> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN() /*----------------------------------------------------------------------------- * Formatters manip impl *-----------------------------------------------------------------------------*/ struct fmaster { // obj_type_id -> set of unique object_formatter instances sorted by name // [NOTE] type_id is stored as string view! using fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >; fmt_storage_t fmt_storage; using registry_t = std::unordered_map<const objbase*, const object_formatter*>; registry_t registry; using archive_registry_t = std::unordered_multimap<const object_formatter*, void*>; archive_registry_t archive_registry; // sync access to data above std::mutex fmt_guard, reg_guard, arch_reg_guard; fmaster() {} fmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {} fmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {} static auto self() -> fmaster& { static fmaster& self = []() -> fmaster& { // generate random key auto& kstorage = kernel::idx_key_storage(to_string(gen_uuid())); auto r = kstorage.insert_element(0, fmaster()); if(!r.first) throw error("Failed to make impl of object formatters in kernel storage!"); return *r.first; }(); return self; } auto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool { auto solo = std::lock_guard{ fmt_guard }; return fmt_storage[obj_type.name].insert(std::move(of)).second; } auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool { // deny removing fallback binary formatter if(fmt_name == detail::bin_fmt_name) return false; auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { auto& fmt_set = fmts->second; if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) { // erase format fmt_set.erase(pfmt); return true; } } return false; } auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool { auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) return fmts->second.find(fmt_name) != fmts->second.end(); return false; } auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> { auto solo = std::lock_guard{ fmt_guard }; auto res = std::vector<std::string>{}; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { res.reserve(fmts->second.size()); for(const auto& f : fmts->second) res.emplace_back(f.name); } return res; } auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* { auto solo = std::lock_guard{ fmt_guard }; if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) { auto& fmt_set = fmts->second; if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) return &const_cast<object_formatter&>(*pfmt); } return nullptr; } auto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void { auto solo = std::lock_guard{ reg_guard }; registry[&obj] = obj_fmt; } auto deregister_formatter(const objbase& obj) -> void { auto solo = std::lock_guard{ reg_guard }; registry.erase(&obj); } auto get_obj_formatter(const objbase* obj) -> const object_formatter* { auto solo = std::lock_guard{ reg_guard }; if(auto r = registry.find(obj); r != registry.end()) return r->second; return nullptr; } auto register_archive(const object_formatter* frm, void* archive) -> void { auto solo = std::lock_guard{ arch_reg_guard }; archive_registry.emplace(frm, archive); } auto deregister_archive(const object_formatter* frm) -> void { auto solo = std::lock_guard{ arch_reg_guard }; archive_registry.erase(frm); } auto deregister_archive(const object_formatter* frm, void* archive) -> void { auto solo = std::lock_guard{ arch_reg_guard }; for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) { if(a->second == archive) { archive_registry.erase(a); break; } } } auto contains_archive(const object_formatter* frm, void* archive) -> bool { auto solo = std::lock_guard{ arch_reg_guard }; for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) { if(a->second == archive) return true; } return false; } }; NAMESPACE_END() /*----------------------------------------------------------------------------- * Formatters manip public API *-----------------------------------------------------------------------------*/ #define FM fmaster::self() auto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool { return FM.install_formatter(obj_type, std::move(of)); } auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool { return FM.uninstall_formatter(obj_type_id, std::move(fmt_name)); } auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool { return FM.formatter_installed(obj_type_id, fmt_name); } auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> { return FM.list_installed_formatters(obj_type_id); } auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* { return FM.get_formatter(obj_type_id, fmt_name); } auto get_obj_formatter(const objbase* obj) -> const object_formatter* { return FM.get_obj_formatter(obj); } /*----------------------------------------------------------------------------- * object_formatter *-----------------------------------------------------------------------------*/ object_formatter::object_formatter( std::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_ ) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_) {} // compare formatters by name auto operator<(const object_formatter& lhs, const object_formatter& rhs) { return lhs.name < rhs.name; } // ... and with arbitrary string key auto operator<(const object_formatter& lhs, std::string_view rhs) { return lhs.name < rhs; } auto operator<(std::string_view lhs, const object_formatter& rhs) { return lhs < rhs.name; } auto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error { // if obj has empty payload, skip save if(obj.empty_payload()) return error::quiet(tree::Error::EmptyData); const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }}; return error::eval_safe([&] { FM.register_formatter(obj, this); first(*this, obj, std::move(obj_fname), name); }); } auto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error { const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }}; return error::eval_safe([&] { FM.register_formatter(obj, this); second(*this, obj, std::move(obj_fname), name); }); } auto object_formatter::bind_archive(void* archive) const -> void { FM.register_archive(this, archive); } auto object_formatter::unbind_archive(void* archive) const -> void { FM.deregister_archive(this, archive); } auto object_formatter::unbind_archive() const -> void { FM.deregister_archive(this); } auto object_formatter::is_archive_binded(void* archive) const -> bool { return FM.contains_archive(this, archive); } NAMESPACE_END(blue_sky) <|endoftext|>