text
stringlengths
54
60.6k
<commit_before><commit_msg>add special comment expected by bin/new_test.sh<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $ */ /* */ /* 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 */ // constant defining number of NEST PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t NEST_PLL_FREQ_BUCKETS = 5; // Nest PLL frequency in MHZ // index is bucket number const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] = { 1600, 1866, 2000, 2133, 2400 }; // I2C bus divisor // index is bucket number // The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] = { 25, 29, 31, 33, 37 }; // constant defining number of MEM PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t MEM_PLL_FREQ_BUCKETS = 5; // MEM PLL frequency in MHz // index is bucket number const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] = { 1866, 2133, 2400, 2666, 2666 }; // constant definining number of OBUS PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t OBUS_PLL_FREQ_BUCKETS = 3; // OBUS PLL frequency in MHz // index is bucket number const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] = { 1250, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] = { 1563, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] = { 1563, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1563 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_23[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1563 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] = { 1601, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1601 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_12[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1601 }; const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1611 }; <commit_msg>Adding p9c DD13 support<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $ */ /* */ /* 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 */ // constant defining number of NEST PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t NEST_PLL_FREQ_BUCKETS = 5; // Nest PLL frequency in MHZ // index is bucket number const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] = { 1600, 1866, 2000, 2133, 2400 }; // I2C bus divisor // index is bucket number // The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] = { 25, 29, 31, 33, 37 }; // constant defining number of MEM PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t MEM_PLL_FREQ_BUCKETS = 5; // MEM PLL frequency in MHz // index is bucket number const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] = { 1866, 2133, 2400, 2666, 2666 }; // constant definining number of OBUS PLL frequency options ('buckets') // to be built into unsigned HW image const uint8_t OBUS_PLL_FREQ_BUCKETS = 3; // OBUS PLL frequency in MHz // index is bucket number const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] = { 1250, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] = { 1563, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] = { 1563, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1563 }; const uint32_t OBUS_PLL_FREQ_LIST_P9N_23[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1563 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] = { 1601, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1601 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_12[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1601 }; const uint32_t OBUS_PLL_FREQ_LIST_P9C_13[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1601 }; const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1611 }; const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] = { 1611, 1250, 1611 }; <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/check.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 check.C /// @brief Subroutines for checking MSS FIR /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <lib/fir/fir.H> #include <lib/fir/check.H> #include <lib/utils/assert_noexit.H> #include <generic/memory/lib/utils/find.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace check { /// /// @brief A small, local, class to hold some of the FFDC information we need from the ports /// struct fir_ffdc { /// /// @brief fir_ffdc ctor /// @param[in] the MCA target the FFDC was collected from /// @param[in] the cal FIR information /// @param[in] the phy FIR information /// fir_ffdc( const fapi2::Target<TARGET_TYPE_MCA>& i_target, const uint64_t i_calfir, const uint64_t i_phyfir ): iv_target(i_target), iv_calfir(i_calfir), iv_phyfir(i_phyfir) {} ~fir_ffdc() = default; fir_ffdc() = delete; fapi2::Target<TARGET_TYPE_MCA> iv_target; uint64_t iv_calfir; uint64_t iv_phyfir; }; /// /// @brief Check FIR bits during PHY reset /// @note For DDRPHYFIR and some MBACALFIR errors, up to and including phy reset, need to /// handle within the phy reset procedure, since we may get errors from a 'non-functional' /// magic port, which PRD can't analyze. /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode during_phy_reset( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { // Save off the current current_err fapi2::ReturnCode l_current_err(fapi2::current_err); // Error path: if we hit error before FIR check (we can see that in current_err), and FIR check also // finds something, commit first error and exit phy reset with new error from FIR check // If bit on, call out MCA with deconfig and gard, including DDRPHYFIR and MBACALFIR in FFDC // Do FIR check on all ports, so we can log errors from multiple ports that happen to have FIR bits on // Create a mask from the bits Marc wants us to check fapi2::buffer<uint64_t> l_calfir_mask; l_calfir_mask.setBit<MCA_MBACALFIRQ_MBA_RECOVERABLE_ERROR>() .setBit<MCA_MBACALFIRQ_MBA_NONRECOVERABLE_ERROR>() .setBit<MCA_MBACALFIRQ_SM_1HOT_ERR>(); fapi2::buffer<uint64_t> l_phyfir_mask; l_phyfir_mask.setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_0>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_1>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_2>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_3>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_5>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_6>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_7>(); // Go grab the MCA_MBACALFIRQ for each port. We only save off some of the FFDC information for the ports which // have FIR set. This allows us to 1) see if we have any thing to do (empty vector means we don't) and 2) gives us // all the information we need to log all the proper errors. std::vector< fir_ffdc> l_fir_ffdc; for (const auto& p : mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint64_t> l_calfir_data; fapi2::buffer<uint64_t> l_phyfir_data; fapi2::buffer<uint64_t> l_calfir_masked; fapi2::buffer<uint64_t> l_phyfir_masked; FAPI_TRY( mss::getScom(p, MCA_MBACALFIRQ, l_calfir_data) ); FAPI_TRY( mss::getScom(p, MCA_IOM_PHY0_DDRPHY_FIR_REG, l_phyfir_data) ); l_calfir_masked = l_calfir_data & l_calfir_mask; l_phyfir_masked = l_phyfir_data & l_phyfir_mask; // If either has set bits we make a little record in the vector if ((l_calfir_masked != 0) || (l_phyfir_masked != 0)) { l_fir_ffdc.push_back( fir_ffdc(p, l_calfir_data, l_phyfir_data) ); } // Clear the FIR FAPI_TRY( mss::putScom(p, MCA_MBACALFIRQ_AND, l_calfir_masked.invert()) ); FAPI_TRY( mss::putScom(p, MCA_IOM_PHY0_DDRPHY_FIR_REG_AND, l_phyfir_masked.invert()) ); } FAPI_INF("seeing FIRs set on %d ports", l_fir_ffdc.size()); // Ok, we know if l_fir_ffdc is empty that we had no FIR bits set. In this case we just return fapi2::current_err // as it represents the error state of our caller. If there were no errors seen by the caller, this will be // SUCCESS, and our caller will return SUCCESS. If there was an error, we don't disturb it, we just return // is so the caller can pass it back to it's caller (if there are FIR we'll disrupt current_err ...) if (l_fir_ffdc.size() == 0) { return l_current_err; } // Ok so if we're here we have FIR bits set. Not sure it matters what they are, we're returning them in the FFDC // and calling out/deconfig the port. First thing we do is commit whatever was in fapi2::current_err, if it's not // success. if (l_current_err != fapi2::FAPI2_RC_SUCCESS) { fapi2::logError(l_current_err); } // Now log all the errors which represent all the errors found from the ports. for (const fir_ffdc& f : l_fir_ffdc) { MSS_ASSERT_NOEXIT(false, fapi2::MSS_DDR_PHY_RESET_PORT_FIR() .set_CAL_FIR(f.iv_calfir) .set_PHY_FIR(f.iv_phyfir) .set_MCA_TARGET(f.iv_target), "Reporting FIR bits set for %s (cal: 0x%016lx phy: 0x%016lx", mss::c_str(f.iv_target), f.iv_calfir, f.iv_phyfir); } // The last thing we want to do is to create a new error code noting there were FIR set for any of the ports // during PHY reset and pass that back so it goes upstream. This will jump right to the label ... FAPI_ASSERT(false, fapi2::MSS_DDR_PHY_RESET_PORT_FIRS_REPORTED().set_MCBIST_TARGET(i_target)); fapi_try_exit: return fapi2::current_err; } } } <commit_msg>L3 support for ddr_phy_reset, termination_control<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/check.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 check.C /// @brief Subroutines for checking MSS FIR /// // *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <lib/fir/fir.H> #include <lib/fir/check.H> #include <lib/utils/assert_noexit.H> #include <generic/memory/lib/utils/find.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace check { /// /// @brief A small, local, class to hold some of the FFDC information we need from the ports /// struct fir_ffdc { /// /// @brief fir_ffdc ctor /// @param[in] the MCA target the FFDC was collected from /// @param[in] the cal FIR information /// @param[in] the phy FIR information /// fir_ffdc( const fapi2::Target<TARGET_TYPE_MCA>& i_target, const uint64_t i_calfir, const uint64_t i_phyfir ): iv_target(i_target), iv_calfir(i_calfir), iv_phyfir(i_phyfir) {} ~fir_ffdc() = default; fir_ffdc() = delete; fapi2::Target<TARGET_TYPE_MCA> iv_target; uint64_t iv_calfir; uint64_t iv_phyfir; }; /// /// @brief Check FIR bits during PHY reset /// @note For DDRPHYFIR and some MBACALFIR errors, up to and including phy reset, need to /// handle within the phy reset procedure, since we may get errors from a 'non-functional' /// magic port, which PRD can't analyze. /// @param[in] i_target the fapi2::Target MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode during_phy_reset( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { // Save off the current current_err fapi2::ReturnCode l_current_err(fapi2::current_err); // Error path: if we hit error before FIR check (we can see that in current_err), and FIR check also // finds something, commit first error and exit phy reset with new error from FIR check // If bit on, call out MCA with deconfig and gard, including DDRPHYFIR and MBACALFIR in FFDC // Do FIR check on all ports, so we can log errors from multiple ports that happen to have FIR bits on // Create a mask from the bits Marc wants us to check fapi2::buffer<uint64_t> l_calfir_mask; l_calfir_mask.setBit<MCA_MBACALFIRQ_MBA_RECOVERABLE_ERROR>() .setBit<MCA_MBACALFIRQ_MBA_NONRECOVERABLE_ERROR>() .setBit<MCA_MBACALFIRQ_SM_1HOT_ERR>(); fapi2::buffer<uint64_t> l_phyfir_mask; l_phyfir_mask.setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_0>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_1>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_2>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_3>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_5>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_6>() .setBit<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_7>(); // Go grab the MCA_MBACALFIRQ for each port. We only save off some of the FFDC information for the ports which // have FIR set. This allows us to 1) see if we have any thing to do (empty vector means we don't) and 2) gives us // all the information we need to log all the proper errors. std::vector< fir_ffdc> l_fir_ffdc; for (const auto& p : mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target)) { fapi2::buffer<uint64_t> l_calfir_data; fapi2::buffer<uint64_t> l_phyfir_data; fapi2::buffer<uint64_t> l_calfir_masked; fapi2::buffer<uint64_t> l_phyfir_masked; FAPI_TRY( mss::getScom(p, MCA_MBACALFIRQ, l_calfir_data) ); FAPI_TRY( mss::getScom(p, MCA_IOM_PHY0_DDRPHY_FIR_REG, l_phyfir_data) ); l_calfir_masked = l_calfir_data & l_calfir_mask; l_phyfir_masked = l_phyfir_data & l_phyfir_mask; // If either has set bits we make a little record in the vector if ((l_calfir_masked != 0) || (l_phyfir_masked != 0)) { l_fir_ffdc.push_back( fir_ffdc(p, l_calfir_data, l_phyfir_data) ); } // Clear the FIR FAPI_TRY( mss::putScom(p, MCA_MBACALFIRQ_AND, l_calfir_masked.invert()) ); FAPI_TRY( mss::putScom(p, MCA_IOM_PHY0_DDRPHY_FIR_REG_AND, l_phyfir_masked.invert()) ); } FAPI_INF("seeing FIRs set on %d ports", l_fir_ffdc.size()); // Ok, we know if l_fir_ffdc is empty that we had no FIR bits set. In this case we just return fapi2::current_err // as it represents the error state of our caller. If there were no errors seen by the caller, this will be // SUCCESS, and our caller will return SUCCESS. If there was an error, we don't disturb it, we just return // is so the caller can pass it back to it's caller (if there are FIR we'll disrupt current_err ...) if (l_fir_ffdc.size() == 0) { return l_current_err; } // Ok so if we're here we have FIR bits set. Not sure it matters what they are, we're returning them in the FFDC // and calling out/deconfig the port. First thing we do is commit whatever was in fapi2::current_err, if it's not // success. if (l_current_err != fapi2::FAPI2_RC_SUCCESS) { fapi2::logError(l_current_err); } // Now log all the errors which represent all the errors found from the ports. for (const fir_ffdc& f : l_fir_ffdc) { MSS_ASSERT_NOEXIT(false, fapi2::MSS_DDR_PHY_RESET_PORT_FIR() .set_CAL_FIR(f.iv_calfir) .set_PHY_FIR(f.iv_phyfir) .set_MCA_TARGET(f.iv_target), "Reporting FIR bits set for %s (cal: 0x%016lx phy: 0x%016lx", mss::c_str(f.iv_target), f.iv_calfir, f.iv_phyfir); } // The last thing we want to do is to create a new error code noting there were FIR set for any of the ports // during PHY reset and pass that back so it goes upstream. This will jump right to the label ... FAPI_ASSERT(false, fapi2::MSS_DDR_PHY_RESET_PORT_FIRS_REPORTED().set_MCBIST_TARGET(i_target)); fapi_try_exit: return fapi2::current_err; } } } <|endoftext|>
<commit_before>#include <cppunit/Test.h> #include <cppunit/TestAssert.h> #include <cppunit/extensions/HelperMacros.h> #include "goal_adaptive_resource_weight_test.h" #include "goal_adaptive_resource_weight.h" #include "timeops.h" //CPPUNIT_TEST_SUITE_REGISTRATION(GoalAdaptiveResourceWeightTest); void GoalAdaptiveResourceWeightTest::testWeight() { fprintf(stderr, "Testing weight change over 1 second\n"); weight = new GoalAdaptiveResourceWeight("test", 10, secondsInFuture(60)); double initWeight = weight->getWeight(); usleep(1000000); weight->reportSpentResource(0); weight->updateWeight(); double smallerWeight = weight->getWeight(); CPPUNIT_ASSERT(smallerWeight < initWeight); weight->reportSpentResource(5); double nextWeight = weight->getWeight(); CPPUNIT_ASSERT_DOUBLES_EQUAL(smallerWeight, nextWeight, 0.00001); weight->updateWeight(); double largerWeight = weight->getWeight(); CPPUNIT_ASSERT(largerWeight > smallerWeight); } void GoalAdaptiveResourceWeightTest::testConstantlyIncreasingWeight() { double duration = 20.0; fprintf(stderr, "Testing increasing weight over %.1f seconds\n", duration); struct timeval goalTime = secondsInFuture(duration); weight = new GoalAdaptiveResourceWeight("test", duration * (duration + 1) / 2.0, goalTime); double initWeight = weight->getWeight(); double prevWeight = initWeight; usleep(1000000); weight->reportSpentResource(0); weight->updateWeight(); CPPUNIT_ASSERT(weight->getWeight() < prevWeight); prevWeight = weight->getWeight(); for (int i = 0; i < (int) duration; ++i) { weight->reportSpentResource(duration - i + 1); usleep(1000000); //fprintf(stderr, "New weight: %.6f\n", weight->getWeight()); double curWeight = weight->getWeight(); struct timeval now; TIME(now); if (timercmp(&goalTime, &now, <)) { break; } CPPUNIT_ASSERT(prevWeight <= curWeight); prevWeight = weight->getWeight(); } CPPUNIT_ASSERT(initWeight < prevWeight); } void GoalAdaptiveResourceWeightTest::testWeightUpdatesPeriodically() { fprintf(stderr, "Testing periodic weight update\n"); weight = new GoalAdaptiveResourceWeight("test", 100, secondsInFuture(60)); // reduce the weight with zero-spending periods int no_spend_seconds = 5; int num_updates = 100; fprintf(stderr, "Spending nothing for %d seconds\n", no_spend_seconds); for (int i = 0; i < num_updates; ++i) { weight->reportSpentResource(0); weight->updateWeight(); usleep((no_spend_seconds * 1000000) / num_updates);; } fprintf(stderr, "Waiting 60 seconds for expected weight update\n"); double curWeight = weight->getWeight(); weight->reportSpentResource(100); struct timeval end = secondsInFuture(60); struct timeval now; TIME(now); while (timercmp(&now, &end, <)) { if (weight->getWeight() - curWeight > 0.1) { return; } usleep(1000000); TIME(now); } CPPUNIT_FAIL("Weight should have been updated"); } struct timeval GoalAdaptiveResourceWeightTest::secondsInFuture(double seconds) { struct timeval future; TIME(future); struct timeval addend = {(int)seconds, 0}; addend.tv_usec = (suseconds_t) ((seconds - addend.tv_sec) * 1000000.0); timeradd(&future, &addend, &future); return future; } void GoalAdaptiveResourceWeightTest::setUp() { weight = NULL; } void GoalAdaptiveResourceWeightTest::tearDown() { delete weight; weight = NULL; } <commit_msg>Whoops, forgot to uncomment the slower tests.<commit_after>#include <cppunit/Test.h> #include <cppunit/TestAssert.h> #include <cppunit/extensions/HelperMacros.h> #include "goal_adaptive_resource_weight_test.h" #include "goal_adaptive_resource_weight.h" #include "timeops.h" CPPUNIT_TEST_SUITE_REGISTRATION(GoalAdaptiveResourceWeightTest); void GoalAdaptiveResourceWeightTest::testWeight() { fprintf(stderr, "Testing weight change over 1 second\n"); weight = new GoalAdaptiveResourceWeight("test", 10, secondsInFuture(60)); double initWeight = weight->getWeight(); usleep(1000000); weight->reportSpentResource(0); weight->updateWeight(); double smallerWeight = weight->getWeight(); CPPUNIT_ASSERT(smallerWeight < initWeight); weight->reportSpentResource(5); double nextWeight = weight->getWeight(); CPPUNIT_ASSERT_DOUBLES_EQUAL(smallerWeight, nextWeight, 0.00001); weight->updateWeight(); double largerWeight = weight->getWeight(); CPPUNIT_ASSERT(largerWeight > smallerWeight); } void GoalAdaptiveResourceWeightTest::testConstantlyIncreasingWeight() { double duration = 20.0; fprintf(stderr, "Testing increasing weight over %.1f seconds\n", duration); struct timeval goalTime = secondsInFuture(duration); weight = new GoalAdaptiveResourceWeight("test", duration * (duration + 1) / 2.0, goalTime); double initWeight = weight->getWeight(); double prevWeight = initWeight; usleep(1000000); weight->reportSpentResource(0); weight->updateWeight(); CPPUNIT_ASSERT(weight->getWeight() < prevWeight); prevWeight = weight->getWeight(); for (int i = 0; i < (int) duration; ++i) { weight->reportSpentResource(duration - i + 1); usleep(1000000); //fprintf(stderr, "New weight: %.6f\n", weight->getWeight()); double curWeight = weight->getWeight(); struct timeval now; TIME(now); if (timercmp(&goalTime, &now, <)) { break; } CPPUNIT_ASSERT(prevWeight <= curWeight); prevWeight = weight->getWeight(); } CPPUNIT_ASSERT(initWeight < prevWeight); } void GoalAdaptiveResourceWeightTest::testWeightUpdatesPeriodically() { fprintf(stderr, "Testing periodic weight update\n"); weight = new GoalAdaptiveResourceWeight("test", 100, secondsInFuture(60)); // reduce the weight with zero-spending periods int no_spend_seconds = 5; int num_updates = 100; fprintf(stderr, "Spending nothing for %d seconds\n", no_spend_seconds); for (int i = 0; i < num_updates; ++i) { weight->reportSpentResource(0); weight->updateWeight(); usleep((no_spend_seconds * 1000000) / num_updates);; } fprintf(stderr, "Waiting 60 seconds for expected weight update\n"); double curWeight = weight->getWeight(); weight->reportSpentResource(100); struct timeval end = secondsInFuture(60); struct timeval now; TIME(now); while (timercmp(&now, &end, <)) { if (weight->getWeight() - curWeight > 0.1) { return; } usleep(1000000); TIME(now); } CPPUNIT_FAIL("Weight should have been updated"); } struct timeval GoalAdaptiveResourceWeightTest::secondsInFuture(double seconds) { struct timeval future; TIME(future); struct timeval addend = {(int)seconds, 0}; addend.tv_usec = (suseconds_t) ((seconds - addend.tv_sec) * 1000000.0); timeradd(&future, &addend, &future); return future; } void GoalAdaptiveResourceWeightTest::setUp() { weight = NULL; } void GoalAdaptiveResourceWeightTest::tearDown() { delete weight; weight = NULL; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_subroutine_executor.H $ */ /* */ /* 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 fapi2_sub_executor.H /// /// @brief Defines the FAPI2 Subroutine Executor Macro. /// /// The FAPI2 Subroutine Executor macro is called to execute a chip-op /// or subroutine. /// #ifndef FAPI2SUBEXECUTOR_H_ #define FAPI2SUBEXECUTOR_H_ #include <plat_sub_executor.H> /** * @brief Subroutine Executor macro * * This macro calls a PLAT macro which will do any platform specific work to * execute the Subroutine (e.g. dlopening a shared library) */ #define FAPI_CALL_SUBROUTINE(RC, CHIPOP, FUNC, _args_...) \ FAPI_PLAT_CALL_SUBROUTINE(RC, CHIPOP, FUNC, ##_args_) #endif // FAPI2SUBEXECUTOR_H_ <commit_msg>Remove CHIPOP parameter from FAPI_CALL_SUBROUTINE<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_subroutine_executor.H $ */ /* */ /* 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 fapi2_sub_executor.H /// /// @brief Defines the FAPI2 Subroutine Executor Macro. /// /// The FAPI2 Subroutine Executor macro is called to execute a chip-op /// or subroutine. /// #ifndef FAPI2SUBEXECUTOR_H_ #define FAPI2SUBEXECUTOR_H_ #include <subroutine_executor.H> /** * @brief Subroutine Executor macro * * This macro calls a PLAT macro which will do any platform specific work to * execute the Subroutine (e.g. dlopening a shared library) */ #define FAPI_CALL_SUBROUTINE(RC, FUNC, _args_...) \ FAPI_PLAT_CALL_SUBROUTINE(RC, FUNC, ##_args_) #endif // FAPI2SUBEXECUTOR_H_ <|endoftext|>
<commit_before>#include "consoleUtil.h" #include "Deck.h" #include "TexasHoldem.h" using namespace std; #define TABLE_X 10 #define TABLE_Y (COM_Y+PLAYER_HT+1) #define TABLE_HT 3 #define TABLE_WD (2+2*5+1*4+2) #define PLAYER_HT 4 #define PLAYER_WD (1+8+1) // " COMPUTER ", " HUMAN " #define COM_X (TABLE_X + (TABLE_WD - PLAYER_WD) / 2) #define COM_Y 2 #define COM_BET_X (COM_X + PLAYER_WD + 1) #define COM_BET_Y (COM_Y + 1) #define MAN_X COM_X #define MAN_Y (TABLE_Y+TABLE_HT+1) #define MAN_BET_X (MAN_X + PLAYER_WD + 1) #define MAN_BET_Y (MAN_Y + 1) #define MENU_X 2 #define MENU_Y (MAN_Y+PLAYER_HT+1) #define POT_X (TABLE_X + TABLE_WD + 1) #define POT_Y (TABLE_Y + 1) TexasHoldem g_table; int g_comIX; int g_manIX; void draw_card(int x, int y, Card c) { setCursorPos(x, y); } void draw_com() { setCursorPos(COM_X, COM_Y); setColor(COL_BLACK, COL_YELLOW); cout << " COMPUTER "; setColor(COL_GRAY, COL_BLACK); setCursorPos(COM_X, COM_Y+1); cout << "chip:" << g_table.chip(g_comIX); if( g_comIX == g_table.dealerIX() ) { setCursorPos(COM_X - 2, COM_Y); cout << "D"; } if( g_comIX == g_table.BBIX() ) { setCursorPos(COM_X - 3, COM_Y + 1); cout << "BB"; } if( g_comIX == g_table.SBIX() ) { setCursorPos(COM_X - 3, COM_Y + 1); cout << "SB"; } setCursorPos(COM_BET_X, COM_BET_Y); cout << "bet:" << g_table.bet(g_comIX) << " "; setColor(COL_BLACK, COL_CYAN); setCursorPos(COM_X, COM_Y+2); cout << " "; setCursorPos(COM_X+3, COM_Y+2); cout << " "; } void draw_human() { setCursorPos(MAN_X, MAN_Y); setColor(COL_BLACK, COL_YELLOW); cout << " HUMAN "; setColor(COL_GRAY, COL_BLACK); setCursorPos(MAN_X, MAN_Y+1); cout << "chip:" << g_table.chip(g_manIX); setCursorPos(MAN_BET_X, MAN_BET_Y); cout << "bet:" << g_table.bet(g_manIX) << " "; if( g_manIX == g_table.dealerIX() ) { setCursorPos(MAN_X - 2, MAN_Y); cout << "D"; } if( g_manIX == g_table.BBIX() ) { setCursorPos(MAN_X - 3, MAN_Y + 1); cout << "BB"; } if( g_manIX == g_table.SBIX() ) { setCursorPos(MAN_X - 3, MAN_Y + 1); cout << "SB"; } Card c1, c2; g_table.getHoleCards(0, c1, c2); if( c1.m_suit == Card::SPADES || c1.m_suit == Card::CLUBS ) setColor(COL_BLACK, COL_WHITE); else setColor(COL_RED, COL_WHITE); setCursorPos(MAN_X, MAN_Y+2); coutW(c1.toStringW()); //cout << " "; if( c2.m_suit == Card::SPADES || c2.m_suit == Card::CLUBS ) setColor(COL_BLACK, COL_WHITE); else setColor(COL_RED, COL_WHITE); setCursorPos(MAN_X+3, MAN_Y+2); coutW(c2.toStringW()); //cout << "?? ??"; } void draw_table() { setColor(COL_WHITE, COL_DARK_GREEN); for(int k = 0; k < TABLE_HT; ++k) { setCursorPos(TABLE_X, k + TABLE_Y); for(int i = 0; i < TABLE_WD; ++i) cout << " "; } setCursorPos(TABLE_X + 2, TABLE_Y + 1); cout << "?? ?? ?? ?? ??"; setColor(COL_GRAY, COL_BLACK); setCursorPos(POT_X, POT_Y); cout << "Pot:" << g_table.pot() << " "; } void draw_menu() { setCursorPos(MENU_X, MENU_Y); setColor(COL_GRAY, COL_BLACK); cout << "[Fold] [Check] [Call] [Raise] 0"; } int main() { g_table.addPlayer(Player("YOU", 200)); g_manIX = 0; g_table.addPlayer(Player("COM", 200, /*comp:*/true)); g_comIX = 1; g_table.setDealer(); g_table.dealHoleCards(); setColor(COL_BLACK, COL_WHITE); setCursorPos(5, 0); cout << "*** Texas Hold'em Poker ***"; draw_com(); draw_human(); draw_table(); draw_menu(); getchar(); return 0; } /* e[uőR~jeBJ[hɍ킹 fB[}[N\ BB, SB }[N\ `bv𐳂\ pot \ evC[̃xbgz\ mt19937 ɕύX J[h\Fwiɍ or Ԃŕ` ĂJ[h̓VAŕ\ */ <commit_msg>◎ メニューをデータ化 ◎ 左右キーでメニュー選択可能に<commit_after>#include "consoleUtil.h" #include "Deck.h" #include "TexasHoldem.h" #include <windows.h> #include <conio.h> using namespace std; #define TABLE_X 10 #define TABLE_Y (COM_Y+PLAYER_HT+1) #define TABLE_HT 3 #define TABLE_WD (2+2*5+1*4+2) #define PLAYER_HT 4 #define PLAYER_WD (1+8+1) // " COMPUTER ", " HUMAN " #define COM_X (TABLE_X + (TABLE_WD - PLAYER_WD) / 2) #define COM_Y 2 #define COM_BET_X (COM_X + PLAYER_WD + 1) #define COM_BET_Y (COM_Y + 1) #define MAN_X COM_X #define MAN_Y (TABLE_Y+TABLE_HT+1) #define MAN_BET_X (MAN_X + PLAYER_WD + 1) #define MAN_BET_Y (MAN_Y + 1) #define POT_X (TABLE_X + TABLE_WD + 1) #define POT_Y (TABLE_Y + 1) #define MENU_X 2 #define MENU_Y (MAN_Y+PLAYER_HT+1) #define N_MENU 3 // j[I #define KEY_LEFT 0x4b #define KEY_RIGHT 0x4d TexasHoldem g_table; int g_comIX; int g_manIX; int g_menuIX; // IĂ郁j[IX const char *g_menu[] = { "FOLD", "CHECK/CALL", "RAISE" }; void draw_card(int x, int y, Card c) { setCursorPos(x, y); } void draw_com() { setCursorPos(COM_X, COM_Y); setColor(COL_BLACK, COL_YELLOW); cout << " COMPUTER "; setColor(COL_GRAY, COL_BLACK); setCursorPos(COM_X, COM_Y+1); cout << "chip:" << g_table.chip(g_comIX); if( g_comIX == g_table.dealerIX() ) { setCursorPos(COM_X - 2, COM_Y); cout << "D"; } if( g_comIX == g_table.BBIX() ) { setCursorPos(COM_X - 3, COM_Y + 1); cout << "BB"; } if( g_comIX == g_table.SBIX() ) { setCursorPos(COM_X - 3, COM_Y + 1); cout << "SB"; } setCursorPos(COM_BET_X, COM_BET_Y); cout << "bet:" << g_table.bet(g_comIX) << " "; setColor(COL_BLACK, COL_CYAN); setCursorPos(COM_X, COM_Y+2); cout << " "; setCursorPos(COM_X+3, COM_Y+2); cout << " "; } void draw_human() { setCursorPos(MAN_X, MAN_Y); setColor(COL_BLACK, COL_YELLOW); cout << " HUMAN "; setColor(COL_GRAY, COL_BLACK); setCursorPos(MAN_X, MAN_Y+1); cout << "chip:" << g_table.chip(g_manIX); setCursorPos(MAN_BET_X, MAN_BET_Y); cout << "bet:" << g_table.bet(g_manIX) << " "; if( g_manIX == g_table.dealerIX() ) { setCursorPos(MAN_X - 2, MAN_Y); cout << "D"; } if( g_manIX == g_table.BBIX() ) { setCursorPos(MAN_X - 3, MAN_Y + 1); cout << "BB"; } if( g_manIX == g_table.SBIX() ) { setCursorPos(MAN_X - 3, MAN_Y + 1); cout << "SB"; } Card c1, c2; g_table.getHoleCards(0, c1, c2); if( c1.m_suit == Card::SPADES || c1.m_suit == Card::CLUBS ) setColor(COL_BLACK, COL_WHITE); else setColor(COL_RED, COL_WHITE); setCursorPos(MAN_X, MAN_Y+2); coutW(c1.toStringW()); //cout << " "; if( c2.m_suit == Card::SPADES || c2.m_suit == Card::CLUBS ) setColor(COL_BLACK, COL_WHITE); else setColor(COL_RED, COL_WHITE); setCursorPos(MAN_X+3, MAN_Y+2); coutW(c2.toStringW()); //cout << "?? ??"; } void draw_table() { setColor(COL_WHITE, COL_DARK_GREEN); for(int k = 0; k < TABLE_HT; ++k) { setCursorPos(TABLE_X, k + TABLE_Y); for(int i = 0; i < TABLE_WD; ++i) cout << " "; } setCursorPos(TABLE_X + 2, TABLE_Y + 1); cout << "?? ?? ?? ?? ??"; setColor(COL_GRAY, COL_BLACK); setCursorPos(POT_X, POT_Y); cout << "Pot:" << g_table.pot() << " "; } void draw_menu() { setCursorPos(MENU_X, MENU_Y); for (int i = 0; i < N_MENU; ++i) { if( i == g_menuIX ) setColor(COL_BLACK, COL_WHITE); else setColor(COL_GRAY, COL_BLACK); cout << "[" << g_menu[i] << "]"; setColor(COL_GRAY, COL_BLACK); cout << " "; } //setColor(COL_GRAY, COL_BLACK); //cout << "[Fold] [Check] [Call] [Raise] 0"; } int main() { g_table.addPlayer(Player("YOU", 200)); g_manIX = 0; g_table.addPlayer(Player("COM", 200, /*comp:*/true)); g_comIX = 1; g_table.setDealer(); g_table.dealHoleCards(); setColor(COL_BLACK, COL_WHITE); setCursorPos(5, 0); cout << "*** Texas Hold'em Poker ***"; draw_com(); draw_human(); draw_table(); for (;;) { draw_menu(); int ch = _getch(); if( ch == 'Q' || ch == 'q' ) break; if( ch == 0xe0 ) { ch = _getch(); if( ch == KEY_LEFT && g_menuIX != 0 ) --g_menuIX; else if( ch == KEY_RIGHT && g_menuIX < N_MENU - 1) ++g_menuIX; } if( ch == '\r' || ch == '\n' ) { // j[m break; } } //getchar(); return 0; } /* e[uőR~jeBJ[hɍ킹 fB[}[N\ BB, SB }[N\ `bv𐳂\ pot \ evC[̃xbgz\ mt19937 ɕύX J[h\Fwiɍ or Ԃŕ` ĂJ[h̓VAŕ\ j[f[^ EL[Ńj[I”\ */ <|endoftext|>
<commit_before><commit_msg>Need <boost/functional/hash.hpp> for boost::hash<commit_after><|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include <cstdint> #include <cstring> #include <iostream> #include <stdexcept> #include <adios2.h> #include <gtest/gtest.h> #include "TestData.h" class SstReadTest : public ::testing::Test { public: SstReadTest() = default; }; adios2::Params engineParams = {}; // parsed from command line int TimeGapExpected = 0; int IgnoreTimeGap = 1; // Number of steps std::size_t NSteps = 200; static std::string Trim(std::string &str) { size_t first = str.find_first_not_of(' '); size_t last = str.find_last_not_of(' '); return str.substr(first, (last - first + 1)); } /* * Engine parameters spec is a poor-man's JSON. name:value pairs are separated * by commas. White space is trimmed off front and back. No quotes or anything * fancy allowed. */ static adios2::Params ParseEngineParams(std::string Input) { std::istringstream ss(Input); std::string Param; adios2::Params Ret = {}; while (std::getline(ss, Param, ',')) { std::istringstream ss2(Param); std::string ParamName; std::string ParamValue; std::getline(ss2, ParamName, ':'); if (!std::getline(ss2, ParamValue, ':')) { throw std::invalid_argument("Engine parameter \"" + Param + "\" missing value"); } Ret[Trim(ParamName)] = Trim(ParamValue); } return Ret; } // ADIOS2 Sst read TEST_F(SstReadTest, ADIOS2SstRead) { // Each process would write a 1x8 array and all processes would // form a mpiSize * Nx 1D array const std::string fname = "ADIOS2SstServer"; int mpiRank = 0, mpiSize = 1; int TimeGapDetected = 0; #ifdef ADIOS2_HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); #endif // Write test data using ADIOS2 #ifdef ADIOS2_HAVE_MPI adios2::ADIOS adios(MPI_COMM_WORLD, adios2::DebugON); #else adios2::ADIOS adios(true); #endif adios2::IO io = adios.DeclareIO("TestIO"); // Create the Engine io.SetEngine("Sst"); io.SetParameters(engineParams); adios2::Engine engine = io.Open(fname, adios2::Mode::Read); unsigned int t = -1; std::vector<std::time_t> write_times; while (engine.BeginStep() == adios2::StepStatus::OK) { const size_t currentStep = engine.CurrentStep(); if (t == -1) t = currentStep; // starting out EXPECT_EQ(currentStep, static_cast<size_t>(t)); int writerSize; auto var_i8 = io.InquireVariable<int8_t>("i8"); EXPECT_TRUE(var_i8); ASSERT_EQ(var_i8.ShapeID(), adios2::ShapeID::GlobalArray); /* must be a multiple of Nx */ ASSERT_EQ(var_i8.Shape()[0] % Nx, 0); /* take the first size as something that gives us writer size */ writerSize = var_i8.Shape()[0] / 10; auto var_i16 = io.InquireVariable<int16_t>("i16"); EXPECT_TRUE(var_i16); ASSERT_EQ(var_i16.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i16.Shape()[0], writerSize * Nx); auto var_i32 = io.InquireVariable<int32_t>("i32"); EXPECT_TRUE(var_i32); ASSERT_EQ(var_i32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i32.Shape()[0], writerSize * Nx); auto var_i64 = io.InquireVariable<int64_t>("i64"); EXPECT_TRUE(var_i64); ASSERT_EQ(var_i64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i64.Shape()[0], writerSize * Nx); auto var_r32 = io.InquireVariable<float>("r32"); EXPECT_TRUE(var_r32); ASSERT_EQ(var_r32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r32.Shape()[0], writerSize * Nx); auto var_r64 = io.InquireVariable<double>("r64"); EXPECT_TRUE(var_r64); ASSERT_EQ(var_r64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64.Shape()[0], writerSize * Nx); auto var_r64_2d = io.InquireVariable<double>("r64_2d"); EXPECT_TRUE(var_r64_2d); ASSERT_EQ(var_r64_2d.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64_2d.Shape()[0], writerSize * Nx); ASSERT_EQ(var_r64_2d.Shape()[1], 2); auto var_r64_2d_rev = io.InquireVariable<double>("r64_2d_rev"); EXPECT_TRUE(var_r64_2d_rev); ASSERT_EQ(var_r64_2d_rev.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64_2d_rev.Shape()[0], 2); ASSERT_EQ(var_r64_2d_rev.Shape()[1], writerSize * Nx); auto var_time = io.InquireVariable<int64_t>("time"); EXPECT_TRUE(var_time); ASSERT_EQ(var_time.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_time.Shape()[0], writerSize); long unsigned int myStart = (writerSize * Nx / mpiSize) * mpiRank; long unsigned int myLength = ((writerSize * Nx + mpiSize - 1) / mpiSize); if (myStart + myLength > writerSize * Nx) { myLength = writerSize * Nx - myStart; } const adios2::Dims start{myStart}; const adios2::Dims count{myLength}; const adios2::Dims start2{myStart, 0}; const adios2::Dims count2{myLength, 2}; const adios2::Dims start3{0, myStart}; const adios2::Dims count3{2, myLength}; const adios2::Dims start_time{myStart}; const adios2::Dims count_time{1}; const adios2::Box<adios2::Dims> sel(start, count); const adios2::Box<adios2::Dims> sel2(start2, count2); const adios2::Box<adios2::Dims> sel3(start3, count3); const adios2::Box<adios2::Dims> sel_time(start_time, count_time); var_i8.SetSelection(sel); var_i16.SetSelection(sel); var_i32.SetSelection(sel); var_i64.SetSelection(sel); var_r32.SetSelection(sel); var_r64.SetSelection(sel); var_r64_2d.SetSelection(sel2); var_r64_2d_rev.SetSelection(sel3); var_time.SetSelection(sel_time); in_I8.reserve(myLength); in_I16.reserve(myLength); in_I32.reserve(myLength); in_I64.reserve(myLength); in_R32.reserve(myLength); in_R64.reserve(myLength); in_R64_2d.reserve(myLength * 2); in_R64_2d_rev.reserve(myLength * 2); engine.Get(var_i8, in_I8.data()); engine.Get(var_i16, in_I16.data()); engine.Get(var_i32, in_I32.data()); engine.Get(var_i64, in_I64.data()); engine.Get(var_r32, in_R32.data()); engine.Get(var_r64, in_R64.data()); engine.Get(var_r64_2d, in_R64_2d.data()); engine.Get(var_r64_2d_rev, in_R64_2d_rev.data()); std::time_t write_time; engine.Get(var_time, (int64_t *)&write_time); try { engine.EndStep(); EXPECT_EQ(validateSstTestData(myStart, myLength, t), 0); write_times.push_back(write_time); } catch (...) {std::cout << "Exception in EndStep, writer failed";} ++t; if (NSteps != -1) { NSteps--; if (NSteps == 0) { break; } } } if ((write_times.back() - write_times.front()) > 1) { TimeGapDetected++; } if (!IgnoreTimeGap) { if (TimeGapExpected) { EXPECT_TRUE(TimeGapDetected); } else { EXPECT_FALSE(TimeGapDetected); } } // Close the file engine.Close(); } //****************************************************************************** // main //****************************************************************************** int main(int argc, char **argv) { #ifdef ADIOS2_HAVE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); while ((argc > 1) && (argv[1][0] == '-')) { if (std::string(argv[1]) == "--num_steps") { std::istringstream ss(argv[2]); if (!(ss >> NSteps)) std::cerr << "Invalid number for num_steps " << argv[1] << '\n'; argv++; argc--; std::cout << "Done, Nsteps was " << NSteps << " argc now " << argc << std::endl; } else if (std::string(argv[1]) == "--expect_time_gap") { TimeGapExpected++; IgnoreTimeGap = 0; } else if (std::string(argv[1]) == "--expect_contiguous_time") { TimeGapExpected = 0; IgnoreTimeGap = 0; } else if (std::string(argv[1]) == "--ignore_time_gap") { IgnoreTimeGap++; } else { throw std::invalid_argument("Unknown argument \"" + std::string(argv[1]) + "\""); } argv++; argc--; } if (argc > 1) { engineParams = ParseEngineParams(argv[1]); } result = RUN_ALL_TESTS(); #ifdef ADIOS2_HAVE_MPI MPI_Finalize(); #endif return result; } <commit_msg>clang-format<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include <cstdint> #include <cstring> #include <iostream> #include <stdexcept> #include <adios2.h> #include <gtest/gtest.h> #include "TestData.h" class SstReadTest : public ::testing::Test { public: SstReadTest() = default; }; adios2::Params engineParams = {}; // parsed from command line int TimeGapExpected = 0; int IgnoreTimeGap = 1; // Number of steps std::size_t NSteps = 200; static std::string Trim(std::string &str) { size_t first = str.find_first_not_of(' '); size_t last = str.find_last_not_of(' '); return str.substr(first, (last - first + 1)); } /* * Engine parameters spec is a poor-man's JSON. name:value pairs are separated * by commas. White space is trimmed off front and back. No quotes or anything * fancy allowed. */ static adios2::Params ParseEngineParams(std::string Input) { std::istringstream ss(Input); std::string Param; adios2::Params Ret = {}; while (std::getline(ss, Param, ',')) { std::istringstream ss2(Param); std::string ParamName; std::string ParamValue; std::getline(ss2, ParamName, ':'); if (!std::getline(ss2, ParamValue, ':')) { throw std::invalid_argument("Engine parameter \"" + Param + "\" missing value"); } Ret[Trim(ParamName)] = Trim(ParamValue); } return Ret; } // ADIOS2 Sst read TEST_F(SstReadTest, ADIOS2SstRead) { // Each process would write a 1x8 array and all processes would // form a mpiSize * Nx 1D array const std::string fname = "ADIOS2SstServer"; int mpiRank = 0, mpiSize = 1; int TimeGapDetected = 0; #ifdef ADIOS2_HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); #endif // Write test data using ADIOS2 #ifdef ADIOS2_HAVE_MPI adios2::ADIOS adios(MPI_COMM_WORLD, adios2::DebugON); #else adios2::ADIOS adios(true); #endif adios2::IO io = adios.DeclareIO("TestIO"); // Create the Engine io.SetEngine("Sst"); io.SetParameters(engineParams); adios2::Engine engine = io.Open(fname, adios2::Mode::Read); unsigned int t = -1; std::vector<std::time_t> write_times; while (engine.BeginStep() == adios2::StepStatus::OK) { const size_t currentStep = engine.CurrentStep(); if (t == -1) t = currentStep; // starting out EXPECT_EQ(currentStep, static_cast<size_t>(t)); int writerSize; auto var_i8 = io.InquireVariable<int8_t>("i8"); EXPECT_TRUE(var_i8); ASSERT_EQ(var_i8.ShapeID(), adios2::ShapeID::GlobalArray); /* must be a multiple of Nx */ ASSERT_EQ(var_i8.Shape()[0] % Nx, 0); /* take the first size as something that gives us writer size */ writerSize = var_i8.Shape()[0] / 10; auto var_i16 = io.InquireVariable<int16_t>("i16"); EXPECT_TRUE(var_i16); ASSERT_EQ(var_i16.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i16.Shape()[0], writerSize * Nx); auto var_i32 = io.InquireVariable<int32_t>("i32"); EXPECT_TRUE(var_i32); ASSERT_EQ(var_i32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i32.Shape()[0], writerSize * Nx); auto var_i64 = io.InquireVariable<int64_t>("i64"); EXPECT_TRUE(var_i64); ASSERT_EQ(var_i64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i64.Shape()[0], writerSize * Nx); auto var_r32 = io.InquireVariable<float>("r32"); EXPECT_TRUE(var_r32); ASSERT_EQ(var_r32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r32.Shape()[0], writerSize * Nx); auto var_r64 = io.InquireVariable<double>("r64"); EXPECT_TRUE(var_r64); ASSERT_EQ(var_r64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64.Shape()[0], writerSize * Nx); auto var_r64_2d = io.InquireVariable<double>("r64_2d"); EXPECT_TRUE(var_r64_2d); ASSERT_EQ(var_r64_2d.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64_2d.Shape()[0], writerSize * Nx); ASSERT_EQ(var_r64_2d.Shape()[1], 2); auto var_r64_2d_rev = io.InquireVariable<double>("r64_2d_rev"); EXPECT_TRUE(var_r64_2d_rev); ASSERT_EQ(var_r64_2d_rev.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64_2d_rev.Shape()[0], 2); ASSERT_EQ(var_r64_2d_rev.Shape()[1], writerSize * Nx); auto var_time = io.InquireVariable<int64_t>("time"); EXPECT_TRUE(var_time); ASSERT_EQ(var_time.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_time.Shape()[0], writerSize); long unsigned int myStart = (writerSize * Nx / mpiSize) * mpiRank; long unsigned int myLength = ((writerSize * Nx + mpiSize - 1) / mpiSize); if (myStart + myLength > writerSize * Nx) { myLength = writerSize * Nx - myStart; } const adios2::Dims start{myStart}; const adios2::Dims count{myLength}; const adios2::Dims start2{myStart, 0}; const adios2::Dims count2{myLength, 2}; const adios2::Dims start3{0, myStart}; const adios2::Dims count3{2, myLength}; const adios2::Dims start_time{myStart}; const adios2::Dims count_time{1}; const adios2::Box<adios2::Dims> sel(start, count); const adios2::Box<adios2::Dims> sel2(start2, count2); const adios2::Box<adios2::Dims> sel3(start3, count3); const adios2::Box<adios2::Dims> sel_time(start_time, count_time); var_i8.SetSelection(sel); var_i16.SetSelection(sel); var_i32.SetSelection(sel); var_i64.SetSelection(sel); var_r32.SetSelection(sel); var_r64.SetSelection(sel); var_r64_2d.SetSelection(sel2); var_r64_2d_rev.SetSelection(sel3); var_time.SetSelection(sel_time); in_I8.reserve(myLength); in_I16.reserve(myLength); in_I32.reserve(myLength); in_I64.reserve(myLength); in_R32.reserve(myLength); in_R64.reserve(myLength); in_R64_2d.reserve(myLength * 2); in_R64_2d_rev.reserve(myLength * 2); engine.Get(var_i8, in_I8.data()); engine.Get(var_i16, in_I16.data()); engine.Get(var_i32, in_I32.data()); engine.Get(var_i64, in_I64.data()); engine.Get(var_r32, in_R32.data()); engine.Get(var_r64, in_R64.data()); engine.Get(var_r64_2d, in_R64_2d.data()); engine.Get(var_r64_2d_rev, in_R64_2d_rev.data()); std::time_t write_time; engine.Get(var_time, (int64_t *)&write_time); try { engine.EndStep(); EXPECT_EQ(validateSstTestData(myStart, myLength, t), 0); write_times.push_back(write_time); } catch (...) { std::cout << "Exception in EndStep, writer failed"; } ++t; if (NSteps != -1) { NSteps--; if (NSteps == 0) { break; } } } if ((write_times.back() - write_times.front()) > 1) { TimeGapDetected++; } if (!IgnoreTimeGap) { if (TimeGapExpected) { EXPECT_TRUE(TimeGapDetected); } else { EXPECT_FALSE(TimeGapDetected); } } // Close the file engine.Close(); } //****************************************************************************** // main //****************************************************************************** int main(int argc, char **argv) { #ifdef ADIOS2_HAVE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); while ((argc > 1) && (argv[1][0] == '-')) { if (std::string(argv[1]) == "--num_steps") { std::istringstream ss(argv[2]); if (!(ss >> NSteps)) std::cerr << "Invalid number for num_steps " << argv[1] << '\n'; argv++; argc--; std::cout << "Done, Nsteps was " << NSteps << " argc now " << argc << std::endl; } else if (std::string(argv[1]) == "--expect_time_gap") { TimeGapExpected++; IgnoreTimeGap = 0; } else if (std::string(argv[1]) == "--expect_contiguous_time") { TimeGapExpected = 0; IgnoreTimeGap = 0; } else if (std::string(argv[1]) == "--ignore_time_gap") { IgnoreTimeGap++; } else { throw std::invalid_argument("Unknown argument \"" + std::string(argv[1]) + "\""); } argv++; argc--; } if (argc > 1) { engineParams = ParseEngineParams(argv[1]); } result = RUN_ALL_TESTS(); #ifdef ADIOS2_HAVE_MPI MPI_Finalize(); #endif return result; } <|endoftext|>
<commit_before>// Author: Josh Haberman (jhaberman@gmail.com) // This code is in the public domain. #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <iomanip> #include <gmpxx.h> using namespace std; mpz_class bitat(int bit) { return mpz_class(1) << bit; } mpz_class mask(int bits) { return bitat(bits) - 1; } void dumpfp(mpz_class whole, mpz_class numer, int denom_lg2) { mpz_class denom = bitat(denom_lg2); while ((numer & 0x1) == 0 && (denom & 0x1) == 0) { numer >>= 1; denom >>= 1; denom_lg2--; } mpz_class digits = 10; again: mpz_class product = numer * digits; mpz_class fraction = product / denom; mpz_class product2 = fraction * denom; if (product2 != product) { digits *= 10; goto again; } if (whole > 0) cout << whole << " + "; cout << numer << "/2^" << denom_lg2; cout << " (" << whole << "." << fraction << ")"; } void dumpfp2(mpz_class raw, int sig_bits, int exp_bits) { // In these calculations we rely on the general properties of IEEE floating // point: X bits of significant, followed by an implicit "1", followed by // Y bits of exponent and a sign bit. The exponent is expected to be biased // by half of the exponent's domain. // // Note that this will *not* work for "long double" because it does not use // an implicit 1 in its significand. mpz_class sig_scale = bitat(sig_bits), sig = raw & mask(sig_bits), sig2 = sig_scale + sig, expbias = mask(exp_bits - 1); int sign = mpz_class(raw >> (sig_bits + exp_bits)).get_si(), exp = mpz_class(raw >> sig_bits & mask(exp_bits)).get_si(), exp2 = mpz_class(exp - expbias).get_si(); cout << " raw = 0x" << hex << raw << "\n"; cout << " sign = 0x" << hex << sign << "\n"; if (exp2 == (expbias + 1)) { cout << " exponent = 0x" << hex << exp << " (NaN or Infinity)\n"; if (sig != 0) cout << " significand = " << hex << sig << " (non-zero indicates NaN)\n"; else cout << " significand = " << hex << sig << " (zero indicates Infinity)\n"; } else { cout << " exponent = 0x" << hex << exp << " (" << dec << exp2 << ")\n"; cout << " significand = 0x" << hex << sig << dec << "\n"; cout << "\n"; cout << " VALUE CALCULATION =\n"; cout << " significand ("; dumpfp(1, sig, sig_bits); cout << ")\n"; cout << " * 2^exponent (2^" << exp2 << ")\n"; cout << " = VALUE ("; if (exp2 >= sig_bits) { cout << (sig2 << (exp2 - sig_bits)); } else { int split = sig_bits - exp2; mpz_class whole = sig2 >> split; mpz_class frac = sig2 - (whole << split); dumpfp(whole, frac, split); } cout << ")"; } cout << "\n\n"; } mpz_class getraw(void *val, size_t size) { unsigned char bytes[128]; memcpy(bytes, val, size); mpz_class raw(0); for (int i = 0; i < size; i++) { raw *= 256; raw += bytes[size-i-1]; } return raw; } void dumpfloat(float x) { printf("Single Precision (IEEE 32-bit):\n"); dumpfp2(getraw(&x, sizeof(float)), 23, 8); } void dumpdouble(double x) { printf("Double Precision (IEEE 64-bit):\n"); dumpfp2(getraw(&x, sizeof(double)), 52, 11); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: dumpfp 0.12345\n"); return 1; } long double x = strtold(argv[1], NULL); dumpfloat(x); dumpdouble(x); return 0; } <commit_msg>Added some comments.<commit_after>// Author: Josh Haberman (jhaberman@gmail.com) // This code is in the public domain. #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <iomanip> #include <gmpxx.h> using namespace std; mpz_class bitat(int bit) { return mpz_class(1) << bit; } mpz_class mask(int bits) { return bitat(bits) - 1; } void dumpfp(mpz_class whole, mpz_class numer, int denom_lg2) { mpz_class denom = bitat(denom_lg2); // Reduce the fraction for nicer display. while ((numer & 0x1) == 0 && (denom & 0x1) == 0) { numer >>= 1; denom >>= 1; denom_lg2--; } // Pick the fewest number of digits that will precisely represent the value. mpz_class digits = 10; again: mpz_class product = numer * digits; mpz_class fraction = product / denom; mpz_class product2 = fraction * denom; if (product2 != product) { digits *= 10; goto again; } if (whole > 0) cout << whole << " + "; cout << numer << "/2^" << denom_lg2; cout << " (" << whole << "." << fraction << ")"; } void dumpfp2(mpz_class raw, int sig_bits, int exp_bits) { // In these calculations we rely on the general properties of IEEE floating // point: X bits of significant, followed by an implicit "1", followed by // Y bits of exponent and a sign bit. The exponent is expected to be biased // by half of the exponent's domain. // // Note that this will *not* work for "long double" because it does not use // an implicit 1 in its significand. mpz_class sig_scale = bitat(sig_bits), sig = raw & mask(sig_bits), sig2 = sig_scale + sig, expbias = mask(exp_bits - 1); int sign = mpz_class(raw >> (sig_bits + exp_bits)).get_si(), exp = mpz_class(raw >> sig_bits & mask(exp_bits)).get_si(), exp2 = mpz_class(exp - expbias).get_si(); cout << " raw = 0x" << hex << raw << "\n"; cout << " sign = 0x" << hex << sign << "\n"; if (exp2 == (expbias + 1)) { cout << " exponent = 0x" << hex << exp << " (NaN or Infinity)\n"; if (sig != 0) cout << " significand = " << hex << sig << " (non-zero indicates NaN)\n"; else cout << " significand = " << hex << sig << " (zero indicates Infinity)\n"; } else { cout << " exponent = 0x" << hex << exp << " (" << dec << exp2 << ")\n"; cout << " significand = 0x" << hex << sig << dec << "\n"; cout << "\n"; cout << " VALUE CALCULATION =\n"; cout << " significand ("; dumpfp(1, sig, sig_bits); cout << ")\n"; cout << " * 2^exponent (2^" << exp2 << ")\n"; cout << " = VALUE ("; if (exp2 >= sig_bits) { cout << (sig2 << (exp2 - sig_bits)); } else { int split = sig_bits - exp2; mpz_class whole = sig2 >> split; mpz_class frac = sig2 - (whole << split); dumpfp(whole, frac, split); } cout << ")\n"; } cout << "\n"; } // Gets an integer value corresponding to the given raw bytes. // The currently will only work on a little-endian machine. mpz_class getraw(void *val, size_t size) { unsigned char bytes[128]; memcpy(bytes, val, size); mpz_class raw(0); for (int i = 0; i < size; i++) { raw *= 256; raw += bytes[size-i-1]; } return raw; } void dumpfloat(float x) { printf("Single Precision (IEEE 32-bit):\n"); dumpfp2(getraw(&x, sizeof(float)), 23, 8); } void dumpdouble(double x) { printf("Double Precision (IEEE 64-bit):\n"); dumpfp2(getraw(&x, sizeof(double)), 52, 11); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: dumpfp 0.12345\n"); return 1; } long double x = strtold(argv[1], NULL); dumpfloat(x); dumpdouble(x); return 0; } <|endoftext|>
<commit_before>#include "routing/bicycle_directions.hpp" #include "routing/bicycle_model.hpp" #include "routing/features_road_graph.hpp" #include "routing/nearest_edge_finder.hpp" #include "routing/pedestrian_directions.hpp" #include "routing/pedestrian_model.hpp" #include "routing/road_graph_router.hpp" #include "routing/route.hpp" #include "coding/reader_wrapper.hpp" #include "indexer/feature.hpp" #include "indexer/feature_altitude.hpp" #include "indexer/ftypes_matcher.hpp" #include "indexer/index.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/mwm_version.hpp" #include "geometry/distance.hpp" #include "std/algorithm.hpp" #include "std/queue.hpp" #include "std/set.hpp" #include "base/assert.hpp" using platform::CountryFile; using platform::LocalCountryFile; namespace routing { namespace { size_t constexpr kMaxRoadCandidates = 6; size_t constexpr kTestConnectivityVisitJunctionsLimit = 25; uint64_t constexpr kMinPedestrianMwmVersion = 150713; // Check if the found edges lays on mwm with pedestrian routing support. bool CheckMwmVersion(vector<pair<Edge, Junction>> const & vicinities, vector<string> & mwmNames) { mwmNames.clear(); for (auto const & vicinity : vicinities) { auto const mwmInfo = vicinity.first.GetFeatureId().m_mwmId.GetInfo(); // mwmInfo gets version from a path of the file, so we must read the version header to be sure. ModelReaderPtr reader = FilesContainerR(mwmInfo->GetLocalFile().GetPath(MapOptions::Map)) .GetReader(VERSION_FILE_TAG); ReaderSrc src(reader.GetPtr()); version::MwmVersion version; version::ReadVersion(src, version); if (version.GetVersion() < kMinPedestrianMwmVersion) mwmNames.push_back(mwmInfo->GetCountryName()); } return !mwmNames.empty(); } // Checks is edge connected with world graph. // Function does BFS while it finds some number of edges, if graph ends // before this number is reached then junction is assumed as not connected to the world graph. bool CheckGraphConnectivity(IRoadGraph const & graph, Junction const & junction, size_t limit) { queue<Junction> q; q.push(junction); set<Junction> visited; vector<Edge> edges; while (!q.empty()) { Junction const node = q.front(); q.pop(); if (visited.find(node) != visited.end()) continue; visited.insert(node); if (limit == visited.size()) return true; edges.clear(); graph.GetOutgoingEdges(node, edges); for (Edge const & e : edges) q.push(e.GetEndJunction()); } return false; } // Find closest candidates in the world graph void FindClosestEdges(IRoadGraph const & graph, m2::PointD const & point, vector<pair<Edge, Junction>> & vicinity) { // WARNING: Take only one vicinity, with, maybe, its inverse. It is // an oversimplification that is not as easily solved as tuning up // this constant because if you set it too high you risk to find a // feature that you cannot in fact reach because of an obstacle. // Using only the closest feature minimizes (but not eliminates) // this risk. vector<pair<Edge, Junction>> candidates; graph.FindClosestEdges(point, kMaxRoadCandidates, candidates); vicinity.clear(); for (auto const & candidate : candidates) { auto const & edge = candidate.first; if (CheckGraphConnectivity(graph, edge.GetStartJunction(), kTestConnectivityVisitJunctionsLimit)) { vicinity.emplace_back(candidate); // Need to add a reverse edge, if exists, because fake edges // must be added for reverse edge too. IRoadGraph::TEdgeVector revEdges; graph.GetOutgoingEdges(edge.GetEndJunction(), revEdges); for (auto const & revEdge : revEdges) { if (revEdge.GetFeatureId() == edge.GetFeatureId() && revEdge.GetEndJunction() == edge.GetStartJunction() && revEdge.GetSegId() == edge.GetSegId()) { vicinity.emplace_back(revEdge, candidate.second); break; } } break; } } } } // namespace RoadGraphRouter::~RoadGraphRouter() {} RoadGraphRouter::RoadGraphRouter(string const & name, Index const & index, TCountryFileFn const & countryFileFn, IRoadGraph::Mode mode, unique_ptr<IVehicleModelFactory> && vehicleModelFactory, unique_ptr<IRoutingAlgorithm> && algorithm, unique_ptr<IDirectionsEngine> && directionsEngine) : m_name(name) , m_countryFileFn(countryFileFn) , m_index(index) , m_algorithm(move(algorithm)) , m_roadGraph(make_unique<FeaturesRoadGraph>(index, mode, move(vehicleModelFactory))) , m_directionsEngine(move(directionsEngine)) { } void RoadGraphRouter::ClearState() { m_roadGraph->ClearState(); } bool RoadGraphRouter::CheckMapExistence(m2::PointD const & point, Route & route) const { string const fileName = m_countryFileFn(point); if (!m_index.GetMwmIdByCountryFile(CountryFile(fileName)).IsAlive()) { route.AddAbsentCountry(fileName); return false; } return true; } IRouter::ResultCode RoadGraphRouter::CalculateRoute(m2::PointD const & startPoint, m2::PointD const & /* startDirection */, m2::PointD const & finalPoint, RouterDelegate const & delegate, Route & route) { if (!CheckMapExistence(startPoint, route) || !CheckMapExistence(finalPoint, route)) return IRouter::RouteFileNotExist; vector<pair<Edge, Junction>> finalVicinity; FindClosestEdges(*m_roadGraph, finalPoint, finalVicinity); if (finalVicinity.empty()) return IRouter::EndPointNotFound; // TODO (ldragunov) Remove this check after several releases. (Estimated in november) vector<string> mwmNames; if (CheckMwmVersion(finalVicinity, mwmNames)) { for (auto const & name : mwmNames) route.AddAbsentCountry(name); } vector<pair<Edge, Junction>> startVicinity; FindClosestEdges(*m_roadGraph, startPoint, startVicinity); if (startVicinity.empty()) return IRouter::StartPointNotFound; // TODO (ldragunov) Remove this check after several releases. (Estimated in november) if (CheckMwmVersion(startVicinity, mwmNames)) { for (auto const & name : mwmNames) route.AddAbsentCountry(name); } if (!route.GetAbsentCountries().empty()) return IRouter::FileTooOld; // Let us assume that the closest to startPoint/finalPoint feature point has the same altitude // with startPoint/finalPoint. Junction const startPos(startPoint, startVicinity.front().second.GetAltitude()); Junction const finalPos(finalPoint, finalVicinity.front().second.GetAltitude()); m_roadGraph->ResetFakes(); m_roadGraph->AddFakeEdges(startPos, startVicinity); m_roadGraph->AddFakeEdges(finalPos, finalVicinity); RoutingResult<Junction> result; IRoutingAlgorithm::Result const resultCode = m_algorithm->CalculateRoute(*m_roadGraph, startPos, finalPos, delegate, result); if (resultCode == IRoutingAlgorithm::Result::OK) { ASSERT(!result.path.empty(), ()); ASSERT_EQUAL(result.path.front(), startPos, ()); ASSERT_EQUAL(result.path.back(), finalPos, ()); ASSERT_GREATER(result.distance, 0., ()); ReconstructRoute(move(result.path), route, delegate); } m_roadGraph->ResetFakes(); if (delegate.IsCancelled()) return IRouter::Cancelled; if (!route.IsValid()) return IRouter::RouteNotFound; switch (resultCode) { case IRoutingAlgorithm::Result::OK: return IRouter::NoError; case IRoutingAlgorithm::Result::NoPath: return IRouter::RouteNotFound; case IRoutingAlgorithm::Result::Cancelled: return IRouter::Cancelled; } ASSERT(false, ("Unexpected IRoutingAlgorithm::Result code:", resultCode)); return IRouter::RouteNotFound; } void RoadGraphRouter::ReconstructRoute(vector<Junction> && path, Route & route, my::Cancellable const & cancellable) const { CHECK(!path.empty(), ("Can't reconstruct route from an empty list of positions.")); // By some reason there're two adjacent positions on a road with // the same end-points. This could happen, for example, when // direction on a road was changed. But it doesn't matter since // this code reconstructs only geometry of a route. path.erase(unique(path.begin(), path.end()), path.end()); if (path.size() == 1) path.emplace_back(path.back()); Route::TTimes times; Route::TTurns turnsDir; vector<Junction> junctions; // @TODO(bykoianko) streetNames is not filled in Generate(). It should be done. Route::TStreets streetNames; if (m_directionsEngine) m_directionsEngine->Generate(*m_roadGraph, path, times, turnsDir, junctions, cancellable); vector<m2::PointD> routeGeometry; JunctionsToPoints(junctions, routeGeometry); feature::TAltitudes altitudes; JunctionsToAltitudes(junctions, altitudes); route.SetGeometry(routeGeometry.begin(), routeGeometry.end()); route.SetSectionTimes(move(times)); route.SetTurnInstructions(move(turnsDir)); route.SetStreetNames(move(streetNames)); route.SetAltitudes(move(altitudes)); } unique_ptr<IRouter> CreatePedestrianAStarRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new PedestrianModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new PedestrianDirectionsEngine()); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-pedestrian", index, countryFileFn, IRoadGraph::Mode::IgnoreOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } unique_ptr<IRouter> CreatePedestrianAStarBidirectionalRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new PedestrianModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarBidirectionalRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new PedestrianDirectionsEngine()); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-bidirectional-pedestrian", index, countryFileFn, IRoadGraph::Mode::IgnoreOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } unique_ptr<IRouter> CreateBicycleAStarBidirectionalRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new BicycleModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarBidirectionalRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new BicycleDirectionsEngine(index)); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-bidirectional-bicycle", index, countryFileFn, IRoadGraph::Mode::ObeyOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } } // namespace routing <commit_msg>[routing] Fixed connectivity checking code.<commit_after>#include "routing/bicycle_directions.hpp" #include "routing/bicycle_model.hpp" #include "routing/features_road_graph.hpp" #include "routing/nearest_edge_finder.hpp" #include "routing/pedestrian_directions.hpp" #include "routing/pedestrian_model.hpp" #include "routing/road_graph_router.hpp" #include "routing/route.hpp" #include "coding/reader_wrapper.hpp" #include "indexer/feature.hpp" #include "indexer/feature_altitude.hpp" #include "indexer/ftypes_matcher.hpp" #include "indexer/index.hpp" #include "platform/country_file.hpp" #include "platform/local_country_file.hpp" #include "platform/mwm_version.hpp" #include "geometry/distance.hpp" #include "std/algorithm.hpp" #include "std/queue.hpp" #include "std/set.hpp" #include "base/assert.hpp" using platform::CountryFile; using platform::LocalCountryFile; namespace routing { namespace { size_t constexpr kMaxRoadCandidates = 6; size_t constexpr kTestConnectivityVisitJunctionsLimit = 25; uint64_t constexpr kMinPedestrianMwmVersion = 150713; // Check if the found edges lays on mwm with pedestrian routing support. bool CheckMwmVersion(vector<pair<Edge, Junction>> const & vicinities, vector<string> & mwmNames) { mwmNames.clear(); for (auto const & vicinity : vicinities) { auto const mwmInfo = vicinity.first.GetFeatureId().m_mwmId.GetInfo(); // mwmInfo gets version from a path of the file, so we must read the version header to be sure. ModelReaderPtr reader = FilesContainerR(mwmInfo->GetLocalFile().GetPath(MapOptions::Map)) .GetReader(VERSION_FILE_TAG); ReaderSrc src(reader.GetPtr()); version::MwmVersion version; version::ReadVersion(src, version); if (version.GetVersion() < kMinPedestrianMwmVersion) mwmNames.push_back(mwmInfo->GetCountryName()); } return !mwmNames.empty(); } // Checks is edge connected with world graph. // Function does BFS while it finds some number of edges, if graph ends // before this number is reached then junction is assumed as not connected to the world graph. bool CheckGraphConnectivity(IRoadGraph const & graph, Junction const & junction, size_t limit) { queue<Junction> q; q.push(junction); set<Junction> visited; visited.insert(junction); vector<Edge> edges; while (!q.empty() && visited.size() < limit) { Junction const u = q.front(); q.pop(); edges.clear(); graph.GetOutgoingEdges(u, edges); for (Edge const & edge : edges) { Junction const & v = edge.GetEndJunction(); if (visited.count(v) == 0) { q.push(v); visited.insert(v); } } } return visited.size() >= limit; } // Find closest candidates in the world graph void FindClosestEdges(IRoadGraph const & graph, m2::PointD const & point, vector<pair<Edge, Junction>> & vicinity) { // WARNING: Take only one vicinity, with, maybe, its inverse. It is // an oversimplification that is not as easily solved as tuning up // this constant because if you set it too high you risk to find a // feature that you cannot in fact reach because of an obstacle. // Using only the closest feature minimizes (but not eliminates) // this risk. vector<pair<Edge, Junction>> candidates; graph.FindClosestEdges(point, kMaxRoadCandidates, candidates); vicinity.clear(); for (auto const & candidate : candidates) { auto const & edge = candidate.first; if (CheckGraphConnectivity(graph, edge.GetEndJunction(), kTestConnectivityVisitJunctionsLimit)) { vicinity.emplace_back(candidate); // Need to add a reverse edge, if exists, because fake edges // must be added for reverse edge too. IRoadGraph::TEdgeVector revEdges; graph.GetOutgoingEdges(edge.GetEndJunction(), revEdges); for (auto const & revEdge : revEdges) { if (revEdge.GetFeatureId() == edge.GetFeatureId() && revEdge.GetEndJunction() == edge.GetStartJunction() && revEdge.GetSegId() == edge.GetSegId()) { vicinity.emplace_back(revEdge, candidate.second); break; } } break; } } } } // namespace RoadGraphRouter::~RoadGraphRouter() {} RoadGraphRouter::RoadGraphRouter(string const & name, Index const & index, TCountryFileFn const & countryFileFn, IRoadGraph::Mode mode, unique_ptr<IVehicleModelFactory> && vehicleModelFactory, unique_ptr<IRoutingAlgorithm> && algorithm, unique_ptr<IDirectionsEngine> && directionsEngine) : m_name(name) , m_countryFileFn(countryFileFn) , m_index(index) , m_algorithm(move(algorithm)) , m_roadGraph(make_unique<FeaturesRoadGraph>(index, mode, move(vehicleModelFactory))) , m_directionsEngine(move(directionsEngine)) { } void RoadGraphRouter::ClearState() { m_roadGraph->ClearState(); } bool RoadGraphRouter::CheckMapExistence(m2::PointD const & point, Route & route) const { string const fileName = m_countryFileFn(point); if (!m_index.GetMwmIdByCountryFile(CountryFile(fileName)).IsAlive()) { route.AddAbsentCountry(fileName); return false; } return true; } IRouter::ResultCode RoadGraphRouter::CalculateRoute(m2::PointD const & startPoint, m2::PointD const & /* startDirection */, m2::PointD const & finalPoint, RouterDelegate const & delegate, Route & route) { if (!CheckMapExistence(startPoint, route) || !CheckMapExistence(finalPoint, route)) return IRouter::RouteFileNotExist; vector<pair<Edge, Junction>> finalVicinity; FindClosestEdges(*m_roadGraph, finalPoint, finalVicinity); if (finalVicinity.empty()) return IRouter::EndPointNotFound; // TODO (ldragunov) Remove this check after several releases. (Estimated in november) vector<string> mwmNames; if (CheckMwmVersion(finalVicinity, mwmNames)) { for (auto const & name : mwmNames) route.AddAbsentCountry(name); } vector<pair<Edge, Junction>> startVicinity; FindClosestEdges(*m_roadGraph, startPoint, startVicinity); if (startVicinity.empty()) return IRouter::StartPointNotFound; // TODO (ldragunov) Remove this check after several releases. (Estimated in november) if (CheckMwmVersion(startVicinity, mwmNames)) { for (auto const & name : mwmNames) route.AddAbsentCountry(name); } if (!route.GetAbsentCountries().empty()) return IRouter::FileTooOld; // Let us assume that the closest to startPoint/finalPoint feature point has the same altitude // with startPoint/finalPoint. Junction const startPos(startPoint, startVicinity.front().second.GetAltitude()); Junction const finalPos(finalPoint, finalVicinity.front().second.GetAltitude()); m_roadGraph->ResetFakes(); m_roadGraph->AddFakeEdges(startPos, startVicinity); m_roadGraph->AddFakeEdges(finalPos, finalVicinity); RoutingResult<Junction> result; IRoutingAlgorithm::Result const resultCode = m_algorithm->CalculateRoute(*m_roadGraph, startPos, finalPos, delegate, result); if (resultCode == IRoutingAlgorithm::Result::OK) { ASSERT(!result.path.empty(), ()); ASSERT_EQUAL(result.path.front(), startPos, ()); ASSERT_EQUAL(result.path.back(), finalPos, ()); ASSERT_GREATER(result.distance, 0., ()); ReconstructRoute(move(result.path), route, delegate); } m_roadGraph->ResetFakes(); if (delegate.IsCancelled()) return IRouter::Cancelled; if (!route.IsValid()) return IRouter::RouteNotFound; switch (resultCode) { case IRoutingAlgorithm::Result::OK: return IRouter::NoError; case IRoutingAlgorithm::Result::NoPath: return IRouter::RouteNotFound; case IRoutingAlgorithm::Result::Cancelled: return IRouter::Cancelled; } ASSERT(false, ("Unexpected IRoutingAlgorithm::Result code:", resultCode)); return IRouter::RouteNotFound; } void RoadGraphRouter::ReconstructRoute(vector<Junction> && path, Route & route, my::Cancellable const & cancellable) const { CHECK(!path.empty(), ("Can't reconstruct route from an empty list of positions.")); // By some reason there're two adjacent positions on a road with // the same end-points. This could happen, for example, when // direction on a road was changed. But it doesn't matter since // this code reconstructs only geometry of a route. path.erase(unique(path.begin(), path.end()), path.end()); if (path.size() == 1) path.emplace_back(path.back()); Route::TTimes times; Route::TTurns turnsDir; vector<Junction> junctions; // @TODO(bykoianko) streetNames is not filled in Generate(). It should be done. Route::TStreets streetNames; if (m_directionsEngine) m_directionsEngine->Generate(*m_roadGraph, path, times, turnsDir, junctions, cancellable); vector<m2::PointD> routeGeometry; JunctionsToPoints(junctions, routeGeometry); feature::TAltitudes altitudes; JunctionsToAltitudes(junctions, altitudes); route.SetGeometry(routeGeometry.begin(), routeGeometry.end()); route.SetSectionTimes(move(times)); route.SetTurnInstructions(move(turnsDir)); route.SetStreetNames(move(streetNames)); route.SetAltitudes(move(altitudes)); } unique_ptr<IRouter> CreatePedestrianAStarRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new PedestrianModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new PedestrianDirectionsEngine()); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-pedestrian", index, countryFileFn, IRoadGraph::Mode::IgnoreOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } unique_ptr<IRouter> CreatePedestrianAStarBidirectionalRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new PedestrianModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarBidirectionalRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new PedestrianDirectionsEngine()); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-bidirectional-pedestrian", index, countryFileFn, IRoadGraph::Mode::IgnoreOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } unique_ptr<IRouter> CreateBicycleAStarBidirectionalRouter(Index & index, TCountryFileFn const & countryFileFn) { unique_ptr<IVehicleModelFactory> vehicleModelFactory(new BicycleModelFactory()); unique_ptr<IRoutingAlgorithm> algorithm(new AStarBidirectionalRoutingAlgorithm()); unique_ptr<IDirectionsEngine> directionsEngine(new BicycleDirectionsEngine(index)); unique_ptr<IRouter> router(new RoadGraphRouter( "astar-bidirectional-bicycle", index, countryFileFn, IRoadGraph::Mode::ObeyOnewayTag, move(vehicleModelFactory), move(algorithm), move(directionsEngine))); return router; } } // namespace routing <|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_INTERACTIONFORCEFIELD_ConstantForceField_INL #define SOFA_COMPONENT_INTERACTIONFORCEFIELD_ConstantForceField_INL #include <sofa/core/componentmodel/behavior/ForceField.inl> #include "RestShapeSpringsForceField.h" #include <sofa/helper/system/config.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField() : points(initData(&points, "points", "points where the forces are applied")) , stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position")) {} template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addForce(VecDeriv& f, const VecCoord& p, const VecDeriv& ) { const VecCoord& p_0 = *this->mstate->getX0(); f.resize(p.size()); const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); if ( k.size()!= indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<indices.size(); i++) { const unsigned int index = indices[i]; Deriv dx = p[index] - p_0[index]; f[index] -= dx * k[0] ; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[0] ; } } else { for (unsigned int i=0; i<indices.size(); i++) { const unsigned int index = indices[i]; Deriv dx = p[index] - p_0[index]; f[index] -= dx * k[index] ; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[i] ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addDForce(VecDeriv& df, const VecDeriv &dx, double kFactor, double ) { const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); if (k.size()!= indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<indices.size(); i++) { df[indices[i]] -= dx[indices[i]] * k[0] * kFactor; } } else { for (unsigned int i=0; i<indices.size(); i++) { // df[ indices[i] ] -= dx[indices[i]] * k[i] * kFactor ; df[indices[i]] -= dx[indices[i]] * k[indices[i]] * kFactor ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addKToMatrix(sofa::defaulttype::BaseMatrix * mat, double kFact, unsigned int &offset) { const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); const int N = Coord::static_size; unsigned int curIndex = 0; if (k.size()!= indices.size() ) { for (unsigned int index = 0; index < indices.size(); index++) { curIndex = indices[index]; for(unsigned int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, kFact * k[0]); } } } else { for (unsigned int index = 0; index < indices.size(); index++) { curIndex = indices[index]; for(unsigned int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, kFact * k[curIndex]); } } } } //template <class DataTypes> //double RestShapeSpringsForceField<DataTypes>::getPotentialEnergy(const VecCoord& x) //{ // const VecIndex& indices = points.getValue(); // const VecDeriv& f = forces.getValue(); // double e=0; // unsigned int i = 0; // for (; i<f.size(); i++) // { // e -= f[i]*x[indices[i]]; // } // for (; i<indices.size(); i++) // { // e -= f[f.size()-1]*x[indices[i]]; // } // return e; //} //template <class DataTypes> //void RestShapeSpringsForceField<DataTypes>::setForce( unsigned i, const Deriv& force ) //{ // VecIndex& indices = *points.beginEdit(); // VecDeriv& f = *forces.beginEdit(); // indices.push_back(i); // f.push_back( force ); // points.endEdit(); // forces.endEdit(); //} template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::draw() { /* if (!getContext()->getShowForceFields()) return; /// \todo put this in the parent class const VecIndex& indices = points.getValue(); const VecDeriv& f = forces.getValue(); const VecCoord& x = *this->mstate->getX(); glDisable(GL_LIGHTING); glBegin(GL_LINES); glColor3f(0,1,0); for (unsigned int i=0; i<indices.size(); i++) { Real xx,xy,xz,fx,fy,fz; DataTypes::get(xx,xy,xz,x[indices[i]]); DataTypes::get(fx,fy,fz,f[(i<f.size()) ? i : f.size()-1]); glVertex3f( (GLfloat)xx, (GLfloat)xy, (GLfloat)xz ); glVertex3f( (GLfloat)(xx+fx), (GLfloat)(xy+fy), (GLfloat)(xz+fz) ); } glEnd(); */ } template <class DataTypes> bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* ) { return false; } } // namespace forcefield } // namespace component } // namespace sofa #endif <commit_msg>r3755/sofa-dev : FIX : Remove Warnings...<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_INTERACTIONFORCEFIELD_ConstantForceField_INL #define SOFA_COMPONENT_INTERACTIONFORCEFIELD_ConstantForceField_INL #include <sofa/core/componentmodel/behavior/ForceField.inl> #include "RestShapeSpringsForceField.h" #include <sofa/helper/system/config.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField() : points(initData(&points, "points", "points where the forces are applied")) , stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position")) {} template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addForce(VecDeriv& f, const VecCoord& p, const VecDeriv& ) { const VecCoord& p_0 = *this->mstate->getX0(); f.resize(p.size()); const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); if ( k.size()!= indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<indices.size(); i++) { const unsigned int index = indices[i]; Deriv dx = p[index] - p_0[index]; f[index] -= dx * k[0] ; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[0] ; } } else { for (unsigned int i=0; i<indices.size(); i++) { const unsigned int index = indices[i]; Deriv dx = p[index] - p_0[index]; f[index] -= dx * k[index] ; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[i] ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addDForce(VecDeriv& df, const VecDeriv &dx, double kFactor, double ) { const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); if (k.size()!= indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<indices.size(); i++) { df[indices[i]] -= dx[indices[i]] * k[0] * kFactor; } } else { for (unsigned int i=0; i<indices.size(); i++) { // df[ indices[i] ] -= dx[indices[i]] * k[i] * kFactor ; df[indices[i]] -= dx[indices[i]] * k[indices[i]] * kFactor ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addKToMatrix(sofa::defaulttype::BaseMatrix * mat, double kFact, unsigned int &offset) { const VecIndex& indices = points.getValue(); const VecReal& k = stiffness.getValue(); const int N = Coord::static_size; unsigned int curIndex = 0; if (k.size()!= indices.size() ) { for (unsigned int index = 0; index < indices.size(); index++) { curIndex = indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, kFact * k[0]); } } } else { for (unsigned int index = 0; index < indices.size(); index++) { curIndex = indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, kFact * k[curIndex]); } } } } //template <class DataTypes> //double RestShapeSpringsForceField<DataTypes>::getPotentialEnergy(const VecCoord& x) //{ // const VecIndex& indices = points.getValue(); // const VecDeriv& f = forces.getValue(); // double e=0; // unsigned int i = 0; // for (; i<f.size(); i++) // { // e -= f[i]*x[indices[i]]; // } // for (; i<indices.size(); i++) // { // e -= f[f.size()-1]*x[indices[i]]; // } // return e; //} //template <class DataTypes> //void RestShapeSpringsForceField<DataTypes>::setForce( unsigned i, const Deriv& force ) //{ // VecIndex& indices = *points.beginEdit(); // VecDeriv& f = *forces.beginEdit(); // indices.push_back(i); // f.push_back( force ); // points.endEdit(); // forces.endEdit(); //} template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::draw() { /* if (!getContext()->getShowForceFields()) return; /// \todo put this in the parent class const VecIndex& indices = points.getValue(); const VecDeriv& f = forces.getValue(); const VecCoord& x = *this->mstate->getX(); glDisable(GL_LIGHTING); glBegin(GL_LINES); glColor3f(0,1,0); for (unsigned int i=0; i<indices.size(); i++) { Real xx,xy,xz,fx,fy,fz; DataTypes::get(xx,xy,xz,x[indices[i]]); DataTypes::get(fx,fy,fz,f[(i<f.size()) ? i : f.size()-1]); glVertex3f( (GLfloat)xx, (GLfloat)xy, (GLfloat)xz ); glVertex3f( (GLfloat)(xx+fx), (GLfloat)(xy+fy), (GLfloat)(xz+fz) ); } glEnd(); */ } template <class DataTypes> bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* ) { return false; } } // namespace forcefield } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #define BOID_COUNT 1024u namespace Intrinsic { namespace Core { namespace Components { void SwarmManager::init() { _INTR_LOG_INFO("Inititializing Character Controller Component Manager..."); Dod::Components::ComponentManagerBase< SwarmData, _INTR_MAX_SWARM_COMPONENT_COUNT>::_initComponentManager(); Dod::Components::ComponentManagerEntry SwarmEntry; { SwarmEntry.createFunction = Components::SwarmManager::createSwarm; SwarmEntry.destroyFunction = Components::SwarmManager::destroySwarm; SwarmEntry.createResourcesFunction = Components::SwarmManager::createResources; SwarmEntry.destroyResourcesFunction = Components::SwarmManager::destroyResources; SwarmEntry.getComponentForEntityFunction = Components::SwarmManager::getComponentForEntity; SwarmEntry.resetToDefaultFunction = Components::SwarmManager::resetToDefault; Application::_componentManagerMapping[_N(Swarm)] = SwarmEntry; Application::_orderedComponentManagers.push_back(SwarmEntry); } Dod::PropertyCompilerEntry propCompilerSwarm; { propCompilerSwarm.compileFunction = Components::SwarmManager::compileDescriptor; propCompilerSwarm.initFunction = Components::SwarmManager::initFromDescriptor; propCompilerSwarm.ref = Dod::Ref(); Application::_componentPropertyCompilerMapping[_N(Swarm)] = propCompilerSwarm; } } void SwarmManager::updateSwarms(const SwarmRefArray& p_Swarms, float p_DeltaT) { for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; _INTR_ARRAY(Boid)& boids = Components::SwarmManager::_boids(swarmRef); const NodeRefArray nodes = Components::SwarmManager::_nodes(swarmRef); _INTR_ASSERT(boids.size() == nodes.size() && "Node vs boid count does not match"); glm::vec3& currentCenterOfMass = Components::SwarmManager::_currentCenterOfMass(swarmRef); glm::vec3& currentAverageVelocity = Components::SwarmManager::_currentAverageVelocity(swarmRef); Components::NodeRef swarmNodeRef = Components::NodeManager::getComponentForEntity( Components::SwarmManager::_entity(swarmRef)); // Simulate boids and apply position to node glm::vec3 newCenterOfMass = glm::vec3(0.0f); glm::vec3 newAvgVelocity = glm::vec3(0.0f); { for (uint32_t boidIdx = 0u; boidIdx < boids.size(); ++boidIdx) { NodeRef nodeRef = nodes[boidIdx]; Boid& boid = boids[boidIdx]; static const float boidAcc = 10.0f; static const float boidMinDistSqr = 4.0f * 4.0f; static const float distanceRuleWeight = 2.0f; static const float targetRuleWeight = 0.9f; static const float minTargetDist = 2.0f; static const float matchVelWeight = 0.01f; static const float centerOfMassWeight = 0.8f; static const float maxVel = 15.0f; static uint32_t boidsToCheck = 10u; // Fly towards center of mass { const glm::vec3 boidToCenter = currentCenterOfMass - boid.pos; const float boidToCenterDist = glm::length(boidToCenter); if (boidToCenterDist > _INTR_EPSILON) boid.vel += boidToCenter / boidToCenterDist * p_DeltaT * boidAcc * centerOfMassWeight; } // Keep a distance for (uint32_t boidCompareNum = 0u; boidCompareNum < boidsToCheck; ++boidCompareNum) { const uint32_t boidToCompareIdx = Math::calcRandomNumber() % boids.size(); if (boidToCompareIdx == boidIdx) continue; const Boid& boidToCompare = boids[boidToCompareIdx]; const float distSqr = glm::distance2(boidToCompare.pos, boid.pos); if (distSqr < boidMinDistSqr && distSqr > _INTR_EPSILON) { boid.vel += boidAcc * glm::normalize(boidToCompare.pos - boid.pos) * -1.0f * p_DeltaT * distanceRuleWeight; } } // Match velocities { boid.vel += currentAverageVelocity * matchVelWeight * p_DeltaT; } // Target the node of the component { const glm::vec3 boidToComponent = Components::NodeManager::_worldPosition(swarmNodeRef) - boid.pos; const float boidToComponentDist = glm::length(boidToComponent); if (boidToComponentDist > _INTR_EPSILON && boidToComponentDist > minTargetDist) boid.vel += boidToComponent / boidToComponentDist * boidAcc * p_DeltaT * targetRuleWeight; } newCenterOfMass += boid.pos; float velLen = glm::length(boid.vel); if (velLen > maxVel) { boid.vel = boid.vel / velLen * maxVel; } newAvgVelocity += boid.vel; boid.pos += boid.vel * p_DeltaT; Components::NodeManager::_position(nodeRef) = boid.pos; Components::NodeManager::_orientation(nodeRef) = glm::rotation( glm::normalize(boid.vel + 0.01f), glm::vec3(0.0f, 0.0f, -1.0f)); } Components::NodeManager::updateTransforms(nodes); } currentCenterOfMass = newCenterOfMass / (float)boids.size(); currentAverageVelocity = newAvgVelocity / (float)boids.size(); } } void SwarmManager::createResources(const SwarmRefArray& p_Swarms) { Components::MeshRefArray meshComponentsToCreate; for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; for (uint32_t i = 0u; i < BOID_COUNT; ++i) { Entity::EntityRef entityRef = Entity::EntityManager::createEntity(_N(Boid)); Components::NodeRef nodeRef = Components::NodeManager::createNode(entityRef); Components::NodeManager::attachChild(World::getRootNode(), nodeRef); Components::NodeManager::_size(nodeRef) = glm::vec3(0.25f, 0.25f, 0.25f); Components::MeshRef meshRef = Components::MeshManager::createMesh(entityRef); Components::MeshManager::resetToDefault(meshRef); Components::MeshManager::_descMeshName(meshRef) = _N(monkey); Components::NodeRef swarmNodeRef = Components::NodeManager::getComponentForEntity( Components::SwarmManager::_entity(swarmRef)); Components::SwarmManager::_boids(swarmRef).push_back( {Components::NodeManager::_position(swarmNodeRef), glm::vec3(0.0f)}); Components::SwarmManager::_nodes(swarmRef).push_back(nodeRef); meshComponentsToCreate.push_back(meshRef); } } Components::NodeManager::rebuildTreeAndUpdateTransforms(); Components::MeshManager::createResources(meshComponentsToCreate); } void SwarmManager::destroyResources(const SwarmRefArray& p_Swarms) { for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; _INTR_ARRAY(Boid)& boids = Components::SwarmManager::_boids(swarmRef); NodeRefArray& nodes = Components::SwarmManager::_nodes(swarmRef); for (uint32_t i = 0u; i < nodes.size(); ++i) { World::destroyNodeFull(nodes[i]); } boids.clear(); nodes.clear(); } } } } } <commit_msg>Tweaked swarm<commit_after>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #define BOID_COUNT 256u namespace Intrinsic { namespace Core { namespace Components { void SwarmManager::init() { _INTR_LOG_INFO("Inititializing Character Controller Component Manager..."); Dod::Components::ComponentManagerBase< SwarmData, _INTR_MAX_SWARM_COMPONENT_COUNT>::_initComponentManager(); Dod::Components::ComponentManagerEntry SwarmEntry; { SwarmEntry.createFunction = Components::SwarmManager::createSwarm; SwarmEntry.destroyFunction = Components::SwarmManager::destroySwarm; SwarmEntry.createResourcesFunction = Components::SwarmManager::createResources; SwarmEntry.destroyResourcesFunction = Components::SwarmManager::destroyResources; SwarmEntry.getComponentForEntityFunction = Components::SwarmManager::getComponentForEntity; SwarmEntry.resetToDefaultFunction = Components::SwarmManager::resetToDefault; Application::_componentManagerMapping[_N(Swarm)] = SwarmEntry; Application::_orderedComponentManagers.push_back(SwarmEntry); } Dod::PropertyCompilerEntry propCompilerSwarm; { propCompilerSwarm.compileFunction = Components::SwarmManager::compileDescriptor; propCompilerSwarm.initFunction = Components::SwarmManager::initFromDescriptor; propCompilerSwarm.ref = Dod::Ref(); Application::_componentPropertyCompilerMapping[_N(Swarm)] = propCompilerSwarm; } } void SwarmManager::updateSwarms(const SwarmRefArray& p_Swarms, float p_DeltaT) { for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; _INTR_ARRAY(Boid)& boids = Components::SwarmManager::_boids(swarmRef); const NodeRefArray nodes = Components::SwarmManager::_nodes(swarmRef); _INTR_ASSERT(boids.size() == nodes.size() && "Node vs boid count does not match"); glm::vec3& currentCenterOfMass = Components::SwarmManager::_currentCenterOfMass(swarmRef); glm::vec3& currentAverageVelocity = Components::SwarmManager::_currentAverageVelocity(swarmRef); Components::NodeRef swarmNodeRef = Components::NodeManager::getComponentForEntity( Components::SwarmManager::_entity(swarmRef)); // Simulate boids and apply position to node glm::vec3 newCenterOfMass = glm::vec3(0.0f); glm::vec3 newAvgVelocity = glm::vec3(0.0f); { for (uint32_t boidIdx = 0u; boidIdx < boids.size(); ++boidIdx) { NodeRef nodeRef = nodes[boidIdx]; Boid& boid = boids[boidIdx]; static const float boidAcc = 10.0f; static const float boidMinDistSqr = 4.0f * 4.0f; static const float distanceRuleWeight = 0.05f; static const float targetRuleWeight = 0.9f; static const float minTargetDist = 2.0f; static const float matchVelWeight = 0.01f; static const float centerOfMassWeight = 0.8f; static const float maxVel = 15.0f; static uint32_t boidsToCheck = 10u; // Fly towards center of mass { const glm::vec3 boidToCenter = currentCenterOfMass - boid.pos; const float boidToCenterDist = glm::length(boidToCenter); if (boidToCenterDist > _INTR_EPSILON) boid.vel += boidToCenter / boidToCenterDist * p_DeltaT * boidAcc * centerOfMassWeight; } // Keep a distance for (uint32_t boidToCompareIdx = 0u; boidToCompareIdx < boids.size(); ++boidToCompareIdx) { if (boidToCompareIdx == boidIdx) continue; const Boid& boidToCompare = boids[boidToCompareIdx]; const float distSqr = glm::distance2(boidToCompare.pos, boid.pos); if (distSqr < boidMinDistSqr && distSqr > _INTR_EPSILON) { boid.vel += boidAcc * glm::normalize(boidToCompare.pos - boid.pos) * -1.0f * p_DeltaT * distanceRuleWeight; } } // Match velocities { boid.vel += currentAverageVelocity * matchVelWeight * p_DeltaT; } // Target the node of the component { const glm::vec3 boidToComponent = Components::NodeManager::_worldPosition(swarmNodeRef) - boid.pos; const float boidToComponentDist = glm::length(boidToComponent); if (boidToComponentDist > _INTR_EPSILON && boidToComponentDist > minTargetDist) boid.vel += boidToComponent / boidToComponentDist * boidAcc * p_DeltaT * targetRuleWeight; } newCenterOfMass += boid.pos; float velLen = glm::length(boid.vel); if (velLen > maxVel) { boid.vel = boid.vel / velLen * maxVel; } newAvgVelocity += boid.vel; boid.pos += boid.vel * p_DeltaT; Components::NodeManager::_position(nodeRef) = boid.pos; Components::NodeManager::_orientation(nodeRef) = glm::rotation( glm::normalize(boid.vel + 0.01f), glm::vec3(0.0f, 0.0f, -1.0f)); } Components::NodeManager::updateTransforms(nodes); } currentCenterOfMass = newCenterOfMass / (float)boids.size(); currentAverageVelocity = newAvgVelocity / (float)boids.size(); } } void SwarmManager::createResources(const SwarmRefArray& p_Swarms) { Components::MeshRefArray meshComponentsToCreate; for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; for (uint32_t i = 0u; i < BOID_COUNT; ++i) { Entity::EntityRef entityRef = Entity::EntityManager::createEntity(_N(Boid)); Components::NodeRef nodeRef = Components::NodeManager::createNode(entityRef); Components::NodeManager::attachChild(World::getRootNode(), nodeRef); Components::NodeManager::_size(nodeRef) = glm::vec3(0.25f, 0.25f, 0.25f); Components::MeshRef meshRef = Components::MeshManager::createMesh(entityRef); Components::MeshManager::resetToDefault(meshRef); Components::MeshManager::_descMeshName(meshRef) = _N(monkey); Components::NodeRef swarmNodeRef = Components::NodeManager::getComponentForEntity( Components::SwarmManager::_entity(swarmRef)); Components::SwarmManager::_boids(swarmRef).push_back( {Components::NodeManager::_position(swarmNodeRef), glm::vec3(0.0f)}); Components::SwarmManager::_nodes(swarmRef).push_back(nodeRef); meshComponentsToCreate.push_back(meshRef); } } Components::NodeManager::rebuildTreeAndUpdateTransforms(); Components::MeshManager::createResources(meshComponentsToCreate); } void SwarmManager::destroyResources(const SwarmRefArray& p_Swarms) { for (uint32_t swarmIdx = 0u; swarmIdx < p_Swarms.size(); ++swarmIdx) { SwarmRef swarmRef = p_Swarms[swarmIdx]; _INTR_ARRAY(Boid)& boids = Components::SwarmManager::_boids(swarmRef); NodeRefArray& nodes = Components::SwarmManager::_nodes(swarmRef); for (uint32_t i = 0u; i < nodes.size(); ++i) { World::destroyNodeFull(nodes[i]); } boids.clear(); nodes.clear(); } } } } } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 metaverse developers (see AUTHORS) * * This file is part of mvs-node. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/bitcoin/chain/attachment/message/message.hpp> #include <sstream> #include <boost/iostreams/stream.hpp> #include <metaverse/bitcoin/utility/container_sink.hpp> #include <metaverse/bitcoin/utility/container_source.hpp> #include <metaverse/bitcoin/utility/istream_reader.hpp> #include <metaverse/bitcoin/utility/ostream_writer.hpp> namespace libbitcoin { namespace chain { blockchain_message::blockchain_message(): content_("") { } blockchain_message::blockchain_message(std::string content): content_(content) { } blockchain_message blockchain_message::factory_from_data(const data_chunk& data) { blockchain_message instance; instance.from_data(data); return instance; } blockchain_message blockchain_message::factory_from_data(std::istream& stream) { blockchain_message instance; instance.from_data(stream); return instance; } blockchain_message blockchain_message::factory_from_data(reader& source) { blockchain_message instance; instance.from_data(source); return instance; } void blockchain_message::reset() { content_ = ""; } bool blockchain_message::is_valid() const { return !(content_.empty() || content_.size()+1>BLOCKCHAIN_MESSAGE_FIX_SIZE); } bool blockchain_message::from_data(const data_chunk& data) { data_source istream(data); return from_data(istream); } bool blockchain_message::from_data(std::istream& stream) { istream_reader source(stream); return from_data(source); } bool blockchain_message::from_data(reader& source) { reset(); content_ = source.read_string(); auto result = static_cast<bool>(source); return result; } data_chunk blockchain_message::to_data() const { data_chunk data; data_sink ostream(data); to_data(ostream); ostream.flush(); //BITCOIN_ASSERT(data.size() == serialized_size()); return data; } void blockchain_message::to_data(std::ostream& stream) const { ostream_writer sink(stream); to_data(sink); } void blockchain_message::to_data(writer& sink) const { if (content_.size() < BLOCKCHAIN_MESSAGE_FIX_SIZE) { sink.write_string(content_); } else { sink.write_string(content_.substr(0, BLOCKCHAIN_MESSAGE_FIX_SIZE)); } } uint64_t blockchain_message::serialized_size() const { size_t len = content_.size() + 1; return std::min(len, BLOCKCHAIN_MESSAGE_FIX_SIZE); } std::string blockchain_message::to_string() const { std::ostringstream ss; ss << "\t content = " << content_ << "\n"; return ss.str(); } const std::string& blockchain_message::get_content() const { return content_; } void blockchain_message::set_content(const std::string& content) { size_t len = std::min(content.size()+1, BLOCKCHAIN_MESSAGE_FIX_SIZE); this->content_ = content.substr(0, len); } } // namspace chain } // namspace libbitcoin <commit_msg>modify blockchain_message is_valid.<commit_after>/** * Copyright (c) 2011-2015 metaverse developers (see AUTHORS) * * This file is part of mvs-node. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/bitcoin/chain/attachment/message/message.hpp> #include <sstream> #include <boost/iostreams/stream.hpp> #include <metaverse/bitcoin/utility/container_sink.hpp> #include <metaverse/bitcoin/utility/container_source.hpp> #include <metaverse/bitcoin/utility/istream_reader.hpp> #include <metaverse/bitcoin/utility/ostream_writer.hpp> namespace libbitcoin { namespace chain { blockchain_message::blockchain_message(): content_("") { } blockchain_message::blockchain_message(std::string content): content_(content) { } blockchain_message blockchain_message::factory_from_data(const data_chunk& data) { blockchain_message instance; instance.from_data(data); return instance; } blockchain_message blockchain_message::factory_from_data(std::istream& stream) { blockchain_message instance; instance.from_data(stream); return instance; } blockchain_message blockchain_message::factory_from_data(reader& source) { blockchain_message instance; instance.from_data(source); return instance; } void blockchain_message::reset() { content_ = ""; } static size_t get_string_serialized_size(const std::string& str) { size_t length = str.size(); if (length < 0xfd) { return length + 1; } if (length <= 0xffff) { return length + 3; } if (length <= 0xffffffff) { return length + 5; } return length + 9; } bool blockchain_message::is_valid() const { return !(content_.empty() || get_string_serialized_size(content_) + 1 > BLOCKCHAIN_MESSAGE_FIX_SIZE); } bool blockchain_message::from_data(const data_chunk& data) { data_source istream(data); return from_data(istream); } bool blockchain_message::from_data(std::istream& stream) { istream_reader source(stream); return from_data(source); } bool blockchain_message::from_data(reader& source) { reset(); content_ = source.read_string(); auto result = static_cast<bool>(source); return result; } data_chunk blockchain_message::to_data() const { data_chunk data; data_sink ostream(data); to_data(ostream); ostream.flush(); //BITCOIN_ASSERT(data.size() == serialized_size()); return data; } void blockchain_message::to_data(std::ostream& stream) const { ostream_writer sink(stream); to_data(sink); } void blockchain_message::to_data(writer& sink) const { sink.write_string(content_); } uint64_t blockchain_message::serialized_size() const { size_t len = get_string_serialized_size(content_) + 1; return std::min(len, BLOCKCHAIN_MESSAGE_FIX_SIZE); } std::string blockchain_message::to_string() const { std::ostringstream ss; ss << "\t content = " << content_ << "\n"; return ss.str(); } const std::string& blockchain_message::get_content() const { return content_; } void blockchain_message::set_content(const std::string& content) { size_t len = std::min(content.size()+1, BLOCKCHAIN_MESSAGE_FIX_SIZE); this->content_ = content.substr(0, len); } } // namspace chain } // namspace libbitcoin <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/commands/createasset.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> #include <metaverse/explorer/extensions/exception.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ createasset *************************/ void validate(boost::any& v, const std::vector<std::string>& values, non_negative_uint64*, int) { using namespace boost::program_options; validators::check_first_occurrence(v); std::string const& s = validators::get_single_string(values); if (s[0] == '-') { throw argument_legality_exception{"volume must not be negative number."}; } v = boost::any(non_negative_uint64 { boost::lexical_cast<uint64_t>(s) } ); } console_result createasset::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& blockchain = node.chain_impl(); blockchain.is_account_passwd_valid(auth_.name, auth_.auth); // check options if (option_.symbol.empty()) throw asset_symbol_length_exception{"asset symbol can not be empty."}; if (option_.symbol.length() > ASSET_DETAIL_SYMBOL_FIX_SIZE) throw asset_symbol_length_exception{"asset symbol length must be less than 64."}; // check did if (option_.issuer.empty()) throw did_symbol_length_exception{"issuer can not be empty."}; if (option_.issuer.length() > DID_DETAIL_SYMBOL_FIX_SIZE) throw did_symbol_length_exception{"issuer symbol length must be less than 64."}; if(!blockchain.is_did_exist(option_.issuer)) throw did_symbol_existed_exception{"the did for issuer is not exist in blockchain,maybe you should issuedid first"}; if (option_.description.length() > ASSET_DETAIL_DESCRIPTION_FIX_SIZE) throw asset_description_length_exception{"asset description length must be less than 64."}; auto threshold = option_.secondaryissue_threshold; if ((threshold < -1) || (threshold > 100)) { throw asset_secondaryissue_threshold_exception{"secondaryissue threshold value error, is must be -1 or in range of 0 to 100."}; } if (option_.decimal_number > 19u) throw asset_amount_exception{"asset decimal number must less than 20."}; if (option_.maximum_supply.volume == 0u) throw argument_legality_exception{"volume must not be zero."}; // maybe throw blockchain.uppercase_symbol(option_.symbol); if(bc::wallet::symbol::is_sensitive(option_.symbol)) { throw asset_symbol_name_exception{"invalid symbol start with " + option_.symbol}; } if(blockchain.is_asset_exist(option_.symbol)) throw asset_symbol_existed_exception{"symbol is already used."}; auto acc = std::make_shared<asset_detail>(); acc->set_symbol(option_.symbol); acc->set_maximum_supply(option_.maximum_supply.volume); acc->set_decimal_number(static_cast<uint8_t>(option_.decimal_number)); acc->set_issuer(auth_.name); acc->set_description(option_.description); // use 127 to represent freely secondary issue, and 255 for its secondary issued status. acc->set_secondaryissue_threshold((threshold == -1) ? asset_detail::freely_secondaryissue_threshold : static_cast<uint8_t>(threshold)); blockchain.store_account_asset(acc); auto& aroot = jv_output; Json::Value asset_data = config::json_helper(get_api_version()).prop_list(*acc, true); asset_data["status"] = "unissued"; aroot["asset"] = asset_data; return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <commit_msg>fix bug<commit_after>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/commands/createasset.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> #include <metaverse/explorer/extensions/exception.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ createasset *************************/ void validate(boost::any& v, const std::vector<std::string>& values, non_negative_uint64*, int) { using namespace boost::program_options; validators::check_first_occurrence(v); std::string const& s = validators::get_single_string(values); if (s[0] == '-') { throw argument_legality_exception{"volume must not be negative number."}; } v = boost::any(non_negative_uint64 { boost::lexical_cast<uint64_t>(s) } ); } console_result createasset::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& blockchain = node.chain_impl(); blockchain.is_account_passwd_valid(auth_.name, auth_.auth); // check options if (option_.symbol.empty()) throw asset_symbol_length_exception{"asset symbol can not be empty."}; if (option_.symbol.length() > ASSET_DETAIL_SYMBOL_FIX_SIZE) throw asset_symbol_length_exception{"asset symbol length must be less than 64."}; // check did if (option_.issuer.empty()) throw did_symbol_length_exception{"issuer can not be empty."}; if (option_.issuer.length() > DID_DETAIL_SYMBOL_FIX_SIZE) throw did_symbol_length_exception{"issuer symbol length must be less than 64."}; if(!blockchain.is_did_exist(option_.issuer)) throw did_symbol_existed_exception{"the did for issuer is not exist in blockchain,maybe you should issuedid first"}; if (option_.description.length() > ASSET_DETAIL_DESCRIPTION_FIX_SIZE) throw asset_description_length_exception{"asset description length must be less than 64."}; auto threshold = option_.secondaryissue_threshold; if ((threshold < -1) || (threshold > 100)) { throw asset_secondaryissue_threshold_exception{"secondaryissue threshold value error, is must be -1 or in range of 0 to 100."}; } if (option_.decimal_number > 19u) throw asset_amount_exception{"asset decimal number must less than 20."}; if (option_.maximum_supply.volume == 0u) throw argument_legality_exception{"volume must not be zero."}; // maybe throw blockchain.uppercase_symbol(option_.symbol); if(bc::wallet::symbol::is_sensitive(option_.symbol)) { throw asset_symbol_name_exception{"invalid symbol start with " + option_.symbol}; } if(blockchain.is_asset_exist(option_.symbol)) throw asset_symbol_existed_exception{"symbol is already used."}; auto acc = std::make_shared<asset_detail>(); acc->set_symbol(option_.symbol); acc->set_maximum_supply(option_.maximum_supply.volume); acc->set_decimal_number(static_cast<uint8_t>(option_.decimal_number)); acc->set_issuer(option_.issuer); acc->set_description(option_.description); // use 127 to represent freely secondary issue, and 255 for its secondary issued status. acc->set_secondaryissue_threshold((threshold == -1) ? asset_detail::freely_secondaryissue_threshold : static_cast<uint8_t>(threshold)); blockchain.store_account_asset(acc); auto& aroot = jv_output; Json::Value asset_data = config::json_helper(get_api_version()).prop_list(*acc, true); asset_data["status"] = "unissued"; aroot["asset"] = asset_data; return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQTSSAResultSubWidget.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "CopasiFileDialog.h" #include "copasi/core/CRootContainer.h" #include "copasi/tssanalysis/CTSSATask.h" #include "copasi/tssanalysis/CTSSAProblem.h" #include "copasi/core/CDataArray.h" #include "copasi/commandline/CLocaleString.h" #include "copasi/model/CModel.h" #include "copasi/math/CMathContainer.h" #include "copasi/CopasiDataModel/CDataModel.h" const CDataArray * pResult; /* * Constructs a CQTSSAResultSubWidget as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQTSSAResultSubWidget::CQTSSAResultSubWidget(QWidget* parent, const char* name, Qt::WindowFlags fl) : CopasiWidget(parent, name, fl) { setupUi(this); init(); } /* * Destroys the object and frees any allocated resources */ CQTSSAResultSubWidget::~CQTSSAResultSubWidget() { // no need to delete child widgets, Qt does it all for us } void CQTSSAResultSubWidget::saveDataToFile() { C_INT32 Answer = QMessageBox::No; QString fileName; while (Answer == QMessageBox::No) { fileName = CopasiFileDialog::getSaveFileName(this, "Save File Dialog", "untitled.txt", "Text Files (*.txt)", "Save to"); if (fileName.isEmpty()) return; // Checks whether the file exists Answer = checkSelection(this, fileName); if (Answer == QMessageBox::Cancel) return; } std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str()); if (file.fail()) return; assert(CRootContainer::getDatamodelList()->size() > 0); CCopasiTask* mpTask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!mpTask) return; CCopasiProblem* mpProblem = mpTask->getProblem(); mpProblem->printResult(&file); return; } void CQTSSAResultSubWidget::slotTableChanged() { std::string name = static_cast<std::string >(mpBox1->currentText().toUtf8()); if (name == "Reactions slow space" || name == "Reactions contribution to the mode" || name == "Reactions distribution between modes " || name == "Reactions fast space" || name == "Participation Index" || name == "Fast Participation Index" || name == "Slow Participation Index" || name == "Normed Participation Index (by column)" || name == "Normed Participation Index (by row)" || name == "Importance Index" || name == "Normed Importance Index (by row)") { CColorScaleSimple* tcs = new CColorScaleSimple(); tcs->setSymmetric(true); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); } else { //CColorScaleAdvanced * tcs = new CColorScaleAdvanced(); //tcs->setColorMin(QColor(240, 240, 240)); //tcs->setColorMax(QColor(0, 255, 0)); CColorScaleSimple* tcs = new CColorScaleSimple(); tcs->setSymmetric(true); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); } pResult = pMethod->getTable(name); mpArrayWidget->setArrayAnnotation(pResult); } //set time and step number void CQTSSAResultSubWidget::slotTimeAndStepChanged() { int s = mpSlider->value(); mpLabelTime->setNum((double)pMethod->getTimeForStep(s - 1)); mpLabelStep->setNum(s); } //switch between time scale and table views void CQTSSAResultSubWidget::changeContents() { if (mpIndex == 0) { mpTimeScaleWidget->show(); //mpArrayWidget->hide(); //mpBox1->hide(); //mpButton->setText("Show Tables"); mpButton->setText("Hide Time scales"); mpIndex = 1; } else { mpTimeScaleWidget->hide(); //mpBox1->show(); //mpArrayWidget->show(); mpButton->setText("Show Time scales"); mpIndex = 0; } } void CQTSSAResultSubWidget::init() { assert(mpDataModel != NULL); pTSSATask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!pTSSATask) return; pProblem = dynamic_cast<CTSSAProblem*>(pTSSATask->getProblem()); pModel = & pTSSATask->getMathContainer()->getModel(); pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); mpLabelTime->setNum(0); mpLabelStep->setNum(0); connect(mpBox1, SIGNAL(currentIndexChanged(int)), this, SLOT(slotTableChanged(/* int */))); //set colorsettings for ArrayAnnotationWidgets CColorScaleAdvanced * tcs = new CColorScaleAdvanced(); tcs->setColorMin(QColor(240, 240, 240)); tcs->setColorMax(QColor(0, 255, 0)); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); connect(mpSlider, SIGNAL(valueChanged(int)), this, SLOT(changeInterval())); connect(mpButton, SIGNAL(clicked()), this, SLOT(changeContents())); connect(ButtonSaveData, SIGNAL(clicked()), this, SLOT(saveDataToFile())); mpBox1->setEditable(false); mpIndex = 0; mpTimeScaleWidget->hide(); mpBox1->show(); mpArrayWidget->show(); } void CQTSSAResultSubWidget::displayResult() { assert(mpDataModel != NULL); pTSSATask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!pTSSATask) return; pProblem = dynamic_cast<CTSSAProblem*>(pTSSATask->getProblem()); pModel = & pTSSATask->getMathContainer()->getModel(); pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); QString a = FROM_UTF8(pModel->getTimeUnitName()); mpSlider->setRange(1, pProblem->getStepNumber()); mpSlider->setValue(mpSlider->minimum()); mpBox1->clear(); unsigned C_INT i; for (i = 0; i < pMethod->getTableNames().size(); i++) { mpBox1->insertItem(0, FROM_UTF8(pMethod->getTableNames()[i])); } mpArrayWidget->switchToTable(); mpSlider->setDisabled(false); mpSlider->setFocus(); changeInterval(); } /** * Clear ArrayAnnotation-widgets. **/ void CQTSSAResultSubWidget::discardOldResults() { mpArrayWidget->setArrayAnnotation(NULL); mpArrayWidget->clearWidget(); mpTimeScaleWidget->clearWidget(); mpSlider->setDisabled(true); } /** * Get the results for the requested step from the method. * Fill widgets with this results. **/ void CQTSSAResultSubWidget::changeInterval() { // ensure we always have a valid method pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); slotTimeAndStepChanged(); int s = mpSlider->value(); if (pMethod->setAnnotationM(s - 1)) { std::string name = TO_UTF8(mpBox1->currentText()); pResult = pMethod->getTable(name); mpArrayWidget->setArrayAnnotation(pResult); CVector< C_FLOAT64> vec = pMethod->getVec_TimeScale(s); mpTimeScaleWidget->paintTimeScale(vec); } else { //mpSlider->setDisabled(true); mpArrayWidget->setArrayAnnotation(NULL); mpTimeScaleWidget->clearWidget(); } } <commit_msg>- issue 2905: need to acquire method again, as slotTableChanged can be invoked after the old method is out of scope<commit_after>// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQTSSAResultSubWidget.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "CopasiFileDialog.h" #include "copasi/core/CRootContainer.h" #include "copasi/tssanalysis/CTSSATask.h" #include "copasi/tssanalysis/CTSSAProblem.h" #include "copasi/core/CDataArray.h" #include "copasi/commandline/CLocaleString.h" #include "copasi/model/CModel.h" #include "copasi/math/CMathContainer.h" #include "copasi/CopasiDataModel/CDataModel.h" const CDataArray * pResult; /* * Constructs a CQTSSAResultSubWidget as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQTSSAResultSubWidget::CQTSSAResultSubWidget(QWidget* parent, const char* name, Qt::WindowFlags fl) : CopasiWidget(parent, name, fl) { setupUi(this); init(); } /* * Destroys the object and frees any allocated resources */ CQTSSAResultSubWidget::~CQTSSAResultSubWidget() { // no need to delete child widgets, Qt does it all for us } void CQTSSAResultSubWidget::saveDataToFile() { C_INT32 Answer = QMessageBox::No; QString fileName; while (Answer == QMessageBox::No) { fileName = CopasiFileDialog::getSaveFileName(this, "Save File Dialog", "untitled.txt", "Text Files (*.txt)", "Save to"); if (fileName.isEmpty()) return; // Checks whether the file exists Answer = checkSelection(this, fileName); if (Answer == QMessageBox::Cancel) return; } std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str()); if (file.fail()) return; assert(CRootContainer::getDatamodelList()->size() > 0); CCopasiTask* mpTask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!mpTask) return; CCopasiProblem* mpProblem = mpTask->getProblem(); mpProblem->printResult(&file); return; } void CQTSSAResultSubWidget::slotTableChanged() { std::string name = static_cast<std::string >(mpBox1->currentText().toUtf8()); if (name == "Reactions slow space" || name == "Reactions contribution to the mode" || name == "Reactions distribution between modes " || name == "Reactions fast space" || name == "Participation Index" || name == "Fast Participation Index" || name == "Slow Participation Index" || name == "Normed Participation Index (by column)" || name == "Normed Participation Index (by row)" || name == "Importance Index" || name == "Normed Importance Index (by row)") { CColorScaleSimple* tcs = new CColorScaleSimple(); tcs->setSymmetric(true); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); } else { //CColorScaleAdvanced * tcs = new CColorScaleAdvanced(); //tcs->setColorMin(QColor(240, 240, 240)); //tcs->setColorMax(QColor(0, 255, 0)); CColorScaleSimple* tcs = new CColorScaleSimple(); tcs->setSymmetric(true); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); } pTSSATask = dynamic_cast< CTSSATask * >(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!pTSSATask) return; pProblem = dynamic_cast< CTSSAProblem * >(pTSSATask->getProblem()); pModel = &pTSSATask->getMathContainer()->getModel(); pMethod = dynamic_cast< CTSSAMethod * >(pTSSATask->getMethod()); pResult = pMethod->getTable(name); mpArrayWidget->setArrayAnnotation(pResult); } //set time and step number void CQTSSAResultSubWidget::slotTimeAndStepChanged() { int s = mpSlider->value(); mpLabelTime->setNum((double)pMethod->getTimeForStep(s - 1)); mpLabelStep->setNum(s); } //switch between time scale and table views void CQTSSAResultSubWidget::changeContents() { if (mpIndex == 0) { mpTimeScaleWidget->show(); //mpArrayWidget->hide(); //mpBox1->hide(); //mpButton->setText("Show Tables"); mpButton->setText("Hide Time scales"); mpIndex = 1; } else { mpTimeScaleWidget->hide(); //mpBox1->show(); //mpArrayWidget->show(); mpButton->setText("Show Time scales"); mpIndex = 0; } } void CQTSSAResultSubWidget::init() { assert(mpDataModel != NULL); pTSSATask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!pTSSATask) return; pProblem = dynamic_cast<CTSSAProblem*>(pTSSATask->getProblem()); pModel = & pTSSATask->getMathContainer()->getModel(); pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); mpLabelTime->setNum(0); mpLabelStep->setNum(0); connect(mpBox1, SIGNAL(currentIndexChanged(int)), this, SLOT(slotTableChanged(/* int */))); //set colorsettings for ArrayAnnotationWidgets CColorScaleAdvanced * tcs = new CColorScaleAdvanced(); tcs->setColorMin(QColor(240, 240, 240)); tcs->setColorMax(QColor(0, 255, 0)); mpArrayWidget->setColorCoding(tcs); mpArrayWidget->setColorScalingAutomatic(true); connect(mpSlider, SIGNAL(valueChanged(int)), this, SLOT(changeInterval())); connect(mpButton, SIGNAL(clicked()), this, SLOT(changeContents())); connect(ButtonSaveData, SIGNAL(clicked()), this, SLOT(saveDataToFile())); mpBox1->setEditable(false); mpIndex = 0; mpTimeScaleWidget->hide(); mpBox1->show(); mpArrayWidget->show(); } void CQTSSAResultSubWidget::displayResult() { assert(mpDataModel != NULL); pTSSATask = dynamic_cast<CTSSATask *>(&mpDataModel->getTaskList()->operator[]("Time Scale Separation Analysis")); if (!pTSSATask) return; pProblem = dynamic_cast<CTSSAProblem*>(pTSSATask->getProblem()); pModel = & pTSSATask->getMathContainer()->getModel(); pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); QString a = FROM_UTF8(pModel->getTimeUnitName()); mpSlider->setRange(1, pProblem->getStepNumber()); mpSlider->setValue(mpSlider->minimum()); mpBox1->clear(); unsigned C_INT i; for (i = 0; i < pMethod->getTableNames().size(); i++) { mpBox1->insertItem(0, FROM_UTF8(pMethod->getTableNames()[i])); } mpArrayWidget->switchToTable(); mpSlider->setDisabled(false); mpSlider->setFocus(); changeInterval(); } /** * Clear ArrayAnnotation-widgets. **/ void CQTSSAResultSubWidget::discardOldResults() { mpArrayWidget->setArrayAnnotation(NULL); mpArrayWidget->clearWidget(); mpTimeScaleWidget->clearWidget(); mpSlider->setDisabled(true); } /** * Get the results for the requested step from the method. * Fill widgets with this results. **/ void CQTSSAResultSubWidget::changeInterval() { // ensure we always have a valid method pMethod = dynamic_cast<CTSSAMethod*>(pTSSATask->getMethod()); slotTimeAndStepChanged(); int s = mpSlider->value(); if (pMethod->setAnnotationM(s - 1)) { std::string name = TO_UTF8(mpBox1->currentText()); pResult = pMethod->getTable(name); mpArrayWidget->setArrayAnnotation(pResult); CVector< C_FLOAT64> vec = pMethod->getVec_TimeScale(s); mpTimeScaleWidget->paintTimeScale(vec); } else { //mpSlider->setDisabled(true); mpArrayWidget->setArrayAnnotation(NULL); mpTimeScaleWidget->clearWidget(); } } <|endoftext|>
<commit_before>#include <spark-pusher.h> #include <Ethernet.h> #include <PusherClient.h><commit_msg>add setup<commit_after>#include <spark-pusher.h> #include <Ethernet.h> #include <PusherClient.h> PusherClient client; void setup() { if(client.connect("your-api-key-here")) { client.subscribe("robot_channel"); client.bind("forward", moveForward); } else { while(1) {} } } void loop() { } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 Deniz Erbilgin 2016 */ /* * Driver and sanity test for portable C++ unit tests for this library. */ #include <stdint.h> #include <gtest/gtest.h> #include <utility/OTV0P2BASE_Util.h> // Sanity test. TEST(SanityTest,SelfTest) { EXPECT_EQ(42, 42); } //// Minimally test a real library function. //TEST(SanityTest,ShouldConvertFromHex) //{ // const char s[] = "0a"; // // This works. It's inline and only in the header. // EXPECT_EQ(10, OTV0P2BASE::parseHexDigit(s[1])); // // The compiler can't find this for some reason (function def in source file). // EXPECT_EQ(10, OTV0P2BASE::parseHexByte(s)); //} /** * @brief Getting started with the gtest libraries. * @note - Add the following to Project>Properties>C/C++ Build>Settings>GCC G++ linker>Libraries (-l): * - gtest * - gtest_main * - pthread * - Select Google Testing in Run>Run Configuration>C/C++ Unit Test>testTest>C/C++ Testing and click Apply then Run * - Saved the test config */ /** * See also: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md */ <commit_msg>TODO-996: printing test build time as confidence measure<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 Deniz Erbilgin 2016 */ /* * Driver and sanity test for portable C++ unit tests for this library. */ #include <stdint.h> #include <gtest/gtest.h> #include <utility/OTV0P2BASE_Util.h> // Sanity test. TEST(SanityTest,SelfTest) { EXPECT_EQ(42, 42); fputs("Built at: " __DATE__ " " __TIME__, stderr); } //// Minimally test a real library function. //TEST(SanityTest,ShouldConvertFromHex) //{ // const char s[] = "0a"; // // This works. It's inline and only in the header. // EXPECT_EQ(10, OTV0P2BASE::parseHexDigit(s[1])); // // The compiler can't find this for some reason (function def in source file). // EXPECT_EQ(10, OTV0P2BASE::parseHexByte(s)); //} /** * @brief Getting started with the gtest libraries. * @note - Add the following to Project>Properties>C/C++ Build>Settings>GCC G++ linker>Libraries (-l): * - gtest * - gtest_main * - pthread * - Select Google Testing in Run>Run Configuration>C/C++ Unit Test>testTest>C/C++ Testing and click Apply then Run * - Saved the test config */ /** * See also: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md */ <|endoftext|>
<commit_before>#include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <vector> class Image { public: Image(const char* filename) { std::ifstream stream(filename); if (stream.is_open()) { readFromStream(stream); } else { std::cerr << "File " << filename << " should exist." << std::endl; } } Image(std::istream& stream) { readFromStream(stream); } std::int64_t rows() const { return nRows_; } std::int64_t cols() const { return nCols_; } bool correct() const { return correct_; } double operator[](std::size_t i) const { return i < data_.size() ? data_[i] : 0.0; } private: void readFromStream(std::istream& stream) { std::string line; while (std::getline(stream, line)) { std::int64_t col{ 0 }; std::istringstream iss(line); double v; while (iss >> v) { data_.push_back(v); ++col; } if (col > 0) { if (nCols_ == -1) { nCols_ = col; } else if (nCols_ != col) { std::cerr << "Different number of values in rows." << std::endl; return; } ++nRows_; } } correct_ = true; } std::int64_t nRows_{ 0 }; std::int64_t nCols_{ -1 }; bool correct_{ false }; std::vector<double> data_; }; struct DifferenceStats { double absDifSum{ 0.0 }; double relDifSum{ 0.0 }; double totalSum{ 0.0 }; int pixelNum{ 0 }; }; DifferenceStats computeDifference( Image const& image1, Image const& image2, std::ostream& difStream, std::ostream& absDifStream, std::ostream& relDifStream) { DifferenceStats stats; std::size_t i=0; for (std::int64_t x=0; x!=image1.rows(); ++x) { for (std::int64_t y=0; y!=image1.cols(); ++y) { double const dif = image1[i] - image2[i]; double const absDif = std::abs(dif); double const mean = 0.5*(image1[i] + image2[i]); difStream << dif << "\t"; absDifStream << absDif << "\t"; stats.absDifSum += absDif; stats.totalSum += mean; if (image1[i] != 0 && image2[i] != 0) { ++stats.pixelNum; double const meanAbs = 0.5*(std::abs(image1[i]) + std::abs(image2[i])); stats.relDifSum += absDif / meanAbs; relDifStream << absDif / meanAbs << "\t"; } else { relDifStream << "0\t"; } ++i; } difStream << std::endl; absDifStream << std::endl; relDifStream << std::endl; } return stats; } #ifdef ENABLE_UNIT_TESTS #include "tests/DifferTests.inl" #else int main( int argc, char *argv[] ) { if (argc != 3) { std::cerr << argv[0] << " requires 2 arguments." << std::endl; return 0; } Image image1(argv[1]); Image image2(argv[2]); if (!image1.correct() || !image2.correct()) { return 0; } if (image1.rows() != image2.rows() || image1.cols() != image2.cols()) { std::cerr << argv[1] << " (" << image1.rows() << "x" << image1.cols() << ") and " << argv[2] << " (" << image2.rows() <<"x" << image2.cols() << ") should have the same shape." << std::endl; return 0; } std::ofstream difStream("dif.dat"); std::ofstream absDifStream("dif_abs.dat"); std::ofstream relDifStream("dif_rel.dat"); difStream.precision(14); absDifStream.precision(14); relDifStream.precision(14); DifferenceStats stats = computeDifference(image1, image2, difStream, absDifStream, relDifStream); std::cout << "dif= " << stats.absDifSum << " meandif= " << stats.absDifSum/stats.pixelNum << " meanreldif= " << stats.relDifSum/stats.pixelNum << " n= " << stats.pixelNum << std::endl << "refsum= " << stats.absDifSum/stats.totalSum << std::endl; } #endif <commit_msg>Add imdiff help<commit_after>#include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <vector> class Image { public: Image(const char* filename) { std::ifstream stream(filename); if (stream.is_open()) { readFromStream(stream); } else { std::cerr << "File " << filename << " should exist." << std::endl; } } Image(std::istream& stream) { readFromStream(stream); } std::int64_t rows() const { return nRows_; } std::int64_t cols() const { return nCols_; } bool correct() const { return correct_; } double operator[](std::size_t i) const { return i < data_.size() ? data_[i] : 0.0; } private: void readFromStream(std::istream& stream) { std::string line; while (std::getline(stream, line)) { std::int64_t col{ 0 }; std::istringstream iss(line); double v; while (iss >> v) { data_.push_back(v); ++col; } if (col > 0) { if (nCols_ == -1) { nCols_ = col; } else if (nCols_ != col) { std::cerr << "Different number of values in rows." << std::endl; return; } ++nRows_; } } correct_ = true; } std::int64_t nRows_{ 0 }; std::int64_t nCols_{ -1 }; bool correct_{ false }; std::vector<double> data_; }; struct DifferenceStats { double absDifSum{ 0.0 }; double relDifSum{ 0.0 }; double totalSum{ 0.0 }; int pixelNum{ 0 }; }; DifferenceStats computeDifference( Image const& image1, Image const& image2, std::ostream& difStream, std::ostream& absDifStream, std::ostream& relDifStream) { DifferenceStats stats; std::size_t i=0; for (std::int64_t x=0; x!=image1.rows(); ++x) { for (std::int64_t y=0; y!=image1.cols(); ++y) { double const dif = image1[i] - image2[i]; double const absDif = std::abs(dif); double const mean = 0.5*(image1[i] + image2[i]); difStream << dif << "\t"; absDifStream << absDif << "\t"; stats.absDifSum += absDif; stats.totalSum += mean; if (image1[i] != 0 && image2[i] != 0) { ++stats.pixelNum; double const meanAbs = 0.5*(std::abs(image1[i]) + std::abs(image2[i])); stats.relDifSum += absDif / meanAbs; relDifStream << absDif / meanAbs << "\t"; } else { relDifStream << "0\t"; } ++i; } difStream << std::endl; absDifStream << std::endl; relDifStream << std::endl; } return stats; } #ifdef ENABLE_UNIT_TESTS #include "tests/DifferTests.inl" #else int main( int argc, char *argv[] ) { if (argc > 1 && (std::string(argv[1]) == "-h" || std::string(argv[1]) == "--help")) { std::cout << "Usage: " << argv[0] << " [OPTION] FILE1 FILE2\n" << "Compare image files FILE1 and FILE2 and creates difference files.\n" << "Options:\n" << "\t-h, --help\tdisplay this help and exit.\n"; return 0; } if (argc != 3) { std::cerr << argv[0] << " requires two image filenames as arguments." << std::endl; return 0; } Image image1(argv[1]); Image image2(argv[2]); if (!image1.correct() || !image2.correct()) { return 0; } if (image1.rows() != image2.rows() || image1.cols() != image2.cols()) { std::cerr << argv[1] << " (" << image1.rows() << "x" << image1.cols() << ") and " << argv[2] << " (" << image2.rows() <<"x" << image2.cols() << ") should have the same shape." << std::endl; return 0; } std::ofstream difStream("dif.dat"); std::ofstream absDifStream("dif_abs.dat"); std::ofstream relDifStream("dif_rel.dat"); difStream.precision(14); absDifStream.precision(14); relDifStream.precision(14); DifferenceStats stats = computeDifference(image1, image2, difStream, absDifStream, relDifStream); std::cout << "dif= " << stats.absDifSum << " meandif= " << stats.absDifSum/stats.pixelNum << " meanreldif= " << stats.relDifSum/stats.pixelNum << " n= " << stats.pixelNum << std::endl << "refsum= " << stats.absDifSum/stats.totalSum << std::endl; } #endif <|endoftext|>
<commit_before>#include "acmacs-base/range.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/counter.hh" #include "acmacs-base/string-from-chars.hh" #include "acmacs-virus/virus-name-v1.hh" #include "acmacs-draw/surface-cairo.hh" #include "acmacs-draw/geographic-map.hh" #include "seqdb-3/seqdb.hh" #include "geographic-map.hh" // ---------------------------------------------------------------------- void GeographicMapPoints::draw(acmacs::surface::Surface& aSurface) const { for (const auto& point: *this) { point.draw(aSurface); } } // GeographicMapPoints::draw // ---------------------------------------------------------------------- GeographicMapDraw::~GeographicMapDraw() { } // GeographicMapDraw::~GeographicMapDraw // ---------------------------------------------------------------------- void GeographicMapDraw::prepare(acmacs::surface::Surface&) { } // GeographicMapDraw::prepare // ---------------------------------------------------------------------- void GeographicMapDraw::draw(acmacs::surface::Surface& aOutlineSurface, acmacs::surface::Surface& aPointSurface) const { geographic_map_draw(aOutlineSurface, mOutline, mOutlineWidth); mPoints.draw(aPointSurface); mTitle.draw(aOutlineSurface); } // GeographicMapDraw::draw // ---------------------------------------------------------------------- void GeographicMapDraw::draw(std::string aFilename, double aImageWidth) { const acmacs::Size size = geographic_map_size(); acmacs::surface::PdfCairo outline_surface(aFilename, aImageWidth, aImageWidth / size.width * size.height, size.width); auto& point_surface = outline_surface.subsurface(outline_surface.viewport().origin, Scaled{outline_surface.viewport().size.width}, geographic_map_viewport(), false); prepare(point_surface); draw(outline_surface, point_surface); } // GeographicMapDraw::draw // ---------------------------------------------------------------------- void GeographicMapDraw::add_point(long aPriority, double aLat, double aLong, const acmacs::color::Modifier& aFill, Pixels aSize, const acmacs::color::Modifier& aOutline, Pixels aOutlineWidth) { mPoints.emplace_back(LongLat{aLong, -aLat}, aPriority); auto& style = mPoints.back(); style.shape(acmacs::PointShape::Circle); style.fill(aFill); style.outline(aOutline); style.outline_width(aOutlineWidth); style.size(aSize); } // GeographicMapDraw::add_point // ---------------------------------------------------------------------- GeographicMapColoring::~GeographicMapColoring() { } // ---------------------------------------------------------------------- static inline std::string location_of_antigen(const hidb::Antigen& antigen) { const std::string name{antigen.name()}; auto location = virus_name::location(name); if (location == "GEORGIA") { const auto& hidb = hidb::get(acmacs::virus::type_subtype_t{virus_name::virus_type(name)}); if (hidb.tables()->most_recent(antigen.tables())->lab() == "CDC") { // std::cerr << "WARNING: GEORGIA: " << antigen->full_name() << '\n'; location = "GEORGIA STATE"; // somehow disambiguate } } return location; } // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByContinent::color(const hidb::Antigen& aAntigen) const { try { const std::string continent{acmacs::locationdb::get().continent(location_of_antigen(aAntigen))}; return {continent, mColors.at(continent)}; } catch (std::exception&) { return {"UNKNOWN", {GREY50}}; } } // ColoringByContinent::color // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByClade::color(const hidb::Antigen& aAntigen) const { ColoringData result(GREY50); std::string tag{"UNKNOWN"}; try { if (const auto ref = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref) { tag = "SEQUENCED"; const auto& clades_of_seq = ref.seq().clades; std::vector<std::string_view> clade_data; std::copy_if(clades_of_seq.begin(), clades_of_seq.end(), std::back_inserter(clade_data), [this](const auto& clade) { return this->mColors.find(clade) != this->mColors.end(); }); if (clade_data.size() == 1) { tag = clade_data.front(); } else if (clade_data.size() > 1) { if (std::find(clade_data.begin(), clade_data.end(), "2A1") != clade_data.end()) { tag = "2A1"; // 2A1 has higher priority over 3C.2A } else if (std::find(clade_data.begin(), clade_data.end(), "2A2") != clade_data.end()) { tag = "2A2"; // 2A2 has higher priority over 3C.2A } else { std::cerr << "DEBUG: multi-clades: " << clade_data << '\n'; tag = clade_data.front(); } } if (tag != "UNKNOWN") result = mColors.at(tag); } } catch (std::exception& err) { fmt::print(stderr, "ERROR: ColoringByClade {}: {}\n", aAntigen.full_name(), err); } catch (...) { fmt::print(stderr, "ERROR: ColoringByClade {}: unknown exception\n", aAntigen.full_name()); } // std::cerr << "DEBUG: ColoringByClade " << aAntigen.full_name() << ": " << (tag == "UNKNOWN" ? "Not Sequenced" : tag) << ' ' << result.fill << '\n'; return {tag, result}; } // ColoringByClade::color // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByAminoAcid::color(const hidb::Antigen& aAntigen) const { ColoringData result(GREY50); std::string tag{"UNKNOWN"}; try { const auto& seqdb = acmacs::seqdb::get(); std::string aa_report; if (const auto ref = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref) { rjson::for_each(settings_["apply"], [sequence = ref.aa_aligned(seqdb),&result,&tag,&aa_report](const rjson::value& apply_entry) { if (rjson::get_or(apply_entry, "sequenced", false)) { result = rjson::get_or(apply_entry, "color", "pink"); tag = "SEQUENCED"; } else if (const auto& aa = apply_entry["aa"]; !aa.is_null()) { if (!aa.is_array()) throw std::runtime_error("invalid \"aa\" settings value, array of strings expected"); bool satisfied = true; std::string tag_to_use; aa_report.append(" -"); rjson::for_each(aa, [sequence,&satisfied,&tag_to_use,&aa_report](const rjson::value& aa_entry) { const std::string_view pos_aa_s{aa_entry.to<std::string_view>()}; const auto pos = acmacs::seqdb::pos1_t{acmacs::string::from_chars<size_t>(pos_aa_s.substr(0, pos_aa_s.size() - 1))}; if (pos < acmacs::seqdb::pos1_t{1} || pos >= sequence.size() || sequence.at(pos) != pos_aa_s.back()) { satisfied = false; aa_report.append(fmt::format(" [{}!{}]", pos_aa_s, sequence.at(pos))); } else { tag_to_use.append(fmt::format(" {}", pos_aa_s)); aa_report.append(fmt::format(" [{}={}]", pos_aa_s, sequence.at(pos))); } }); if (satisfied) { result = rjson::get_or(apply_entry, "color", "pink"); tag = tag_to_use.substr(1); // remove leading space } } }); } if (rjson::get_or(settings_, "report", false)) fmt::print(stderr, "DEBUG: ColoringByAminoAcid {}: {} <-- {} {}\n", aAntigen.full_name(), tag, aa_report, result.fill); } catch (std::exception& err) { fmt::print(stderr, "ERROR: ColoringByAminoAcid {}: {}\n", aAntigen.full_name(), err); } catch (...) { fmt::print(stderr, "ERROR: ColoringByAminoAcid {}: unknown exception\n", aAntigen.full_name()); } return {tag, result}; } // ColoringByAminoAcid::color // ---------------------------------------------------------------------- void GeographicMapWithPointsFromHidb::prepare(acmacs::surface::Surface& aSurface) { GeographicMapDraw::prepare(aSurface); const double point_scaled = aSurface.convert(mPointSize).value(); for (const auto& location_color: mPointsAtLocation) { if (const auto location = acmacs::locationdb::get().find(location_color.first); location.has_value()) { const double center_lat = location->latitude(), center_long = location->longitude(); auto iter = location_color.second.iterator(); auto [coloring_data, priority] = *iter; add_point(priority, center_lat, center_long, coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width); ++iter; for (size_t circle_no = 1; iter; ++circle_no) { const double distance = point_scaled * mDensity * static_cast<double>(circle_no); const size_t circle_capacity = static_cast<size_t>(M_PI * 2.0 * distance * static_cast<double>(circle_no) / (point_scaled * mDensity)); const size_t points_on_circle = std::min(circle_capacity, iter.left()); const double step = 2.0 * M_PI / static_cast<double>(points_on_circle); for (auto index: acmacs::range(0UL, points_on_circle)) { std::tie(coloring_data, priority) = *iter; add_point(priority, center_lat + distance * std::cos(static_cast<double>(index) * step), center_long + distance * std::sin(static_cast<double>(index) * step), coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width); ++iter; } } } } sort_points(); } // GeographicMapWithPointsFromHidb::prepare // ---------------------------------------------------------------------- void GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by(const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, const std::vector<std::string>& aPriority, std::string_view aStartDate, std::string_view aEndDate) { // std::cerr << "add_points_from_hidb_colored_by" << '\n'; const auto& hidb = hidb::get(acmacs::virus::type_subtype_t{mVirusType}); auto antigens = hidb.antigens()->date_range(aStartDate, aEndDate); fmt::print("\nINFO: dates: {}..{} antigens: {}\n", aStartDate, aEndDate, antigens.size()); if (!aPriority.empty()) fmt::print("INFO: priority: {} (the last in this list to be drawn on top of others)\n", aPriority); acmacs::Counter<std::string> tag_counter; for (auto antigen: antigens) { auto [tag, coloring_data] = aColorOverride.color(*antigen); if (coloring_data.fill.is_no_change()) std::tie(tag, coloring_data) = aColoring.color(*antigen); tag_counter.count(tag); try { const auto found = std::find(std::begin(aPriority), std::end(aPriority), tag); mPointsAtLocation.add(location_of_antigen(*antigen), found == std::end(aPriority) ? 0 : (found - std::begin(aPriority) + 1), coloring_data); } catch (virus_name::Unrecognized&) { // thrown by location_of_antigen() -> virus_name::location() } } fmt::print("INFO: tags:\n{}", tag_counter.report_sorted_max_first()); // std::transform(mPoints.begin(), mPoints.end(), std::ostream_iterator<std::string>(std::cerr, "\n"), [](const auto& e) -> std::string { return e.first; }); } // GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by // ---------------------------------------------------------------------- void GeographicTimeSeries::draw(std::string_view aFilenamePrefix, const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, double aImageWidth) const { for (const auto& slot : time_series_) { auto map = map_; // make a copy! map.add_points_from_hidb_colored_by(aColoring, aColorOverride, priority_, date::display(slot.first), date::display(slot.after_last)); map.title().add_line(acmacs::time_series::text_name(slot)); map.draw(fmt::format("{}{}.pdf", aFilenamePrefix, acmacs::time_series::numeric_name(slot)), aImageWidth); } } // GeographicTimeSeries::draw // ---------------------------------------------------------------------- GeographicMapColoring::TagColor ColoringByLineageAndDeletionMutants::color(const hidb::Antigen& aAntigen) const { try { const auto& seqdb = acmacs::seqdb::get(); if (const auto ref_2del = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref_2del && ref_2del.has_clade(seqdb, "2DEL2017")) { // fmt::print(stderr, "DEBUG: 2del {}\n", aAntigen.full_name()); return {"VICTORIA_2DEL", mDeletionMutantColor.empty() ? mColors.at("VICTORIA_2DEL") : ColoringData{mDeletionMutantColor}}; } else if (const auto ref_3del = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref_3del && ref_3del.has_clade(seqdb, "3DEL2017")) { // fmt::print(stderr, "DEBUG: 3del {}\n", aAntigen.full_name()); return {"VICTORIA_3DEL", mDeletionMutantColor.empty() ? mColors.at("VICTORIA_3DEL") : ColoringData{mDeletionMutantColor}}; } else { const auto lineage = aAntigen.lineage().to_string(); // fmt::print(stderr, "DEBUG: {} {}\n", lineage.substr(0, 3), aAntigen.full_name()); return {lineage, mColors.at(lineage)}; } } catch (...) { return {"UNKNOWN", {GREY50}}; } } // ColoringByLineageAndDeletionMutants::color // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>bug fix in the geographic ts generator<commit_after>#include "acmacs-base/range.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/counter.hh" #include "acmacs-base/string-from-chars.hh" #include "acmacs-virus/virus-name-v1.hh" #include "acmacs-draw/surface-cairo.hh" #include "acmacs-draw/geographic-map.hh" #include "seqdb-3/seqdb.hh" #include "geographic-map.hh" // ---------------------------------------------------------------------- void GeographicMapPoints::draw(acmacs::surface::Surface& aSurface) const { for (const auto& point: *this) { point.draw(aSurface); } } // GeographicMapPoints::draw // ---------------------------------------------------------------------- GeographicMapDraw::~GeographicMapDraw() { } // GeographicMapDraw::~GeographicMapDraw // ---------------------------------------------------------------------- void GeographicMapDraw::prepare(acmacs::surface::Surface&) { } // GeographicMapDraw::prepare // ---------------------------------------------------------------------- void GeographicMapDraw::draw(acmacs::surface::Surface& aOutlineSurface, acmacs::surface::Surface& aPointSurface) const { geographic_map_draw(aOutlineSurface, mOutline, mOutlineWidth); mPoints.draw(aPointSurface); mTitle.draw(aOutlineSurface); } // GeographicMapDraw::draw // ---------------------------------------------------------------------- void GeographicMapDraw::draw(std::string aFilename, double aImageWidth) { const acmacs::Size size = geographic_map_size(); acmacs::surface::PdfCairo outline_surface(aFilename, aImageWidth, aImageWidth / size.width * size.height, size.width); auto& point_surface = outline_surface.subsurface(outline_surface.viewport().origin, Scaled{outline_surface.viewport().size.width}, geographic_map_viewport(), false); prepare(point_surface); draw(outline_surface, point_surface); } // GeographicMapDraw::draw // ---------------------------------------------------------------------- void GeographicMapDraw::add_point(long aPriority, double aLat, double aLong, const acmacs::color::Modifier& aFill, Pixels aSize, const acmacs::color::Modifier& aOutline, Pixels aOutlineWidth) { mPoints.emplace_back(LongLat{aLong, -aLat}, aPriority); auto& style = mPoints.back(); style.shape(acmacs::PointShape::Circle); style.fill(aFill); style.outline(aOutline); style.outline_width(aOutlineWidth); style.size(aSize); } // GeographicMapDraw::add_point // ---------------------------------------------------------------------- GeographicMapColoring::~GeographicMapColoring() { } // ---------------------------------------------------------------------- static inline std::string location_of_antigen(const hidb::Antigen& antigen) { const std::string name{antigen.name()}; auto location = virus_name::location(name); if (location == "GEORGIA") { const auto& hidb = hidb::get(acmacs::virus::type_subtype_t{virus_name::virus_type(name)}); if (hidb.tables()->most_recent(antigen.tables())->lab() == "CDC") { // std::cerr << "WARNING: GEORGIA: " << antigen->full_name() << '\n'; location = "GEORGIA STATE"; // somehow disambiguate } } return location; } // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByContinent::color(const hidb::Antigen& aAntigen) const { try { const std::string continent{acmacs::locationdb::get().continent(location_of_antigen(aAntigen))}; return {continent, mColors.at(continent)}; } catch (std::exception&) { return {"UNKNOWN", {GREY50}}; } } // ColoringByContinent::color // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByClade::color(const hidb::Antigen& aAntigen) const { ColoringData result(GREY50); std::string tag{"UNKNOWN"}; try { if (const auto ref = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref) { tag = "SEQUENCED"; const auto& clades_of_seq = ref.seq_with_sequence(acmacs::seqdb::get()).clades; std::vector<std::string_view> clade_data; std::copy_if(clades_of_seq.begin(), clades_of_seq.end(), std::back_inserter(clade_data), [this](const auto& clade) { return this->mColors.find(clade) != this->mColors.end(); }); if (clade_data.size() == 1) { tag = clade_data.front(); } else if (clade_data.size() > 1) { if (std::find(clade_data.begin(), clade_data.end(), "2A1") != clade_data.end()) { tag = "2A1"; // 2A1 has higher priority over 3C.2A } else if (std::find(clade_data.begin(), clade_data.end(), "2A2") != clade_data.end()) { tag = "2A2"; // 2A2 has higher priority over 3C.2A } else { std::cerr << "DEBUG: multi-clades: " << clade_data << '\n'; tag = clade_data.front(); } } if (tag != "UNKNOWN") result = mColors.at(tag); // AD_DEBUG("{:10s} {:50s} {:50s} {}", tag, aAntigen.full_name(), ref.seq_id(), clades_of_seq); } } catch (std::exception& err) { fmt::print(stderr, "ERROR: ColoringByClade {}: {}\n", aAntigen.full_name(), err); } catch (...) { fmt::print(stderr, "ERROR: ColoringByClade {}: unknown exception\n", aAntigen.full_name()); } // std::cerr << "DEBUG: ColoringByClade " << aAntigen.full_name() << ": " << (tag == "UNKNOWN" ? "Not Sequenced" : tag) << ' ' << result.fill << '\n'; return {tag, result}; } // ColoringByClade::color // ---------------------------------------------------------------------- ColorOverride::TagColor ColoringByAminoAcid::color(const hidb::Antigen& aAntigen) const { ColoringData result(GREY50); std::string tag{"UNKNOWN"}; try { const auto& seqdb = acmacs::seqdb::get(); std::string aa_report; if (const auto ref = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref) { rjson::for_each(settings_["apply"], [sequence = ref.aa_aligned(seqdb),&result,&tag,&aa_report](const rjson::value& apply_entry) { if (rjson::get_or(apply_entry, "sequenced", false)) { result = rjson::get_or(apply_entry, "color", "pink"); tag = "SEQUENCED"; } else if (const auto& aa = apply_entry["aa"]; !aa.is_null()) { if (!aa.is_array()) throw std::runtime_error("invalid \"aa\" settings value, array of strings expected"); bool satisfied = true; std::string tag_to_use; aa_report.append(" -"); rjson::for_each(aa, [sequence,&satisfied,&tag_to_use,&aa_report](const rjson::value& aa_entry) { const std::string_view pos_aa_s{aa_entry.to<std::string_view>()}; const auto pos = acmacs::seqdb::pos1_t{acmacs::string::from_chars<size_t>(pos_aa_s.substr(0, pos_aa_s.size() - 1))}; if (pos < acmacs::seqdb::pos1_t{1} || pos >= sequence.size() || sequence.at(pos) != pos_aa_s.back()) { satisfied = false; aa_report.append(fmt::format(" [{}!{}]", pos_aa_s, sequence.at(pos))); } else { tag_to_use.append(fmt::format(" {}", pos_aa_s)); aa_report.append(fmt::format(" [{}={}]", pos_aa_s, sequence.at(pos))); } }); if (satisfied) { result = rjson::get_or(apply_entry, "color", "pink"); tag = tag_to_use.substr(1); // remove leading space } } }); } if (rjson::get_or(settings_, "report", false)) fmt::print(stderr, "DEBUG: ColoringByAminoAcid {}: {} <-- {} {}\n", aAntigen.full_name(), tag, aa_report, result.fill); } catch (std::exception& err) { fmt::print(stderr, "ERROR: ColoringByAminoAcid {}: {}\n", aAntigen.full_name(), err); } catch (...) { fmt::print(stderr, "ERROR: ColoringByAminoAcid {}: unknown exception\n", aAntigen.full_name()); } return {tag, result}; } // ColoringByAminoAcid::color // ---------------------------------------------------------------------- void GeographicMapWithPointsFromHidb::prepare(acmacs::surface::Surface& aSurface) { GeographicMapDraw::prepare(aSurface); const double point_scaled = aSurface.convert(mPointSize).value(); for (const auto& location_color: mPointsAtLocation) { if (const auto location = acmacs::locationdb::get().find(location_color.first); location.has_value()) { const double center_lat = location->latitude(), center_long = location->longitude(); auto iter = location_color.second.iterator(); auto [coloring_data, priority] = *iter; add_point(priority, center_lat, center_long, coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width); ++iter; for (size_t circle_no = 1; iter; ++circle_no) { const double distance = point_scaled * mDensity * static_cast<double>(circle_no); const size_t circle_capacity = static_cast<size_t>(M_PI * 2.0 * distance * static_cast<double>(circle_no) / (point_scaled * mDensity)); const size_t points_on_circle = std::min(circle_capacity, iter.left()); const double step = 2.0 * M_PI / static_cast<double>(points_on_circle); for (auto index: acmacs::range(0UL, points_on_circle)) { std::tie(coloring_data, priority) = *iter; add_point(priority, center_lat + distance * std::cos(static_cast<double>(index) * step), center_long + distance * std::sin(static_cast<double>(index) * step), coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width); ++iter; } } } } sort_points(); } // GeographicMapWithPointsFromHidb::prepare // ---------------------------------------------------------------------- void GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by(const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, const std::vector<std::string>& aPriority, std::string_view aStartDate, std::string_view aEndDate) { // std::cerr << "add_points_from_hidb_colored_by" << '\n'; const auto& hidb = hidb::get(acmacs::virus::type_subtype_t{mVirusType}); auto antigens = hidb.antigens()->date_range(aStartDate, aEndDate); fmt::print("\nINFO: dates: {}..{} antigens: {}\n", aStartDate, aEndDate, antigens.size()); if (!aPriority.empty()) fmt::print("INFO: priority: {} (the last in this list to be drawn on top of others)\n", aPriority); acmacs::Counter<std::string> tag_counter; for (auto antigen: antigens) { auto [tag, coloring_data] = aColorOverride.color(*antigen); if (coloring_data.fill.is_no_change()) std::tie(tag, coloring_data) = aColoring.color(*antigen); tag_counter.count(tag); try { const auto found = std::find(std::begin(aPriority), std::end(aPriority), tag); mPointsAtLocation.add(location_of_antigen(*antigen), found == std::end(aPriority) ? 0 : (found - std::begin(aPriority) + 1), coloring_data); } catch (virus_name::Unrecognized&) { // thrown by location_of_antigen() -> virus_name::location() } } fmt::print("INFO: tags:\n{}", tag_counter.report_sorted_max_first()); // std::transform(mPoints.begin(), mPoints.end(), std::ostream_iterator<std::string>(std::cerr, "\n"), [](const auto& e) -> std::string { return e.first; }); } // GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by // ---------------------------------------------------------------------- void GeographicTimeSeries::draw(std::string_view aFilenamePrefix, const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, double aImageWidth) const { for (const auto& slot : time_series_) { auto map = map_; // make a copy! map.add_points_from_hidb_colored_by(aColoring, aColorOverride, priority_, date::display(slot.first), date::display(slot.after_last)); map.title().add_line(acmacs::time_series::text_name(slot)); map.draw(fmt::format("{}{}.pdf", aFilenamePrefix, acmacs::time_series::numeric_name(slot)), aImageWidth); } } // GeographicTimeSeries::draw // ---------------------------------------------------------------------- GeographicMapColoring::TagColor ColoringByLineageAndDeletionMutants::color(const hidb::Antigen& aAntigen) const { try { const auto& seqdb = acmacs::seqdb::get(); if (const auto ref_2del = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref_2del && ref_2del.has_clade(seqdb, "2DEL2017")) { // fmt::print(stderr, "DEBUG: 2del {}\n", aAntigen.full_name()); return {"VICTORIA_2DEL", mDeletionMutantColor.empty() ? mColors.at("VICTORIA_2DEL") : ColoringData{mDeletionMutantColor}}; } else if (const auto ref_3del = acmacs::seqdb::get().find_hi_name(aAntigen.full_name()); ref_3del && ref_3del.has_clade(seqdb, "3DEL2017")) { // fmt::print(stderr, "DEBUG: 3del {}\n", aAntigen.full_name()); return {"VICTORIA_3DEL", mDeletionMutantColor.empty() ? mColors.at("VICTORIA_3DEL") : ColoringData{mDeletionMutantColor}}; } else { const auto lineage = aAntigen.lineage().to_string(); // fmt::print(stderr, "DEBUG: {} {}\n", lineage.substr(0, 3), aAntigen.full_name()); return {lineage, mColors.at(lineage)}; } } catch (...) { return {"UNKNOWN", {GREY50}}; } } // ColoringByLineageAndDeletionMutants::color // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#pragma once #include "acmacs-base/point-coordinates.hh" #include "acmacs-base/line.hh" #include "acmacs-base/size-scale.hh" #include "acmacs-base/number-of-dimensions.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace detail { using TransformationBase = std::array<double, 16>; constexpr size_t transformation_size = 4; constexpr std::array<size_t, transformation_size> transformation_row_base{0, transformation_size, transformation_size * 2, transformation_size * 3}; } // namespace detail // (N+1)xN matrix handling transformation in N-dimensional space. The last row is for translation // handles transformation and translation in 2D and 3D class Transformation : public detail::TransformationBase { public: Transformation(number_of_dimensions_t num_dim = number_of_dimensions_t{2}) : detail::TransformationBase{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{num_dim} {} Transformation(const Transformation&) = default; Transformation(double a11, double a12, double a21, double a22) : detail::TransformationBase{a11, a12, 0.0, 0.0, a21, a22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{2} { } Transformation& operator=(const Transformation&) = default; Transformation& operator=(Transformation&&) = default; bool operator==(const Transformation& rhs) const { return std::equal(begin(), end(), rhs.begin()); } bool operator!=(const Transformation& rhs) const { return !operator==(rhs); } void reset(number_of_dimensions_t num_dim) { operator=(Transformation(num_dim)); } constexpr double _x(size_t offset) const { return operator[](offset); } constexpr double& _x(size_t offset) { return operator[](offset); } constexpr double _x(size_t row, size_t column) const { return operator[](detail::transformation_row_base[row] + column); } constexpr double& _x(size_t row, size_t column) { return operator[](detail::transformation_row_base[row] + column); } template <typename S> constexpr double& operator()(S row, S column) { return _x(static_cast<size_t>(row), static_cast<size_t>(column)); } template <typename S> constexpr double operator()(S row, S column) const { return _x(static_cast<size_t>(row), static_cast<size_t>(column)); } template <typename S> constexpr double& translation(S dimension) { return _x(detail::transformation_size - 1, static_cast<size_t>(dimension)); } template <typename S> constexpr double translation(S dimension) const { return _x(detail::transformation_size - 1, static_cast<size_t>(dimension)); } std::vector<double> as_vector() const { switch (*number_of_dimensions) { case 2: return {_x(0, 0), _x(0, 1), _x(1, 0), _x(1, 1)}; case 3: return {_x(0, 0), _x(0, 1), _x(0, 2), _x(1, 0), _x(1, 1), _x(1, 2), _x(2, 0), _x(2, 1), _x(2, 2)}; } return {}; } template <typename Iterator> Transformation& set(Iterator first, size_t size) { switch (size) { case 4: _x(0, 0) = *first++; _x(0, 1) = *first++; _x(1, 0) = *first++; _x(1, 1) = *first++; break; case 9: _x(0, 0) = *first++; _x(0, 1) = *first++; _x(0, 2) = *first++; _x(1, 0) = *first++; _x(1, 1) = *first++; _x(1, 2) = *first++; _x(2, 0) = *first++; _x(2, 1) = *first++; _x(2, 2) = *first++; } return *this; } // 2D -------------------------------------------------- constexpr double a() const { return _x(0, 0); } constexpr double& a() { return _x(0, 0); } constexpr double b() const { return _x(0, 1); } constexpr double& b() { return _x(0, 1); } constexpr double c() const { return _x(1, 0); } constexpr double& c() { return _x(1, 0); } constexpr double d() const { return _x(1, 1); } constexpr double& d() { return _x(1, 1); } Transformation& set(double a11, double a12, double a21, double a22) { a() = a11; b() = a12; c() = a21; d() = a22; return *this; } void rotate(double aAngle) { const double cos = std::cos(aAngle); const double sin = std::sin(aAngle); const double r0 = cos * a() + -sin * c(); const double r1 = cos * b() + -sin * d(); c() = sin * a() + cos * c(); d() = sin * b() + cos * d(); a() = r0; b() = r1; } void rotate(Rotation aAngle) { return rotate(*aAngle); } void flip_transformed(double x, double y) { const double x2y2 = x * x - y * y, xy = 2 * x * y; const double r0 = x2y2 * a() + xy * c(); const double r1 = x2y2 * b() + xy * d(); c() = xy * a() + -x2y2 * c(); d() = xy * b() + -x2y2 * d(); a() = r0; b() = r1; } // reflect about a line specified with vector [aX, aY] void flip(double aX, double aY) { // vector [aX, aY] must be first transformed using inversion of this const auto inv = inverse(); const double x = aX * inv.a() + aY * inv.c(); const double y = aX * inv.b() + aY * inv.d(); flip_transformed(x, y); } void multiply_by(const Transformation& t) { const auto r0 = a() * t.a() + b() * t.c(); const auto r1 = a() * t.b() + b() * t.d(); const auto r2 = c() * t.a() + d() * t.c(); const auto r3 = c() * t.b() + d() * t.d(); a() = r0; b() = r1; c() = r2; d() = r3; } LineDefinedByEquation transform(LineDefinedByEquation source) const { const auto p1 = transform(PointCoordinates{0, source.intercept()}); const auto p2 = transform(PointCoordinates{1, source.slope() + source.intercept()}); const auto slope = (p2.y() - p1.y()) / (p2.x() - p1.x()); return {slope, p1.y() - slope * p1.x()}; } double determinant() const { return a() * d() - b() * c(); } class singular : public std::exception { }; Transformation inverse() const { const auto deter = determinant(); if (float_zero(deter)) throw singular{}; return {d() / deter, -b() / deter, -c() / deter, a() / deter}; } double difference(const Transformation& another) const { if (number_of_dimensions != another.number_of_dimensions) throw std::runtime_error("cannot compare transformations with different number_of_dimensions"); double sum{0.0}; for (number_of_dimensions_t i1{0}; i1 < number_of_dimensions; ++i1) for (number_of_dimensions_t i2{0}; i2 < number_of_dimensions; ++i2) sum += sqr(_x(*i1, *i2) - another._x(*i1, *i2)); return sum; } // 2D and 3D -------------------------------------------------- PointCoordinates transform(const PointCoordinates& source) const { switch (*source.number_of_dimensions()) { case 2: return PointCoordinates(source.x() * a() + source.y() * c(), source.x() * b() + source.y() * d()); case 3: return PointCoordinates(source.x() * _x(0, 0) + source.y() * _x(1, 0) + source.z() * _x(2, 0), source.x() * _x(0, 1) + source.y() * _x(1, 1) + source.z() * _x(2, 1), source.x() * _x(0, 2) + source.y() * _x(1, 2) + source.z() * _x(2, 2)); } throw std::runtime_error("invalid number_of_dimensions in PointCoordinates"); } template <typename Iter> void transform(Iter first, Iter last) const { for (; first != last; ++first) *first = transform(*first); } // 3D -------------------------------------------------- number_of_dimensions_t number_of_dimensions{2}; bool valid() const { return std::none_of(begin(), end(), [](auto val) { return std::isnan(val); }); } }; // class Transformation } // namespace acmacs // ---------------------------------------------------------------------- template <> struct fmt::formatter<acmacs::Transformation> : public fmt::formatter<acmacs::fmt_helper::default_formatter> { template <typename FormatContext> auto format(const acmacs::Transformation& transformation, FormatContext& ctx) { switch (*transformation.number_of_dimensions) { case 2: return format_to(ctx.out(), "[{}, {}, {}, {}]", transformation.a(), transformation.b(), transformation.c(), transformation.d()); case 3: return format_to(ctx.out(), "[[{}, {}, {}], [{}, {}, {}], [{}, {}, {}]]", transformation._x(0, 0), transformation._x(0, 1), transformation._x(0, 2), transformation._x(1, 0), transformation._x(1, 1), transformation._x(1, 2), transformation._x(2, 0), transformation._x(2, 1), transformation._x(2, 2)); } return format_to(ctx.out(), ""); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>minor fixes<commit_after>#pragma once #include "acmacs-base/point-coordinates.hh" #include "acmacs-base/line.hh" #include "acmacs-base/size-scale.hh" #include "acmacs-base/number-of-dimensions.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace detail { using TransformationBase = std::array<double, 16>; constexpr size_t transformation_size = 4; constexpr std::array<size_t, transformation_size> transformation_row_base{0, transformation_size, transformation_size * 2, transformation_size * 3}; } // namespace detail // (N+1)xN matrix handling transformation in N-dimensional space. The last row is for translation // handles transformation and translation in 2D and 3D class Transformation : public detail::TransformationBase { public: Transformation(number_of_dimensions_t num_dim = number_of_dimensions_t{2}) : detail::TransformationBase{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{num_dim} {} Transformation(const Transformation&) = default; Transformation(double a11, double a12, double a21, double a22) : detail::TransformationBase{a11, a12, 0.0, 0.0, a21, a22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{2} { } Transformation& operator=(const Transformation&) = default; Transformation& operator=(Transformation&&) = default; bool operator==(const Transformation& rhs) const { return std::equal(begin(), end(), rhs.begin()); } bool operator!=(const Transformation& rhs) const { return !operator==(rhs); } void reset(number_of_dimensions_t num_dim) { operator=(Transformation(num_dim)); } constexpr double _x(size_t offset) const { return operator[](offset); } constexpr double& _x(size_t offset) { return operator[](offset); } constexpr double _x(size_t row, size_t column) const { return operator[](detail::transformation_row_base[row] + column); } constexpr double& _x(size_t row, size_t column) { return operator[](detail::transformation_row_base[row] + column); } template <typename S> constexpr double& operator()(S row, S column) { return _x(static_cast<size_t>(row), static_cast<size_t>(column)); } template <typename S> constexpr double operator()(S row, S column) const { return _x(static_cast<size_t>(row), static_cast<size_t>(column)); } template <typename S> constexpr double& translation(S dimension) { return _x(detail::transformation_size - 1, static_cast<size_t>(dimension)); } template <typename S> constexpr double translation(S dimension) const { return _x(detail::transformation_size - 1, static_cast<size_t>(dimension)); } std::vector<double> as_vector() const { switch (*number_of_dimensions) { case 2: return {_x(0, 0), _x(0, 1), _x(1, 0), _x(1, 1)}; case 3: return {_x(0, 0), _x(0, 1), _x(0, 2), _x(1, 0), _x(1, 1), _x(1, 2), _x(2, 0), _x(2, 1), _x(2, 2)}; } return {}; } template <typename Iterator> Transformation& set(Iterator first, size_t size) { switch (size) { case 4: _x(0, 0) = *first++; _x(0, 1) = *first++; _x(1, 0) = *first++; _x(1, 1) = *first++; break; case 9: _x(0, 0) = *first++; _x(0, 1) = *first++; _x(0, 2) = *first++; _x(1, 0) = *first++; _x(1, 1) = *first++; _x(1, 2) = *first++; _x(2, 0) = *first++; _x(2, 1) = *first++; _x(2, 2) = *first++; } return *this; } // 2D -------------------------------------------------- constexpr double a() const { return _x(0, 0); } constexpr double& a() { return _x(0, 0); } constexpr double b() const { return _x(0, 1); } constexpr double& b() { return _x(0, 1); } constexpr double c() const { return _x(1, 0); } constexpr double& c() { return _x(1, 0); } constexpr double d() const { return _x(1, 1); } constexpr double& d() { return _x(1, 1); } Transformation& set(double a11, double a12, double a21, double a22) { a() = a11; b() = a12; c() = a21; d() = a22; return *this; } void rotate(double aAngle) { const double cos = std::cos(aAngle); const double sin = std::sin(aAngle); const double r0 = cos * a() + -sin * c(); const double r1 = cos * b() + -sin * d(); c() = sin * a() + cos * c(); d() = sin * b() + cos * d(); a() = r0; b() = r1; } void rotate(Rotation aAngle) { return rotate(*aAngle); } void flip_transformed(double x, double y) { const double x2y2 = x * x - y * y, xy = 2 * x * y; const double r0 = x2y2 * a() + xy * c(); const double r1 = x2y2 * b() + xy * d(); c() = xy * a() + -x2y2 * c(); d() = xy * b() + -x2y2 * d(); a() = r0; b() = r1; } // reflect about a line specified with vector [aX, aY] void flip(double aX, double aY) { // vector [aX, aY] must be first transformed using inversion of this const auto inv = inverse(); const double x = aX * inv.a() + aY * inv.c(); const double y = aX * inv.b() + aY * inv.d(); flip_transformed(x, y); } void multiply_by(const Transformation& t) { const auto r0 = a() * t.a() + b() * t.c(); const auto r1 = a() * t.b() + b() * t.d(); const auto r2 = c() * t.a() + d() * t.c(); const auto r3 = c() * t.b() + d() * t.d(); a() = r0; b() = r1; c() = r2; d() = r3; } LineDefinedByEquation transform(LineDefinedByEquation source) const { const auto p1 = transform(PointCoordinates{0, source.intercept()}); const auto p2 = transform(PointCoordinates{1, source.slope() + source.intercept()}); const auto slope = (p2.y() - p1.y()) / (p2.x() - p1.x()); return {slope, p1.y() - slope * p1.x()}; } double determinant() const { return a() * d() - b() * c(); } class singular : public std::exception { }; Transformation inverse() const { const auto deter = determinant(); if (float_zero(deter)) throw singular{}; return {d() / deter, -b() / deter, -c() / deter, a() / deter}; } double difference(const Transformation& another) const { if (number_of_dimensions != another.number_of_dimensions) throw std::runtime_error("cannot compare transformations with different number_of_dimensions"); double sum{0.0}; for (number_of_dimensions_t i1{0}; i1 < number_of_dimensions; ++i1) for (number_of_dimensions_t i2{0}; i2 < number_of_dimensions; ++i2) sum += sqr(_x(*i1, *i2) - another._x(*i1, *i2)); return sum; } // 2D and 3D -------------------------------------------------- PointCoordinates transform(const PointCoordinates& source) const { switch (*source.number_of_dimensions()) { case 2: return PointCoordinates(source.x() * a() + source.y() * c(), source.x() * b() + source.y() * d()); case 3: return PointCoordinates(source.x() * _x(0, 0) + source.y() * _x(1, 0) + source.z() * _x(2, 0), source.x() * _x(0, 1) + source.y() * _x(1, 1) + source.z() * _x(2, 1), source.x() * _x(0, 2) + source.y() * _x(1, 2) + source.z() * _x(2, 2)); } throw std::runtime_error("invalid number_of_dimensions in PointCoordinates"); } template <typename Iter> void transform(Iter first, Iter last) const { for (; first != last; ++first) *first = transform(*first); } // 3D -------------------------------------------------- number_of_dimensions_t number_of_dimensions{2}; bool valid() const { return std::none_of(begin(), end(), [](auto val) { return std::isnan(val); }); } }; // class Transformation } // namespace acmacs // ---------------------------------------------------------------------- template <> struct fmt::formatter<acmacs::Transformation> : public fmt::formatter<acmacs::fmt_helper::default_formatter> { template <typename FormatContext> auto format(const acmacs::Transformation& transformation, FormatContext& ctx) { switch (*transformation.number_of_dimensions) { case 2: return format_to(ctx.out(), "[{}, {}, {}, {}]", transformation.a(), transformation.b(), transformation.c(), transformation.d()); case 3: return format_to(ctx.out(), "[[{}, {}, {}], [{}, {}, {}], [{}, {}, {}]]", transformation._x(0, 0), transformation._x(0, 1), transformation._x(0, 2), transformation._x(1, 0), transformation._x(1, 1), transformation._x(1, 2), transformation._x(2, 0), transformation._x(2, 1), transformation._x(2, 2)); } return format_to(ctx.out(), ""); } }; // ---------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #pragma once #include "JsonBuffer.hpp" namespace ArduinoJson { // Implements a JsonBuffer with fixed memory allocation. // The template paramenter CAPACITY specifies the capacity of the buffer in // bytes. template <size_t CAPACITY> class StaticJsonBuffer : public JsonBuffer { public: explicit StaticJsonBuffer() : _size(0) {} virtual ~StaticJsonBuffer() {} size_t capacity() const { return CAPACITY; } size_t size() const { return _size; } // void clear() { _size = 0; } protected: virtual void* alloc(size_t size) { if (_size + size > CAPACITY) return NULL; void* p = &_buffer[_size]; _size += size; return p; } private: uint8_t _buffer[CAPACITY]; size_t _size; }; } <commit_msg>Removed comment line<commit_after>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #pragma once #include "JsonBuffer.hpp" namespace ArduinoJson { // Implements a JsonBuffer with fixed memory allocation. // The template paramenter CAPACITY specifies the capacity of the buffer in // bytes. template <size_t CAPACITY> class StaticJsonBuffer : public JsonBuffer { public: explicit StaticJsonBuffer() : _size(0) {} virtual ~StaticJsonBuffer() {} size_t capacity() const { return CAPACITY; } size_t size() const { return _size; } protected: virtual void* alloc(size_t size) { if (_size + size > CAPACITY) return NULL; void* p = &_buffer[_size]; _size += size; return p; } private: uint8_t _buffer[CAPACITY]; size_t _size; }; } <|endoftext|>
<commit_before>// @(#)root/proof:$Id$ // Author: Sangsu Ryu 22/06/2010 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSelHandleDataSet // // // // PROOF selector for file cache release. // // List of files to be cleaned for each node is provided by client. // // // ////////////////////////////////////////////////////////////////////////// #define TSelHandleDataSet_cxx #include "TSelHandleDataSet.h" #include "TDSet.h" #include "TFile.h" #include "TMap.h" #include "TParameter.h" #include "TProofBenchTypes.h" #include "TSystem.h" #include "TUrl.h" #include <unistd.h> #include <fcntl.h> ClassImp(TSelHandleDataSet) //______________________________________________________________________________ void TSelHandleDataSet::SlaveBegin(TTree *) { // Init the type from the input parameters TObject *o = fInput->FindObject("PROOF_Benchmark_HandleDSType"); if (o) fType = dynamic_cast<TPBHandleDSType *>(o); TNamed *n = dynamic_cast<TNamed *>(fInput->FindObject("PROOF_Benchmark_DestDir")); if (n) { fDestDir = n->GetTitle(); if (gSystem->AccessPathName(fDestDir)) { // Create the directory if (gSystem->mkdir(fDestDir, kTRUE) != 0) { fDestDir = ""; Error("SlaveBegin", "could not create dir '%s'", fDestDir.Data()); } else { if (gSystem->AccessPathName(fDestDir, kWritePermission)) { fDestDir = ""; Error("SlaveBegin", "dir '%s' is not writable by this process", fDestDir.Data()); } else { Info("SlaveBegin", "dir '%s' successfully created", fDestDir.Data()); } } } } // Use default if nothing found in the input list if (!fType) fType = new TPBHandleDSType(TPBHandleDSType::kReleaseCache); } //______________________________________________________________________________ void TSelHandleDataSet::ReleaseCache(const char *fn) { // Release the memory cache associated with file 'fn'. #if defined(R__LINUX) TString filename(fn); Int_t fd; fd = open(filename.Data(), O_RDONLY); if (fd) { fdatasync(fd); posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); close(fd); Info("ReleaseCache", "file cache for file '%s' cleaned ...", filename.Data()); } else { Error("ReleaseCache", "cannot open file '%s' for cache clean up", filename.Data()); } #else Info("ReleaseCache", "dummy function: file '%s' untouched ...", fn); #endif // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::CheckCache(const char * /*fn*/) { // Check the memory cache associated with file 'fn'. Warning("CheckCache", "cache checker not implemented yet"); // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::RemoveFile(const char *fn) { // Physically remove the file 'fn'. if (!gSystem->AccessPathName(fn, kWritePermission)) { if (gSystem->Unlink(fn) != 0) { Error("RemoveFile", "problems removing file '%s' ...", fn); } else { if (!gSystem->AccessPathName(fn)) Warning("RemoveFile", "'unlink' returned success but the file still exists ('%s')", fn); } } else { if (!gSystem->AccessPathName(fn)) { Error("RemoveFile", "file '%s' cannot removed by this process", fn); } else { Error("RemoveFile", "file '%s' does not exists", fn); } } // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::CopyFile(const char *fn) { // Copy file 'fn' to fDestDir // Check if we have a destination dir if (fDestDir.IsNull()) { Error("CopyFile", "destination dir undefined: file '%s' not copied", fn); return; } TString basefn = gSystem->BaseName(TUrl(fn, kTRUE).GetFile()); TString dst = TString::Format("%s/%s", fDestDir.Data(), basefn.Data()); if (!TFile::Cp(fn, dst.Data())) { Error("CopyFile", "problems copying file '%s' to '%s'", fn, dst.Data()); return; } Info("CopyFile", "file '%s' created ...", dst.Data()); // Done return; } //______________________________________________________________________________ Bool_t TSelHandleDataSet::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either TTree::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // WARNING when a selector is used with a TChain, you must use // the pointer to the current TTree to call GetEntry(entry). // The entry is always the local entry number in the current tree. // Assuming that fChain is the pointer to the TChain being processed, // use fChain->GetTree()->GetEntry(entry). TDSetElement *fCurrent = 0; TPair *elemPair = 0; if (fInput && (elemPair = dynamic_cast<TPair *> (fInput->FindObject("PROOF_CurrentElement")))) { if ((fCurrent = dynamic_cast<TDSetElement *>(elemPair->Value()))) { Info("Process", "entry %lld: file: '%s'", entry, fCurrent->GetName()); } else { Error("Process", "entry %lld: no file specified!", entry); return kFALSE; } } if (fType->GetType() == TPBHandleDSType::kReleaseCache) { // Release the file cache ReleaseCache(TUrl(fCurrent->GetName()).GetFile()); } else if (fType->GetType() == TPBHandleDSType::kCheckCache) { // Check the file cache CheckCache(TUrl(fCurrent->GetName()).GetFile()); } else if (fType->GetType() == TPBHandleDSType::kRemoveFiles) { // Remove the file RemoveFile(fCurrent->GetName()); } else if (fType->GetType() == TPBHandleDSType::kCopyFiles) { // Copy file CopyFile(fCurrent->GetName()); } else { // Type unknown Warning("Process", "type: %d is unknown", fType->GetType()); } return kTRUE; } <commit_msg><commit_after>// @(#)root/proof:$Id$ // Author: Sangsu Ryu 22/06/2010 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSelHandleDataSet // // // // PROOF selector for file cache release. // // List of files to be cleaned for each node is provided by client. // // // ////////////////////////////////////////////////////////////////////////// #define TSelHandleDataSet_cxx #include "TSelHandleDataSet.h" #include "TDSet.h" #include "TEnv.h" #include "TFile.h" #include "TMap.h" #include "TParameter.h" #include "TProofBenchTypes.h" #include "TSystem.h" #include "TUrl.h" #include <unistd.h> #include <fcntl.h> ClassImp(TSelHandleDataSet) //______________________________________________________________________________ void TSelHandleDataSet::SlaveBegin(TTree *) { // Init the type from the input parameters TObject *o = fInput->FindObject("PROOF_Benchmark_HandleDSType"); if (o) fType = dynamic_cast<TPBHandleDSType *>(o); TNamed *n = dynamic_cast<TNamed *>(fInput->FindObject("PROOF_Benchmark_DestDir")); if (n) { fDestDir = n->GetTitle(); if (gSystem->AccessPathName(fDestDir)) { // Create the directory if (gSystem->mkdir(fDestDir, kTRUE) != 0) { fDestDir = ""; Error("SlaveBegin", "could not create dir '%s'", fDestDir.Data()); } else { if (gSystem->AccessPathName(fDestDir, kWritePermission)) { fDestDir = ""; Error("SlaveBegin", "dir '%s' is not writable by this process", fDestDir.Data()); } else { Info("SlaveBegin", "dir '%s' successfully created", fDestDir.Data()); } } } } // Use default if nothing found in the input list if (!fType) fType = new TPBHandleDSType(TPBHandleDSType::kReleaseCache); } //______________________________________________________________________________ void TSelHandleDataSet::ReleaseCache(const char *fn) { // Release the memory cache associated with file 'fn'. #if defined(R__LINUX) TString filename(fn); Int_t fd; fd = open(filename.Data(), O_RDONLY); if (fd > -1) { fdatasync(fd); posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); close(fd); Info("ReleaseCache", "file cache for file '%s' cleaned ...", filename.Data()); } else { Error("ReleaseCache", "cannot open file '%s' for cache clean up", filename.Data()); } #else Info("ReleaseCache", "dummy function: file '%s' untouched ...", fn); #endif // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::CheckCache(const char * /*fn*/) { // Check the memory cache associated with file 'fn'. Warning("CheckCache", "cache checker not implemented yet"); // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::RemoveFile(const char *fn) { // Physically remove the file 'fn'. if (!gSystem->AccessPathName(fn, kWritePermission)) { if (gSystem->Unlink(fn) != 0) { Error("RemoveFile", "problems removing file '%s' ...", fn); } else { if (!gSystem->AccessPathName(fn)) Warning("RemoveFile", "'unlink' returned success but the file still exists ('%s')", fn); } } else { if (!gSystem->AccessPathName(fn)) { Error("RemoveFile", "file '%s' cannot removed by this process", fn); } else { Error("RemoveFile", "file '%s' does not exists", fn); } } // Done return; } //______________________________________________________________________________ void TSelHandleDataSet::CopyFile(const char *fn) { // Copy file 'fn' to fDestDir // Check if we have a destination dir if (fDestDir.IsNull()) { Error("CopyFile", "destination dir undefined: file '%s' not copied", fn); return; } TString basefn = gSystem->BaseName(TUrl(fn, kTRUE).GetFile()); TString dst = TString::Format("%s/%s", fDestDir.Data(), basefn.Data()); if (!TFile::Cp(fn, dst.Data())) { Error("CopyFile", "problems copying file '%s' to '%s'", fn, dst.Data()); return; } Info("CopyFile", "file '%s' created ...", dst.Data()); // Done return; } //______________________________________________________________________________ Bool_t TSelHandleDataSet::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either TTree::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // WARNING when a selector is used with a TChain, you must use // the pointer to the current TTree to call GetEntry(entry). // The entry is always the local entry number in the current tree. // Assuming that fChain is the pointer to the TChain being processed, // use fChain->GetTree()->GetEntry(entry). TDSetElement *fCurrent = 0; TPair *elemPair = 0; if (fInput && (elemPair = dynamic_cast<TPair *> (fInput->FindObject("PROOF_CurrentElement")))) { if ((fCurrent = dynamic_cast<TDSetElement *>(elemPair->Value()))) { Info("Process", "entry %lld: file: '%s'", entry, fCurrent->GetName()); } else { Error("Process", "entry %lld: no file specified!", entry); return kFALSE; } } // Resolve the file type; this also adjusts names for Xrd based systems TString fname(fCurrent->GetName()); TString lfname = gEnv->GetValue("Path.Localroot", ""); TFile::EFileType type = TFile::GetType(fname, "", &lfname); TString fproto = TUrl(fname).GetProtocol(); if (type == TFile::kLocal && fproto != "root" && fproto != "xrd") lfname = TUrl(fname).GetFileAndOptions(); if (fType->GetType() == TPBHandleDSType::kReleaseCache) { // Release the file cache if (type == TFile::kLocal) { ReleaseCache(lfname); } else { Error("Process", "attempt to call ReleaseCache for a non-local file: '%s'", fname.Data()); } } else if (fType->GetType() == TPBHandleDSType::kCheckCache) { // Check the file cache if (type == TFile::kLocal) { CheckCache(lfname); } else { Error("Process", "attempt to call CheckCache for a non-local file: '%s'", fname.Data()); } } else if (fType->GetType() == TPBHandleDSType::kRemoveFiles) { // Remove the file RemoveFile(fname); } else if (fType->GetType() == TPBHandleDSType::kCopyFiles) { // Copy file CopyFile(fname); } else { // Type unknown Warning("Process", "type: %d is unknown", fType->GetType()); } return kTRUE; } <|endoftext|>
<commit_before>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__ #define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__ #include <algorithm> #include <limits> #include <iterator> #include <vector> #include <aleph/geometry/distances/Traits.hh> #include <aleph/math/SymmetricMatrix.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> namespace aleph { namespace geometry { template <class Distance, class Container, class InputIterator> auto buildWitnessComplex( const Container& container, InputIterator begin, InputIterator end, unsigned nu = 2, typename Distance::ResultType R = typename Distance::ResultType() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, unsigned> > { using IndexType = typename std::iterator_traits<InputIterator>::value_type; using DataType = typename Distance::ResultType; using Traits = aleph::distances::Traits<Distance>; using VertexType = unsigned; // TODO: make configurable using Simplex = topology::Simplex<DataType, VertexType>; using SimplicialComplex = topology::SimplicialComplex<Simplex>; // These are only the *indices* of the landmarks, with respect to the // underlying point cloud. std::vector<IndexType> landmarkIndices( begin, end ); auto n = landmarkIndices.size(); auto N = container.size(); auto d = container.dimension(); // Much of the behaviour below will be undefined if we permit such // situations to occur. if( n == 0 || N == 0 ) return {}; // Distance matrix between a set of $n$ landmarks (rows) and $N$ data // points. std::vector< std::vector<DataType> > D; D.reserve( n ); Distance dist; Traits traits; for( std::size_t i = 0; i < n; i++ ) { std::vector<DataType> distances; distances.reserve( N ); auto&& landmark = container[ landmarkIndices.at(i) ]; for( std::size_t j = 0; j < N; j++ ) { auto&& point = container[j]; distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) ); } D.push_back( distances ); } // Records the appearance times of each potential edge in the witness // complex. aleph::math::SymmetricMatrix<DataType> M( n ); for( std::size_t i = 0; i < n; i++ ) { for( std::size_t j = i+1; j < n; j++ ) { auto min = std::numeric_limits<DataType>::max(); for( std::size_t k = 0; k < N; k++ ) min = std::min( min, std::max( D[i][k], D[j][k] ) ); M(i,j) = min; } } // Get smallest entries of the distance matrix. This is required for // deciding whether a specific edge is valid or not, with respect to // the given parameters. std::vector<DataType> smallest( N ); if( nu != 0 ) { for( std::size_t col = 0; col < N; col++ ) { // FIXME: getting the column like this is extremely wasteful; // would it not be nicer to store the values differently? std::vector<DataType> column( n ); for( std::size_t i = 0; i < n; i++ ) column[i] = D[i][col]; std::nth_element( column.begin(), column.begin() + nu - 1, column.end() ); smallest[col] = column.at( nu - 1 ); } } auto max = *std::max_element( smallest.begin(), smallest.end() ); std::vector<Simplex> simplices; for( std::size_t i = 0; i < n; i++ ) { simplices.push_back( Simplex( static_cast<VertexType>(i) ) ); for( std::size_t j = i+1; j < n; j++ ) { // Skip pairs that cannot possibly give rise to an edge because of // their distance to each other. if( M(i,j) > R + max ) continue; for( std::size_t col = 0; col < N; col++ ) { if( M(i,j) <= R + smallest.at(col) ) { auto u = static_cast<VertexType>(i); auto v = static_cast<VertexType>(j); simplices.push_back( Simplex( {u,v}, M(i,j) ) ); break; } } } } return SimplicialComplex( simplices.begin(), simplices.end() ); } } // namespace geometry } // namespace aleph #endif <commit_msg>Added Rips expansion to witness complex<commit_after>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__ #define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__ #include <algorithm> #include <limits> #include <iterator> #include <vector> #include <aleph/geometry/RipsExpander.hh> #include <aleph/geometry/distances/Traits.hh> #include <aleph/math/SymmetricMatrix.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> namespace aleph { namespace geometry { template <class Distance, class Container, class InputIterator> auto buildWitnessComplex( const Container& container, InputIterator begin, InputIterator end, unsigned nu = 2, typename Distance::ResultType R = typename Distance::ResultType() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, unsigned> > { using IndexType = typename std::iterator_traits<InputIterator>::value_type; using DataType = typename Distance::ResultType; using Traits = aleph::distances::Traits<Distance>; using VertexType = unsigned; // TODO: make configurable using Simplex = topology::Simplex<DataType, VertexType>; using SimplicialComplex = topology::SimplicialComplex<Simplex>; // These are only the *indices* of the landmarks, with respect to the // underlying point cloud. std::vector<IndexType> landmarkIndices( begin, end ); auto n = landmarkIndices.size(); auto N = container.size(); auto d = container.dimension(); // Much of the behaviour below will be undefined if we permit such // situations to occur. if( n == 0 || N == 0 ) return {}; // Distance matrix between a set of $n$ landmarks (rows) and $N$ data // points. std::vector< std::vector<DataType> > D; D.reserve( n ); Distance dist; Traits traits; for( std::size_t i = 0; i < n; i++ ) { std::vector<DataType> distances; distances.reserve( N ); auto&& landmark = container[ landmarkIndices.at(i) ]; for( std::size_t j = 0; j < N; j++ ) { auto&& point = container[j]; distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) ); } D.push_back( distances ); } // Records the appearance times of each potential edge in the witness // complex. aleph::math::SymmetricMatrix<DataType> M( n ); for( std::size_t i = 0; i < n; i++ ) { for( std::size_t j = i+1; j < n; j++ ) { auto min = std::numeric_limits<DataType>::max(); for( std::size_t k = 0; k < N; k++ ) min = std::min( min, std::max( D[i][k], D[j][k] ) ); M(i,j) = min; } } // Get smallest entries of the distance matrix. This is required for // deciding whether a specific edge is valid or not, with respect to // the given parameters. std::vector<DataType> smallest( N ); if( nu != 0 ) { for( std::size_t col = 0; col < N; col++ ) { // FIXME: getting the column like this is extremely wasteful; // would it not be nicer to store the values differently? std::vector<DataType> column( n ); for( std::size_t i = 0; i < n; i++ ) column[i] = D[i][col]; std::nth_element( column.begin(), column.begin() + nu - 1, column.end() ); smallest[col] = column.at( nu - 1 ); } } auto max = *std::max_element( smallest.begin(), smallest.end() ); std::vector<Simplex> simplices; for( std::size_t i = 0; i < n; i++ ) { simplices.push_back( Simplex( static_cast<VertexType>(i) ) ); for( std::size_t j = i+1; j < n; j++ ) { // Skip pairs that cannot possibly give rise to an edge because of // their distance to each other. if( M(i,j) > R + max ) continue; for( std::size_t col = 0; col < N; col++ ) { if( M(i,j) <= R + smallest.at(col) ) { auto u = static_cast<VertexType>(i); auto v = static_cast<VertexType>(j); // FIXME: this is incorrect; there could be edges with // a smaller weight simplices.push_back( Simplex( {u,v}, M(i,j) ) ); break; } } } } aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; SimplicialComplex K = SimplicialComplex( simplices.begin(), simplices.end() ); SimplicialComplex L = ripsExpander( K, static_cast<unsigned>(n) ); // TODO: make dimension configurable? L = ripsExpander.assignMaximumWeight( L ); return L; } } // namespace geometry } // namespace aleph #endif <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <map> #include <set> #include "teckyl/tc/lang/parser.h" #include "teckyl/tc/lang/sema.h" #include <llvm/Support/CommandLine.h> #include <llvm/Support/ErrorHandling.h> #include <mlir/IR/Verifier.h> #include <mlir/IR/Builders.h> #include <mlir/IR/Module.h> #include <mlir/Dialect/StandardOps/EDSC/Intrinsics.h> #include <mlir/Dialect/Linalg/IR/LinalgOps.h> #include "mlir/Dialect/SCF/SCF.h" #include "teckyl/HeaderGen.h" #include "teckyl/MLIRGen.h" // Commandline options static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-"), llvm::cl::value_desc("filename")); enum Action { None, DumpAST, DumpMLIR, DumpHeader, DumpInference }; static llvm::cl::opt<enum Action> emitAction( "emit", llvm::cl::desc("Select the kind of output desired"), llvm::cl::values(clEnumValN(DumpAST, "ast", "output the AST dump")), llvm::cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")), llvm::cl::values(clEnumValN( DumpHeader, "header", "Output a C header file with signatures for generated functions")), llvm::cl::values(clEnumValN(DumpInference, "inference", "output inference results"))); static llvm::cl::opt<std::string> includeGuard( "include-guard", llvm::cl::desc( "Header include guard used for protection againstdouble inclusion"), llvm::cl::init("FILE_GENERATED_BY_TECKYL"), llvm::cl::value_desc("symbol")); static llvm::cl::opt<teckyl::MLIRGenOptions::BodyOp> bodyOp( "body-op", llvm::cl::desc("Select the operation used for the body of computations"), llvm::cl::values(clEnumValN(teckyl::MLIRGenOptions::BodyOp::LinalgGeneric, "linalg.generic", "Linalg.generic")), llvm::cl::values(clEnumValN(teckyl::MLIRGenOptions::BodyOp::ScfFor, "scf.for", "Sets of nested instances of Scf.for"))); static llvm::cl::opt<bool> specializeLinalgOps( "specialize-linalg-ops", llvm::cl::desc("Use structured Ops from the linalg dialect for common " "operation (e.g., matrix multiplications)"), llvm::cl::init(false)); // Reads an entire file into a string std::string readFile(const std::string &filename) { std::ifstream ifs(filename); if (!ifs.good()) THROW_OR_ASSERT(teckyl::Exception("Could not open file " + filename)); return std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } // Parses a string with TCs and returns a map with one entry for each // kernel, composed of the kernel's name and its AST. std::map<std::string, lang::Def> parse(const std::string &tc, const std::string &filename) { lang::Parser parser(tc, filename); std::map<std::string, lang::Def> parsed; while (parser.L.cur().kind != lang::TK_EOF) { auto t = parser.parseFunction(); auto def = lang::Def(t); auto name = def.name().name(); parsed.emplace(std::make_pair(name, def)); } return parsed; } // Dumps the AST for a set of kernels to stdout void dumpAST(const std::map<std::string, lang::Def> &tcs) { for (const auto &res : tcs) std::cout << res.second << std::endl; } // Dumps the inference results from the semantic analysis for a set of // kernels to stdout void dumpInference(const std::map<std::string, lang::Def> &tcs) { tc::CompilerOptions co; co.printRanges = true; lang::Sema sema(co); for (const auto &res : tcs) auto func = sema.checkFunction(res.second); } // Generates an MLIR representation for each TC kernel and dumps a // textual representation to stdout. // // Returns 0 on success or 1 in case of an error. void dumpMLIR(const std::map<std::string, lang::Def> &tcs) { mlir::registerDialect<mlir::StandardOpsDialect>(); mlir::registerDialect<mlir::linalg::LinalgDialect>(); mlir::registerDialect<mlir::scf::SCFDialect>(); mlir::MLIRContext context; mlir::ModuleOp module; mlir::OpBuilder builder(&context); teckyl::MLIRGenOptions options; lang::Sema sema; options.body_op = bodyOp; options.specialize_linalg_ops = specializeLinalgOps; if (options.specialize_linalg_ops && options.body_op != teckyl::MLIRGenOptions::BodyOp::LinalgGeneric) { THROW_OR_ASSERT( teckyl::Exception("--specialize-linalg-ops can only be used in " "conjunction with --body-op=linalg.generic")); } module = mlir::ModuleOp::create(builder.getUnknownLoc()); for (auto &tc : tcs) { lang::TreeRef checked = sema.checkFunction(tc.second); mlir::FuncOp f = teckyl::buildMLIRFunction(context, tc.first, lang::Def(checked), options); module.push_back(f); } module.print(llvm::outs()); if (mlir::failed(mlir::verify(module))) llvm_unreachable("Module verification error"); } int main(int argc, char **argv) { std::map<std::string, lang::Def> tcs; llvm::cl::ParseCommandLineOptions(argc, argv, "teckyl frontend\n"); #ifdef COMPILE_WITH_EXCEPTIONS try { #endif // COMPILE_WITH_EXCEPTIONS std::string source = readFile(inputFilename); tcs = parse(source, inputFilename); switch (emitAction) { case Action::DumpAST: dumpAST(tcs); break; case Action::DumpMLIR: dumpMLIR(tcs); break; case Action::DumpHeader: std::cout << teckyl::genHeader(tcs, includeGuard); break; case Action::DumpInference: dumpInference(tcs); break; default: THROW_OR_ASSERT(teckyl::Exception("Unknown action")); } #ifdef COMPILE_WITH_EXCEPTIONS } catch (teckyl::Exception &e) { std::cerr << "Error: " << e.getMessage() << std::endl; return 1; } catch (...) { std::cerr << "An unknown error has occured." << std::endl; return 1; } #endif // COMPILE_WITH_EXCEPTIONS } <commit_msg>Teckyl: Print error with contents of lang::ErrorReport when parsing fails<commit_after>#include <fstream> #include <iostream> #include <map> #include <set> #include "teckyl/tc/lang/parser.h" #include "teckyl/tc/lang/sema.h" #include <llvm/Support/CommandLine.h> #include <llvm/Support/ErrorHandling.h> #include <mlir/IR/Verifier.h> #include <mlir/IR/Builders.h> #include <mlir/IR/Module.h> #include <mlir/Dialect/StandardOps/EDSC/Intrinsics.h> #include <mlir/Dialect/Linalg/IR/LinalgOps.h> #include "mlir/Dialect/SCF/SCF.h" #include "teckyl/HeaderGen.h" #include "teckyl/MLIRGen.h" // Commandline options static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-"), llvm::cl::value_desc("filename")); enum Action { None, DumpAST, DumpMLIR, DumpHeader, DumpInference }; static llvm::cl::opt<enum Action> emitAction( "emit", llvm::cl::desc("Select the kind of output desired"), llvm::cl::values(clEnumValN(DumpAST, "ast", "output the AST dump")), llvm::cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")), llvm::cl::values(clEnumValN( DumpHeader, "header", "Output a C header file with signatures for generated functions")), llvm::cl::values(clEnumValN(DumpInference, "inference", "output inference results"))); static llvm::cl::opt<std::string> includeGuard( "include-guard", llvm::cl::desc( "Header include guard used for protection againstdouble inclusion"), llvm::cl::init("FILE_GENERATED_BY_TECKYL"), llvm::cl::value_desc("symbol")); static llvm::cl::opt<teckyl::MLIRGenOptions::BodyOp> bodyOp( "body-op", llvm::cl::desc("Select the operation used for the body of computations"), llvm::cl::values(clEnumValN(teckyl::MLIRGenOptions::BodyOp::LinalgGeneric, "linalg.generic", "Linalg.generic")), llvm::cl::values(clEnumValN(teckyl::MLIRGenOptions::BodyOp::ScfFor, "scf.for", "Sets of nested instances of Scf.for"))); static llvm::cl::opt<bool> specializeLinalgOps( "specialize-linalg-ops", llvm::cl::desc("Use structured Ops from the linalg dialect for common " "operation (e.g., matrix multiplications)"), llvm::cl::init(false)); // Reads an entire file into a string std::string readFile(const std::string &filename) { std::ifstream ifs(filename); if (!ifs.good()) THROW_OR_ASSERT(teckyl::Exception("Could not open file " + filename)); return std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } // Parses a string with TCs and returns a map with one entry for each // kernel, composed of the kernel's name and its AST. std::map<std::string, lang::Def> parse(const std::string &tc, const std::string &filename) { lang::Parser parser(tc, filename); std::map<std::string, lang::Def> parsed; while (parser.L.cur().kind != lang::TK_EOF) { auto t = parser.parseFunction(); auto def = lang::Def(t); auto name = def.name().name(); parsed.emplace(std::make_pair(name, def)); } return parsed; } // Dumps the AST for a set of kernels to stdout void dumpAST(const std::map<std::string, lang::Def> &tcs) { for (const auto &res : tcs) std::cout << res.second << std::endl; } // Dumps the inference results from the semantic analysis for a set of // kernels to stdout void dumpInference(const std::map<std::string, lang::Def> &tcs) { tc::CompilerOptions co; co.printRanges = true; lang::Sema sema(co); for (const auto &res : tcs) auto func = sema.checkFunction(res.second); } // Generates an MLIR representation for each TC kernel and dumps a // textual representation to stdout. // // Returns 0 on success or 1 in case of an error. void dumpMLIR(const std::map<std::string, lang::Def> &tcs) { mlir::registerDialect<mlir::StandardOpsDialect>(); mlir::registerDialect<mlir::linalg::LinalgDialect>(); mlir::registerDialect<mlir::scf::SCFDialect>(); mlir::MLIRContext context; mlir::ModuleOp module; mlir::OpBuilder builder(&context); teckyl::MLIRGenOptions options; lang::Sema sema; options.body_op = bodyOp; options.specialize_linalg_ops = specializeLinalgOps; if (options.specialize_linalg_ops && options.body_op != teckyl::MLIRGenOptions::BodyOp::LinalgGeneric) { THROW_OR_ASSERT( teckyl::Exception("--specialize-linalg-ops can only be used in " "conjunction with --body-op=linalg.generic")); } module = mlir::ModuleOp::create(builder.getUnknownLoc()); for (auto &tc : tcs) { lang::TreeRef checked = sema.checkFunction(tc.second); mlir::FuncOp f = teckyl::buildMLIRFunction(context, tc.first, lang::Def(checked), options); module.push_back(f); } module.print(llvm::outs()); if (mlir::failed(mlir::verify(module))) llvm_unreachable("Module verification error"); } int main(int argc, char **argv) { std::map<std::string, lang::Def> tcs; llvm::cl::ParseCommandLineOptions(argc, argv, "teckyl frontend\n"); #ifdef COMPILE_WITH_EXCEPTIONS try { #endif // COMPILE_WITH_EXCEPTIONS std::string source = readFile(inputFilename); tcs = parse(source, inputFilename); switch (emitAction) { case Action::DumpAST: dumpAST(tcs); break; case Action::DumpMLIR: dumpMLIR(tcs); break; case Action::DumpHeader: std::cout << teckyl::genHeader(tcs, includeGuard); break; case Action::DumpInference: dumpInference(tcs); break; default: THROW_OR_ASSERT(teckyl::Exception("Unknown action")); } #ifdef COMPILE_WITH_EXCEPTIONS } catch (teckyl::Exception &e) { std::cerr << "Error: " << e.getMessage() << std::endl; return 1; } catch (lang::ErrorReport &r) { std::cerr << "Error: " << r.what() << std::endl; return 1; } catch (...) { std::cerr << "An unknown error has occured." << std::endl; return 1; } #endif // COMPILE_WITH_EXCEPTIONS } <|endoftext|>
<commit_before>/* Copyright (c) 2011, The Mineserver Project 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 the The Mineserver Project 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 HOLDER 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. */ /* Original code: http://pastebin.com/niWTqLvk */ /* struct RegionFile { struct ChunkOffset { int sector_number; char sector_count; } chunk_offsets[1024]; struct ChunkTimestamp { int timestamp; } chunk_timestamps[1024]; struct Sector { int length; char version; char data[length - 1]; } sectors[file_length / 4096 - 1]; } */ #ifdef WIN32 #include <conio.h> #include <WinSock2.h> #else #include <netinet/in.h> #endif #include <fstream> #include <vector> #include <string> #include <stdint.h> #include <time.h> #include "mcregion.h" #include "tools.h" RegionFile::RegionFile(): sizeDelta(0) { } bool RegionFile::openFile(std::string mapDir, int32_t chunkX, int32_t chunkZ) { std::string strchunkZ; std::string strchunkX; my_itoa(abs(chunkZ >> 5),strchunkZ,10); if((chunkZ < 0)) strchunkZ.append('-',1); my_itoa(abs(chunkX >> 5),strchunkX,10); if((chunkX < 0)) strchunkX.append('-',1); regionFile.open(std::string(mapDir + "/r." + strchunkZ + "." + strchunkX + ".mcr"), std::ios::binary); //Store file length regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); //New file? if(fileLength < SECTOR_BYTES) { int zeroInt = 0; //Offsets for (int i = 0; i < SECTOR_INTS; i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),4); } //Timestamps for (int i = 0; i < SECTOR_INTS; i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),4); } //Get new size regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); } //Not multiple of 4096 if(fileLength & 0xffff != 0) { int zeroInt = 0; for (int i = 0; i < 0xfff-(fileLength & 0xfff); i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),1); } //Get new size regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); } int sectorCount = fileLength/SECTOR_BYTES; sectorFree.assign(sectorCount, true); //Offsets sectorFree[0] = false; //Timestamps sectorFree[1] = false; //Read sectors and mark used for (int i = 0; i < SECTOR_INTS; i++) { int offset = 0; regionFile.read(reinterpret_cast<char *>(&offset),4); offset = ntohl(offset); offsets[i] = offset; if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree.size()) { for (int sectorNum = 0; sectorNum < (offset & 0xFF); sectorNum++) { sectorFree[(offset >> 8) + sectorNum] = false; } } } //Read timestamps for (int i = 0; i < SECTOR_INTS; ++i) { int lastModValue = 0; regionFile.read(reinterpret_cast<char *>(&lastModValue),4); lastModValue = ntohl(lastModValue); timestamps[i] = lastModValue; } return true; } bool RegionFile::writeChunk(int8_t *chunkdata, int32_t datalen, int32_t x, int32_t z) { int offset = getOffset(x, z); int sectorNumber = offset >> 8; int sectorsAllocated = offset & 0xFF; int sectorsNeeded = (datalen + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1; // maximum chunk size is 1MB if (sectorsNeeded >= 256) { return false; } //Current space is large enought if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) { write(sectorNumber, chunkdata, datalen); } //Need more space! else { //Free current sectors for (int i = 0; i < sectorsAllocated; ++i) { sectorFree[sectorNumber + i] = true; } int runStart = -1; for(int i = 0; i < sectorFree.size(); i++) { if(sectorFree[i]) { runStart = i; break; } } int runLength = 0; if (runStart != -1) { for (int i = runStart; i < sectorFree.size(); i++) { //Not first? if (runLength != 0) { if (sectorFree[i]) runLength++; else runLength = 0; } //Reset on first else if (sectorFree[i]) { runStart = i; runLength = 1; } //We have the space if (runLength >= sectorsNeeded) { break; } } } //Did we find the space we need? if (runLength >= sectorsNeeded) { sectorNumber = runStart; setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); //Reserve space for (int i = 0; i < sectorsNeeded; ++i) { sectorFree[sectorNumber + i] = false; } //Write data write(sectorNumber, chunkdata, datalen); } //If no space, grow file else { regionFile.seekp(0, std::ios::end); sectorNumber = sectorFree.size(); for (int i = 0; i < sectorsNeeded; ++i) { char zerobyte = 0; for(int b = 0; b < SECTOR_BYTES; b++) { regionFile.write(&zerobyte, 1); } sectorFree.push_back(false); } sizeDelta += SECTOR_BYTES * sectorsNeeded; //Write chunk data write(sectorNumber, chunkdata, datalen); setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); } } setTimestamp(x, z, time(NULL)); } bool RegionFile::readChunk(int8_t *chunkdata, int32_t *datalen, int32_t x, int32_t z) { int offset = getOffset(x, z); //Chunk not found if (offset == 0) { return false; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; //Invalid sector if (sectorNumber + numSectors > sectorFree.size()) { return false; } regionFile.seekg(sectorNumber * SECTOR_BYTES); int length = 0; regionFile.read(reinterpret_cast<char *>(&length),4); length = ntohl(length); //Invalid length? if(length > SECTOR_BYTES * numSectors) { return false; } char version; regionFile.read(&version,1); //TODO: do something with version? *datalen = length; chunkdata = new int8_t[length]; regionFile.read((char *)chunkdata, length); return true; }<commit_msg>another RegionFile fix ;D<commit_after>/* Copyright (c) 2011, The Mineserver Project 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 the The Mineserver Project 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 HOLDER 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. */ /* Original code: http://pastebin.com/niWTqLvk */ /* struct RegionFile { struct ChunkOffset { int sector_number; char sector_count; } chunk_offsets[1024]; struct ChunkTimestamp { int timestamp; } chunk_timestamps[1024]; struct Sector { int length; char version; char data[length - 1]; } sectors[file_length / 4096 - 1]; } */ #ifdef WIN32 #include <conio.h> #include <WinSock2.h> #else #include <netinet/in.h> #endif #include <fstream> #include <vector> #include <string> #include <stdint.h> #include <time.h> #include "mcregion.h" #include "tools.h" RegionFile::RegionFile(): sizeDelta(0) { } bool RegionFile::openFile(std::string mapDir, int32_t chunkX, int32_t chunkZ) { std::string strchunkZ; std::string strchunkX; my_itoa(abs(chunkZ >> 5),strchunkZ,10); if((chunkZ < 0)) strchunkZ.append('-',1); my_itoa(abs(chunkX >> 5),strchunkX,10); if((chunkX < 0)) strchunkX.append('-',1); regionFile.open(std::string(mapDir + "/r." + strchunkZ + "." + strchunkX + ".mcr").c_str(), std::ios::binary); //Store file length regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); //New file? if(fileLength < SECTOR_BYTES) { int zeroInt = 0; //Offsets for (int i = 0; i < SECTOR_INTS; i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),4); } //Timestamps for (int i = 0; i < SECTOR_INTS; i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),4); } //Get new size regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); } //Not multiple of 4096 if(fileLength & 0xffff != 0) { int zeroInt = 0; for (int i = 0; i < 0xfff-(fileLength & 0xfff); i++) { regionFile.write(reinterpret_cast<const char *>(&zeroInt),1); } //Get new size regionFile.seekg (0, std::ios::end); fileLength = regionFile.tellg(); regionFile.seekg (0, std::ios::beg); } int sectorCount = fileLength/SECTOR_BYTES; sectorFree.assign(sectorCount, true); //Offsets sectorFree[0] = false; //Timestamps sectorFree[1] = false; //Read sectors and mark used for (int i = 0; i < SECTOR_INTS; i++) { int offset = 0; regionFile.read(reinterpret_cast<char *>(&offset),4); offset = ntohl(offset); offsets[i] = offset; if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree.size()) { for (int sectorNum = 0; sectorNum < (offset & 0xFF); sectorNum++) { sectorFree[(offset >> 8) + sectorNum] = false; } } } //Read timestamps for (int i = 0; i < SECTOR_INTS; ++i) { int lastModValue = 0; regionFile.read(reinterpret_cast<char *>(&lastModValue),4); lastModValue = ntohl(lastModValue); timestamps[i] = lastModValue; } return true; } bool RegionFile::writeChunk(int8_t *chunkdata, int32_t datalen, int32_t x, int32_t z) { int offset = getOffset(x, z); int sectorNumber = offset >> 8; int sectorsAllocated = offset & 0xFF; int sectorsNeeded = (datalen + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1; // maximum chunk size is 1MB if (sectorsNeeded >= 256) { return false; } //Current space is large enought if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) { write(sectorNumber, chunkdata, datalen); } //Need more space! else { //Free current sectors for (int i = 0; i < sectorsAllocated; ++i) { sectorFree[sectorNumber + i] = true; } int runStart = -1; for(int i = 0; i < sectorFree.size(); i++) { if(sectorFree[i]) { runStart = i; break; } } int runLength = 0; if (runStart != -1) { for (int i = runStart; i < sectorFree.size(); i++) { //Not first? if (runLength != 0) { if (sectorFree[i]) runLength++; else runLength = 0; } //Reset on first else if (sectorFree[i]) { runStart = i; runLength = 1; } //We have the space if (runLength >= sectorsNeeded) { break; } } } //Did we find the space we need? if (runLength >= sectorsNeeded) { sectorNumber = runStart; setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); //Reserve space for (int i = 0; i < sectorsNeeded; ++i) { sectorFree[sectorNumber + i] = false; } //Write data write(sectorNumber, chunkdata, datalen); } //If no space, grow file else { regionFile.seekp(0, std::ios::end); sectorNumber = sectorFree.size(); for (int i = 0; i < sectorsNeeded; ++i) { char zerobyte = 0; for(int b = 0; b < SECTOR_BYTES; b++) { regionFile.write(&zerobyte, 1); } sectorFree.push_back(false); } sizeDelta += SECTOR_BYTES * sectorsNeeded; //Write chunk data write(sectorNumber, chunkdata, datalen); setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); } } setTimestamp(x, z, time(NULL)); } bool RegionFile::readChunk(int8_t *chunkdata, int32_t *datalen, int32_t x, int32_t z) { int offset = getOffset(x, z); //Chunk not found if (offset == 0) { return false; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; //Invalid sector if (sectorNumber + numSectors > sectorFree.size()) { return false; } regionFile.seekg(sectorNumber * SECTOR_BYTES); int length = 0; regionFile.read(reinterpret_cast<char *>(&length),4); length = ntohl(length); //Invalid length? if(length > SECTOR_BYTES * numSectors) { return false; } char version; regionFile.read(&version,1); //TODO: do something with version? *datalen = length; chunkdata = new int8_t[length]; regionFile.read((char *)chunkdata, length); return true; }<|endoftext|>
<commit_before>#include <pcl/common/common.h> #include <image_geometry/pinhole_camera_model.h> #include <common/small_helpers.hpp> #include <opencv2/core/core.hpp> #ifndef PROJECT_2D_H_ #define PROJECT_2D_H_ namespace project2d { inline void project_2d( const image_geometry::PinholeCameraModel &camera_model, const pcl::PointCloud<pcl::PointXYZI> &in, pcl::PointCloud<pcl::PointXY> &out_2d, pcl::PointCloud<pcl::PointXYZI> &out_3d, unsigned int camera_width = 1024, unsigned int camera_height = 768 ) { BOOST_FOREACH (const pcl::PointXYZI& pt, in.points) { if( pt.z > 1) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, camera_width ) && between<int>( 0, point_image.y, camera_height ) ) { // Point in image push to 2d and 3d point pcl::PointXY pt_2d; pt_2d.x = point_image.x; pt_2d.y = point_image.y; out_2d.push_back(pt_2d); out_3d.push_back(pt); } } } } enum Field{ INTENSITY, DEPTH }; template <typename PointT> void project_2d( const image_geometry::PinholeCameraModel &camera_model, const pcl::PointCloud<PointT> &in, cv::Mat &image, Field field = DEPTH, int point_size = 1, float min_distance = 1 ) { BOOST_FOREACH (const PointT& pt, in.points) { if( pt.z > min_distance) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, image.rows ) && between<int>( 0, point_image.y, image.cols ) ) { switch(field){ default: case DEPTH: cv::circle(image, point_image, point_size, cv::Scalar(pt.z), -1); break; case INTENSITY: cv::circle(image, point_image, point_size, cv::Scalar(pt.intensity), -1); break; } } } } } template <typename PointT> void project_2d( const image_geometry::PinholeCameraModel &camera_model, pcl::PointCloud<PointT> &in, std::vector<std::vector<boost::shared_ptr<pcl::PointXYZI> > > &out, int image_width, int image_height) { unsigned int hits = 0; BOOST_FOREACH (pcl::PointXYZI& pt, in.points){ if( pt.z > 1) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, image_width ) && between<int>( 0, point_image.y, image_height ) ) { // Point in image push to 2d and 3d point out[point_image.x][point_image.y].reset(new pcl::PointXYZI(pt)); //printf("project_2d: point: z: %f \n", out[point_image.x][point_image.y]->z); ++hits; } } } } template <typename PointT> void project_2d( std::vector<std::vector<boost::shared_ptr<PointT> > > &in, cv::Mat &out, Field field = INTENSITY, int point_size = 1 ) { for(int y = 0; y < in[0].size(); y++) { for(int x = 0; x < in.size(); x++) { cv::Point3i value; if( in[x][y]){ /* found something */ switch(field){ default: case DEPTH: cv::circle(out, cv::Point2i(x,y), point_size, cv::Scalar(in[x][y]->z), -1); break; case INTENSITY: cv::circle(out, cv::Point2i(x,y), point_size, cv::Scalar(in[x][y]->intensity), -1); break; } } } } } } #endif <commit_msg>fixed mixed rows cols<commit_after>#include <pcl/common/common.h> #include <image_geometry/pinhole_camera_model.h> #include <common/small_helpers.hpp> #include <opencv2/core/core.hpp> #ifndef PROJECT_2D_H_ #define PROJECT_2D_H_ namespace project2d { inline void project_2d( const image_geometry::PinholeCameraModel &camera_model, const pcl::PointCloud<pcl::PointXYZI> &in, pcl::PointCloud<pcl::PointXY> &out_2d, pcl::PointCloud<pcl::PointXYZI> &out_3d, unsigned int camera_width = 1024, unsigned int camera_height = 768 ) { BOOST_FOREACH (const pcl::PointXYZI& pt, in.points) { if( pt.z > 1) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, camera_width ) && between<int>( 0, point_image.y, camera_height ) ) { // Point in image push to 2d and 3d point pcl::PointXY pt_2d; pt_2d.x = point_image.x; pt_2d.y = point_image.y; out_2d.push_back(pt_2d); out_3d.push_back(pt); } } } } enum Field{ INTENSITY, DEPTH }; template <typename PointT> void project_2d( const image_geometry::PinholeCameraModel &camera_model, const pcl::PointCloud<PointT> &in, cv::Mat &image, Field field = DEPTH, int point_size = 1, float min_distance = 1 ) { BOOST_FOREACH (const PointT& pt, in.points) { if( pt.z > min_distance) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, image.cols ) && between<int>( 0, point_image.y, image.rows ) ) { switch(field){ default: case DEPTH: cv::circle(image, point_image, point_size, cv::Scalar(pt.z), -1); break; case INTENSITY: cv::circle(image, point_image, point_size, cv::Scalar(pt.intensity), -1); break; } } } } } template <typename PointT> void project_2d( const image_geometry::PinholeCameraModel &camera_model, pcl::PointCloud<PointT> &in, std::vector<std::vector<boost::shared_ptr<pcl::PointXYZI> > > &out, int image_width, int image_height) { unsigned int hits = 0; BOOST_FOREACH (pcl::PointXYZI& pt, in.points){ if( pt.z > 1) { // min distance from camera 1m cv::Point2f point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z)); if( between<int>(0, point_image.x, image_width ) && between<int>( 0, point_image.y, image_height ) ) { // Point in image push to 2d and 3d point out[point_image.x][point_image.y].reset(new pcl::PointXYZI(pt)); //printf("project_2d: point: z: %f \n", out[point_image.x][point_image.y]->z); ++hits; } } } } template <typename PointT> void project_2d( std::vector<std::vector<boost::shared_ptr<PointT> > > &in, cv::Mat &out, Field field = INTENSITY, int point_size = 1 ) { for(int y = 0; y < in[0].size(); y++) { for(int x = 0; x < in.size(); x++) { cv::Point3i value; if( in[x][y]){ /* found something */ switch(field){ default: case DEPTH: cv::circle(out, cv::Point2i(x,y), point_size, cv::Scalar(in[x][y]->z), -1); break; case INTENSITY: cv::circle(out, cv::Point2i(x,y), point_size, cv::Scalar(in[x][y]->intensity), -1); break; } } } } } } #endif <|endoftext|>
<commit_before><commit_msg>Use MObject::hasObj to test for shadingEngine nodes<commit_after><|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log: AliT0Preprocessor.cxx,v $ Revision 1.8 2007/12/07 15:22:51 alla bug fixed by Alberto Revision 1.7 2007/12/06 16:35:24 alla new bugs fixed by Tomek Revision 1.5 2007/11/23 19:28:52 alla bug fixed Version 2.1 2007/11/21 Preprocessor storing data to OCDB (T.Malkiewicz) Version 1.1 2006/10 Preliminary test version (T.Malkiewicz) */ // T0 preprocessor: // 1) takes data from DCS and passes it to the class AliTOFDataDCS // for processing and writes the result to the Reference DB. // 2) takes data form DAQ (both from Laser Calibration and Physics runs), // processes it, and stores either to OCDB or to Reference DB. #include "AliT0Preprocessor.h" #include "AliT0DataDCS.h" #include "AliT0CalibWalk.h" #include "AliT0CalibTimeEq.h" #include "AliCDBMetaData.h" #include "AliDCSValue.h" #include "AliCDBEntry.h" #include "AliLog.h" #include <TTimeStamp.h> #include <TFile.h> #include <TObjString.h> #include <TNamed.h> #include "AliT0Dqclass.h" #include "TClass.h" ClassImp(AliT0Preprocessor) //____________________________________________________ AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : AliPreprocessor("T00", shuttle), fData(0) { //constructor AddRunType("PHYSICS"); AddRunType("STANDALONE"); AddRunType("AMPLITUDE_CALIBRATION"); } //____________________________________________________ AliT0Preprocessor::~AliT0Preprocessor() { //destructor delete fData; fData = 0; } //____________________________________________________ void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime) { // Creates AliT0DataDCS object AliPreprocessor::Initialize(run, startTime, endTime); AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString())); fData = new AliT0DataDCS(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery()); } //____________________________________________________ Bool_t AliT0Preprocessor::ProcessDCS(){ // Check whether DCS should be processed or not... TString runType = GetRunType(); Log(Form("ProcessDCS - RunType: %s",runType.Data())); if((runType == "STANDALONE")|| (runType == "PHYSICS") ){ // return kFALSE; return kTRUE; }else{ return kFALSE; } } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){ // Fills data into AliT0DataDCS object Log("Processing DCS DP"); Bool_t resultDCSMap=kFALSE; Bool_t resultDCSStore=kFALSE; if(!dcsAliasMap) { Log("No DCS input data"); return 1; } else { resultDCSMap=fData->ProcessData(*dcsAliasMap); if(!resultDCSMap) { Log("Error when processing DCS data"); return 2;// return error Code for processed DCS data not stored } else { AliCDBMetaData metaDataDCS; metaDataDCS.SetBeamPeriod(0); metaDataDCS.SetResponsible("Tomasz Malkiewicz"); metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object."); AliInfo("Storing DCS Data"); resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS); if (!resultDCSStore) { Log("Some problems occurred while storing DCS data results in ReferenceDB"); return 2;// return error Code for processed DCS data not stored } } } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessLaser() { // Processing data from DAQ Standalone run Log("Processing Laser calibration - Walk Correction"); Bool_t resultLaser = kFALSE; Bool_t writeok = kFALSE; //processing DAQ TList* list = GetFileSources(kDAQ, "AMPLITUDE_CALIBRATION"); AliT0CalibWalk *laser = new AliT0CalibWalk(); TObjString *source; if (list) { TIter iter(list); while ((source = dynamic_cast<TObjString *> (iter.Next()))) { const char *laserFile = GetFile(kDAQ, "AMPLITUDE_CALIBRATION", source->GetName()); if (laserFile) { Log(Form("File with Id AMPLITUDE_CALIBRAION found in source %s!", source->GetName())); writeok = laser->MakeWalkCorrGraph(laserFile); } } AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Tomek&Michal"); metaData.SetComment("Walk correction from laser runs."); if (writeok) resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1); else { Log(Form("writeok = %d no peaks in CFD spectra",writeok)); return 0; } Log(Form("resultLaser = %d",resultLaser)); if (!resultLaser) { Log("No Laser Data stored"); return 3;//return error code for failure in storing Laser Data } } else { Log(Form("Could not find file with Id AMPLITUDE_CALIBRAION ")); return 1; } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessPhysics(){ //Processing data from DAQ Physics run Log("Processing Physics"); Bool_t resultOnline=kFALSE; //processing DAQ TList* listPhys = GetFileSources(kDAQ, "PHYSICS"); if (listPhys) { TIter iter(listPhys); TObjString *sourcePhys; while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next()))) { const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName()); if (filePhys) { AliT0CalibTimeEq *online = new AliT0CalibTimeEq(); online->Reset(); Bool_t writeok = online->ComputeOnlineParams(filePhys); AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Alla Maevskaya"); metaData.SetComment("Time equalizing result."); if (writeok) resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1); else { Log(Form("writeok = %d not enough data for equalizing",resultOnline)); return 0; } Log(Form("resultOnline = %d",resultOnline)); delete online; } else { Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName())); return 1; } } if (!resultOnline) { Log("No Data stored"); return 4;//return error code for failure in storing OCDB Data } } else { Log("No sources found for id PHYSICS!"); return 1; } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap ) { // T0 preprocessor return codes: // return=0 : all ok // return=1 : no DCS input data // return=2 : failed to store DCS data // return=3 : no Laser data (Walk correction) // return=4 : failed to store OCDB time equalized data // return=5 : no DAQ input for OCDB // return=6 : failed to retrieve DAQ data from OCDB // return=7 : failed to store T0 OCDB data // return=8 : not enough data for equalizing Bool_t dcsDP = ProcessDCS(); Log(Form("dcsDP = %d",dcsDP)); TString runType = GetRunType(); Log(Form("RunType: %s",runType.Data())); //processing if(runType == "STANDALONE"){ if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } } if(runType == "AMPLITUDE_CALIBRATION"){ Int_t iresultLaser = ProcessLaser(); if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } Log(Form("iresultLaser = %d",iresultLaser)); return iresultLaser; } else if(runType == "PHYSICS"){ Int_t iresultPhysics = ProcessPhysics(); if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } Log(Form("iresultPhysics = %d",iresultPhysics)); return iresultPhysics; } return 0; } <commit_msg> Writingg DSC DP only for physics runs<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log: AliT0Preprocessor.cxx,v $ Revision 1.8 2007/12/07 15:22:51 alla bug fixed by Alberto Revision 1.7 2007/12/06 16:35:24 alla new bugs fixed by Tomek Revision 1.5 2007/11/23 19:28:52 alla bug fixed Version 2.1 2007/11/21 Preprocessor storing data to OCDB (T.Malkiewicz) Version 1.1 2006/10 Preliminary test version (T.Malkiewicz) */ // T0 preprocessor: // 1) takes data from DCS and passes it to the class AliTOFDataDCS // for processing and writes the result to the Reference DB. // 2) takes data form DAQ (both from Laser Calibration and Physics runs), // processes it, and stores either to OCDB or to Reference DB. #include "AliT0Preprocessor.h" #include "AliT0DataDCS.h" #include "AliT0CalibWalk.h" #include "AliT0CalibTimeEq.h" #include "AliCDBMetaData.h" #include "AliDCSValue.h" #include "AliCDBEntry.h" #include "AliLog.h" #include <TTimeStamp.h> #include <TFile.h> #include <TObjString.h> #include <TNamed.h> #include "AliT0Dqclass.h" #include "TClass.h" ClassImp(AliT0Preprocessor) //____________________________________________________ AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : AliPreprocessor("T00", shuttle), fData(0) { //constructor AddRunType("PHYSICS"); AddRunType("STANDALONE"); AddRunType("AMPLITUDE_CALIBRATION"); } //____________________________________________________ AliT0Preprocessor::~AliT0Preprocessor() { //destructor delete fData; fData = 0; } //____________________________________________________ void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime) { // Creates AliT0DataDCS object AliPreprocessor::Initialize(run, startTime, endTime); AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString())); fData = new AliT0DataDCS(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery()); } //____________________________________________________ Bool_t AliT0Preprocessor::ProcessDCS(){ // Check whether DCS should be processed or not... TString runType = GetRunType(); Log(Form("ProcessDCS - RunType: %s",runType.Data())); if(runType == "PHYSICS" ) return kTRUE; else return kFALSE; } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){ // Fills data into AliT0DataDCS object Log("Processing DCS DP"); Bool_t resultDCSMap=kFALSE; Bool_t resultDCSStore=kFALSE; if(!dcsAliasMap) { Log("No DCS input data"); return 1; } else { resultDCSMap=fData->ProcessData(*dcsAliasMap); if(!resultDCSMap) { Log("Error when processing DCS data"); return 2;// return error Code for processed DCS data not stored } else { AliCDBMetaData metaDataDCS; metaDataDCS.SetBeamPeriod(0); metaDataDCS.SetResponsible("Tomasz Malkiewicz"); metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object."); AliInfo("Storing DCS Data"); resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS); if (!resultDCSStore) { Log("Some problems occurred while storing DCS data results in ReferenceDB"); return 2;// return error Code for processed DCS data not stored } } } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessLaser() { // Processing data from DAQ Standalone run Log("Processing Laser calibration - Walk Correction"); Bool_t resultLaser = kFALSE; Bool_t writeok = kFALSE; //processing DAQ TList* list = GetFileSources(kDAQ, "AMPLITUDE_CALIBRATION"); AliT0CalibWalk *laser = new AliT0CalibWalk(); TObjString *source; if (list) { TIter iter(list); while ((source = dynamic_cast<TObjString *> (iter.Next()))) { const char *laserFile = GetFile(kDAQ, "AMPLITUDE_CALIBRATION", source->GetName()); if (laserFile) { Log(Form("File with Id AMPLITUDE_CALIBRAION found in source %s!", source->GetName())); writeok = laser->MakeWalkCorrGraph(laserFile); } } AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Tomek&Michal"); metaData.SetComment("Walk correction from laser runs."); if (writeok) resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1); else { Log(Form("writeok = %d no peaks in CFD spectra",writeok)); return 0; } Log(Form("resultLaser = %d",resultLaser)); if (!resultLaser) { Log("No Laser Data stored"); return 3;//return error code for failure in storing Laser Data } } else { Log(Form("Could not find file with Id AMPLITUDE_CALIBRAION ")); return 1; } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::ProcessPhysics(){ //Processing data from DAQ Physics run Log("Processing Physics"); Bool_t resultOnline=kFALSE; //processing DAQ TList* listPhys = GetFileSources(kDAQ, "PHYSICS"); if (listPhys) { TIter iter(listPhys); TObjString *sourcePhys; while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next()))) { const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName()); if (filePhys) { AliT0CalibTimeEq *online = new AliT0CalibTimeEq(); online->Reset(); Bool_t writeok = online->ComputeOnlineParams(filePhys); AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("Alla Maevskaya"); metaData.SetComment("Time equalizing result."); if (writeok) resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1); else { Log(Form("writeok = %d not enough data for equalizing",resultOnline)); return 0; } Log(Form("resultOnline = %d",resultOnline)); delete online; } else { Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName())); return 1; } } if (!resultOnline) { Log("No Data stored"); return 4;//return error code for failure in storing OCDB Data } } else { Log("No sources found for id PHYSICS!"); return 1; } return 0; } //____________________________________________________ UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap ) { // T0 preprocessor return codes: // return=0 : all ok // return=1 : no DCS input data // return=2 : failed to store DCS data // return=3 : no Laser data (Walk correction) // return=4 : failed to store OCDB time equalized data // return=5 : no DAQ input for OCDB // return=6 : failed to retrieve DAQ data from OCDB // return=7 : failed to store T0 OCDB data // return=8 : not enough data for equalizing Bool_t dcsDP = ProcessDCS(); Log(Form("dcsDP = %d",dcsDP)); TString runType = GetRunType(); Log(Form("RunType: %s",runType.Data())); //processing if(runType == "STANDALONE"){ if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } } if(runType == "AMPLITUDE_CALIBRATION"){ Int_t iresultLaser = ProcessLaser(); if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } Log(Form("iresultLaser = %d",iresultLaser)); return iresultLaser; } else if(runType == "PHYSICS"){ Int_t iresultPhysics = ProcessPhysics(); if(dcsDP==1){ Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap); return iresultDCS; } Log(Form("iresultPhysics = %d",iresultPhysics)); return iresultPhysics; } return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // Component for redoing the reconstruction from the clusters and tracks // // The new calibration data used // // In reality it overwrites the content of the ESD // /* gSystem->Load("libANALYSIS"); gSystem->Load("libTPCcalib"); // gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros"); gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+") AliXRDPROOFtoolkit tool; TChain * chainCl = tool.MakeChain("calib.txt","Clusters",0,1); chainCl->Lookup(); TChain * chainTr = tool.MakeChain("calib.txt","Tracks",0,1); chainTr->Lookup(); */ // marian.ivanov@cern.ch // #include "AliTPCcalibCalib.h" #include "TSystem.h" #include "TFile.h" #include "TTreeStream.h" #include "AliLog.h" #include "TTimeStamp.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliESDtrack.h" #include "AliTracker.h" #include "AliTPCClusterParam.h" #include "AliTPCcalibDB.h" #include "AliTPCTransform.h" #include "AliTPCclusterMI.h" #include "AliTPCseed.h" ClassImp(AliTPCcalibCalib) AliTPCcalibCalib::AliTPCcalibCalib(): AliTPCcalibBase() { // // Constructor // } AliTPCcalibCalib::AliTPCcalibCalib(const Text_t *name, const Text_t *title) :AliTPCcalibBase() { SetName(name); SetTitle(title); } AliTPCcalibCalib::AliTPCcalibCalib(const AliTPCcalibCalib&calib): AliTPCcalibBase(calib) { // // copy constructor // } AliTPCcalibCalib &AliTPCcalibCalib::operator=(const AliTPCcalibCalib&calib){ // // // ((AliTPCcalibBase *)this)->operator=(calib); return *this; } AliTPCcalibCalib::~AliTPCcalibCalib() { // // destructor // } void AliTPCcalibCalib::Process(AliESDEvent *event){ // // // if (!event) { return; } AliESDfriend *ESDfriend=static_cast<AliESDfriend*>(event->FindListObject("AliESDfriend")); if (!ESDfriend) { return; } if (GetDebugLevel()>20) printf("Hallo world: Im here\n"); Int_t ntracks=event->GetNumberOfTracks(); // // // for (Int_t i=0;i<ntracks;++i) { AliESDtrack *track = event->GetTrack(i); const AliExternalTrackParam * trackIn = track->GetInnerParam(); const AliExternalTrackParam * trackOut = track->GetOuterParam(); if (!trackIn) continue; if (!trackOut) continue; AliESDfriendTrack *friendTrack = ESDfriend->GetTrack(i); TObject *calibObject; AliTPCseed *seed = 0; for (Int_t l=0;(calibObject=friendTrack->GetCalibObject(l));++l) { if ((seed=dynamic_cast<AliTPCseed*>(calibObject))) break; } if (!seed) continue; RefitTrack(track, seed); } return; } Bool_t AliTPCcalibCalib::RefitTrack(AliESDtrack * track, AliTPCseed *seed){ // // Refit track // // // First apply calibration // AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform(); for (Int_t irow=0;irow<159;irow++) { AliTPCclusterMI *cluster=seed->GetClusterPointer(irow); if (!cluster) continue; AliTPCclusterMI cl0(*cluster); Double_t x[3]={cluster->GetRow(),cluster->GetPad(),cluster->GetTimeBin()}; Int_t i[1]={cluster->GetDetector()}; transform->Transform(x,i,0,1); // // get position correction // Int_t ipad=0; if (cluster->GetDetector()>35) ipad=1; Float_t dy =AliTPCClusterParam::SPosCorrection(0,ipad,cluster->GetPad(),cluster->GetTimeBin(),cluster->GetZ(),cluster->GetSigmaY2(),cluster->GetSigmaZ2(),cluster->GetMax()); Float_t dz =AliTPCClusterParam::SPosCorrection(1,ipad,cluster->GetPad(),cluster->GetTimeBin(),cluster->GetZ(),cluster->GetSigmaY2(),cluster->GetSigmaZ2(),cluster->GetMax()); //x[1]-=dy; //x[2]-=dz; // cluster->SetX(x[0]); cluster->SetY(x[1]); cluster->SetZ(x[2]); if (fStreamLevel>2){ TTreeSRedirector *cstream = GetDebugStreamer(); if (cstream){ (*cstream)<<"Clusters"<< "run="<<fRun<< // run number "event="<<fEvent<< // event number "time="<<fTime<< // time stamp of event "trigger="<<fTrigger<< // trigger "mag="<<fMagF<< // magnetic field "cl0.="<<&cl0<< "cl.="<<cluster<< "cy="<<dy<< "cz="<<dz<< "\n"; } } } Int_t ncl = seed->GetNumberOfClusters(); Double_t covar[15]; for (Int_t i=0;i<15;i++) covar[i]=0; covar[0]=10.*10.; covar[2]=10.*10.; covar[5]=10.*10./(64.*64.); covar[9]=10.*10./(64.*64.); covar[14]=1*1; // // And now do refit // AliExternalTrackParam * trackInOld = (AliExternalTrackParam*)track->GetInnerParam(); AliExternalTrackParam * trackOutOld = (AliExternalTrackParam*)track->GetOuterParam(); AliExternalTrackParam trackIn = *trackOutOld; AliExternalTrackParam trackOut = *trackInOld; trackIn.ResetCovariance(200.); trackOut.ResetCovariance(200.); trackIn.AddCovariance(covar); trackOut.AddCovariance(covar); Double_t xyz[3]; Int_t nclIn=0,nclOut=0; // // Refit out // for (Int_t irow=0; irow<160; irow++){ AliTPCclusterMI *cl=seed->GetClusterPointer(irow); if (!cl) continue; if (cl->GetX()<80) continue; Int_t sector = cl->GetDetector(); Float_t dalpha = TMath::DegToRad()*(sector%18*20.+10.)-trackOut.GetAlpha(); if (TMath::Abs(dalpha)>0.01) trackOut.Rotate(TMath::DegToRad()*(sector%18*20.+10.)); Double_t r[3]={cl->GetX(),cl->GetY(),cl->GetZ()}; Double_t cov[3]={0.01,0.,0.01}; //TODO: correct error parametrisation trackOut.GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); if (trackOut.PropagateTo(r[0],bz)) nclOut++; if (RejectCluster(cl,&trackOut)) continue; trackOut.Update(&r[1],cov); } // // Refit in // for (Int_t irow=159; irow>0; irow--){ AliTPCclusterMI *cl=seed->GetClusterPointer(irow); if (!cl) continue; if (cl->GetX()<80) continue; Int_t sector = cl->GetDetector(); Float_t dalpha = TMath::DegToRad()*(sector%18*20.+10.)-trackIn.GetAlpha(); if (TMath::Abs(dalpha)>0.01) trackIn.Rotate(TMath::DegToRad()*(sector%18*20.+10.)); Double_t r[3]={cl->GetX(),cl->GetY(),cl->GetZ()}; Double_t cov[3]={0.01,0.,0.01}; //TODO: correct error parametrisation trackOut.GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); if (trackIn.PropagateTo(r[0],bz)) nclIn++; if (RejectCluster(cl,&trackIn)) continue; trackIn.Update(&r[1],cov); } trackIn.Rotate(trackInOld->GetAlpha()); trackOut.Rotate(trackOutOld->GetAlpha()); // trackInOld->GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); trackIn.PropagateTo(trackInOld->GetX(),bz); // trackOutOld->GetXYZ(xyz); bz = AliTracker::GetBz(xyz); trackOut.PropagateTo(trackOutOld->GetX(),bz); if (fStreamLevel>0){ TTreeSRedirector *cstream = GetDebugStreamer(); if (cstream){ (*cstream)<<"Tracks"<< "run="<<fRun<< // run number "event="<<fEvent<< // event number "time="<<fTime<< // time stamp of event "trigger="<<fTrigger<< // trigger "mag="<<fMagF<< // magnetic field "nclIn="<<nclIn<< "nclOut="<<nclOut<< "ncl="<<ncl<< "TrIn0.="<<trackInOld<< "TrOut0.="<<trackOutOld<< "TrIn1.="<<&trackIn<< "TrOut1.="<<&trackOut<< "\n"; } } // // And now rewrite ESDtrack // (*trackInOld) = trackIn; (*trackOutOld) = trackOut; AliExternalTrackParam *t = &trackIn; track->Set(t->GetX(),t->GetAlpha(),t->GetParameter(),t->GetCovariance()); return kTRUE; } Bool_t AliTPCcalibCalib::RejectCluster(AliTPCclusterMI* cl, AliExternalTrackParam * param){ // // check the acceptance of cluster // Cut on edge effects // Bool_t isReject = kFALSE; Float_t edgeY = cl->GetX()*TMath::Tan(TMath::Pi()/18); Float_t dist = edgeY - TMath::Abs(cl->GetY()); if (param) dist = TMath::Abs(edgeY - TMath::Abs(param->GetY())); if (dist<3) isReject=kTRUE; if (cl->GetType()<0) isReject=kTRUE; return isReject; } <commit_msg>Set the ExB correction according to the B field from ESD (Marian)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // Component for redoing the reconstruction from the clusters and tracks // // The new calibration data used // // In reality it overwrites the content of the ESD // /* gSystem->Load("libANALYSIS"); gSystem->Load("libTPCcalib"); // gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros"); gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+") AliXRDPROOFtoolkit tool; TChain * chainCl = tool.MakeChain("calib.txt","Clusters",0,1); chainCl->Lookup(); TChain * chainTr = tool.MakeChain("calib.txt","Tracks",0,1); chainTr->Lookup(); */ // marian.ivanov@cern.ch // #include "AliTPCcalibCalib.h" #include "TSystem.h" #include "TFile.h" #include "TTreeStream.h" #include "AliLog.h" #include "TTimeStamp.h" #include "AliESDEvent.h" #include "AliESDfriend.h" #include "AliESDtrack.h" #include "AliTracker.h" #include "AliTPCClusterParam.h" #include "AliTPCcalibDB.h" #include "AliTPCTransform.h" #include "AliTPCclusterMI.h" #include "AliTPCseed.h" ClassImp(AliTPCcalibCalib) AliTPCcalibCalib::AliTPCcalibCalib(): AliTPCcalibBase() { // // Constructor // } AliTPCcalibCalib::AliTPCcalibCalib(const Text_t *name, const Text_t *title) :AliTPCcalibBase() { SetName(name); SetTitle(title); } AliTPCcalibCalib::AliTPCcalibCalib(const AliTPCcalibCalib&calib): AliTPCcalibBase(calib) { // // copy constructor // } AliTPCcalibCalib &AliTPCcalibCalib::operator=(const AliTPCcalibCalib&calib){ // // // ((AliTPCcalibBase *)this)->operator=(calib); return *this; } AliTPCcalibCalib::~AliTPCcalibCalib() { // // destructor // } void AliTPCcalibCalib::Process(AliESDEvent *event){ // // // if (!event) { return; } AliESDfriend *ESDfriend=static_cast<AliESDfriend*>(event->FindListObject("AliESDfriend")); if (!ESDfriend) { return; } if (GetDebugLevel()>20) printf("Hallo world: Im here\n"); Int_t ntracks=event->GetNumberOfTracks(); AliTPCcalibDB::Instance()->SetExBField(fMagF); // // // for (Int_t i=0;i<ntracks;++i) { AliESDtrack *track = event->GetTrack(i); const AliExternalTrackParam * trackIn = track->GetInnerParam(); const AliExternalTrackParam * trackOut = track->GetOuterParam(); if (!trackIn) continue; if (!trackOut) continue; AliESDfriendTrack *friendTrack = ESDfriend->GetTrack(i); TObject *calibObject; AliTPCseed *seed = 0; for (Int_t l=0;(calibObject=friendTrack->GetCalibObject(l));++l) { if ((seed=dynamic_cast<AliTPCseed*>(calibObject))) break; } if (!seed) continue; RefitTrack(track, seed); } return; } Bool_t AliTPCcalibCalib::RefitTrack(AliESDtrack * track, AliTPCseed *seed){ // // Refit track // // // First apply calibration // AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform(); for (Int_t irow=0;irow<159;irow++) { AliTPCclusterMI *cluster=seed->GetClusterPointer(irow); if (!cluster) continue; AliTPCclusterMI cl0(*cluster); Double_t x[3]={cluster->GetRow(),cluster->GetPad(),cluster->GetTimeBin()}; Int_t i[1]={cluster->GetDetector()}; transform->Transform(x,i,0,1); // // get position correction // Int_t ipad=0; if (cluster->GetDetector()>35) ipad=1; Float_t dy =AliTPCClusterParam::SPosCorrection(0,ipad,cluster->GetPad(),cluster->GetTimeBin(),cluster->GetZ(),cluster->GetSigmaY2(),cluster->GetSigmaZ2(),cluster->GetMax()); Float_t dz =AliTPCClusterParam::SPosCorrection(1,ipad,cluster->GetPad(),cluster->GetTimeBin(),cluster->GetZ(),cluster->GetSigmaY2(),cluster->GetSigmaZ2(),cluster->GetMax()); //x[1]-=dy; //x[2]-=dz; // cluster->SetX(x[0]); cluster->SetY(x[1]); cluster->SetZ(x[2]); if (fStreamLevel>2){ TTreeSRedirector *cstream = GetDebugStreamer(); if (cstream){ (*cstream)<<"Clusters"<< "run="<<fRun<< // run number "event="<<fEvent<< // event number "time="<<fTime<< // time stamp of event "trigger="<<fTrigger<< // trigger "mag="<<fMagF<< // magnetic field "cl0.="<<&cl0<< "cl.="<<cluster<< "cy="<<dy<< "cz="<<dz<< "\n"; } } } Int_t ncl = seed->GetNumberOfClusters(); Double_t covar[15]; for (Int_t i=0;i<15;i++) covar[i]=0; covar[0]=10.*10.; covar[2]=10.*10.; covar[5]=10.*10./(64.*64.); covar[9]=10.*10./(64.*64.); covar[14]=1*1; // // And now do refit // AliExternalTrackParam * trackInOld = (AliExternalTrackParam*)track->GetInnerParam(); AliExternalTrackParam * trackOutOld = (AliExternalTrackParam*)track->GetOuterParam(); AliExternalTrackParam trackIn = *trackOutOld; AliExternalTrackParam trackOut = *trackInOld; trackIn.ResetCovariance(200.); trackOut.ResetCovariance(200.); trackIn.AddCovariance(covar); trackOut.AddCovariance(covar); Double_t xyz[3]; Int_t nclIn=0,nclOut=0; // // Refit out // for (Int_t irow=0; irow<160; irow++){ AliTPCclusterMI *cl=seed->GetClusterPointer(irow); if (!cl) continue; if (cl->GetX()<80) continue; Int_t sector = cl->GetDetector(); Float_t dalpha = TMath::DegToRad()*(sector%18*20.+10.)-trackOut.GetAlpha(); if (TMath::Abs(dalpha)>0.01) trackOut.Rotate(TMath::DegToRad()*(sector%18*20.+10.)); Double_t r[3]={cl->GetX(),cl->GetY(),cl->GetZ()}; Double_t cov[3]={0.01,0.,0.01}; //TODO: correct error parametrisation trackOut.GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); if (trackOut.PropagateTo(r[0],bz)) nclOut++; if (RejectCluster(cl,&trackOut)) continue; trackOut.Update(&r[1],cov); } // // Refit in // for (Int_t irow=159; irow>0; irow--){ AliTPCclusterMI *cl=seed->GetClusterPointer(irow); if (!cl) continue; if (cl->GetX()<80) continue; Int_t sector = cl->GetDetector(); Float_t dalpha = TMath::DegToRad()*(sector%18*20.+10.)-trackIn.GetAlpha(); if (TMath::Abs(dalpha)>0.01) trackIn.Rotate(TMath::DegToRad()*(sector%18*20.+10.)); Double_t r[3]={cl->GetX(),cl->GetY(),cl->GetZ()}; Double_t cov[3]={0.01,0.,0.01}; //TODO: correct error parametrisation trackOut.GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); if (trackIn.PropagateTo(r[0],bz)) nclIn++; if (RejectCluster(cl,&trackIn)) continue; trackIn.Update(&r[1],cov); } trackIn.Rotate(trackInOld->GetAlpha()); trackOut.Rotate(trackOutOld->GetAlpha()); // trackInOld->GetXYZ(xyz); Double_t bz = AliTracker::GetBz(xyz); trackIn.PropagateTo(trackInOld->GetX(),bz); // trackOutOld->GetXYZ(xyz); bz = AliTracker::GetBz(xyz); trackOut.PropagateTo(trackOutOld->GetX(),bz); if (fStreamLevel>0){ TTreeSRedirector *cstream = GetDebugStreamer(); if (cstream){ (*cstream)<<"Tracks"<< "run="<<fRun<< // run number "event="<<fEvent<< // event number "time="<<fTime<< // time stamp of event "trigger="<<fTrigger<< // trigger "mag="<<fMagF<< // magnetic field "nclIn="<<nclIn<< "nclOut="<<nclOut<< "ncl="<<ncl<< "TrIn0.="<<trackInOld<< "TrOut0.="<<trackOutOld<< "TrIn1.="<<&trackIn<< "TrOut1.="<<&trackOut<< "\n"; } } // // And now rewrite ESDtrack // (*trackInOld) = trackIn; (*trackOutOld) = trackOut; AliExternalTrackParam *t = &trackIn; track->Set(t->GetX(),t->GetAlpha(),t->GetParameter(),t->GetCovariance()); return kTRUE; } Bool_t AliTPCcalibCalib::RejectCluster(AliTPCclusterMI* cl, AliExternalTrackParam * param){ // // check the acceptance of cluster // Cut on edge effects // Bool_t isReject = kFALSE; Float_t edgeY = cl->GetX()*TMath::Tan(TMath::Pi()/18); Float_t dist = edgeY - TMath::Abs(cl->GetY()); if (param) dist = TMath::Abs(edgeY - TMath::Abs(param->GetY())); if (dist<3) isReject=kTRUE; if (cl->GetType()<0) isReject=kTRUE; return isReject; } <|endoftext|>
<commit_before>// // Mark.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 06/06/12. // Copyright (c) 2012 IGO Software SL. All rights reserved. // #include "Mark.hpp" #include "Camera.hpp" #include "GL.hpp" #include "TexturesHandler.hpp" #include "FloatBufferBuilderFromCartesian3D.hpp" #include "IGLTextureId.hpp" #include "IDownloader.hpp" #include "IImageDownloadListener.hpp" #include "MarkTouchListener.hpp" #include "ITextUtils.hpp" #include "IImageListener.hpp" #include "FloatBufferBuilderFromCartesian2D.hpp" #include "GLFeature.hpp" #include "Vector2D.hpp" class MarkLabelImageListener : public IImageListener { private: IImage* _iconImage; Mark* _mark; public: MarkLabelImageListener(IImage* iconImage, Mark* mark) : _iconImage(iconImage), _mark(mark) { } void imageCreated(IImage* image) { if (_iconImage != NULL) { IFactory::instance()->deleteImage(_iconImage); _iconImage = NULL; } if (image == NULL) { _mark->onTextureDownloadError(); } else { _mark->onTextureDownload(image); } } }; class IconDownloadListener : public IImageDownloadListener { private: Mark* _mark; const std::string _label; const bool _labelBottom; const float _labelFontSize; const Color* _labelFontColor; const Color* _labelShadowColor; const int _labelGapSize; public: IconDownloadListener(Mark* mark, const std::string& label, bool labelBottom, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, const int labelGapSize) : _mark(mark), _label(label), _labelBottom(labelBottom), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(labelGapSize) { } void onDownload(const URL& url, IImage* image, bool expired) { const bool hasLabel = ( _label.length() != 0 ); if (hasLabel) { #ifdef C_CODE LabelPosition labelPosition = _labelBottom ? Bottom : Right; #endif #ifdef JAVA_CODE LabelPosition labelPosition = _labelBottom ? LabelPosition.Bottom : LabelPosition.Right; #endif ITextUtils::instance()->labelImage(image, _label, labelPosition, _labelGapSize, _labelFontSize, _labelFontColor, _labelShadowColor, new MarkLabelImageListener(image, _mark), true); } else { _mark->onTextureDownload(image); } } void onError(const URL& url) { ILogger::instance()->logError("Error trying to download image \"%s\"", url.getPath().c_str()); _mark->onTextureDownloadError(); } void onCancel(const URL& url) { // ILogger::instance()->logError("Download canceled for image \"%s\"", url.getPath().c_str()); _mark->onTextureDownloadError(); } void onCanceledDownload(const URL& url, IImage* image, bool expired) { // do nothing } }; IFloatBuffer* Mark::_billboardTexCoord = NULL; Mark::Mark(const std::string& label, const URL iconURL, const Geodetic3D& position, double minDistanceToCamera, const bool labelBottom, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, const int labelGapSize, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(label), _iconURL(iconURL), _position(new Geodetic3D(position)), _labelBottom(labelBottom), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(labelGapSize), _textureId(NULL), _cartesianPosition(NULL), //_vertices(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( iconURL.getPath() + "_" + label ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(const std::string& label, const Geodetic3D& position, double minDistanceToCamera, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(label), _labelBottom(true), _iconURL("", false), _position(new Geodetic3D(position)), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), //_vertices(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( "_" + label ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(const URL iconURL, const Geodetic3D& position, double minDistanceToCamera, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(""), _labelBottom(true), _iconURL(iconURL), _position(new Geodetic3D(position)), _labelFontSize(20), _labelFontColor(Color::newFromRGBA(1, 1, 1, 1)), _labelShadowColor(Color::newFromRGBA(0, 0, 0, 1)), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), //_vertices(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( iconURL.getPath() + "_" ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(IImage* image, const std::string& imageID, const Geodetic3D& position, double minDistanceToCamera, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(""), _labelBottom(true), _iconURL(URL("", false)), _position(new Geodetic3D(position)), _labelFontSize(20), _labelFontColor(NULL), _labelShadowColor(NULL), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), //_vertices(NULL), _textureSolved(true), _textureImage(image), _renderedMark(false), _textureWidth(image->getWidth()), _textureHeight(image->getHeight()), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( imageID ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } void Mark::initialize(const G3MContext* context, long long downloadPriority) { _surfaceElevationProvider = context->getSurfaceElevationProvider(); if (_surfaceElevationProvider != NULL) { _surfaceElevationProvider->addListener(_position->_latitude, _position->_longitude, this); } if (!_textureSolved) { const bool hasLabel = ( _label.length() != 0 ); const bool hasIconURL = ( _iconURL.getPath().length() != 0 ); if (hasIconURL) { IDownloader* downloader = context->getDownloader(); downloader->requestImage(_iconURL, downloadPriority, TimeInterval::fromDays(30), true, new IconDownloadListener(this, _label, _labelBottom, _labelFontSize, _labelFontColor, _labelShadowColor, _labelGapSize), true); } else { if (hasLabel) { ITextUtils::instance()->createLabelImage(_label, _labelFontSize, _labelFontColor, _labelShadowColor, new MarkLabelImageListener(NULL, this), true); } else { ILogger::instance()->logWarning("Marker created without label nor icon"); } } } } void Mark::onTextureDownloadError() { _textureSolved = true; delete _labelFontColor; delete _labelShadowColor; ILogger::instance()->logError("Can't create texture for Mark (iconURL=\"%s\", label=\"%s\")", _iconURL.getPath().c_str(), _label.c_str()); } void Mark::onTextureDownload(IImage* image) { _textureSolved = true; delete _labelFontColor; delete _labelShadowColor; _textureImage = image; _textureWidth = _textureImage->getWidth(); _textureHeight = _textureImage->getHeight(); } bool Mark::isReady() const { return _textureSolved; } Mark::~Mark() { delete _position; if (_surfaceElevationProvider != NULL) { _surfaceElevationProvider->removeListener(this); } delete _cartesianPosition; // delete _vertices; if (_autoDeleteListener) { delete _listener; } if (_autoDeleteUserData) { delete _userData; } if (_textureImage != NULL) { IFactory::instance()->deleteImage(_textureImage); } } Vector3D* Mark::getCartesianPosition(const Planet* planet) { if (_cartesianPosition == NULL) { _cartesianPosition = new Vector3D( planet->toCartesian(*_position) ); } return _cartesianPosition; } bool Mark::touched() { return (_listener == NULL) ? false : _listener->touchedMark(this); } void Mark::setMinDistanceToCamera(double minDistanceToCamera) { _minDistanceToCamera = minDistanceToCamera; } double Mark::getMinDistanceToCamera() { return _minDistanceToCamera; } void Mark::createGLState(const Planet* planet){ Geodetic3D positionWithSurfaceElevation(_position->_latitude, _position->_longitude, _position->_height + _currentSurfaceElevation); const Vector3D pos( planet->toCartesian(positionWithSurfaceElevation) ); _glState.addGLFeature(new BillboardGLFeature(pos, _textureWidth, _textureHeight), false); if (_textureId != NULL){ _glState.addGLFeature(new TextureGLFeature(_textureId, getBillboardTexCoords(), 2, 0, false, 0, true, GLBlendFactor::srcAlpha(), GLBlendFactor::oneMinusSrcAlpha(), false, Vector2D::zero(), Vector2D::zero()), false); } } IFloatBuffer* Mark::getBillboardTexCoords() { if (_billboardTexCoord == NULL) { FloatBufferBuilderFromCartesian2D texCoor; texCoor.add(1,1); texCoor.add(1,0); texCoor.add(0,1); texCoor.add(0,0); _billboardTexCoord = texCoor.create(); } return _billboardTexCoord; } void Mark::render(const G3MRenderContext* rc, const Vector3D& cameraPosition, const GLState* parentGLState, const Planet* planet, GL* gl) { const Vector3D* markPosition = getCartesianPosition(planet); const Vector3D markCameraVector = markPosition->sub(cameraPosition); // mark will be renderered only if is renderable by distance and placed on a visible globe area bool renderableByDistance; if (_minDistanceToCamera == 0) { renderableByDistance = true; } else { const double squaredDistanceToCamera = markCameraVector.squaredLength(); renderableByDistance = ( squaredDistanceToCamera <= (_minDistanceToCamera * _minDistanceToCamera) ); } _renderedMark = false; if (renderableByDistance) { const Vector3D normalAtMarkPosition = planet->geodeticSurfaceNormal(*markPosition); if (normalAtMarkPosition.angleBetween(markCameraVector)._radians > HALF_PI) { if (_textureId == NULL) { if (_textureImage != NULL) { _textureId = rc->getTexturesHandler()->getGLTextureId(_textureImage, GLFormat::rgba(), _imageID, false); rc->getFactory()->deleteImage(_textureImage); _textureImage = NULL; createGLState(planet); } } else{ if (_glState.getNumberOfGLFeatures() == 0){ createGLState(planet); //GLState was disposed due to elevation change } _glState.setParent(parentGLState); //Linking with parent rc->getGL()->drawArrays(GLPrimitive::triangleStrip(), 0, 4, &_glState, *rc->getGPUProgramManager()); _renderedMark = true; } } } } void Mark::elevationChanged(const Geodetic2D& position, double rawElevation, //Without considering vertical exaggeration double verticalExaggeration){ _currentSurfaceElevation = rawElevation * verticalExaggeration; _glState.clearAllGLFeatures(); } <commit_msg>uBillboardPosition<commit_after>// // Mark.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 06/06/12. // Copyright (c) 2012 IGO Software SL. All rights reserved. // #include "Mark.hpp" #include "Camera.hpp" #include "GL.hpp" #include "TexturesHandler.hpp" #include "FloatBufferBuilderFromCartesian3D.hpp" #include "IGLTextureId.hpp" #include "IDownloader.hpp" #include "IImageDownloadListener.hpp" #include "MarkTouchListener.hpp" #include "ITextUtils.hpp" #include "IImageListener.hpp" #include "FloatBufferBuilderFromCartesian2D.hpp" #include "GLFeature.hpp" #include "Vector2D.hpp" class MarkLabelImageListener : public IImageListener { private: IImage* _iconImage; Mark* _mark; public: MarkLabelImageListener(IImage* iconImage, Mark* mark) : _iconImage(iconImage), _mark(mark) { } void imageCreated(IImage* image) { if (_iconImage != NULL) { IFactory::instance()->deleteImage(_iconImage); _iconImage = NULL; } if (image == NULL) { _mark->onTextureDownloadError(); } else { _mark->onTextureDownload(image); } } }; class IconDownloadListener : public IImageDownloadListener { private: Mark* _mark; const std::string _label; const bool _labelBottom; const float _labelFontSize; const Color* _labelFontColor; const Color* _labelShadowColor; const int _labelGapSize; public: IconDownloadListener(Mark* mark, const std::string& label, bool labelBottom, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, const int labelGapSize) : _mark(mark), _label(label), _labelBottom(labelBottom), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(labelGapSize) { } void onDownload(const URL& url, IImage* image, bool expired) { const bool hasLabel = ( _label.length() != 0 ); if (hasLabel) { #ifdef C_CODE LabelPosition labelPosition = _labelBottom ? Bottom : Right; #endif #ifdef JAVA_CODE LabelPosition labelPosition = _labelBottom ? LabelPosition.Bottom : LabelPosition.Right; #endif ITextUtils::instance()->labelImage(image, _label, labelPosition, _labelGapSize, _labelFontSize, _labelFontColor, _labelShadowColor, new MarkLabelImageListener(image, _mark), true); } else { _mark->onTextureDownload(image); } } void onError(const URL& url) { ILogger::instance()->logError("Error trying to download image \"%s\"", url.getPath().c_str()); _mark->onTextureDownloadError(); } void onCancel(const URL& url) { // ILogger::instance()->logError("Download canceled for image \"%s\"", url.getPath().c_str()); _mark->onTextureDownloadError(); } void onCanceledDownload(const URL& url, IImage* image, bool expired) { // do nothing } }; IFloatBuffer* Mark::_billboardTexCoord = NULL; Mark::Mark(const std::string& label, const URL iconURL, const Geodetic3D& position, double minDistanceToCamera, const bool labelBottom, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, const int labelGapSize, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(label), _iconURL(iconURL), _position(new Geodetic3D(position)), _labelBottom(labelBottom), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(labelGapSize), _textureId(NULL), _cartesianPosition(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( iconURL.getPath() + "_" + label ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(const std::string& label, const Geodetic3D& position, double minDistanceToCamera, const float labelFontSize, const Color* labelFontColor, const Color* labelShadowColor, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(label), _labelBottom(true), _iconURL("", false), _position(new Geodetic3D(position)), _labelFontSize(labelFontSize), _labelFontColor(labelFontColor), _labelShadowColor(labelShadowColor), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( "_" + label ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(const URL iconURL, const Geodetic3D& position, double minDistanceToCamera, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(""), _labelBottom(true), _iconURL(iconURL), _position(new Geodetic3D(position)), _labelFontSize(20), _labelFontColor(Color::newFromRGBA(1, 1, 1, 1)), _labelShadowColor(Color::newFromRGBA(0, 0, 0, 1)), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), _textureSolved(false), _textureImage(NULL), _renderedMark(false), _textureWidth(0), _textureHeight(0), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( iconURL.getPath() + "_" ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } Mark::Mark(IImage* image, const std::string& imageID, const Geodetic3D& position, double minDistanceToCamera, MarkUserData* userData, bool autoDeleteUserData, MarkTouchListener* listener, bool autoDeleteListener) : _label(""), _labelBottom(true), _iconURL(URL("", false)), _position(new Geodetic3D(position)), _labelFontSize(20), _labelFontColor(NULL), _labelShadowColor(NULL), _labelGapSize(2), _textureId(NULL), _cartesianPosition(NULL), _textureSolved(true), _textureImage(image), _renderedMark(false), _textureWidth(image->getWidth()), _textureHeight(image->getHeight()), _userData(userData), _autoDeleteUserData(autoDeleteUserData), _minDistanceToCamera(minDistanceToCamera), _listener(listener), _autoDeleteListener(autoDeleteListener), _imageID( imageID ), _surfaceElevationProvider(NULL), _currentSurfaceElevation(0.0) { } void Mark::initialize(const G3MContext* context, long long downloadPriority) { _surfaceElevationProvider = context->getSurfaceElevationProvider(); if (_surfaceElevationProvider != NULL) { _surfaceElevationProvider->addListener(_position->_latitude, _position->_longitude, this); } if (!_textureSolved) { const bool hasLabel = ( _label.length() != 0 ); const bool hasIconURL = ( _iconURL.getPath().length() != 0 ); if (hasIconURL) { IDownloader* downloader = context->getDownloader(); downloader->requestImage(_iconURL, downloadPriority, TimeInterval::fromDays(30), true, new IconDownloadListener(this, _label, _labelBottom, _labelFontSize, _labelFontColor, _labelShadowColor, _labelGapSize), true); } else { if (hasLabel) { ITextUtils::instance()->createLabelImage(_label, _labelFontSize, _labelFontColor, _labelShadowColor, new MarkLabelImageListener(NULL, this), true); } else { ILogger::instance()->logWarning("Marker created without label nor icon"); } } } } void Mark::onTextureDownloadError() { _textureSolved = true; delete _labelFontColor; delete _labelShadowColor; ILogger::instance()->logError("Can't create texture for Mark (iconURL=\"%s\", label=\"%s\")", _iconURL.getPath().c_str(), _label.c_str()); } void Mark::onTextureDownload(IImage* image) { _textureSolved = true; delete _labelFontColor; delete _labelShadowColor; _textureImage = image; _textureWidth = _textureImage->getWidth(); _textureHeight = _textureImage->getHeight(); } bool Mark::isReady() const { return _textureSolved; } Mark::~Mark() { delete _position; if (_surfaceElevationProvider != NULL) { _surfaceElevationProvider->removeListener(this); } delete _cartesianPosition; if (_autoDeleteListener) { delete _listener; } if (_autoDeleteUserData) { delete _userData; } if (_textureImage != NULL) { IFactory::instance()->deleteImage(_textureImage); } } Vector3D* Mark::getCartesianPosition(const Planet* planet) { if (_cartesianPosition == NULL) { _cartesianPosition = new Vector3D( planet->toCartesian(*_position) ); } return _cartesianPosition; } bool Mark::touched() { return (_listener == NULL) ? false : _listener->touchedMark(this); } void Mark::setMinDistanceToCamera(double minDistanceToCamera) { _minDistanceToCamera = minDistanceToCamera; } double Mark::getMinDistanceToCamera() { return _minDistanceToCamera; } void Mark::createGLState(const Planet* planet){ Geodetic3D positionWithSurfaceElevation(_position->_latitude, _position->_longitude, _position->_height + _currentSurfaceElevation); const Vector3D pos( planet->toCartesian(positionWithSurfaceElevation) ); _glState.addGLFeature(new BillboardGLFeature(pos, _textureWidth, _textureHeight), false); if (_textureId != NULL){ _glState.addGLFeature(new TextureGLFeature(_textureId, getBillboardTexCoords(), 2, 0, false, 0, true, GLBlendFactor::srcAlpha(), GLBlendFactor::oneMinusSrcAlpha(), false, Vector2D::zero(), Vector2D::zero()), false); } } IFloatBuffer* Mark::getBillboardTexCoords() { if (_billboardTexCoord == NULL) { FloatBufferBuilderFromCartesian2D texCoor; texCoor.add(1,1); texCoor.add(1,0); texCoor.add(0,1); texCoor.add(0,0); _billboardTexCoord = texCoor.create(); } return _billboardTexCoord; } void Mark::render(const G3MRenderContext* rc, const Vector3D& cameraPosition, const GLState* parentGLState, const Planet* planet, GL* gl) { const Vector3D* markPosition = getCartesianPosition(planet); const Vector3D markCameraVector = markPosition->sub(cameraPosition); // mark will be renderered only if is renderable by distance and placed on a visible globe area bool renderableByDistance; if (_minDistanceToCamera == 0) { renderableByDistance = true; } else { const double squaredDistanceToCamera = markCameraVector.squaredLength(); renderableByDistance = ( squaredDistanceToCamera <= (_minDistanceToCamera * _minDistanceToCamera) ); } _renderedMark = false; if (renderableByDistance) { const Vector3D normalAtMarkPosition = planet->geodeticSurfaceNormal(*markPosition); if (normalAtMarkPosition.angleBetween(markCameraVector)._radians > HALF_PI) { if (_textureId == NULL) { if (_textureImage != NULL) { _textureId = rc->getTexturesHandler()->getGLTextureId(_textureImage, GLFormat::rgba(), _imageID, false); rc->getFactory()->deleteImage(_textureImage); _textureImage = NULL; createGLState(planet); } } else{ if (_glState.getNumberOfGLFeatures() == 0){ createGLState(planet); //GLState was disposed due to elevation change } _glState.setParent(parentGLState); //Linking with parent rc->getGL()->drawArrays(GLPrimitive::triangleStrip(), 0, 4, &_glState, *rc->getGPUProgramManager()); _renderedMark = true; } } } } void Mark::elevationChanged(const Geodetic2D& position, double rawElevation, //Without considering vertical exaggeration double verticalExaggeration){ _currentSurfaceElevation = rawElevation * verticalExaggeration; _glState.clearAllGLFeatures(); } <|endoftext|>
<commit_before>// // Tile.cpp // G3MiOSSDK // // Created by Agustín Trujillo Pino on 12/06/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "Tile.hpp" #include "Mesh.hpp" #include "Camera.hpp" #include "TileTessellator.hpp" #include "TileTexturizer.hpp" //#include "Angle.hpp" //#include "Geodetic3D.hpp" //#include "Vector3D.hpp" //#include "Camera.hpp" //unsigned int Tile::_numIndices = 0; //unsigned int Tile::_numBorderIndices = 0; //unsigned int Tile::_numInnerIndices = 0; //unsigned char * Tile::_indices; //unsigned char *Tile::_borderIndices; //unsigned char *Tile::_innerIndices; //unsigned int Tile::_resolution; //bool Tile::_skirts; Tile::~Tile() { // if (_vertices!=NULL) delete[] _vertices; delete _mesh; } //void Tile::createVertices(const Planet *planet) //{ // const Angle maxLat = _bounds.upper().latitude(); // const Angle maxLon = _bounds.upper().longitude(); // const Angle minLat = _bounds.lower().latitude(); // const Angle minLon = _bounds.lower().longitude(); // // int resol = _resolution; // int resol2 = resol * resol; // int n1 = _resolution - 1; // //double exag = globe->GetExagElevFactor(); // double maxH = 0, H; // Angle latSize = maxLat.sub(minLat); // Angle lonSize = maxLon.sub(minLon); // const double sizeSkirt = 0.95; // // // compute number of vertices in the mesh (there are less vertices if the tiles touches one of the poles) // unsigned int numVertices = resol2; // if (_skirts) numVertices += 4 * resol - 4; // // // if first time for tile, alloc memory // if (_vertices == NULL) { // _vertices = new float[numVertices * 3]; // //textureCoor = new float[numVertices * 2]; // } // // // alloc temp memory to create a matrix of coordinates // double *x = new double[resol2]; // double *y = new double [resol2]; // double *z = new double [resol2]; // float *u = new float[resol2]; // float *v = new float [resol2]; // // // create mesh coordinates // for (int j = 0; j < resol; j++) // for (int i = 0; i < resol; i++) { // unsigned int pos = j * resol + i; // //H = (elev != NULL) ? elev[pos] * exag : 0; // H = 0.0; // if (H > maxH) maxH = H; // //lat = (maxLat.value - latSize.value*j/n1); // //lon = (minLon.value + lonSize.value*i/n1); // Angle lat = Angle::fromDegrees((maxLat.degrees() - latSize.degrees() * j / n1)); // Angle lon = Angle::fromDegrees((minLon.degrees() + lonSize.degrees() * i / n1)); // Geodetic3D g3(lat, lon, H); // Vector3D P = planet->toVector3D(g3); // x[pos] = P.x(); // y[pos] = P.y(); // z[pos] = P.z(); // u[pos] = (float) i / n1; // v[pos] = (float) j / n1; // } // // // compute center of tile // Angle lat = Angle::fromDegrees((minLat.degrees() + maxLat.degrees()) / 2); // Angle lon = Angle::fromDegrees((minLon.degrees() + maxLon.degrees()) / 2); // Geodetic3D g3(lat, lon, maxH); // //Vector3D center = planet->toVector3D(g3); // _center = planet->toVector3D(g3).asMutableVector3D(); // // // create a nxn mesh // unsigned int posV = 0; // //unsigned int posT = 0; // for (int j = 0; j < resol; j++) // for (int i = 0; i < resol; i++) { // unsigned int pos = j * resol + i; // _vertices[posV++] = (float) (x[pos] - _center.x()); // _vertices[posV++] = (float) (y[pos] - _center.y()); // _vertices[posV++] = (float) (z[pos] - _center.z()); // //textureCoor[posT++] = u[pos]; // //textureCoor[posT++] = v[pos]; // } // // // create skirts // if (_skirts) { // // // west side // for (int j = 0; j < resol - 1; j++) { // unsigned int pos = j * resol; // _vertices[posV++] = (float) (x[pos] * sizeSkirt - _center.x()); // _vertices[posV++] = (float) (y[pos] * sizeSkirt - _center.y()); // _vertices[posV++] = (float) (z[pos] * sizeSkirt - _center.z()); // //textureCoor[posT++] = u[pos]; // //textureCoor[posT++] = v[pos]; // } // // // south side // for (int i = 0; i < resol - 1; i++) { // unsigned int pos = (resol - 1) * resol + i; // _vertices[posV++] = (float) (x[pos] * sizeSkirt - _center.x()); // _vertices[posV++] = (float) (y[pos] * sizeSkirt - _center.y()); // _vertices[posV++] = (float) (z[pos] * sizeSkirt - _center.z()); // //textureCoor[posT++] = u[pos]; // //textureCoor[posT++] = v[pos]; // } // // // east side // for (int j = resol - 1; j > 0; j--) { // unsigned int pos = j * resol + resol - 1; // _vertices[posV++] = (float) (x[pos] * sizeSkirt - _center.x()); // _vertices[posV++] = (float) (y[pos] * sizeSkirt - _center.y()); // _vertices[posV++] = (float) (z[pos] * sizeSkirt - _center.z()); // //textureCoor[posT++] = u[pos]; // //textureCoor[posT++] = v[pos]; // } // // // north side // for (int i = resol - 1; i > 0; i--) { // unsigned int pos = i; // _vertices[posV++] = (float) (x[pos] * sizeSkirt - _center.x()); // _vertices[posV++] = (float) (y[pos] * sizeSkirt - _center.y()); // _vertices[posV++] = (float) (z[pos] * sizeSkirt - _center.z()); // //textureCoor[posT++] = u[pos]; // //textureCoor[posT++] = v[pos]; // } // } // // // free temp memory // delete[] x; // delete[] y; // delete[] z; // delete[] u; // delete[] v; //} //void Tile::deleteIndices() //{ // if (_numIndices) { // delete[] _indices; // _numIndices = 0; // } // if (_numInnerIndices) { // delete[] _innerIndices; // _numInnerIndices = 0; // } // if (_numBorderIndices) { // delete[] _borderIndices; // _numBorderIndices = 0; // } //} //void Tile::createIndices(unsigned int resol, bool skirts) //{ // _resolution = resol; // _skirts = skirts; // // // alloc memory // _numIndices = (resol - 1) * (2 * resol + 2) - 1; //remove the first degenerated vertex // if (skirts) _numIndices += 8 * resol - 4; // _indices = new unsigned char[_numIndices]; // // // create indices vector for the mesh // unsigned int posI = 0; // for (int j = 0; j < resol - 1; j++) { // if (j > 0) _indices[posI++] = (unsigned char) (j * resol); // for (int i = 0; i < resol; i++) { // _indices[posI++] = (unsigned char) (j * resol + i); // _indices[posI++] = (unsigned char) (j * resol + i + resol); // } // _indices[posI++] = (unsigned char) (j * resol + 2 * resol - 1); // } // // // create skirts // if (skirts) { // _indices[posI++] = 0; // unsigned int posS = resol * resol; // // // west side // for (int j = 0; j < resol - 1; j++) { // unsigned int pos = j * resol; // _indices[posI++] = (unsigned char) (pos); // _indices[posI++] = (unsigned char) (posS++); // } // // // south side // for (int i = 0; i < resol - 1; i++) { // unsigned int pos = (resol - 1) * resol + i; // _indices[posI++] = (unsigned char) pos; // _indices[posI++] = (unsigned char) (posS++); // } // // // east side // for (int j = resol - 1; j > 0; j--) { // unsigned int pos = j * resol + resol - 1; // _indices[posI++] = (unsigned char) (pos); // _indices[posI++] = (unsigned char) (posS++); // } // // // north side // for (int i = resol - 1; i > 0; i--) { // unsigned int pos = i; // _indices[posI++] = (unsigned char) pos; // _indices[posI++] = (unsigned char) (posS++); // } // // // last triangles // _indices[posI++] = (unsigned char) 0; // _indices[posI++] = (unsigned char) (resol * resol); // _indices[posI++] = (unsigned char) (resol * resol); // } // // // create border indices (wireframe mode) // _numBorderIndices = 4 * (resol - 1); // _borderIndices = new unsigned char[_numBorderIndices]; // posI = 0; // for (int j = 0; j < resol - 1; j++) { // _borderIndices[posI++] = (unsigned char) (j * resol); // } // for (int i = 0; i < resol - 1; i++) { // _borderIndices[posI++] = (unsigned char) ((resol - 1) * resol + i); // } // for (int j = resol - 1; j > 0; j--) { // _borderIndices[posI++] = (unsigned char) (j * resol + resol - 1); // } // for (int i = resol - 1; i > 0; i--) { // _borderIndices[posI++] = (unsigned char) (i); // } // // // create inner indices (wireframe mode) // _numInnerIndices = _numBorderIndices * (resol - 2); // _innerIndices = new unsigned char[_numInnerIndices]; // posI = 0; // for (int j = 1; j < resol - 1; j++) // for (int i = 0; i < resol - 1; i++) { // int pos = j * resol + i; // _innerIndices[posI++] = (unsigned char) pos; // _innerIndices[posI++] = (unsigned char) (pos + 1); // } // for (int i = 1; i < resol - 1; i++) // for (int j = 0; j < resol - 1; j++) { // int pos = j * resol + i; // _innerIndices[posI++] = (unsigned char) pos; // _innerIndices[posI++] = (unsigned char) (pos + resol); // } //} //void Tile::render(const RenderContext* rc) //{ // // obtain the gl object // IGL *gl = rc->getGL(); // // // translate model reference system to tile center // gl->pushMatrix(); // MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(_center.asVector3D()); // gl->multMatrixf(T); // // // set opengl texture and pointers // //gl->BindTexture(idTexture); // gl->vertexPointer(3, 0, _vertices); // //gl->TexCoordPointer(2, 0, textureCoor); // gl->color(0.5f,0.5f,0.8f,1.0f); // // // draw tile geometry // if (true /*g->GetWireframe()*/) { // // // draw solid mesh // gl->enablePolygonOffset(5, 5); // gl->drawTriangleStrip(_numIndices, _indices); // gl->disablePolygonOffset(); // // // draw wireframe // //gl->disableTexture2D(); // //gl->disableTextures(); // gl->lineWidth(1); // gl->color(0.0f, 0.0f, 0.0f, 1.0f); // gl->drawLines(_numInnerIndices, _innerIndices); // gl->lineWidth(2); // gl->color(1.0f, 0.0f, 0.0f, 1.0f); // gl->drawLineLoop(_numBorderIndices, _borderIndices); // //gl->EnableTextures(); // //gl->EnableTexture2D(); // // } else { // // // draw the mesh // gl->drawTriangleStrip(_numIndices, _indices); // } // // // recover original model matrix // gl->popMatrix(); //} Mesh* Tile::getMesh(const RenderContext* rc, const TileTessellator* tessellator) { if (_mesh == NULL) { _mesh = tessellator->createMesh(rc, this); } return _mesh; } bool Tile::isVisible(const RenderContext *rc) { return true; } void Tile::render(const RenderContext* rc, const TileTessellator* tessellator, const TileTexturizer* texturizer) { int ___diego_at_work; // Camera* camera = rc->getCamera(); // Vector3D pos = camera->getPos(); // // double distance = pos.length(); // // rc->getLogger()->logInfo("distance to camera: %f", distance); if (isVisible(rc)) { Mesh* mesh = getMesh(rc, tessellator); if (mesh != NULL) { if (!isTextureSolved()) { mesh = texturizer->texturize(rc, this, mesh); } if (mesh != NULL) { mesh->render(rc); } } } } <commit_msg>advanced in TileRendering<commit_after>// // Tile.cpp // G3MiOSSDK // // Created by Agustín Trujillo Pino on 12/06/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "Tile.hpp" #include "Mesh.hpp" #include "Camera.hpp" #include "TileTessellator.hpp" #include "TileTexturizer.hpp" Tile::~Tile() { delete _mesh; } Mesh* Tile::getMesh(const RenderContext* rc, const TileTessellator* tessellator) { if (_mesh == NULL) { _mesh = tessellator->createMesh(rc, this); } return _mesh; } bool Tile::isVisible(const RenderContext *rc) { return true; } void Tile::render(const RenderContext* rc, const TileTessellator* tessellator, const TileTexturizer* texturizer) { int ___diego_at_work; // Camera* camera = rc->getCamera(); // Vector3D pos = camera->getPos(); // // double distance = pos.length(); // // rc->getLogger()->logInfo("distance to camera: %f", distance); if (isVisible(rc)) { Mesh* mesh = getMesh(rc, tessellator); if (mesh != NULL) { if (!isTextureSolved()) { mesh = texturizer->texturize(rc, this, mesh); } if (mesh != NULL) { mesh->render(rc); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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.hpp" #include <chrono> #include <thread> Iceoryx::Iceoryx(const iox::capro::IdString& publisherName, const iox::capro::IdString& subscriberName) noexcept : m_publisher({"Comedians", publisherName, "Duo"}) , m_subscriber({"Comedians", subscriberName, "Duo"}) { } void Iceoryx::initLeader() noexcept { init(); } void Iceoryx::initFollower() noexcept { init(); } void Iceoryx::init() noexcept { m_publisher.offer(); m_subscriber.subscribe(); std::cout << "Waiting till subscribed ... " << std::endl << std::flush; while (m_subscriber.getSubscriptionState() != iox::SubscribeState::SUBSCRIBED) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } std::cout << "Waiting for subscriber ... " << std::endl << std::flush; while (!m_publisher.hasSubscribers()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void Iceoryx::shutdown() noexcept { m_subscriber.unsubscribe(); std::cout << "Waiting for subscriber to unsubscribe ... " << std::endl << std::flush; while (!m_publisher.hasSubscribers()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } // with stopOffer we disconnect all subscribers and the publisher is no more visible m_publisher.stopOffer(); std::cout << "Finished!" << std::endl; } void Iceoryx::sendPerfTopic(uint32_t payloadSizeInBytes, bool runFlag) noexcept { m_publisher.loan(payloadSizeInBytes).and_then([&](auto& sample) { auto sendSample = static_cast<PerfTopic*>(sample.get()); sendSample->payloadSize = payloadSizeInBytes; sendSample->run = runFlag; sendSample->subPackets = 1; sample.publish(); }); } PerfTopic Iceoryx::receivePerfTopic() noexcept { bool hasMoreSamples{true}; PerfTopic receivedSample; do { m_subscriber.take() .and_then([&](iox::popo::Sample<const void>& sample) { receivedSample = *(static_cast<const PerfTopic*>(sample.get())); }) .if_empty([&] { hasMoreSamples = false; }); } while (!hasMoreSamples); return receivedSample; } <commit_msg>iox-#252 Fix iperf<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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.hpp" #include <chrono> #include <thread> Iceoryx::Iceoryx(const iox::capro::IdString& publisherName, const iox::capro::IdString& subscriberName) noexcept : m_publisher({"Comedians", publisherName, "Duo"}) , m_subscriber({"Comedians", subscriberName, "Duo"}) { } void Iceoryx::initLeader() noexcept { init(); } void Iceoryx::initFollower() noexcept { init(); } void Iceoryx::init() noexcept { m_publisher.offer(); m_subscriber.subscribe(); std::cout << "Waiting till subscribed ... " << std::endl << std::flush; while (m_subscriber.getSubscriptionState() != iox::SubscribeState::SUBSCRIBED) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } std::cout << "Waiting for subscriber ... " << std::endl << std::flush; while (!m_publisher.hasSubscribers()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void Iceoryx::shutdown() noexcept { m_subscriber.unsubscribe(); std::cout << "Waiting for subscriber to unsubscribe ... " << std::endl << std::flush; while (!m_publisher.hasSubscribers()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } // with stopOffer we disconnect all subscribers and the publisher is no more visible m_publisher.stopOffer(); std::cout << "Finished!" << std::endl; } void Iceoryx::sendPerfTopic(uint32_t payloadSizeInBytes, bool runFlag) noexcept { m_publisher.loan(payloadSizeInBytes).and_then([&](auto& sample) { auto sendSample = static_cast<PerfTopic*>(sample.get()); sendSample->payloadSize = payloadSizeInBytes; sendSample->run = runFlag; sendSample->subPackets = 1; sample.publish(); }); } PerfTopic Iceoryx::receivePerfTopic() noexcept { bool hasReceivedSample{false}; PerfTopic receivedSample; do { m_subscriber.take().and_then([&](iox::popo::Sample<const void>& sample) { receivedSample = *(static_cast<const PerfTopic*>(sample.get())); hasReceivedSample = true; }); } while (!hasReceivedSample); return receivedSample; } <|endoftext|>
<commit_before>#include "ovasCAcquisitionServerGUI.h" #include <openvibe/ov_all.h> #include <openvibe-toolkit/ovtk_all.h> #include <gtk/gtk.h> #include <iostream> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace std; int main(int argc, char ** argv) { //___________________________________________________________________// // // CKernelLoader l_oKernelLoader; cout<<"[ INF ] Created kernel loader, trying to load kernel module"<<endl; CString m_sError; #if defined OVAS_OS_Windows if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/OpenViBE-kernel-dynamic.dll", &m_sError)) #else if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/libOpenViBE-kernel-dynamic.so", &m_sError)) #endif { cout<<"[ FAILED ] Error loading kernel ("<<m_sError<<")"<<endl; } else { cout<<"[ INF ] Kernel module loaded, trying to get kernel descriptor"<<endl; IKernelDesc* l_pKernelDesc=NULL; IKernelContext* l_pKernelContext=NULL; l_oKernelLoader.initialize(); l_oKernelLoader.getKernelDesc(l_pKernelDesc); if(!l_pKernelDesc) { cout<<"[ FAILED ] No kernel descriptor"<<endl; } else { cout<<"[ INF ] Got kernel descriptor, trying to create kernel"<<endl; l_pKernelContext=l_pKernelDesc->createKernel("acquisition-server", OpenViBE::Directories::getDataDir() + "/openvibe.conf"); if(!l_pKernelContext) { cout<<"[ FAILED ] No kernel created by kernel descriptor"<<endl; } else { OpenViBEToolkit::initialize(*l_pKernelContext); // For Mister Vincent ! #ifdef OVAS_OS_Windows #ifndef NDEBUG //_asm int 3; #endif #endif IConfigurationManager& l_rConfigurationManager=l_pKernelContext->getConfigurationManager(); l_pKernelContext->getPluginManager().addPluginsFromFiles(l_rConfigurationManager.expand("${Kernel_Plugins}")); //initialise Gtk before 3D context #if (GTK_MAJOR_VERSION == 2) && (GTK_MINOR_VERSION < 32) // although deprecated in newer GTKs, we need to use this on Windows with the older GTK, or acquisition server will crash on startup g_thread_init(NULL); #endif gdk_threads_init(); gtk_init(&argc, &argv); // gtk_rc_parse(OpenViBE::Directories::getDataDir() + "/openvibe-applications/designer/interface.gtkrc"); #if 0 // This is not needed in the acquisition server if(l_rConfigurationManager.expandAsBoolean("${Kernel_3DVisualisationEnabled}")) { l_pKernelContext->getVisualisationManager().initialize3DContext(); } #endif { // If this is encapsulated by gdk_threads_enter() and gdk_threads_exit(), m_pThread->join() can hang when gtk_main() returns before destructor of app has been called. OpenViBEAcquisitionServer::CAcquisitionServerGUI app(*l_pKernelContext); try { gdk_threads_enter(); gtk_main(); gdk_threads_leave(); } catch(...) { l_pKernelContext->getLogManager() << LogLevel_Fatal << "Catched top level exception\n"; } } cout<<"[ INF ] Application terminated, releasing allocated objects"<<endl; OpenViBEToolkit::uninitialize(*l_pKernelContext); l_pKernelDesc->releaseKernel(l_pKernelContext); } } l_oKernelLoader.uninitialize(); l_oKernelLoader.unload(); } return 0; } <commit_msg>Ajust GTK version test to fix warnings in Ubuntu 12.10<commit_after>#include "ovasCAcquisitionServerGUI.h" #include <openvibe/ov_all.h> #include <openvibe-toolkit/ovtk_all.h> #include <gtk/gtk.h> #include <iostream> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace std; int main(int argc, char ** argv) { //___________________________________________________________________// // // CKernelLoader l_oKernelLoader; cout<<"[ INF ] Created kernel loader, trying to load kernel module"<<endl; CString m_sError; #if defined OVAS_OS_Windows if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/OpenViBE-kernel-dynamic.dll", &m_sError)) #else if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/libOpenViBE-kernel-dynamic.so", &m_sError)) #endif { cout<<"[ FAILED ] Error loading kernel ("<<m_sError<<")"<<endl; } else { cout<<"[ INF ] Kernel module loaded, trying to get kernel descriptor"<<endl; IKernelDesc* l_pKernelDesc=NULL; IKernelContext* l_pKernelContext=NULL; l_oKernelLoader.initialize(); l_oKernelLoader.getKernelDesc(l_pKernelDesc); if(!l_pKernelDesc) { cout<<"[ FAILED ] No kernel descriptor"<<endl; } else { cout<<"[ INF ] Got kernel descriptor, trying to create kernel"<<endl; l_pKernelContext=l_pKernelDesc->createKernel("acquisition-server", OpenViBE::Directories::getDataDir() + "/openvibe.conf"); if(!l_pKernelContext) { cout<<"[ FAILED ] No kernel created by kernel descriptor"<<endl; } else { OpenViBEToolkit::initialize(*l_pKernelContext); // For Mister Vincent ! #ifdef OVAS_OS_Windows #ifndef NDEBUG //_asm int 3; #endif #endif IConfigurationManager& l_rConfigurationManager=l_pKernelContext->getConfigurationManager(); l_pKernelContext->getPluginManager().addPluginsFromFiles(l_rConfigurationManager.expand("${Kernel_Plugins}")); //initialise Gtk before 3D context #if (GTK_BINARY_AGE < 2413) // although deprecated in newer GTKs (no more needed after (at least) 2.24.13, deprecated in 2.32), we need to use this on Windows with the older GTK (2.22.1), or acquisition server will crash on startup g_thread_init(NULL); #endif gdk_threads_init(); gtk_init(&argc, &argv); // gtk_rc_parse(OpenViBE::Directories::getDataDir() + "/openvibe-applications/designer/interface.gtkrc"); #if 0 // This is not needed in the acquisition server if(l_rConfigurationManager.expandAsBoolean("${Kernel_3DVisualisationEnabled}")) { l_pKernelContext->getVisualisationManager().initialize3DContext(); } #endif { // If this is encapsulated by gdk_threads_enter() and gdk_threads_exit(), m_pThread->join() can hang when gtk_main() returns before destructor of app has been called. OpenViBEAcquisitionServer::CAcquisitionServerGUI app(*l_pKernelContext); try { gdk_threads_enter(); gtk_main(); gdk_threads_leave(); } catch(...) { l_pKernelContext->getLogManager() << LogLevel_Fatal << "Catched top level exception\n"; } } cout<<"[ INF ] Application terminated, releasing allocated objects"<<endl; OpenViBEToolkit::uninitialize(*l_pKernelContext); l_pKernelDesc->releaseKernel(l_pKernelContext); } } l_oKernelLoader.uninitialize(); l_oKernelLoader.unload(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #ifndef _Stroika_Foundation_Math_Common_inl_ #define _Stroika_Foundation_Math_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Math { /* ******************************************************************************** ************************************ Math::nan ********************************* ******************************************************************************** */ template <typename T> inline T nan () { return numeric_limits<T>::quiet_NaN (); } /* ******************************************************************************** ****************************** Math::RoundUpTo ********************************* ******************************************************************************** */ namespace Private { template <typename T> T RoundUpTo_UnSignedHelper_ (T x, T toNearest); template <typename T, typename UNSIGNED_T> inline T RoundUpTo_SignedHelper_ (T x, T toNearest) { Require (toNearest > 0); if (x < 0) { return (- static_cast<T> (RoundDownTo (static_cast<UNSIGNED_T> (-x), static_cast<UNSIGNED_T> (toNearest)))); } else { return static_cast<T> (RoundUpTo_UnSignedHelper_<UNSIGNED_T> (x, toNearest)); } } template <typename T> inline T RoundUpTo_UnSignedHelper_ (T x, T toNearest) { return (((x + toNearest - 1u) / toNearest) * toNearest); } template <typename T, typename UNSIGNED_T> inline T RoundDownTo_SignedHelper_ (T x, T toNearest) { Require (toNearest > 0); if (x < 0) { return (- static_cast<T> (RoundUpTo (static_cast<UNSIGNED_T> (-x), static_cast<UNSIGNED_T> (toNearest)))); } else { return (RoundDownTo (static_cast<UNSIGNED_T> (x), static_cast<UNSIGNED_T> (toNearest))); } } template <typename T> inline T RoundDownTo_UnSignedHelper_ (T x, T toNearest) { return ((x / toNearest) * toNearest); } } template <> inline int RoundUpTo (int x, int toNearest) { return Private::RoundUpTo_SignedHelper_<int, unsigned int> (x, toNearest); } template <> inline long RoundUpTo (long x, long toNearest) { return Private::RoundUpTo_SignedHelper_<long, unsigned long> (x, toNearest); } template <> inline long long RoundUpTo (long long x, long long toNearest) { return Private::RoundUpTo_SignedHelper_<long long, unsigned long long> (x, toNearest); } template <> inline unsigned int RoundUpTo (unsigned int x, unsigned int toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned int> (x, toNearest); } template <> inline unsigned long RoundUpTo (unsigned long x, unsigned long toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned long> (x, toNearest); } template <> inline unsigned long long RoundUpTo (unsigned long long x, unsigned long long toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned long long> (x, toNearest); } /* ******************************************************************************** **************************** Math::RoundDownTo ********************************* ******************************************************************************** */ template <> inline int RoundDownTo (int x, int toNearest) { return Private::RoundDownTo_SignedHelper_<int, unsigned int> (x, toNearest); } template <> inline long RoundDownTo (long x, long toNearest) { return Private::RoundDownTo_SignedHelper_<long, unsigned long> (x, toNearest); } template <> inline long long RoundDownTo (long long x, long long toNearest) { return Private::RoundDownTo_SignedHelper_<long long, unsigned long long> (x, toNearest); } template <> inline unsigned int RoundDownTo (unsigned int x, unsigned int toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned int> (x, toNearest); } template <> inline unsigned long RoundDownTo (unsigned long x, unsigned long toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned long> (x, toNearest); } template <> inline unsigned long long RoundDownTo (unsigned long long x, unsigned long long toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned long long> (x, toNearest); } /* ******************************************************************************** **************************** Math::NearlyEquals ******************************** ******************************************************************************** */ namespace Private_ { template <typename TC> // @todo see if we can make this constexpr somehow? const inline TC mkCompareEpsilon_ (TC l, TC r) { static_assert (std::is_floating_point<TC>::value, "can only be used for float values"); #if 1 if (l < -10 or l > 10) { static const TC kScale_ = pow (static_cast <TC> (10), - (numeric_limits<TC>::digits10 - 1)); // @todo constexpr? is pow() constexpr? return fabs (l) * kScale_; } #endif return (10000 * numeric_limits<TC>::epsilon ()); } } template <typename T1, typename T2, typename EPSILON_TYPE, typename TC> inline bool NearlyEquals (T1 l, T2 r, EPSILON_TYPE epsilon, typename std::enable_if<std::is_floating_point<TC>::value >::type*) { Require (epsilon >= 0); TC diff = (l - r); if (std::isnan (diff)) { // nan-nan, or inf-inf // maybe other cases shouldnt be considered nearly equals? return std::fpclassify (l) == std::fpclassify (r); } if (std::isinf (diff)) { static const TC kEpsilon_ = Private_::mkCompareEpsilon_ (numeric_limits<TC>::max (), numeric_limits<TC>::max ()); if (not std::isinf (l) and std::fabs (l - numeric_limits<TC>::max ()) <= kEpsilon_) { l = numeric_limits<T1>::infinity (); } if (not std::isinf (l) and std::fabs (l - numeric_limits<TC>::lowest ()) <= kEpsilon_) { l = -numeric_limits<T1>::infinity (); } if (not std::isinf (r) and std::fabs (r - numeric_limits<TC>::max ()) <= kEpsilon_) { r = numeric_limits<T2>::infinity (); } if (not std::isinf (r) and std::fabs (r - numeric_limits<TC>::lowest ()) <= kEpsilon_) { r = -numeric_limits<T2>::infinity (); } if (std::isinf (l) and std::isinf (r)) { return (l > 0) == (r > 0); } } return std::fabs (diff) <= epsilon; } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if<std::is_integral<TC>::value >::type*) { return l == r; } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if<std::is_floating_point<TC>::value >::type*) { return NearlyEquals (l, r, Private_::mkCompareEpsilon_<TC> (l, r)); } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if < !std::is_integral<TC>::value&& !std::is_floating_point<TC>::value >::type*) { return l == r; } /* ******************************************************************************** ************************* Math::PinToSpecialPoint ****************************** ******************************************************************************** */ template <typename T> T PinToSpecialPoint (T p, T special) { return PinToSpecialPoint (p, special, Private_::mkCompareEpsilon_ (special, p)); } template <typename T> T PinToSpecialPoint (T p, T special, T epsilon) { if (Math::NearlyEquals (p, special, epsilon)) { return special; } return p; } /* ******************************************************************************** ***************************** Math::PinInRange ********************************* ******************************************************************************** */ template <typename T> inline T PinInRange (T initialValue, T lowerBound, T upperBound) { Require (lowerBound <= upperBound); return max (lowerBound, min (upperBound, initialValue)); } /* ******************************************************************************** ******************************** Math::AtLeast ********************************* ******************************************************************************** */ template <typename T> inline T AtLeast (T initialValue, T lowerBound) { return max (initialValue, lowerBound); } /* ******************************************************************************** ******************************** Math::AtMost ********************************* ******************************************************************************** */ template <typename T> inline T AtMost (T initialValue, T upperBound) { return min (initialValue, lowerBound); } /* ******************************************************************************** ************************** Math::PinToMaxForType ******************************* ******************************************************************************** */ template <typename NEW_T, typename T> NEW_T PinToMaxForType (T initialValue) { using LargerType = decltype (NEW_T () + T ()); // maybe should use conditional<> for this? return static_cast<NEW_T> (min<LargerType> (initialValue, numeric_limits<NEW_T>::max ())); } /* ******************************************************************************** ********************************** Math::IsOdd ********************************* ******************************************************************************** */ template <typename T> bool IsOdd (T v) { return v % 2 == 1; } /* ******************************************************************************** ********************************* Math::IsEven ********************************* ******************************************************************************** */ template <typename T> bool IsEven (T v) { return v % 2 == 0; } /* ******************************************************************************** ******************************** Math::IsPrime ********************************* ******************************************************************************** */ template <typename T> bool IsPrime (T v) { Require (v >= 0); // no negative numbers // @todo - redo this as http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes but this is simpler and // good enuf for me to test... if (v == 1) { return false; } if (v == 2) { return true; // special case } T checkUpTo = T (sqrt (v) + 1); // Check each number from 3 up to checkUpTo and see if its a divisor for (T d = 2; d <= checkUpTo; ++d) { if (v % d == 0) { return false; } } return true; } } } } #endif /*_Stroika_Foundation_Math_Common_inl_*/ <commit_msg>AtMost<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #ifndef _Stroika_Foundation_Math_Common_inl_ #define _Stroika_Foundation_Math_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Math { /* ******************************************************************************** ************************************ Math::nan ********************************* ******************************************************************************** */ template <typename T> inline T nan () { return numeric_limits<T>::quiet_NaN (); } /* ******************************************************************************** ****************************** Math::RoundUpTo ********************************* ******************************************************************************** */ namespace Private { template <typename T> T RoundUpTo_UnSignedHelper_ (T x, T toNearest); template <typename T, typename UNSIGNED_T> inline T RoundUpTo_SignedHelper_ (T x, T toNearest) { Require (toNearest > 0); if (x < 0) { return (- static_cast<T> (RoundDownTo (static_cast<UNSIGNED_T> (-x), static_cast<UNSIGNED_T> (toNearest)))); } else { return static_cast<T> (RoundUpTo_UnSignedHelper_<UNSIGNED_T> (x, toNearest)); } } template <typename T> inline T RoundUpTo_UnSignedHelper_ (T x, T toNearest) { return (((x + toNearest - 1u) / toNearest) * toNearest); } template <typename T, typename UNSIGNED_T> inline T RoundDownTo_SignedHelper_ (T x, T toNearest) { Require (toNearest > 0); if (x < 0) { return (- static_cast<T> (RoundUpTo (static_cast<UNSIGNED_T> (-x), static_cast<UNSIGNED_T> (toNearest)))); } else { return (RoundDownTo (static_cast<UNSIGNED_T> (x), static_cast<UNSIGNED_T> (toNearest))); } } template <typename T> inline T RoundDownTo_UnSignedHelper_ (T x, T toNearest) { return ((x / toNearest) * toNearest); } } template <> inline int RoundUpTo (int x, int toNearest) { return Private::RoundUpTo_SignedHelper_<int, unsigned int> (x, toNearest); } template <> inline long RoundUpTo (long x, long toNearest) { return Private::RoundUpTo_SignedHelper_<long, unsigned long> (x, toNearest); } template <> inline long long RoundUpTo (long long x, long long toNearest) { return Private::RoundUpTo_SignedHelper_<long long, unsigned long long> (x, toNearest); } template <> inline unsigned int RoundUpTo (unsigned int x, unsigned int toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned int> (x, toNearest); } template <> inline unsigned long RoundUpTo (unsigned long x, unsigned long toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned long> (x, toNearest); } template <> inline unsigned long long RoundUpTo (unsigned long long x, unsigned long long toNearest) { return Private::RoundUpTo_UnSignedHelper_<unsigned long long> (x, toNearest); } /* ******************************************************************************** **************************** Math::RoundDownTo ********************************* ******************************************************************************** */ template <> inline int RoundDownTo (int x, int toNearest) { return Private::RoundDownTo_SignedHelper_<int, unsigned int> (x, toNearest); } template <> inline long RoundDownTo (long x, long toNearest) { return Private::RoundDownTo_SignedHelper_<long, unsigned long> (x, toNearest); } template <> inline long long RoundDownTo (long long x, long long toNearest) { return Private::RoundDownTo_SignedHelper_<long long, unsigned long long> (x, toNearest); } template <> inline unsigned int RoundDownTo (unsigned int x, unsigned int toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned int> (x, toNearest); } template <> inline unsigned long RoundDownTo (unsigned long x, unsigned long toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned long> (x, toNearest); } template <> inline unsigned long long RoundDownTo (unsigned long long x, unsigned long long toNearest) { return Private::RoundDownTo_UnSignedHelper_<unsigned long long> (x, toNearest); } /* ******************************************************************************** **************************** Math::NearlyEquals ******************************** ******************************************************************************** */ namespace Private_ { template <typename TC> // @todo see if we can make this constexpr somehow? const inline TC mkCompareEpsilon_ (TC l, TC r) { static_assert (std::is_floating_point<TC>::value, "can only be used for float values"); #if 1 if (l < -10 or l > 10) { static const TC kScale_ = pow (static_cast <TC> (10), - (numeric_limits<TC>::digits10 - 1)); // @todo constexpr? is pow() constexpr? return fabs (l) * kScale_; } #endif return (10000 * numeric_limits<TC>::epsilon ()); } } template <typename T1, typename T2, typename EPSILON_TYPE, typename TC> inline bool NearlyEquals (T1 l, T2 r, EPSILON_TYPE epsilon, typename std::enable_if<std::is_floating_point<TC>::value >::type*) { Require (epsilon >= 0); TC diff = (l - r); if (std::isnan (diff)) { // nan-nan, or inf-inf // maybe other cases shouldnt be considered nearly equals? return std::fpclassify (l) == std::fpclassify (r); } if (std::isinf (diff)) { static const TC kEpsilon_ = Private_::mkCompareEpsilon_ (numeric_limits<TC>::max (), numeric_limits<TC>::max ()); if (not std::isinf (l) and std::fabs (l - numeric_limits<TC>::max ()) <= kEpsilon_) { l = numeric_limits<T1>::infinity (); } if (not std::isinf (l) and std::fabs (l - numeric_limits<TC>::lowest ()) <= kEpsilon_) { l = -numeric_limits<T1>::infinity (); } if (not std::isinf (r) and std::fabs (r - numeric_limits<TC>::max ()) <= kEpsilon_) { r = numeric_limits<T2>::infinity (); } if (not std::isinf (r) and std::fabs (r - numeric_limits<TC>::lowest ()) <= kEpsilon_) { r = -numeric_limits<T2>::infinity (); } if (std::isinf (l) and std::isinf (r)) { return (l > 0) == (r > 0); } } return std::fabs (diff) <= epsilon; } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if<std::is_integral<TC>::value >::type*) { return l == r; } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if<std::is_floating_point<TC>::value >::type*) { return NearlyEquals (l, r, Private_::mkCompareEpsilon_<TC> (l, r)); } template <typename T1, typename T2, typename TC> inline bool NearlyEquals (T1 l, T2 r, typename std::enable_if < !std::is_integral<TC>::value&& !std::is_floating_point<TC>::value >::type*) { return l == r; } /* ******************************************************************************** ************************* Math::PinToSpecialPoint ****************************** ******************************************************************************** */ template <typename T> T PinToSpecialPoint (T p, T special) { return PinToSpecialPoint (p, special, Private_::mkCompareEpsilon_ (special, p)); } template <typename T> T PinToSpecialPoint (T p, T special, T epsilon) { if (Math::NearlyEquals (p, special, epsilon)) { return special; } return p; } /* ******************************************************************************** ***************************** Math::PinInRange ********************************* ******************************************************************************** */ template <typename T> inline T PinInRange (T initialValue, T lowerBound, T upperBound) { Require (lowerBound <= upperBound); return max (lowerBound, min (upperBound, initialValue)); } /* ******************************************************************************** ******************************** Math::AtLeast ********************************* ******************************************************************************** */ template <typename T> inline T AtLeast (T initialValue, T lowerBound) { return max (initialValue, lowerBound); } /* ******************************************************************************** ******************************** Math::AtMost ********************************* ******************************************************************************** */ template <typename T> inline T AtMost (T initialValue, T upperBound) { return min (initialValue, upperBound); } /* ******************************************************************************** ************************** Math::PinToMaxForType ******************************* ******************************************************************************** */ template <typename NEW_T, typename T> NEW_T PinToMaxForType (T initialValue) { using LargerType = decltype (NEW_T () + T ()); // maybe should use conditional<> for this? return static_cast<NEW_T> (min<LargerType> (initialValue, numeric_limits<NEW_T>::max ())); } /* ******************************************************************************** ********************************** Math::IsOdd ********************************* ******************************************************************************** */ template <typename T> bool IsOdd (T v) { return v % 2 == 1; } /* ******************************************************************************** ********************************* Math::IsEven ********************************* ******************************************************************************** */ template <typename T> bool IsEven (T v) { return v % 2 == 0; } /* ******************************************************************************** ******************************** Math::IsPrime ********************************* ******************************************************************************** */ template <typename T> bool IsPrime (T v) { Require (v >= 0); // no negative numbers // @todo - redo this as http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes but this is simpler and // good enuf for me to test... if (v == 1) { return false; } if (v == 2) { return true; // special case } T checkUpTo = T (sqrt (v) + 1); // Check each number from 3 up to checkUpTo and see if its a divisor for (T d = 2; d <= checkUpTo; ++d) { if (v % d == 0) { return false; } } return true; } } } } #endif /*_Stroika_Foundation_Math_Common_inl_*/ <|endoftext|>
<commit_before> // Qt include #include <QGridLayout> #include <QResizeEvent> #include <QPushButton> #include <QPixmap> #include <QDir> #include <QFile> #include <QFileInfo> #include <QDateTime> // ctk includes #include "ctkLogger.h" // ctkWidgets includes #include "ctkFlowLayout.h" //ctkDICOMCore includes #include "ctkDICOMModel.h" #include "ctkDICOMDatabase.h" // ctkDICOMWidgets includes #include "ctkDICOMThumbnailListWidget.h" #include "ui_ctkDICOMThumbnailListWidget.h" #include "ctkDICOMThumbnailWidget.h" // STD includes #include <iostream> // DCMTK includes #include <dcmimage.h> static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMThumbnailListWidget"); //---------------------------------------------------------------------------- class ctkDICOMThumbnailListWidgetPrivate: public Ui_ctkDICOMThumbnailListWidget { public: ctkDICOMThumbnailListWidgetPrivate(ctkDICOMThumbnailListWidget* parent): q_ptr(parent){ } QString databaseDirectory; QModelIndex currentSelectedModel; void clearAllThumbnails(); void addThumbnailWidget(const QModelIndex &imageIndex, const QModelIndex& sourceIndex, const QString& text); void onPatientModelSelected(const QModelIndex &index); void onStudyModelSelected(const QModelIndex &index); void onSeriesModelSelected(const QModelIndex &index); ctkDICOMThumbnailListWidget* const q_ptr; Q_DECLARE_PUBLIC(ctkDICOMThumbnailListWidget); }; //---------------------------------------------------------------------------- // ctkDICOMThumbnailListWidgetPrivate methods void ctkDICOMThumbnailListWidgetPrivate::onPatientModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex patientIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(patientIndex); int studyCount = model->rowCount(patientIndex); for(int i=0; i<studyCount; i++){ QModelIndex studyIndex = patientIndex.child(i, 0); QModelIndex seriesIndex = studyIndex.child(0, 0); QModelIndex imageIndex = seriesIndex.child(0, 0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if(QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, studyIndex, model->data(studyIndex, Qt::DisplayRole).toString()); } } } } void ctkDICOMThumbnailListWidgetPrivate::onStudyModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex studyIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(studyIndex); int seriesCount = model->rowCount(studyIndex); for(int i=0; i<seriesCount; i++){ QModelIndex seriesIndex = studyIndex.child(i, 0); QModelIndex imageIndex = seriesIndex.child(0, 0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if (QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, seriesIndex, model->data(seriesIndex, Qt::DisplayRole).toString()); } } } } void ctkDICOMThumbnailListWidgetPrivate::onSeriesModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex studyIndex = index.parent(); QModelIndex seriesIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(seriesIndex); int imageCount = model->rowCount(seriesIndex); logger.debug(QString("Thumbs: %1").arg(imageCount)); for (int i = 0 ; i < imageCount ; i++ ) { QModelIndex imageIndex = seriesIndex.child(i,0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if(QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, imageIndex, QString("Image %1").arg(i)); } } } } void ctkDICOMThumbnailListWidgetPrivate::clearAllThumbnails(){ Q_Q(ctkDICOMThumbnailListWidget); // Remove previous displayed thumbnails QLayoutItem* item; while(item = this->scrollAreaContentWidget->layout()->takeAt(0)){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(item->widget()); if(thumbnailWidget){ q->disconnect(thumbnailWidget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SLOT(onThumbnailSelected(ctkDICOMThumbnailWidget))); q->disconnect(thumbnailWidget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SIGNAL(selected(ctkDICOMThumbnailWidget))); q->disconnect(thumbnailWidget, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget)), q, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget))); } item->widget()->deleteLater(); } } void ctkDICOMThumbnailListWidgetPrivate::addThumbnailWidget(const QModelIndex& imageIndex, const QModelIndex& sourceIndex, const QString &text){ Q_Q(ctkDICOMThumbnailListWidget); ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(imageIndex.model())); if(model){ QModelIndex seriesIndex = imageIndex.parent(); QModelIndex studyIndex = seriesIndex.parent(); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; ctkDICOMThumbnailWidget* widget = new ctkDICOMThumbnailWidget(this->scrollAreaContentWidget); QString widgetLabel = text; widget->setText( widgetLabel ); QPixmap pix(thumbnailPath); logger.debug("Setting pixmap to " + thumbnailPath); widget->setPixmap(pix); widget->setSourceIndex(sourceIndex); this->scrollAreaContentWidget->layout()->addWidget(widget); q->connect(widget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SLOT(onThumbnailSelected(ctkDICOMThumbnailWidget))); q->connect(widget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SIGNAL(selected(ctkDICOMThumbnailWidget))); q->connect(widget, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget)), q, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget))); } } //---------------------------------------------------------------------------- // ctkDICOMThumbnailListWidget methods //---------------------------------------------------------------------------- ctkDICOMThumbnailListWidget::ctkDICOMThumbnailListWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMThumbnailListWidgetPrivate(this)) { Q_D(ctkDICOMThumbnailListWidget); d->setupUi(this); d->scrollAreaContentWidget->setLayout(new ctkFlowLayout); } //---------------------------------------------------------------------------- ctkDICOMThumbnailListWidget::~ctkDICOMThumbnailListWidget() { Q_D(ctkDICOMThumbnailListWidget); d->clearAllThumbnails(); } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::setDatabaseDirectory(const QString &directory){ Q_D(ctkDICOMThumbnailListWidget); d->databaseDirectory = directory; } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::selectThumbnail(int index){ Q_D(ctkDICOMThumbnailListWidget); int count = d->scrollAreaContentWidget->layout()->count(); logger.debug("Select thumbnail " + QVariant(index).toString() + " of " + QVariant(count).toString()); if(index >= count)return; for(int i=0; i<count; i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(i == index){ thumbnailWidget->setSelected(true); d->scrollArea->ensureWidgetVisible(thumbnailWidget); }else{ thumbnailWidget->setSelected(false); } } } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::selectThumbnail(const QModelIndex &index){ Q_D(ctkDICOMThumbnailListWidget); if(!d->currentSelectedModel.isValid())return; if(index.parent() != d->currentSelectedModel)return; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ int count = d->scrollAreaContentWidget->layout()->count(); for(int i=0; i<count; i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(thumbnailWidget->sourceIndex() == index){ thumbnailWidget->setSelected(true); d->scrollArea->ensureWidgetVisible(thumbnailWidget); }else{ thumbnailWidget->setSelected(false); } } } } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::onModelSelected(const QModelIndex &index){ Q_D(ctkDICOMThumbnailListWidget); d->clearAllThumbnails(); ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ QModelIndex index0 = index.sibling(index.row(), 0); d->currentSelectedModel = index0; if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::PatientType ){ d->onPatientModelSelected(index0); }else if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::StudyType ){ d->onStudyModelSelected(index0); }else if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::SeriesType ){ d->onSeriesModelSelected(index0); } } this->selectThumbnail(0); } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::onThumbnailSelected(const ctkDICOMThumbnailWidget &widget){ Q_D(ctkDICOMThumbnailListWidget); for(int i=0; i<d->scrollAreaContentWidget->layout()->count(); i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(thumbnailWidget && (&widget != thumbnailWidget)){ thumbnailWidget->setSelected(false); } } } <commit_msg>Display middle-slice thumbnails on ctkDICOMThumbnailListWidget<commit_after> // Qt include #include <QGridLayout> #include <QResizeEvent> #include <QPushButton> #include <QPixmap> #include <QDir> #include <QFile> #include <QFileInfo> #include <QDateTime> // ctk includes #include "ctkLogger.h" // ctkWidgets includes #include "ctkFlowLayout.h" //ctkDICOMCore includes #include "ctkDICOMModel.h" #include "ctkDICOMDatabase.h" // ctkDICOMWidgets includes #include "ctkDICOMThumbnailListWidget.h" #include "ui_ctkDICOMThumbnailListWidget.h" #include "ctkDICOMThumbnailWidget.h" // STD includes #include <iostream> // DCMTK includes #include <dcmimage.h> static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMThumbnailListWidget"); //---------------------------------------------------------------------------- class ctkDICOMThumbnailListWidgetPrivate: public Ui_ctkDICOMThumbnailListWidget { public: ctkDICOMThumbnailListWidgetPrivate(ctkDICOMThumbnailListWidget* parent): q_ptr(parent){ } QString databaseDirectory; QModelIndex currentSelectedModel; void clearAllThumbnails(); void addThumbnailWidget(const QModelIndex &imageIndex, const QModelIndex& sourceIndex, const QString& text); void onPatientModelSelected(const QModelIndex &index); void onStudyModelSelected(const QModelIndex &index); void onSeriesModelSelected(const QModelIndex &index); ctkDICOMThumbnailListWidget* const q_ptr; Q_DECLARE_PUBLIC(ctkDICOMThumbnailListWidget); }; //---------------------------------------------------------------------------- // ctkDICOMThumbnailListWidgetPrivate methods void ctkDICOMThumbnailListWidgetPrivate::onPatientModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex patientIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(patientIndex); int studyCount = model->rowCount(patientIndex); for(int i=0; i<studyCount; i++){ QModelIndex studyIndex = patientIndex.child(i, 0); QModelIndex seriesIndex = studyIndex.child(0, 0); model->fetchMore(seriesIndex); int imageCount = model->rowCount(seriesIndex); QModelIndex imageIndex = seriesIndex.child(imageCount/2, 0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if(QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, studyIndex, model->data(studyIndex, Qt::DisplayRole).toString()); } } } } void ctkDICOMThumbnailListWidgetPrivate::onStudyModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex studyIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(studyIndex); int seriesCount = model->rowCount(studyIndex); for(int i=0; i<seriesCount; i++){ QModelIndex seriesIndex = studyIndex.child(i, 0); model->fetchMore(seriesIndex); int imageCount = model->rowCount(seriesIndex); QModelIndex imageIndex = seriesIndex.child(imageCount/2, 0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if (QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, seriesIndex, model->data(seriesIndex, Qt::DisplayRole).toString()); } } } } void ctkDICOMThumbnailListWidgetPrivate::onSeriesModelSelected(const QModelIndex &index){ Q_Q(ctkDICOMThumbnailListWidget); QModelIndex studyIndex = index.parent(); QModelIndex seriesIndex = index; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ model->fetchMore(seriesIndex); int imageCount = model->rowCount(seriesIndex); logger.debug(QString("Thumbs: %1").arg(imageCount)); for (int i = 0 ; i < imageCount ; i++ ) { QModelIndex imageIndex = seriesIndex.child(i,0); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; if(QFile(thumbnailPath).exists()){ this->addThumbnailWidget(imageIndex, imageIndex, QString("Image %1").arg(i)); } } } } void ctkDICOMThumbnailListWidgetPrivate::clearAllThumbnails(){ Q_Q(ctkDICOMThumbnailListWidget); // Remove previous displayed thumbnails QLayoutItem* item; while(item = this->scrollAreaContentWidget->layout()->takeAt(0)){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(item->widget()); if(thumbnailWidget){ q->disconnect(thumbnailWidget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SLOT(onThumbnailSelected(ctkDICOMThumbnailWidget))); q->disconnect(thumbnailWidget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SIGNAL(selected(ctkDICOMThumbnailWidget))); q->disconnect(thumbnailWidget, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget)), q, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget))); } item->widget()->deleteLater(); } } void ctkDICOMThumbnailListWidgetPrivate::addThumbnailWidget(const QModelIndex& imageIndex, const QModelIndex& sourceIndex, const QString &text){ Q_Q(ctkDICOMThumbnailListWidget); ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(imageIndex.model())); if(model){ QModelIndex seriesIndex = imageIndex.parent(); QModelIndex studyIndex = seriesIndex.parent(); QString thumbnailPath = this->databaseDirectory + "/thumbs/" + model->data(studyIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(seriesIndex ,ctkDICOMModel::UIDRole).toString() + "/" + model->data(imageIndex, ctkDICOMModel::UIDRole).toString() + ".png"; ctkDICOMThumbnailWidget* widget = new ctkDICOMThumbnailWidget(this->scrollAreaContentWidget); QString widgetLabel = text; widget->setText( widgetLabel ); QPixmap pix(thumbnailPath); logger.debug("Setting pixmap to " + thumbnailPath); widget->setPixmap(pix); widget->setSourceIndex(sourceIndex); this->scrollAreaContentWidget->layout()->addWidget(widget); q->connect(widget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SLOT(onThumbnailSelected(ctkDICOMThumbnailWidget))); q->connect(widget, SIGNAL(selected(ctkDICOMThumbnailWidget)), q, SIGNAL(selected(ctkDICOMThumbnailWidget))); q->connect(widget, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget)), q, SIGNAL(doubleClicked(ctkDICOMThumbnailWidget))); } } //---------------------------------------------------------------------------- // ctkDICOMThumbnailListWidget methods //---------------------------------------------------------------------------- ctkDICOMThumbnailListWidget::ctkDICOMThumbnailListWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMThumbnailListWidgetPrivate(this)) { Q_D(ctkDICOMThumbnailListWidget); d->setupUi(this); d->scrollAreaContentWidget->setLayout(new ctkFlowLayout); } //---------------------------------------------------------------------------- ctkDICOMThumbnailListWidget::~ctkDICOMThumbnailListWidget() { Q_D(ctkDICOMThumbnailListWidget); d->clearAllThumbnails(); } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::setDatabaseDirectory(const QString &directory){ Q_D(ctkDICOMThumbnailListWidget); d->databaseDirectory = directory; } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::selectThumbnail(int index){ Q_D(ctkDICOMThumbnailListWidget); int count = d->scrollAreaContentWidget->layout()->count(); logger.debug("Select thumbnail " + QVariant(index).toString() + " of " + QVariant(count).toString()); if(index >= count)return; for(int i=0; i<count; i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(i == index){ thumbnailWidget->setSelected(true); d->scrollArea->ensureWidgetVisible(thumbnailWidget); }else{ thumbnailWidget->setSelected(false); } } } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::selectThumbnail(const QModelIndex &index){ Q_D(ctkDICOMThumbnailListWidget); if(!d->currentSelectedModel.isValid())return; if(index.parent() != d->currentSelectedModel)return; ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ int count = d->scrollAreaContentWidget->layout()->count(); for(int i=0; i<count; i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(thumbnailWidget->sourceIndex() == index){ thumbnailWidget->setSelected(true); d->scrollArea->ensureWidgetVisible(thumbnailWidget); }else{ thumbnailWidget->setSelected(false); } } } } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::onModelSelected(const QModelIndex &index){ Q_D(ctkDICOMThumbnailListWidget); d->clearAllThumbnails(); ctkDICOMModel* model = const_cast<ctkDICOMModel*>(qobject_cast<const ctkDICOMModel*>(index.model())); if(model){ QModelIndex index0 = index.sibling(index.row(), 0); d->currentSelectedModel = index0; if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::PatientType ){ d->onPatientModelSelected(index0); }else if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::StudyType ){ d->onStudyModelSelected(index0); }else if ( model->data(index0,ctkDICOMModel::TypeRole) == ctkDICOMModel::SeriesType ){ d->onSeriesModelSelected(index0); } } this->selectThumbnail(0); } //---------------------------------------------------------------------------- void ctkDICOMThumbnailListWidget::onThumbnailSelected(const ctkDICOMThumbnailWidget &widget){ Q_D(ctkDICOMThumbnailListWidget); for(int i=0; i<d->scrollAreaContentWidget->layout()->count(); i++){ ctkDICOMThumbnailWidget* thumbnailWidget = qobject_cast<ctkDICOMThumbnailWidget*>(d->scrollAreaContentWidget->layout()->itemAt(i)->widget()); if(thumbnailWidget && (&widget != thumbnailWidget)){ thumbnailWidget->setSelected(false); } } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelReader.h" #include <iostream> #include <fstream> #include <locale> mitk::ContourModelReader::ContourModelReader() { m_Success = false; } mitk::ContourModelReader::~ContourModelReader() {} void mitk::ContourModelReader::GenerateData() { std::locale::global(std::locale("C")); m_Success = false; if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } if ( ! this->CanReadFile( m_FileName.c_str() ) ) { itkWarningMacro( << "Sorry, can't read file " << m_FileName << "!" ); return ; } try{ TiXmlDocument doc(m_FileName.c_str()); bool loadOkay = doc.LoadFile(); if (loadOkay) { TiXmlHandle docHandle( &doc ); //handle geometry information TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("head").FirstChildElement("geometryInformation").ToElement(); /*++++ handle n contourModels within data tags ++++*/ unsigned int contourCounter(0); for( TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("data").ToElement(); currentContourModelElement != NULL; currentContourModelElement = currentContourModelElement->NextSiblingElement()) { mitk::ContourModel::Pointer newContourModel = mitk::ContourModel::New(); if(currentContourModelElement->FirstChildElement("timestep") != NULL) { /*++++ handle n timesteps within timestep tags ++++*/ for( TiXmlElement* currentTimeSeries = currentContourModelElement->FirstChildElement("timestep")->ToElement(); currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement()) { unsigned int currentTimeStep(0); currentTimeStep = atoi(currentTimeSeries->Attribute("n")); if( "1" == currentTimeSeries->Attribute("isClosed") ) { newContourModel->Close(currentTimeStep); } this->ReadPoints(newContourModel, currentTimeSeries, currentTimeStep); } /*++++ END handle n timesteps within timestep tags ++++*/ } else { //this should not happen MITK_WARN << "wrong file format!"; //newContourModel = this->ReadPoint(newContourModel, currentContourModelElement, 0); } this->SetNthOutput( contourCounter, newContourModel ); contourCounter++; } /*++++ END handle n contourModels within data tags ++++*/ } else { MITK_WARN << "XML parser error!"; } }catch(...) { MITK_ERROR << "Cannot read contourModel."; m_Success = false; } m_Success = true; } void mitk::ContourModelReader::ReadPoints(mitk::ContourModel::Pointer newContourModel, TiXmlElement* currentTimeSeries, unsigned int currentTimeStep) { //check if the timesteps in contourModel have to be expanded if(currentTimeStep != newContourModel->GetTimeSteps()) { newContourModel->Expand(currentTimeStep+1); } //read all points within controlPoints tag if(currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point") != NULL) { for( TiXmlElement* currentPoint = currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point")->ToElement(); currentPoint != NULL; currentPoint = currentPoint->NextSiblingElement()) { mitk::PointSpecificationType spec((mitk::PointSpecificationType) 0); double x(0.0); double y(0.0); double z(0.0); x = atof(currentPoint->FirstChildElement("x")->GetText()); y = atof(currentPoint->FirstChildElement("y")->GetText()); z = atof(currentPoint->FirstChildElement("z")->GetText()); int b; currentPoint->QueryIntAttribute("isActive", &b); bool isActivePoint = bool(b); mitk::Point3D point; mitk::FillVector3D(point, x, y, z); newContourModel->AddVertex(point, isActivePoint,currentTimeStep); } } else { //nothing to read } } void mitk::ContourModelReader::GenerateOutputInformation() { } int mitk::ContourModelReader::CanReadFile ( const char *name ) { std::ifstream in( name ); bool isGood = in.good(); in.close(); return isGood; } bool mitk::ContourModelReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) { // First check the extension if( filename == "" ) { //MITK_INFO<<"No filename specified."<<std::endl; return false; } // check if image is serie if( filePattern != "" && filePrefix != "" ) return false; bool extensionFound = false; std::string::size_type MPSPos = filename.rfind(".cnt"); if ((MPSPos != std::string::npos) && (MPSPos == filename.length() - 4)) { extensionFound = true; } MPSPos = filename.rfind(".CNT"); if ((MPSPos != std::string::npos) && (MPSPos == filename.length() - 4)) { extensionFound = true; } if( !extensionFound ) { //MITK_INFO<<"The filename extension is not recognized."<<std::endl; return false; } return true; } void mitk::ContourModelReader::ResizeOutputs( const unsigned int& num ) { unsigned int prevNum = this->GetNumberOfOutputs(); this->SetNumberOfOutputs( num ); for ( unsigned int i = prevNum; i < num; ++i ) { this->SetNthOutput( i, this->MakeOutput( i ).GetPointer() ); } } bool mitk::ContourModelReader::GetSuccess() const { return m_Success; } <commit_msg>fixed isClosed attribute reading<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelReader.h" #include <iostream> #include <fstream> #include <locale> mitk::ContourModelReader::ContourModelReader() { m_Success = false; } mitk::ContourModelReader::~ContourModelReader() {} void mitk::ContourModelReader::GenerateData() { std::locale::global(std::locale("C")); m_Success = false; if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } if ( ! this->CanReadFile( m_FileName.c_str() ) ) { itkWarningMacro( << "Sorry, can't read file " << m_FileName << "!" ); return ; } try{ TiXmlDocument doc(m_FileName.c_str()); bool loadOkay = doc.LoadFile(); if (loadOkay) { TiXmlHandle docHandle( &doc ); //handle geometry information TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("head").FirstChildElement("geometryInformation").ToElement(); /*++++ handle n contourModels within data tags ++++*/ unsigned int contourCounter(0); for( TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("data").ToElement(); currentContourModelElement != NULL; currentContourModelElement = currentContourModelElement->NextSiblingElement()) { mitk::ContourModel::Pointer newContourModel = mitk::ContourModel::New(); if(currentContourModelElement->FirstChildElement("timestep") != NULL) { /*++++ handle n timesteps within timestep tags ++++*/ for( TiXmlElement* currentTimeSeries = currentContourModelElement->FirstChildElement("timestep")->ToElement(); currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement()) { unsigned int currentTimeStep(0); currentTimeStep = atoi(currentTimeSeries->Attribute("n")); this->ReadPoints(newContourModel, currentTimeSeries, currentTimeStep); int isClosed; currentTimeSeries->QueryIntAttribute("isClosed", &isClosed); if( isClosed ) { newContourModel->Close(currentTimeStep); } } /*++++ END handle n timesteps within timestep tags ++++*/ } else { //this should not happen MITK_WARN << "wrong file format!"; //newContourModel = this->ReadPoint(newContourModel, currentContourModelElement, 0); } this->SetNthOutput( contourCounter, newContourModel ); contourCounter++; } /*++++ END handle n contourModels within data tags ++++*/ } else { MITK_WARN << "XML parser error!"; } }catch(...) { MITK_ERROR << "Cannot read contourModel."; m_Success = false; } m_Success = true; } void mitk::ContourModelReader::ReadPoints(mitk::ContourModel::Pointer newContourModel, TiXmlElement* currentTimeSeries, unsigned int currentTimeStep) { //check if the timesteps in contourModel have to be expanded if(currentTimeStep != newContourModel->GetTimeSteps()) { newContourModel->Expand(currentTimeStep+1); } //read all points within controlPoints tag if(currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point") != NULL) { for( TiXmlElement* currentPoint = currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point")->ToElement(); currentPoint != NULL; currentPoint = currentPoint->NextSiblingElement()) { mitk::PointSpecificationType spec((mitk::PointSpecificationType) 0); double x(0.0); double y(0.0); double z(0.0); x = atof(currentPoint->FirstChildElement("x")->GetText()); y = atof(currentPoint->FirstChildElement("y")->GetText()); z = atof(currentPoint->FirstChildElement("z")->GetText()); int isActivePoint; currentPoint->QueryIntAttribute("isActive", &isActivePoint); mitk::Point3D point; mitk::FillVector3D(point, x, y, z); newContourModel->AddVertex(point, isActivePoint,currentTimeStep); } } else { //nothing to read } } void mitk::ContourModelReader::GenerateOutputInformation() { } int mitk::ContourModelReader::CanReadFile ( const char *name ) { std::ifstream in( name ); bool isGood = in.good(); in.close(); return isGood; } bool mitk::ContourModelReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) { // First check the extension if( filename == "" ) { //MITK_INFO<<"No filename specified."<<std::endl; return false; } // check if image is serie if( filePattern != "" && filePrefix != "" ) return false; bool extensionFound = false; std::string::size_type MPSPos = filename.rfind(".cnt"); if ((MPSPos != std::string::npos) && (MPSPos == filename.length() - 4)) { extensionFound = true; } MPSPos = filename.rfind(".CNT"); if ((MPSPos != std::string::npos) && (MPSPos == filename.length() - 4)) { extensionFound = true; } if( !extensionFound ) { //MITK_INFO<<"The filename extension is not recognized."<<std::endl; return false; } return true; } void mitk::ContourModelReader::ResizeOutputs( const unsigned int& num ) { unsigned int prevNum = this->GetNumberOfOutputs(); this->SetNumberOfOutputs( num ); for ( unsigned int i = prevNum; i < num; ++i ) { this->SetNthOutput( i, this->MakeOutput( i ).GetPointer() ); } } bool mitk::ContourModelReader::GetSuccess() const { return m_Success; } <|endoftext|>
<commit_before>#include "viewer.h" #include <cstdlib> #include <ctime> #include <GL/gl.h> #include <SDL.h> #include "base/Log.h" #include "base/Guard.h" namespace viewer { int Viewer::run() { typedef base::PtrGuard<SDL_Surface, SDL_FreeSurface> SurfaceGuard; typedef base::RunGuard<SDL_Quit> SDLQuitGuard; if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) != 0) { VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END; return 1; } SDLQuitGuard sdlQuitGuard; SDL_WM_SetCaption("viewer", "viewer"); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SurfaceGuard screen(SDL_SetVideoMode(1024, 600, 24, SDL_OPENGL)); if (!screen) { VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END; return 1; } #if 0 SDL_WM_ToggleFullScreen(screen.get()); #endif try { m_driver = new video::Driver(screen->w, screen->h); } catch (const video::TextException& e) { VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END; return 1; } m_width = screen->w; m_height = screen->h; // Seed random number generator srand(time(NULL)); Uint32 last_time; Uint32 fps = 120; // Initialize time difference counter last_time = SDL_GetTicks(); // Main loop for (;;) { Uint32 this_time = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: goto end; break; default: break; } } try { // TODO Fix wraparound for time difference tick(this_time - last_time); } catch (const std::exception& e) { VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END; return 1; } m_driver->beginScene(); draw(); m_driver->endScene(); last_time = this_time; Sint32 sleep_time = (1000 / fps) - (SDL_GetTicks() - last_time); if (sleep_time > 0) { SDL_Delay(sleep_time); } } end: return 0; } void Viewer::draw() { std::lock_guard<std::mutex> lockGuard(mutex()); const float minNote = 50; const float maxNote = 300; const double noteWidth = 2; // const double noteHeight = 20; double position = 0; for (auto note : cb()) { if (note != 0) { // TODO float compare double ypos = (note - minNote) * (m_height / (maxNote - minNote)); m_driver->draw2DRectangle(position, ypos - 1, position + noteWidth, ypos + 1, video::Color(255, 255, 255, 255)); } position += noteWidth; } { double ypos = (196 - minNote) * (m_height / (maxNote - minNote)); m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(255, 0, 0, 255)); } } } <commit_msg>Add line for A3<commit_after>#include "viewer.h" #include <cstdlib> #include <ctime> #include <GL/gl.h> #include <SDL.h> #include "base/Log.h" #include "base/Guard.h" namespace viewer { int Viewer::run() { typedef base::PtrGuard<SDL_Surface, SDL_FreeSurface> SurfaceGuard; typedef base::RunGuard<SDL_Quit> SDLQuitGuard; if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) != 0) { VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END; return 1; } SDLQuitGuard sdlQuitGuard; SDL_WM_SetCaption("viewer", "viewer"); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SurfaceGuard screen(SDL_SetVideoMode(1024, 600, 24, SDL_OPENGL)); if (!screen) { VIEWER_LOG_ERROR << SDL_GetError() << VIEWER_LOG_END; return 1; } #if 0 SDL_WM_ToggleFullScreen(screen.get()); #endif try { m_driver = new video::Driver(screen->w, screen->h); } catch (const video::TextException& e) { VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END; return 1; } m_width = screen->w; m_height = screen->h; // Seed random number generator srand(time(NULL)); Uint32 last_time; Uint32 fps = 120; // Initialize time difference counter last_time = SDL_GetTicks(); // Main loop for (;;) { Uint32 this_time = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: goto end; break; default: break; } } try { // TODO Fix wraparound for time difference tick(this_time - last_time); } catch (const std::exception& e) { VIEWER_LOG_ERROR << e.what() << VIEWER_LOG_END; return 1; } m_driver->beginScene(); draw(); m_driver->endScene(); last_time = this_time; Sint32 sleep_time = (1000 / fps) - (SDL_GetTicks() - last_time); if (sleep_time > 0) { SDL_Delay(sleep_time); } } end: return 0; } void Viewer::draw() { std::lock_guard<std::mutex> lockGuard(mutex()); const float minNote = 50; const float maxNote = 300; const double noteWidth = 2; // const double noteHeight = 20; double position = 0; for (auto note : cb()) { if (note != 0) { // TODO float compare double ypos = (note - minNote) * (m_height / (maxNote - minNote)); m_driver->draw2DRectangle(position, ypos - 1, position + noteWidth, ypos + 1, video::Color(255, 255, 255, 255)); } position += noteWidth; } // G3 { double ypos = (196 - minNote) * (m_height / (maxNote - minNote)); m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(255, 0, 0, 255)); } // A3 { double ypos = (220 - minNote) * (m_height / (maxNote - minNote)); m_driver->draw2DLine(0, ypos, m_width, ypos, video::Color(100, 0, 0, 255)); } } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "utiltime.h" #include <chrono> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> using namespace std; static int64_t nMockTime = 0; //! For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } int64_t GetTimeMillis() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); } int64_t GetTimeMicros() { return std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } <commit_msg>Revert "Avoid boost::posix_time functions that have potential out-of-bounds read bugs. ref #1459"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "utiltime.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> using namespace std; static int64_t nMockTime = 0; //! For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } int64_t GetTimeMillis() { return (boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } int64_t GetTimeMicros() { return (boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } <|endoftext|>
<commit_before>#include <cassert> #include <sqlite3ext.h> extern const sqlite3_api_routines *sqlite3_api; #include <GraphMol/FMCS/FMCS.h> #include "utils.hpp" #include "mol_fmcs.hpp" #include "mol.hpp" void mol_fmcs_step(sqlite3_context* ctx, int argc, sqlite3_value** argv) { assert(argc == 1); int rc = SQLITE_OK; sqlite3_value *arg = argv[0]; RDKit::ROMOL_SPTR mol(arg_to_romol(arg, &rc)); if ( rc != SQLITE_OK ) { sqlite3_result_error_code(ctx, rc); return; } void **agg = (void **) sqlite3_aggregate_context(ctx, sizeof(void *)); if (agg) { if (!*agg) { *agg = (void *) new std::vector<RDKit::ROMOL_SPTR>; } std::vector<RDKit::ROMOL_SPTR> *mols = (std::vector<RDKit::ROMOL_SPTR> *) *agg; mols->push_back(mol); } } void mol_fmcs_final(sqlite3_context * ctx) { void **agg = (void **) sqlite3_aggregate_context(ctx, 0); if (agg) { if (!*agg) { *agg = (void *) new std::vector<RDKit::ROMOL_SPTR>; } std::vector<RDKit::ROMOL_SPTR> *mols = (std::vector<RDKit::ROMOL_SPTR> *) *agg; RDKit::MCSResult results = findMCS(*mols); sqlite3_result_text(ctx, results.SmartsString.c_str(), -1, SQLITE_TRANSIENT); } else { sqlite3_result_null(ctx); } } int chemicalite_init_mol_fmcs(sqlite3 *db) { (void)db; int rc = SQLITE_OK; rc = sqlite3_create_window_function( db, "mol_find_mcs", 1, // int nArg, SQLITE_UTF8, // int eTextRep, 0, // void *pApp, mol_fmcs_step, // void (*xStep)(sqlite3_context*,int,sqlite3_value**), mol_fmcs_final, // void (*xFinal)(sqlite3_context*), 0, // void (*xValue)(sqlite3_context*), 0, // void (*xInverse)(sqlite3_context*,int,sqlite3_value**), 0 // void(*xDestroy)(void*) ); return rc; } <commit_msg>fix warning<commit_after>#include <cassert> #include <sqlite3ext.h> extern const sqlite3_api_routines *sqlite3_api; #include <GraphMol/FMCS/FMCS.h> #include "utils.hpp" #include "mol_fmcs.hpp" #include "mol.hpp" void mol_fmcs_step(sqlite3_context* ctx, int, sqlite3_value** argv) { int rc = SQLITE_OK; sqlite3_value *arg = argv[0]; RDKit::ROMOL_SPTR mol(arg_to_romol(arg, &rc)); if ( rc != SQLITE_OK ) { sqlite3_result_error_code(ctx, rc); return; } void **agg = (void **) sqlite3_aggregate_context(ctx, sizeof(void *)); if (agg) { if (!*agg) { *agg = (void *) new std::vector<RDKit::ROMOL_SPTR>; } std::vector<RDKit::ROMOL_SPTR> *mols = (std::vector<RDKit::ROMOL_SPTR> *) *agg; mols->push_back(mol); } } void mol_fmcs_final(sqlite3_context * ctx) { void **agg = (void **) sqlite3_aggregate_context(ctx, 0); if (agg) { if (!*agg) { *agg = (void *) new std::vector<RDKit::ROMOL_SPTR>; } std::vector<RDKit::ROMOL_SPTR> *mols = (std::vector<RDKit::ROMOL_SPTR> *) *agg; RDKit::MCSResult results = findMCS(*mols); sqlite3_result_text(ctx, results.SmartsString.c_str(), -1, SQLITE_TRANSIENT); } else { sqlite3_result_null(ctx); } } int chemicalite_init_mol_fmcs(sqlite3 *db) { (void)db; int rc = SQLITE_OK; rc = sqlite3_create_window_function( db, "mol_find_mcs", 1, // int nArg, SQLITE_UTF8, // int eTextRep, 0, // void *pApp, mol_fmcs_step, // void (*xStep)(sqlite3_context*,int,sqlite3_value**), mol_fmcs_final, // void (*xFinal)(sqlite3_context*), 0, // void (*xValue)(sqlite3_context*), 0, // void (*xInverse)(sqlite3_context*,int,sqlite3_value**), 0 // void(*xDestroy)(void*) ); return rc; } <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH #define DUNE_STUFF_FUNCTION_EXPRESSION_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #else #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #include <sstream> #include <vector> #ifdef HAVE_EIGEN #include <Eigen/Core> #endif // HAVE_EIGEN #include <dune/common/fvector.hh> #include <dune/common/dynvector.hh> #include <dune/common/exceptions.hh> #ifdef HAVE_DUNE_FEM #include <dune/fem/function/common/function.hh> #include <dune/fem/space/common/functionspace.hh> #endif // HAVE_DUNE_FEM #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/string.hh> #include "expression/mathexpr.hh" #include "interface.hh" namespace Dune { namespace Stuff { namespace Function { /** \brief Provides a function which evaluates a given mathematical expression at runtime. Given a mathematical expression as a string, a domain \f$ K_d^{m \geq 1} \f$ and a range \f$ K_r^{n \geq 1} \f$ this function represents the map \f{eqnarray} f:K_d^m \to K_r^n\\ x = (x_1, \dots, x_m)' \mapsto (f_1(x), \dots f_n(x))', \f} where \f$ K_d \f$ is the DomainType and \f$ K_r \f$ is the RangeType, usually a power of \f$ \mathcal{R} \f$. The name of the variable as well as the \f$ n \f$ expressions of \f$f_1, \dots, f_n\f$ have to be given in a Dune::ParameterTree in the following form: \code variable: x expression.0: 2*x[0] expression.1: sin(x[1])*x[0]\endcode There have to exist at least \f$n\f$ expressions; the entries of the variable are indexed by \f$[i]\f$ for \f$ 0 \leq i \leq m - 1 \f$. **/ template< class DomainFieldImp, int maxDimDomain, class RangeFieldImp, int maxDimRange > class Expression : public Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > { public: typedef DomainFieldImp DomainFieldType; typedef RangeFieldImp RangeFieldType; typedef Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > BaseType; typedef Expression< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > ThisType; Expression(const std::string _variable, const std::string _expression) { const std::vector< std::string > expressions(1, _expression); setup(_variable, expressions); } // Expression(const std::string variable, const std::string expression) Expression(const std::string _variable, const std::vector< std::string > _expressions) { setup(_variable, _expressions); } // Expression(const std::string variable, const std::vector< std::string >& expressions) Expression(const ThisType& other) { setup(other.variable(), other.expression()); } // Expression(const ThisType& other) static ThisType createFromParamTree(const Dune::ParameterTree& paramTree) { const Dune::Stuff::Common::ExtendedParameterTree extendedParamtree(paramTree); // get variable if (!extendedParamtree.hasKey("variable")) DUNE_THROW(Dune::RangeError, "\nError: missing key 'variable'!"); const std::string variable = extendedParamtree.get("variable", "not_meaningful_default_value"); // get expressions if (!extendedParamtree.hasKey("expression")) DUNE_THROW(Dune::RangeError, "\nError: missing key or vector 'expression'!"); const std::vector< std::string > expressions = extendedParamtree.getVector< std::string >("expression", "not_meaningful_default_value"); // create and return return ThisType(variable, expressions); } // static ThisType createFromParamTree(const Stuff::Common::ExtendedParameterTree& paramTree) ThisType& operator=(const ThisType& other) { if (this != &other) { cleanup(); setup(other.variable(), other.expression()); } return this; } // ThisType& operator=(const ThisType& other) ~Expression() { cleanup(); } // ~Expression() void report(const std::string name = "stuff.function.expression", std::ostream& stream = std::cout, const std::string& prefix = "") const { const std::string tmp = name + "(" + variable() + ") = "; stream << prefix << tmp; if (expression().size() == 1) stream << expression()[0] << std::endl; else { stream << "[ " << expression()[0] << ";" << std::endl; const std::string whitespace = Dune::Stuff::Common::whitespaceify(tmp + "[ "); for (unsigned int i = 1; i < expression().size() - 1; ++i) stream << prefix << whitespace << expression()[i] << ";" << std::endl; stream << prefix << whitespace << expression()[expression().size() -1] << " ]" << std::endl; } } // void report(const std::string, std::ostream&, const std::string&) const std::string variable() const { return variable_; } const std::vector< std::string > expression() const { return expressions_; } unsigned int dimRange() const { return std::min(int(actualDimRange_), maxDimRange); } //! needed for Interface virtual void evaluate(const Dune::FieldVector< DomainFieldImp, maxDimDomain >& arg, Dune::FieldVector< RangeFieldImp, maxDimRange >& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); assert(ret.size() <= dimRange()); // arg for (typename Dune::FieldVector< DomainFieldImp, maxDimDomain >::size_type i = 0; i < arg.size(); ++i) { *(arg_[i]) = arg[i]; } // ret for (typename Dune::FieldVector< RangeFieldImp, maxDimRange >::size_type i = 0; i < ret.size(); ++i) { ret[i] = op_[i]->Val(); } } template< class DomainVectorType, class RangeVectorType > void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); assert(ret.size() <= dimRange()); // arg for (typename Dune::DenseVector< DomainVectorType >::size_type i = 0; i < arg.size(); ++i) { *(arg_[i]) = arg[i]; } // ret for (typename Dune::DenseVector< RangeVectorType >::size_type i = 0; i < ret.size(); ++i) { ret[i] = op_[i]->Val(); } } #ifdef HAVE_EIGEN /** * \attention ret is resized to size dimRange()! */ void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); ret.resize(dimRange()); // arg for (int i = 0; i < arg.size(); ++ i) { *(arg_[i]) = arg(i); } // ret for (int i = 0; i < ret.size(); ++ i) { ret(i) = op_[i]->Val(); } } // void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const #endif // HAVE_EIGEN private: void setup(const std::string& _variable, const std::vector< std::string >& _expressions) { assert(maxDimDomain > 0); assert(maxDimRange > 0); // set expressions if (_expressions.size() < 1) DUNE_THROW(Dune::InvalidStateException,"\nError: Given 'expressions'-vector is empty!"); actualDimRange_ = std::min(int(_expressions.size()), maxDimRange); expressions_ = _expressions; // set variable (i.e. "x") variable_ = _variable; // fill variables (i.e. "x[0]", "x[1]", ...) for (int i = 0; i < maxDimDomain; ++i) { std::stringstream variableStream; variableStream << variable_ << "[" << i << "]"; variables_.push_back(variableStream.str()); } // create epressions for (unsigned int i = 0; i < maxDimDomain; ++i) { arg_[i] = new DomainFieldType(0.0); var_arg_[i] = new RVar(variables_[i].c_str(), arg_[i]); vararray_[i] = var_arg_[i]; } for (unsigned int i = 0; i < dimRange(); ++ i) { op_[i] = new ROperation(expressions_[i].c_str(), maxDimDomain, vararray_); } } // void setup(const std::string& variable, const std::vector< std::string >& expressions) void cleanup() { for (unsigned int i = 0; i < dimRange(); ++i) { delete op_[i]; } for (unsigned int i = 0; i < maxDimDomain; ++i) { delete var_arg_[i]; delete arg_[i]; } } // void cleanup() std::string variable_; std::vector< std::string > variables_; std::vector< std::string > expressions_; unsigned int actualDimRange_; mutable DomainFieldType* arg_[maxDimDomain]; RVar* var_arg_[maxDimDomain]; RVar* vararray_[maxDimDomain]; ROperation* op_[maxDimRange]; }; // class Expression } // namespace Function } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH <commit_msg>[function.expression] minor change<commit_after>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH #define DUNE_STUFF_FUNCTION_EXPRESSION_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #else #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #include <sstream> #include <vector> #ifdef HAVE_EIGEN #include <Eigen/Core> #endif // HAVE_EIGEN #include <dune/common/fvector.hh> #include <dune/common/dynvector.hh> #include <dune/common/exceptions.hh> #ifdef HAVE_DUNE_FEM #include <dune/fem/function/common/function.hh> #include <dune/fem/space/common/functionspace.hh> #endif // HAVE_DUNE_FEM #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/string.hh> #include "expression/mathexpr.hh" #include "interface.hh" namespace Dune { namespace Stuff { namespace Function { /** \brief Provides a function which evaluates a given mathematical expression at runtime. Given a mathematical expression as a string, a domain \f$ K_d^{m \geq 1} \f$ and a range \f$ K_r^{n \geq 1} \f$ this function represents the map \f{eqnarray} f:K_d^m \to K_r^n\\ x = (x_1, \dots, x_m)' \mapsto (f_1(x), \dots f_n(x))', \f} where \f$ K_d \f$ is the DomainType and \f$ K_r \f$ is the RangeType, usually a power of \f$ \mathcal{R} \f$. The name of the variable as well as the \f$ n \f$ expressions of \f$f_1, \dots, f_n\f$ have to be given in a Dune::ParameterTree in the following form: \code variable: x expression.0: 2*x[0] expression.1: sin(x[1])*x[0]\endcode There have to exist at least \f$n\f$ expressions; the entries of the variable are indexed by \f$[i]\f$ for \f$ 0 \leq i \leq m - 1 \f$. **/ template< class DomainFieldImp, int maxDimDomain, class RangeFieldImp, int maxDimRange > class Expression : public Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > { public: typedef DomainFieldImp DomainFieldType; typedef RangeFieldImp RangeFieldType; typedef Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > BaseType; typedef Expression< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > ThisType; Expression(const std::string _variable, const std::string _expression) { const std::vector< std::string > expressions(1, _expression); setup(_variable, expressions); } // Expression(const std::string variable, const std::string expression) Expression(const std::string _variable, const std::vector< std::string > _expressions) { setup(_variable, _expressions); } // Expression(const std::string variable, const std::vector< std::string >& expressions) Expression(const ThisType& other) { setup(other.variable(), other.expression()); } // Expression(const ThisType& other) static ThisType createFromParamTree(const Dune::ParameterTree& paramTree) { const Dune::Stuff::Common::ExtendedParameterTree extendedParamtree(paramTree); // get variable if (!extendedParamtree.hasKey("variable")) DUNE_THROW(Dune::RangeError, "\nError: missing key 'variable'!"); const std::string variable = extendedParamtree.get("variable", "meaningless_default_value"); // get expressions if (!extendedParamtree.hasKey("expression")) DUNE_THROW(Dune::RangeError, "\nError: missing key or vector 'expression'!"); const std::vector< std::string > expressions = extendedParamtree.getVector< std::string >("expression", "meaningless_default_value", 0); // create and return return ThisType(variable, expressions); } // static ThisType createFromParamTree(const Stuff::Common::ExtendedParameterTree& paramTree) ThisType& operator=(const ThisType& other) { if (this != &other) { cleanup(); setup(other.variable(), other.expression()); } return this; } // ThisType& operator=(const ThisType& other) ~Expression() { cleanup(); } // ~Expression() void report(const std::string name = "stuff.function.expression", std::ostream& stream = std::cout, const std::string& prefix = "") const { const std::string tmp = name + "(" + variable() + ") = "; stream << prefix << tmp; if (expression().size() == 1) stream << expression()[0] << std::endl; else { stream << "[ " << expression()[0] << ";" << std::endl; const std::string whitespace = Dune::Stuff::Common::whitespaceify(tmp + "[ "); for (unsigned int i = 1; i < expression().size() - 1; ++i) stream << prefix << whitespace << expression()[i] << ";" << std::endl; stream << prefix << whitespace << expression()[expression().size() -1] << " ]" << std::endl; } } // void report(const std::string, std::ostream&, const std::string&) const std::string variable() const { return variable_; } const std::vector< std::string > expression() const { return expressions_; } unsigned int dimRange() const { return std::min(int(actualDimRange_), maxDimRange); } //! needed for Interface virtual void evaluate(const Dune::FieldVector< DomainFieldImp, maxDimDomain >& arg, Dune::FieldVector< RangeFieldImp, maxDimRange >& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); assert(ret.size() <= dimRange()); // arg for (typename Dune::FieldVector< DomainFieldImp, maxDimDomain >::size_type i = 0; i < arg.size(); ++i) { *(arg_[i]) = arg[i]; } // ret for (typename Dune::FieldVector< RangeFieldImp, maxDimRange >::size_type i = 0; i < ret.size(); ++i) { ret[i] = op_[i]->Val(); } } template< class DomainVectorType, class RangeVectorType > void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); assert(ret.size() <= dimRange()); // arg for (typename Dune::DenseVector< DomainVectorType >::size_type i = 0; i < arg.size(); ++i) { *(arg_[i]) = arg[i]; } // ret for (typename Dune::DenseVector< RangeVectorType >::size_type i = 0; i < ret.size(); ++i) { ret[i] = op_[i]->Val(); } } #ifdef HAVE_EIGEN /** * \attention ret is resized to size dimRange()! */ void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const { // ensure right dimensions assert(arg.size() <= maxDimDomain); ret.resize(dimRange()); // arg for (int i = 0; i < arg.size(); ++ i) { *(arg_[i]) = arg(i); } // ret for (int i = 0; i < ret.size(); ++ i) { ret(i) = op_[i]->Val(); } } // void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const #endif // HAVE_EIGEN private: void setup(const std::string& _variable, const std::vector< std::string >& _expressions) { assert(maxDimDomain > 0); assert(maxDimRange > 0); // set expressions if (_expressions.size() < 1) DUNE_THROW(Dune::InvalidStateException,"\nError: Given 'expressions'-vector is empty!"); actualDimRange_ = std::min(int(_expressions.size()), maxDimRange); expressions_ = _expressions; // set variable (i.e. "x") variable_ = _variable; // fill variables (i.e. "x[0]", "x[1]", ...) for (int i = 0; i < maxDimDomain; ++i) { std::stringstream variableStream; variableStream << variable_ << "[" << i << "]"; variables_.push_back(variableStream.str()); } // create epressions for (unsigned int i = 0; i < maxDimDomain; ++i) { arg_[i] = new DomainFieldType(0.0); var_arg_[i] = new RVar(variables_[i].c_str(), arg_[i]); vararray_[i] = var_arg_[i]; } for (unsigned int i = 0; i < dimRange(); ++ i) { op_[i] = new ROperation(expressions_[i].c_str(), maxDimDomain, vararray_); } } // void setup(const std::string& variable, const std::vector< std::string >& expressions) void cleanup() { for (unsigned int i = 0; i < dimRange(); ++i) { delete op_[i]; } for (unsigned int i = 0; i < maxDimDomain; ++i) { delete var_arg_[i]; delete arg_[i]; } } // void cleanup() std::string variable_; std::vector< std::string > variables_; std::vector< std::string > expressions_; unsigned int actualDimRange_; mutable DomainFieldType* arg_[maxDimDomain]; RVar* var_arg_[maxDimDomain]; RVar* vararray_[maxDimDomain]; ROperation* op_[maxDimRange]; }; // class Expression } // namespace Function } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <tlib/system.hpp> #include <tlib/graphics.hpp> #include <tlib/print.hpp> #include <tlib/malloc.hpp> namespace { uint32_t* z_buffer = nullptr; uint64_t width = 0; uint64_t height = 0; uint64_t x_shift = 0; uint64_t y_shift = 0; uint64_t bytes_per_scan_line = 0; uint64_t red_shift = 0; uint64_t green_shift = 0; uint64_t blue_shift = 0; #include <tlib/Liberation.inl> uint32_t make_color(uint8_t r, uint8_t g, uint8_t b){ return (r << red_shift) + (g << green_shift) + (b << blue_shift); } void fill_buffer(uint32_t color){ auto where = 0; for(size_t j = 0; j < height; ++j){ for(size_t i = 0; i < width; ++i){ z_buffer[where + i] = color; } where += y_shift; } } void draw_pixel(size_t x, size_t y, uint32_t color){ z_buffer[x + y * y_shift] = color; } void draw_hline(size_t x, size_t y, size_t w, uint32_t color){ auto where = x + y * y_shift; for(size_t i = 0; i < w; ++i){ z_buffer[where + i] = color; } } void draw_rect(size_t x, size_t y, size_t w, size_t h, uint32_t color){ auto where = x + y * y_shift; for(size_t j = 0; j < h; ++j){ for(size_t i = 0; i < w; ++i){ z_buffer[where + i] = color; } where += y_shift; } } void draw_char(size_t x, size_t y, char c, uint32_t color){ auto where = x + y * y_shift; auto font_char = &Liberation_VESA_data[c * 16]; for(size_t i = 0; i < 16; ++i){ for(size_t j = 0; j < 8; ++j){ if(font_char[i] & (1 << (8 - j))){ z_buffer[where+j] = color; } } where += y_shift; } } void draw_string(size_t x, size_t y, const char* s, uint32_t color){ while(*s){ draw_char(x, y, *s, color); ++s; x += 8; } } void paint_cursor(){ auto x = graphics::mouse_x(); auto y = graphics::mouse_y(); auto color = make_color(20, 20, 20); draw_pixel(x, y, color); draw_hline(x, y+1, 2, color); draw_hline(x, y+2, 3, color); draw_hline(x, y+3, 4, color); draw_hline(x, y+4, 5, color); draw_hline(x, y+5, 4, color); draw_pixel(x, y+6, color); draw_hline(x+2, y+6, 2, color); draw_hline(x+3, y+7, 2, color); draw_hline(x+3, y+8, 2, color); } void paint_top_bar(){ draw_rect(0, 0, width, 18, make_color(51, 51, 51)); draw_rect(0, 18, width, 2, make_color(25, 25, 25)); auto date = local_date(); auto date_str = sprintf("%u.%u.%u %u:%u", size_t(date.day), size_t(date.month), size_t(date.year), size_t(date.hour), size_t(date.minutes)); draw_char(2, 2, 'T', make_color(30, 30, 30)); draw_string(width - 128, 2, date_str.c_str(), make_color(200, 200, 200)); } struct window { size_t x; size_t y; size_t width; size_t height; uint32_t color; // TODO Relax std::vector to allow for non-default-constructible window(){} window(size_t x, size_t y, size_t width, size_t height) : x(x), y(y), width(width), height(height) { color = make_color(25, 25, 155); } void draw(){ draw_rect(x, y, width, height, color); } }; std::vector<window> windows; } // end of anonnymous namespace int main(int /*argc*/, char* /*argv*/[]){ // Create a default window windows.emplace_back(250, 250, 200, 400); width = graphics::get_width(); height = graphics::get_height(); x_shift = graphics::get_x_shift(); y_shift = graphics::get_y_shift(); bytes_per_scan_line = graphics::get_bytes_per_scan_line(); red_shift = graphics::get_red_shift(); green_shift = graphics::get_green_shift(); blue_shift = graphics::get_blue_shift(); size_t total_size = height * bytes_per_scan_line; auto buffer = new char[total_size]; z_buffer = reinterpret_cast<uint32_t*>(buffer); auto background = make_color(211, 211, 211); set_canonical(false); static constexpr const size_t sleep_timeout = 50; while(true){ fill_buffer(background); paint_top_bar(); for(auto& window : windows){ window.draw(); } paint_cursor(); graphics::redraw(buffer); auto before = ms_time(); auto code = read_input_raw(sleep_timeout); auto after = ms_time(); if(code != keycode::TIMEOUT){ // TODO Handle event at this point user_logf("odin: %u ", static_cast<size_t>(code)); auto duration = after - before; if(duration < sleep_timeout){ sleep_ms(sleep_timeout - duration); } } } set_canonical(true); delete[] buffer; return 0; } <commit_msg>Prepare mouse handling in Odin<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <tlib/system.hpp> #include <tlib/graphics.hpp> #include <tlib/print.hpp> #include <tlib/malloc.hpp> namespace { uint32_t* z_buffer = nullptr; uint64_t width = 0; uint64_t height = 0; uint64_t x_shift = 0; uint64_t y_shift = 0; uint64_t bytes_per_scan_line = 0; uint64_t red_shift = 0; uint64_t green_shift = 0; uint64_t blue_shift = 0; #include <tlib/Liberation.inl> uint32_t make_color(uint8_t r, uint8_t g, uint8_t b){ return (r << red_shift) + (g << green_shift) + (b << blue_shift); } void fill_buffer(uint32_t color){ auto where = 0; for(size_t j = 0; j < height; ++j){ for(size_t i = 0; i < width; ++i){ z_buffer[where + i] = color; } where += y_shift; } } void draw_pixel(size_t x, size_t y, uint32_t color){ z_buffer[x + y * y_shift] = color; } void draw_hline(size_t x, size_t y, size_t w, uint32_t color){ auto where = x + y * y_shift; for(size_t i = 0; i < w; ++i){ z_buffer[where + i] = color; } } void draw_rect(size_t x, size_t y, size_t w, size_t h, uint32_t color){ auto where = x + y * y_shift; for(size_t j = 0; j < h; ++j){ for(size_t i = 0; i < w; ++i){ z_buffer[where + i] = color; } where += y_shift; } } void draw_char(size_t x, size_t y, char c, uint32_t color){ auto where = x + y * y_shift; auto font_char = &Liberation_VESA_data[c * 16]; for(size_t i = 0; i < 16; ++i){ for(size_t j = 0; j < 8; ++j){ if(font_char[i] & (1 << (8 - j))){ z_buffer[where+j] = color; } } where += y_shift; } } void draw_string(size_t x, size_t y, const char* s, uint32_t color){ while(*s){ draw_char(x, y, *s, color); ++s; x += 8; } } void paint_cursor(){ auto x = graphics::mouse_x(); auto y = graphics::mouse_y(); auto color = make_color(20, 20, 20); draw_pixel(x, y, color); draw_hline(x, y+1, 2, color); draw_hline(x, y+2, 3, color); draw_hline(x, y+3, 4, color); draw_hline(x, y+4, 5, color); draw_hline(x, y+5, 4, color); draw_pixel(x, y+6, color); draw_hline(x+2, y+6, 2, color); draw_hline(x+3, y+7, 2, color); draw_hline(x+3, y+8, 2, color); } void paint_top_bar(){ draw_rect(0, 0, width, 18, make_color(51, 51, 51)); draw_rect(0, 18, width, 2, make_color(25, 25, 25)); auto date = local_date(); auto date_str = sprintf("%u.%u.%u %u:%u", size_t(date.day), size_t(date.month), size_t(date.year), size_t(date.hour), size_t(date.minutes)); draw_char(2, 2, 'T', make_color(30, 30, 30)); draw_string(width - 128, 2, date_str.c_str(), make_color(200, 200, 200)); } struct window { size_t x; size_t y; size_t width; size_t height; uint32_t color; // TODO Relax std::vector to allow for non-default-constructible window(){} window(size_t x, size_t y, size_t width, size_t height) : x(x), y(y), width(width), height(height) { color = make_color(25, 25, 155); } void draw(){ draw_rect(x, y, width, height, color); } }; std::vector<window> windows; } // end of anonnymous namespace int main(int /*argc*/, char* /*argv*/[]){ // Create a default window windows.emplace_back(250, 250, 200, 400); width = graphics::get_width(); height = graphics::get_height(); x_shift = graphics::get_x_shift(); y_shift = graphics::get_y_shift(); bytes_per_scan_line = graphics::get_bytes_per_scan_line(); red_shift = graphics::get_red_shift(); green_shift = graphics::get_green_shift(); blue_shift = graphics::get_blue_shift(); size_t total_size = height * bytes_per_scan_line; auto buffer = new char[total_size]; z_buffer = reinterpret_cast<uint32_t*>(buffer); auto background = make_color(211, 211, 211); set_canonical(false); set_mouse(true); static constexpr const size_t sleep_timeout = 50; while(true){ fill_buffer(background); paint_top_bar(); for(auto& window : windows){ window.draw(); } paint_cursor(); graphics::redraw(buffer); auto before = ms_time(); auto code = read_input_raw(sleep_timeout); auto after = ms_time(); if(code != keycode::TIMEOUT){ // TODO Handle event at this point switch(code){ case keycode::MOUSE_LEFT_PRESS: user_logf("odin: left press"); break; case keycode::MOUSE_LEFT_RELEASE: user_logf("odin: left release"); break; case keycode::MOUSE_RIGHT_PRESS: user_logf("odin: right press"); break; case keycode::MOUSE_RIGHT_RELEASE: user_logf("odin: right release"); break; default: user_logf("odin: %u ", static_cast<size_t>(code)); } auto duration = after - before; if(duration < sleep_timeout){ sleep_ms(sleep_timeout - duration); } } } set_canonical(true); set_mouse(false); delete[] buffer; return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> namespace { } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc != 2) { tlib::print_line("usage: ping address_ip"); return 1; } std::string ip(argv[1]); auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } auto socket = tlib::socket_open(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if (!socket) { tlib::printf("ls: socket_open error: %s\n", std::error_message(socket.error())); return 1; } auto status = tlib::listen(*socket, true); if (!status) { tlib::printf("ping: listen error: %s\n", std::error_message(status.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; for(size_t i = 0; i < N; ++i){ auto packet = tlib::prepare_packet(*socket, &desc); if (!packet) { if(packet.error() == std::ERROR_SOCKET_TIMEOUT){ tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(packet.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet->payload + packet->index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; status = tlib::finalize_packet(*socket, *packet); if (!status) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(status.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while(true){ // Make sure we don't wait for more than the timeout if(after > before + timeout_ms){ break; } auto remaining = timeout_ms - (after - before); bool handled = false; auto p = tlib::wait_for_packet(*socket, remaining); if (!p) { if(p.error() == std::ERROR_SOCKET_TIMEOUT){ tlib::printf("%s unreachable\n", ip.c_str()); handled = true; } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(p.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p->payload + p->index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if(command_type == tlib::icmp::type::ECHO_REPLY){ tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } // The rest of the packets are simply ignored tlib::release_packet(*p); } if(handled){ break; } after = tlib::ms_time(); } if(i < N - 1){ tlib::sleep_ms(1000); } } status = tlib::listen(*socket, false); if (!status) { tlib::printf("ping: listen error: %s\n", std::error_message(status.error())); return 1; } tlib::socket_close(*socket); return 0; } <commit_msg>Use the new API<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> namespace { static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc != 2) { tlib::print_line("usage: ping address_ip"); return 1; } std::string ip(argv[1]); auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if(!sock){ tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } sock.listen(true); if(!sock){ tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; for(size_t i = 0; i < N; ++i){ auto packet = sock.prepare_packet(&desc); if (!sock) { if(sock.error() == std::ERROR_SOCKET_TIMEOUT){ tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(sock.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet.payload + packet.index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; sock.finalize_packet(packet); if (!sock) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(sock.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while(true){ // Make sure we don't wait for more than the timeout if(after > before + timeout_ms){ break; } auto remaining = timeout_ms - (after - before); bool handled = false; auto p = sock.wait_for_packet(remaining); if (!sock) { if(sock.error() == std::ERROR_SOCKET_TIMEOUT){ tlib::printf("%s unreachable\n", ip.c_str()); handled = true; sock.clear(); } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(sock.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p.payload + p.index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if(command_type == tlib::icmp::type::ECHO_REPLY){ tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } // The rest of the packets are simply ignored tlib::release_packet(p); } if(handled){ break; } after = tlib::ms_time(); } if(i < N - 1){ tlib::sleep_ms(1000); } } sock.listen(false); return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #define DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #include "DTK_ConfigDefs.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> // expand #include <DTK_DetailsMortonCode.hpp> // morton3D #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTags.hpp> #include <DTK_KokkosHelpers.hpp> // clz #include <Kokkos_Macros.hpp> #include <Kokkos_Pair.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { namespace Details { /** * This structure contains all the functions used to build the BVH. All the * functions are static. */ template <typename DeviceType> struct TreeConstruction { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename ConstViewType> static void calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ); // to assign the Morton code for a given object, we use the centroid point // of its bounding box, and express it relative to the bounding box of the // scene. template <typename ConstViewType> static void assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ); template <typename ConstViewType> static void initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ); static Node *generateHierarchy( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, Kokkos::View<Node *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int *, DeviceType> parents ); static void calculateInternalNodesBoundingVolumes( Kokkos::View<Node const *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int const *, DeviceType> parents ); KOKKOS_INLINE_FUNCTION static int commonPrefix( Kokkos::View<unsigned int *, DeviceType> morton_codes, int i, int j ) { using KokkosHelpers::clz; int const n = morton_codes.extent( 0 ); if ( j < 0 || j > n - 1 ) return -1; // our construction algorithm relies on keys being unique so we handle // explicitly case of duplicate Morton codes by augmenting each key by // a bit representation of its index. if ( morton_codes[i] == morton_codes[j] ) { // clz( k[i] ^ k[j] ) == 32 return 32 + clz( i ^ j ); } return clz( morton_codes[i] ^ morton_codes[j] ); } KOKKOS_FUNCTION static int findSplit( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int first, int last ); KOKKOS_FUNCTION static Kokkos::pair<int, int> determineRange( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int i ); }; template <typename ViewType> class CalculateBoundingBoxOfTheSceneFunctor { public: CalculateBoundingBoxOfTheSceneFunctor( typename ViewType::const_type primitives ) : _primitives( primitives ) { } KOKKOS_INLINE_FUNCTION void init( Box &box ) const { box = Box(); } KOKKOS_INLINE_FUNCTION void operator()( int const i, Box &box ) const { expand( box, _primitives( i ) ); } KOKKOS_INLINE_FUNCTION void join( volatile Box &dst, volatile Box const &src ) const { expand( dst, src ); } private: typename ViewType::const_type _primitives; }; template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ) { static_assert( Kokkos::is_view<ConstViewType>::value, "Must pass a view" ); static_assert( std::is_same<typename ConstViewType::traits::device_type, DeviceType>::value, "Wrong device type" ); // TODO static_assert( is_expandable_v<Box, typename // ConstViewType::value_type), ""); auto const n = primitives.extent( 0 ); Kokkos::parallel_reduce( DTK_MARK_REGION( "calculate_bounding_box_of_the_scene" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), CalculateBoundingBoxOfTheSceneFunctor<decltype( primitives )>( primitives ), scene_bounding_box ); Kokkos::fence(); } template <typename Primitives, typename MortonCodes> inline void assignMortonCodesDispatch( BoxTag, Primitives primitives, MortonCodes morton_codes, Box const &scene_bounding_box ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = morton_codes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "assign_morton_codes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { Point xyz; double a, b; centroid( primitives( i ), xyz ); // scale coordinates with respect to bounding box of the scene for ( int d = 0; d < 3; ++d ) { a = scene_bounding_box.minCorner()[d]; b = scene_bounding_box.maxCorner()[d]; xyz[d] = ( a != b ? ( xyz[d] - a ) / ( b - a ) : 0 ); } morton_codes( i ) = morton3D( xyz[0], xyz[1], xyz[2] ); } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ) { using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; assignMortonCodesDispatch( Tag{}, primitives, morton_codes, scene_bounding_box ); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( BoxTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, primitives( permutation_indices( i ) )}; } ); Kokkos::fence(); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( PointTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, {primitives( permutation_indices( i ) ), primitives( permutation_indices( i ) )}}; } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ) { auto const n = leaf_nodes.extent( 0 ); DTK_REQUIRE( permutation_indices.extent( 0 ) == n ); DTK_REQUIRE( primitives.extent( 0 ) == n ); static_assert( sizeof( typename decltype( permutation_indices )::value_type ) == sizeof( Node * ), "Encoding leaf index in pointer to child is not safe if the " "index and pointer types do not have the same size" ); using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; initializeLeafNodesDispatch( Tag{}, primitives, permutation_indices, leaf_nodes ); } } // namespace Details } // namespace DataTransferKit #endif <commit_msg>Add TreeConstruction::assignMortonCodesDispatch() for PointTag<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #define DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #include "DTK_ConfigDefs.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> // expand #include <DTK_DetailsMortonCode.hpp> // morton3D #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTags.hpp> #include <DTK_KokkosHelpers.hpp> // clz #include <Kokkos_Macros.hpp> #include <Kokkos_Pair.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { namespace Details { /** * This structure contains all the functions used to build the BVH. All the * functions are static. */ template <typename DeviceType> struct TreeConstruction { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename ConstViewType> static void calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ); // to assign the Morton code for a given object, we use the centroid point // of its bounding box, and express it relative to the bounding box of the // scene. template <typename ConstViewType> static void assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ); template <typename ConstViewType> static void initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ); static Node *generateHierarchy( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, Kokkos::View<Node *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int *, DeviceType> parents ); static void calculateInternalNodesBoundingVolumes( Kokkos::View<Node const *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int const *, DeviceType> parents ); KOKKOS_INLINE_FUNCTION static int commonPrefix( Kokkos::View<unsigned int *, DeviceType> morton_codes, int i, int j ) { using KokkosHelpers::clz; int const n = morton_codes.extent( 0 ); if ( j < 0 || j > n - 1 ) return -1; // our construction algorithm relies on keys being unique so we handle // explicitly case of duplicate Morton codes by augmenting each key by // a bit representation of its index. if ( morton_codes[i] == morton_codes[j] ) { // clz( k[i] ^ k[j] ) == 32 return 32 + clz( i ^ j ); } return clz( morton_codes[i] ^ morton_codes[j] ); } KOKKOS_FUNCTION static int findSplit( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int first, int last ); KOKKOS_FUNCTION static Kokkos::pair<int, int> determineRange( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int i ); }; template <typename ViewType> class CalculateBoundingBoxOfTheSceneFunctor { public: CalculateBoundingBoxOfTheSceneFunctor( typename ViewType::const_type primitives ) : _primitives( primitives ) { } KOKKOS_INLINE_FUNCTION void init( Box &box ) const { box = Box(); } KOKKOS_INLINE_FUNCTION void operator()( int const i, Box &box ) const { expand( box, _primitives( i ) ); } KOKKOS_INLINE_FUNCTION void join( volatile Box &dst, volatile Box const &src ) const { expand( dst, src ); } private: typename ViewType::const_type _primitives; }; template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ) { static_assert( Kokkos::is_view<ConstViewType>::value, "Must pass a view" ); static_assert( std::is_same<typename ConstViewType::traits::device_type, DeviceType>::value, "Wrong device type" ); // TODO static_assert( is_expandable_v<Box, typename // ConstViewType::value_type), ""); auto const n = primitives.extent( 0 ); Kokkos::parallel_reduce( DTK_MARK_REGION( "calculate_bounding_box_of_the_scene" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), CalculateBoundingBoxOfTheSceneFunctor<decltype( primitives )>( primitives ), scene_bounding_box ); Kokkos::fence(); } template <typename Primitives, typename MortonCodes> inline void assignMortonCodesDispatch( BoxTag, Primitives primitives, MortonCodes morton_codes, Box const &scene_bounding_box ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = morton_codes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "assign_morton_codes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { Point xyz; double a, b; centroid( primitives( i ), xyz ); // scale coordinates with respect to bounding box of the scene for ( int d = 0; d < 3; ++d ) { a = scene_bounding_box.minCorner()[d]; b = scene_bounding_box.maxCorner()[d]; xyz[d] = ( a != b ? ( xyz[d] - a ) / ( b - a ) : 0 ); } morton_codes( i ) = morton3D( xyz[0], xyz[1], xyz[2] ); } ); Kokkos::fence(); } template <typename Primitives, typename MortonCodes> inline void assignMortonCodesDispatch( PointTag, Primitives primitives, MortonCodes morton_codes, Box const &scene_bounding_box ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = morton_codes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "assign_morton_codes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { Point xyz = primitives( i ); double a, b; // scale coordinates with respect to bounding box of the scene for ( int d = 0; d < 3; ++d ) { a = scene_bounding_box.minCorner()[d]; b = scene_bounding_box.maxCorner()[d]; xyz[d] = ( a != b ? ( xyz[d] - a ) / ( b - a ) : 0 ); } morton_codes( i ) = morton3D( xyz[0], xyz[1], xyz[2] ); } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ) { using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; assignMortonCodesDispatch( Tag{}, primitives, morton_codes, scene_bounding_box ); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( BoxTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, primitives( permutation_indices( i ) )}; } ); Kokkos::fence(); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( PointTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, {primitives( permutation_indices( i ) ), primitives( permutation_indices( i ) )}}; } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ) { auto const n = leaf_nodes.extent( 0 ); DTK_REQUIRE( permutation_indices.extent( 0 ) == n ); DTK_REQUIRE( primitives.extent( 0 ) == n ); static_assert( sizeof( typename decltype( permutation_indices )::value_type ) == sizeof( Node * ), "Encoding leaf index in pointer to child is not safe if the " "index and pointer types do not have the same size" ); using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; initializeLeafNodesDispatch( Tag{}, primitives, permutation_indices, leaf_nodes ); } } // namespace Details } // namespace DataTransferKit #endif <|endoftext|>
<commit_before>/***************************************************************************//** * FILE : timekeeper.hpp */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is libZinc. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2012 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef __ZN_TIME_KEEPER_HPP__ #define __ZN_TIME_KEEPER_HPP__ #include "zinc/timekeeper.h" #include "zinc/timenotifier.hpp" namespace zinc { class TimeKeeper { protected: Cmiss_time_keeper_id id; public: TimeKeeper() : id(0) { } // takes ownership of C handle, responsibility for destroying it explicit TimeKeeper(Cmiss_time_keeper_id in_time_keeper_id) : id(in_time_keeper_id) { } TimeKeeper(const TimeKeeper& timeKeeper) : id(Cmiss_time_keeper_access(timeKeeper.id)) { } TimeKeeper& operator=(const TimeKeeper& timeKeeper) { Cmiss_time_keeper_id temp_id = Cmiss_time_keeper_access(timeKeeper.id); if (0 != id) { Cmiss_time_keeper_destroy(&id); } id = temp_id; return *this; } ~TimeKeeper() { if (0 != id) { Cmiss_time_keeper_destroy(&id); } } bool isValid() { return (0 != id); } Cmiss_time_keeper_id getId() { return id; } enum Attribute { ATTRIBUTE_INVALID = CMISS_TIME_KEEPER_ATTRIBUTE_INVALID, ATTRIBUTE_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_TIME, ATTRIBUTE_MINIMUM_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_MINIMUM_TIME, ATTRIBUTE_MAXIMUM_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_MAXIMUM_TIME, ATTRIBUTE_SPEED = CMISS_TIME_KEEPER_ATTRIBUTE_SPEED }; int getAttributeReal(Attribute attribute) { return Cmiss_time_keeper_get_attribute_real(id, static_cast<Cmiss_time_keeper_attribute>(attribute)); } int setAttributeReal(Attribute attribute, double value) { return Cmiss_time_keeper_set_attribute_real(id, static_cast<Cmiss_time_keeper_attribute>(attribute), value); } TimeNotifier createNotifierRegular(double updateFrequency, double timeOffset) { return TimeNotifier(Cmiss_time_keeper_create_notifier_regular( id, updateFrequency, timeOffset)); } int addTimeNotifier(TimeNotifier timeNotifier) { return Cmiss_time_keeper_add_time_notifier(id, timeNotifier.getId()); } int removeTimeNotifier(TimeNotifier timeNotifier) { return Cmiss_time_keeper_remove_time_notifier(id, timeNotifier.getId()); } }; } // namespace zinc #endif /* __ZN_TIME_KEEPER_HPP__ */ <commit_msg>Removing CMISS_TIME_KEEPER_ATTRIBUTE_SPEED from the C++ API. https://tracker.physiomeproject.org/show_bug.cgi?id=3528<commit_after>/***************************************************************************//** * FILE : timekeeper.hpp */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is libZinc. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2012 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef __ZN_TIME_KEEPER_HPP__ #define __ZN_TIME_KEEPER_HPP__ #include "zinc/timekeeper.h" #include "zinc/timenotifier.hpp" namespace zinc { class TimeKeeper { protected: Cmiss_time_keeper_id id; public: TimeKeeper() : id(0) { } // takes ownership of C handle, responsibility for destroying it explicit TimeKeeper(Cmiss_time_keeper_id in_time_keeper_id) : id(in_time_keeper_id) { } TimeKeeper(const TimeKeeper& timeKeeper) : id(Cmiss_time_keeper_access(timeKeeper.id)) { } TimeKeeper& operator=(const TimeKeeper& timeKeeper) { Cmiss_time_keeper_id temp_id = Cmiss_time_keeper_access(timeKeeper.id); if (0 != id) { Cmiss_time_keeper_destroy(&id); } id = temp_id; return *this; } ~TimeKeeper() { if (0 != id) { Cmiss_time_keeper_destroy(&id); } } bool isValid() { return (0 != id); } Cmiss_time_keeper_id getId() { return id; } enum Attribute { ATTRIBUTE_INVALID = CMISS_TIME_KEEPER_ATTRIBUTE_INVALID, ATTRIBUTE_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_TIME, ATTRIBUTE_MINIMUM_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_MINIMUM_TIME, ATTRIBUTE_MAXIMUM_TIME = CMISS_TIME_KEEPER_ATTRIBUTE_MAXIMUM_TIME }; int getAttributeReal(Attribute attribute) { return Cmiss_time_keeper_get_attribute_real(id, static_cast<Cmiss_time_keeper_attribute>(attribute)); } int setAttributeReal(Attribute attribute, double value) { return Cmiss_time_keeper_set_attribute_real(id, static_cast<Cmiss_time_keeper_attribute>(attribute), value); } TimeNotifier createNotifierRegular(double updateFrequency, double timeOffset) { return TimeNotifier(Cmiss_time_keeper_create_notifier_regular( id, updateFrequency, timeOffset)); } int addTimeNotifier(TimeNotifier timeNotifier) { return Cmiss_time_keeper_add_time_notifier(id, timeNotifier.getId()); } int removeTimeNotifier(TimeNotifier timeNotifier) { return Cmiss_time_keeper_remove_time_notifier(id, timeNotifier.getId()); } }; } // namespace zinc #endif /* __ZN_TIME_KEEPER_HPP__ */ <|endoftext|>
<commit_before>/* * * http_client_tests * ledger-core * * Created by Pierre Pollastri on 01/12/2016. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 <gtest/gtest.h> #include <EventLooper.hpp> #include <EventThread.hpp> #include <NativeThreadDispatcher.hpp> #include <NativePathResolver.hpp> #include <fstream> #include <mongoose.h> #include <MongooseHttpClient.hpp> #include <MongooseSimpleRestServer.hpp> #include <ledger/core/net/HttpClient.hpp> #include <ledger/core/net/HttpJsonHandler.hpp> #include <boost/lexical_cast.hpp> static std::string BIG_TEXT = "Hi guys, I own a Nano S and I am a big fan, however there is a big slice of information that is missing from your website, that is how reliable the Nano S is, how much testing it's been through (and it goes through any time a new software release is distributed) etc. \n" "\n" "Think about it, before I put a few thousands Euros in a wallet that depends on the Nano, I want to be sure it won't die on me, say, three months from now, or if someone spills water on it. Think for example how Corsair describes the \"Survivor\" line of USB keys here http://www.corsair.com/en-gb/usb-drives/flash-survivor . Can you offer anything like this? \n" "\n" "\n" "If not, you should recommend your users not to use the Nano S for nothing more than petty cash.\n" "\n" "What do you reckon?\n" "\n" "\n" "G. "; using namespace ledger::core; TEST(HttpClient, GET) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/say/hello/:to/please", [dispatcher](const RestRequest &request) -> RestResponse { std::string result = "Hello "; result += request.match.get("to"); return {200, "OK", result}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { http.GET("/say/hello/toto/please")().foreach(dispatcher->getMainExecutionContext(), [dispatcher, &server] (const std::shared_ptr<api::HttpUrlConnection> connection) { auto body = connection->readBody(); auto res = std::string((char *)(body.data->data()), body.data->size()); EXPECT_EQ(200, connection->getStatusCode()); EXPECT_EQ("Hello toto", res); std::cout << res << std::endl; server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, GETJson) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/talk/to/me/in/json", [dispatcher](const RestRequest &request) -> RestResponse { return {200, "OK", "{\"the_answer\": 42}"}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/talk/to/me/in/json") .json() .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const HttpRequest::JsonResult& result) { auto& json = *std::get<1>(result); EXPECT_TRUE(json.HasMember("the_answer")); EXPECT_TRUE(json["the_answer"].IsInt()); EXPECT_EQ(42, json["the_answer"].GetInt()); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } TEST(HttpClient, GETJsonError) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/knock/knock/neo", [dispatcher](const RestRequest &request) -> RestResponse { return {301, "Moved Permanently", "{\"not_here\": true}"}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/knock/knock/neo") .json() .onComplete(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Try<HttpRequest::JsonResult>& result) { EXPECT_TRUE(result.isFailure()); auto& json = *std::get<1>(*result.getFailure().getTypeUserData<HttpRequest::JsonResult>().getValue()); EXPECT_TRUE(json.HasMember("not_here")); EXPECT_TRUE(json["not_here"].IsBool()); EXPECT_EQ(true, json["not_here"].GetBool()); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, POST) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->POST("/next/century/postal/service", [dispatcher](const RestRequest &request) -> RestResponse { std::string result(request.message->body.p, request.message->body.len); return {200, "OK", result}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { std::vector<uint8_t> body((uint8_t *)BIG_TEXT.c_str(), (uint8_t *)(BIG_TEXT.c_str() + BIG_TEXT.size())); http.POST("/next/century/postal/service", body)().foreach(dispatcher->getMainExecutionContext(), [dispatcher, &server] (const std::shared_ptr<api::HttpUrlConnection> connection) { auto body = connection->readBody(); auto res = std::string((char *)(body.data->data()), body.data->size()); EXPECT_EQ(200, connection->getStatusCode()); EXPECT_EQ(BIG_TEXT, res); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, GETWithSax) { struct Success { int the_answer; }; struct Failure { int code; bool not_here; }; struct Handler : public HttpJsonHandler<std::shared_ptr<Success>, Failure, Handler> { Handler() {}; bool Bool(bool b) { return true; }; bool RawNumber(const Ch *str, rapidjson::SizeType len, bool copy) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = boost::lexical_cast<int>(std::string(str, len)); return true; } bool Key(const Ch *str, rapidjson::SizeType len, bool copy) { _currentKey = std::string(str, len); if (getStatusCode() >= 200 && getStatusCode() < 300) { _result = std::make_shared<Success>(); } else { _result = Failure(); } return true; } Either<Failure, std::shared_ptr<Success>> build() { return _result; } private: std::string _currentKey; Either<Failure, std::shared_ptr<Success>> _result; }; auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/talk/to/me/in/json", [dispatcher](const RestRequest &request) -> RestResponse { return {200, "OK", "{\"the_answer\": 42}"}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/talk/to/me/in/json") .json<Success, Failure>(Handler()) .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Either<Failure, std::shared_ptr<Success>>& result) { EXPECT_TRUE(result.isRight()); EXPECT_EQ(result.getRight()->the_answer, 42); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } TEST(HttpClient, GETWithSaxError) { struct Success { int the_answer; }; struct Failure { int code; bool not_here; }; struct Handler : public HttpJsonHandler<std::shared_ptr<Success>, Failure, Handler> { Handler() {}; bool Bool(bool b) { if (_currentKey == std::string("not_here")) _result.getLeft().not_here = b; return true; }; bool Uint(unsigned int i) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = i; return true; } bool Int(int i) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = i; return true; } bool Key(const Ch *str, rapidjson::SizeType len, bool copy) { _currentKey = std::string(str, len); if (getStatusCode() >= 200 && getStatusCode() < 300) { _result = std::make_shared<Success>(); } else { _result = Failure(); } return true; } Either<Failure, std::shared_ptr<Success>> build() { return _result; } private: std::string _currentKey; Either<Failure, std::shared_ptr<Success>> _result; }; auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/knock/knock/neo", [dispatcher](const RestRequest &request) -> RestResponse { return {301, "Moved Permanently", "{\"not_here\": true}"}; }); server->start(8000); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/knock/knock/neo") .json<Success, Failure>(Handler()) .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Either<Failure, std::shared_ptr<Success>>& result) { EXPECT_TRUE(result.isLeft()); EXPECT_EQ(result.getLeft().not_here, true); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } <commit_msg>Wait 200ms for server to start in HTTP tests<commit_after>/* * * http_client_tests * ledger-core * * Created by Pierre Pollastri on 01/12/2016. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 <gtest/gtest.h> #include <EventLooper.hpp> #include <EventThread.hpp> #include <NativeThreadDispatcher.hpp> #include <NativePathResolver.hpp> #include <fstream> #include <mongoose.h> #include <MongooseHttpClient.hpp> #include <MongooseSimpleRestServer.hpp> #include <ledger/core/net/HttpClient.hpp> #include <ledger/core/net/HttpJsonHandler.hpp> #include <boost/lexical_cast.hpp> #include <thread> #include <chrono> static std::string BIG_TEXT = "Hi guys, I own a Nano S and I am a big fan, however there is a big slice of information that is missing from your website, that is how reliable the Nano S is, how much testing it's been through (and it goes through any time a new software release is distributed) etc. \n" "\n" "Think about it, before I put a few thousands Euros in a wallet that depends on the Nano, I want to be sure it won't die on me, say, three months from now, or if someone spills water on it. Think for example how Corsair describes the \"Survivor\" line of USB keys here http://www.corsair.com/en-gb/usb-drives/flash-survivor . Can you offer anything like this? \n" "\n" "\n" "If not, you should recommend your users not to use the Nano S for nothing more than petty cash.\n" "\n" "What do you reckon?\n" "\n" "\n" "G. "; using namespace ledger::core; TEST(HttpClient, GET) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/say/hello/:to/please", [dispatcher](const RestRequest &request) -> RestResponse { std::string result = "Hello "; result += request.match.get("to"); return {200, "OK", result}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { http.GET("/say/hello/toto/please")().foreach(dispatcher->getMainExecutionContext(), [dispatcher, &server] (const std::shared_ptr<api::HttpUrlConnection> connection) { auto body = connection->readBody(); auto res = std::string((char *)(body.data->data()), body.data->size()); EXPECT_EQ(200, connection->getStatusCode()); EXPECT_EQ("Hello toto", res); std::cout << res << std::endl; server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, GETJson) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/talk/to/me/in/json", [dispatcher](const RestRequest &request) -> RestResponse { return {200, "OK", "{\"the_answer\": 42}"}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/talk/to/me/in/json") .json() .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const HttpRequest::JsonResult& result) { auto& json = *std::get<1>(result); EXPECT_TRUE(json.HasMember("the_answer")); EXPECT_TRUE(json["the_answer"].IsInt()); EXPECT_EQ(42, json["the_answer"].GetInt()); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } TEST(HttpClient, GETJsonError) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/knock/knock/neo", [dispatcher](const RestRequest &request) -> RestResponse { return {301, "Moved Permanently", "{\"not_here\": true}"}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/knock/knock/neo") .json() .onComplete(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Try<HttpRequest::JsonResult>& result) { EXPECT_TRUE(result.isFailure()); auto& json = *std::get<1>(*result.getFailure().getTypeUserData<HttpRequest::JsonResult>().getValue()); EXPECT_TRUE(json.HasMember("not_here")); EXPECT_TRUE(json["not_here"].IsBool()); EXPECT_EQ(true, json["not_here"].GetBool()); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, POST) { auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->POST("/next/century/postal/service", [dispatcher](const RestRequest &request) -> RestResponse { std::string result(request.message->body.p, request.message->body.len); return {200, "OK", result}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { std::vector<uint8_t> body((uint8_t *)BIG_TEXT.c_str(), (uint8_t *)(BIG_TEXT.c_str() + BIG_TEXT.size())); http.POST("/next/century/postal/service", body)().foreach(dispatcher->getMainExecutionContext(), [dispatcher, &server] (const std::shared_ptr<api::HttpUrlConnection> connection) { auto body = connection->readBody(); auto res = std::string((char *)(body.data->data()), body.data->size()); EXPECT_EQ(200, connection->getStatusCode()); EXPECT_EQ(BIG_TEXT, res); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000) } } TEST(HttpClient, GETWithSax) { struct Success { int the_answer; }; struct Failure { int code; bool not_here; }; struct Handler : public HttpJsonHandler<std::shared_ptr<Success>, Failure, Handler> { Handler() {}; bool Bool(bool b) { return true; }; bool RawNumber(const Ch *str, rapidjson::SizeType len, bool copy) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = boost::lexical_cast<int>(std::string(str, len)); return true; } bool Key(const Ch *str, rapidjson::SizeType len, bool copy) { _currentKey = std::string(str, len); if (getStatusCode() >= 200 && getStatusCode() < 300) { _result = std::make_shared<Success>(); } else { _result = Failure(); } return true; } Either<Failure, std::shared_ptr<Success>> build() { return _result; } private: std::string _currentKey; Either<Failure, std::shared_ptr<Success>> _result; }; auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/talk/to/me/in/json", [dispatcher](const RestRequest &request) -> RestResponse { return {200, "OK", "{\"the_answer\": 42}"}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/talk/to/me/in/json") .json<Success, Failure>(Handler()) .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Either<Failure, std::shared_ptr<Success>>& result) { EXPECT_TRUE(result.isRight()); EXPECT_EQ(result.getRight()->the_answer, 42); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } TEST(HttpClient, GETWithSaxError) { struct Success { int the_answer; }; struct Failure { int code; bool not_here; }; struct Handler : public HttpJsonHandler<std::shared_ptr<Success>, Failure, Handler> { Handler() {}; bool Bool(bool b) { if (_currentKey == std::string("not_here")) _result.getLeft().not_here = b; return true; }; bool Uint(unsigned int i) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = i; return true; } bool Int(int i) { if (_currentKey == std::string("the_answer")) _result.getRight()->the_answer = i; return true; } bool Key(const Ch *str, rapidjson::SizeType len, bool copy) { _currentKey = std::string(str, len); if (getStatusCode() >= 200 && getStatusCode() < 300) { _result = std::make_shared<Success>(); } else { _result = Failure(); } return true; } Either<Failure, std::shared_ptr<Success>> build() { return _result; } private: std::string _currentKey; Either<Failure, std::shared_ptr<Success>> _result; }; auto dispatcher = std::make_shared<NativeThreadDispatcher>(); auto client = std::make_shared<MongooseHttpClient>(dispatcher->getSerialExecutionContext("client")); auto worker = dispatcher->getSerialExecutionContext("worker"); ledger::core::HttpClient http("http://127.0.0.1:8000", client, worker, nullptr); { auto server = std::make_shared<MongooseSimpleRestServer>(dispatcher->getSerialExecutionContext("server")); server->GET("/knock/knock/neo", [dispatcher](const RestRequest &request) -> RestResponse { return {301, "Moved Permanently", "{\"not_here\": true}"}; }); server->start(8000); std::this_thread::sleep_for(std::chrono::milliseconds(200)); worker->execute(::make_runnable([&http, dispatcher, &server] () { http .GET("/knock/knock/neo") .json<Success, Failure>(Handler()) .foreach(dispatcher->getMainExecutionContext(), [&server, dispatcher] (const Either<Failure, std::shared_ptr<Success>>& result) { EXPECT_TRUE(result.isLeft()); EXPECT_EQ(result.getLeft().not_here, true); server->stop(); dispatcher->getMainExecutionContext()->delay(::make_runnable([dispatcher]() { dispatcher->stop(); }), 0); }); })); WAIT_AND_TIMEOUT(dispatcher, 10000); } } <|endoftext|>
<commit_before>/* Copyright (C) 2016-2017 Alexey Dynda This file is part of SSD1306 library. 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/>. */ #include "nano_gfx.h" #include "ssd1306.h" extern const uint8_t *s_font6x8; #define YADDR(y) (((y) >> 3) << m_p) #define BADDR(b) ((b) << m_p) void NanoCanvas::putPixel(uint8_t x, uint8_t y) { if ((x>=m_w) || (y>=m_h)) return; if (m_inverseByte) { m_bytes[YADDR(y) + x] &= ((1 << (y & 0x7))^m_inverseByte); } else { m_bytes[YADDR(y) + x] |= (1 << (y & 0x7)); } }; void NanoCanvas::drawHLine(uint8_t x1, uint8_t y1, uint8_t x2) { if (y1 >= m_h) return; if (x2 < x1) x1 = 0; if (x1 >= m_w) return; if (x2 >= m_w) x2 = m_w - 1; for(uint8_t x = x1; x<=x2; x++) m_bytes[YADDR(y1) + x] |= (1 << (y1 & 0x7)); }; void NanoCanvas::drawVLine(uint8_t x1, uint8_t y1, uint8_t y2) { if (x1 >= m_w) return; if (y2 < y1) y1 = 0; if (y1 >= m_h) return; if (y2 >= m_h) y2 = m_h - 1; for(uint8_t y = y1; y<=y2; y++) m_bytes[YADDR(y) + x1] |= (1 << (y & 0x7)); }; void NanoCanvas::drawRect(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2) { drawHLine(x1, y1, x2); drawHLine(x1, y2, x2); drawVLine(x1, y1, y2); drawVLine(x2, y1, y2); }; void NanoCanvas::fillRect(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, uint8_t templ) { templ ^= m_inverseByte; if ((x1 < x2) && (x1 >= m_w)) return; if ((y1 < y2) && (y1 >= m_h)) return; if (x1 > x2) x1 = 0; if (y1 > y2) y1 = 0; if (x2 >= m_w) x2 = m_w -1; if (y2 >= m_h) y2 = m_h -1; uint8_t bank1 = (y1 >> 3); uint8_t bank2 = (y2 >> 3); for (uint8_t bank = bank1; bank2<=(y2 >> 3); bank++) { uint8_t mask = 0xFF; if (bank1 == bank2) { mask = (mask >> ((y1 & 7) + 7 - (y2 & 7))) << (7 - (y2 & 7)); } else if (bank1 == bank) { mask = (mask >> (y1 & 7)); } else if (bank2 == bank) { mask = (mask << (7 - (y2 & 7))); } for (uint8_t x=x1; x<x2; x++) { m_bytes[BADDR(bank) + x] &= ~mask; m_bytes[BADDR(bank) + x] |= (templ & mask); } } }; void NanoCanvas::clear() { for(uint16_t i=0; i<m_w* (m_h >> 3); i++) { m_bytes[i] = m_inverseByte; } } void NanoCanvas::charF6x8(uint8_t x, uint8_t y, const char ch[], EFontStyle style) { uint8_t i, j; if (y>=m_h) return; j = 0; while(ch[j] != '\0') { uint8_t c = ch[j] - 32; uint8_t ldata = 0; for(i=0;i<6;i++) { if (x>=m_w) return; uint8_t data; if ( style == STYLE_NORMAL ) { data = pgm_read_byte(&s_font6x8[c*6+i]); } else if ( style == STYLE_BOLD ) { data = pgm_read_byte(&s_font6x8[c*6+i]); uint8_t temp = data | ldata; ldata = data; data = temp; } else { data = pgm_read_byte(&s_font6x8[c*6+i + 1]); uint8_t temp = (data & 0xF0) | ldata; ldata = (data & 0x0F); data = temp; } m_bytes[YADDR(y) + x] |= (data << (y & 0x7)); if (y+8 < m_h) m_bytes[YADDR(y) + m_w + x] |= (data >> (8 - (y & 0x7))); x++; } j++; } } void NanoCanvas::drawSpritePgm(uint8_t x, uint8_t y, const uint8_t sprite[]) { uint8_t i; for(i=0;i<8;i++) { if (x >= m_w) { x++; continue; } uint8_t d = pgm_read_byte(&sprite[i]); if (y < m_h) m_bytes[YADDR(y) + x] |= (d << (y & 0x7)); if ((uint8_t)(y + 8) < m_h) m_bytes[YADDR((uint8_t)(y + 8)) + x] |= (d >> (8 - (y & 0x7))); x++; } }; void NanoCanvas::drawSprite(uint8_t x, uint8_t y, const uint8_t sprite[]) { uint8_t i; for(i=0;i<8;i++) { if (x>=m_w) { x++; continue; } uint8_t d = sprite[i]; if (uint8_t(y) < m_h) m_bytes[YADDR(y) + x] |= (d << (y & 0x7)); if ((uint8_t)(y+8) < m_h) m_bytes[YADDR((uint8_t)(y + 8)) + x] |= (d >> (8 - (y & 0x7))); x++; } }; void NanoCanvas::drawSprite(SPRITE *sprite) { uint8_t i; for(i = 0; i < sprite->w; i++) { if ((sprite->x + i) >= m_w) { continue; } uint8_t d = pgm_read_byte(&sprite->data[i]); if (sprite->y < m_h) m_bytes[YADDR(sprite->y) + sprite->x + i] |= (d << (sprite->y & 0x7)); if (uint8_t(sprite->y + 8) < m_h) m_bytes[YADDR(uint8_t(sprite->y + 8)) + sprite->x + i] |= (d >> (8 - (sprite->y & 0x7))); } } void NanoCanvas::blt(uint8_t x, uint8_t y) { ssd1306_drawBuffer(x, y, m_w, m_h, m_bytes); } void NanoCanvas::invert() { for(uint16_t i=0; i<m_w* (m_h >> 3); i++) m_bytes[i] = ~m_bytes[i]; } void NanoCanvas::flipH() { for (uint8_t y=0; y<(m_h>>3); y++) for (uint8_t x=0; x<m_w>>1; x++) { uint8_t temp = m_bytes[YADDR(y) + x]; m_bytes[YADDR(y) + x] = m_bytes[YADDR(y) + m_w - x -1]; m_bytes[YADDR(y) + m_w - x -1] = temp; } } <commit_msg>Text overwriting #7 fix<commit_after>/* Copyright (C) 2016-2017 Alexey Dynda This file is part of SSD1306 library. 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/>. */ #include "nano_gfx.h" #include "ssd1306.h" extern const uint8_t *s_font6x8; #define YADDR(y) (((y) >> 3) << m_p) #define BADDR(b) ((b) << m_p) void NanoCanvas::putPixel(uint8_t x, uint8_t y) { if ((x>=m_w) || (y>=m_h)) return; if (m_inverseByte) { m_bytes[YADDR(y) + x] &= ((1 << (y & 0x7))^m_inverseByte); } else { m_bytes[YADDR(y) + x] |= (1 << (y & 0x7)); } }; void NanoCanvas::drawHLine(uint8_t x1, uint8_t y1, uint8_t x2) { if (y1 >= m_h) return; if (x2 < x1) x1 = 0; if (x1 >= m_w) return; if (x2 >= m_w) x2 = m_w - 1; for(uint8_t x = x1; x<=x2; x++) m_bytes[YADDR(y1) + x] |= (1 << (y1 & 0x7)); }; void NanoCanvas::drawVLine(uint8_t x1, uint8_t y1, uint8_t y2) { if (x1 >= m_w) return; if (y2 < y1) y1 = 0; if (y1 >= m_h) return; if (y2 >= m_h) y2 = m_h - 1; for(uint8_t y = y1; y<=y2; y++) m_bytes[YADDR(y) + x1] |= (1 << (y & 0x7)); }; void NanoCanvas::drawRect(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2) { drawHLine(x1, y1, x2); drawHLine(x1, y2, x2); drawVLine(x1, y1, y2); drawVLine(x2, y1, y2); }; void NanoCanvas::fillRect(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, uint8_t templ) { templ ^= m_inverseByte; if ((x1 < x2) && (x1 >= m_w)) return; if ((y1 < y2) && (y1 >= m_h)) return; if (x1 > x2) x1 = 0; if (y1 > y2) y1 = 0; if (x2 >= m_w) x2 = m_w -1; if (y2 >= m_h) y2 = m_h -1; uint8_t bank1 = (y1 >> 3); uint8_t bank2 = (y2 >> 3); for (uint8_t bank = bank1; bank2<=(y2 >> 3); bank++) { uint8_t mask = 0xFF; if (bank1 == bank2) { mask = (mask >> ((y1 & 7) + 7 - (y2 & 7))) << (7 - (y2 & 7)); } else if (bank1 == bank) { mask = (mask >> (y1 & 7)); } else if (bank2 == bank) { mask = (mask << (7 - (y2 & 7))); } for (uint8_t x=x1; x<x2; x++) { m_bytes[BADDR(bank) + x] &= ~mask; m_bytes[BADDR(bank) + x] |= (templ & mask); } } }; void NanoCanvas::clear() { for(uint16_t i=0; i<m_w* (m_h >> 3); i++) { m_bytes[i] = m_inverseByte; } } void NanoCanvas::charF6x8(uint8_t x, uint8_t y, const char ch[], EFontStyle style) { uint8_t i, j, topMask, bottomMask; if (y>=m_h) return; j = 0; topMask = (0xFF >> (8 - (y & 0x7))); bottomMask = (0xFF << (y & 0x7)); while(ch[j] != '\0') { uint8_t c = ch[j] - 32; uint8_t ldata = 0; for(i=0;i<6;i++) { if (x>=m_w) return; uint8_t data; if ( style == STYLE_NORMAL ) { data = pgm_read_byte(&s_font6x8[c*6+i]); } else if ( style == STYLE_BOLD ) { data = pgm_read_byte(&s_font6x8[c*6+i]); uint8_t temp = data | ldata; ldata = data; data = temp; } else { data = pgm_read_byte(&s_font6x8[c*6+i + 1]); uint8_t temp = (data & 0xF0) | ldata; ldata = (data & 0x0F); data = temp; } m_bytes[YADDR(y) + x] &= topMask; m_bytes[YADDR(y) + x] |= (data << (y & 0x7)); if (y+8 < m_h) { m_bytes[YADDR(y) + m_w + x] &= bottomMask; m_bytes[YADDR(y) + m_w + x] |= (data >> (8 - (y & 0x7))); } x++; } j++; } } void NanoCanvas::drawSpritePgm(uint8_t x, uint8_t y, const uint8_t sprite[]) { uint8_t i; for(i=0;i<8;i++) { if (x >= m_w) { x++; continue; } uint8_t d = pgm_read_byte(&sprite[i]); if (y < m_h) m_bytes[YADDR(y) + x] |= (d << (y & 0x7)); if ((uint8_t)(y + 8) < m_h) m_bytes[YADDR((uint8_t)(y + 8)) + x] |= (d >> (8 - (y & 0x7))); x++; } }; void NanoCanvas::drawSprite(uint8_t x, uint8_t y, const uint8_t sprite[]) { uint8_t i; for(i=0;i<8;i++) { if (x>=m_w) { x++; continue; } uint8_t d = sprite[i]; if (uint8_t(y) < m_h) m_bytes[YADDR(y) + x] |= (d << (y & 0x7)); if ((uint8_t)(y+8) < m_h) m_bytes[YADDR((uint8_t)(y + 8)) + x] |= (d >> (8 - (y & 0x7))); x++; } }; void NanoCanvas::drawSprite(SPRITE *sprite) { uint8_t i; for(i = 0; i < sprite->w; i++) { if ((sprite->x + i) >= m_w) { continue; } uint8_t d = pgm_read_byte(&sprite->data[i]); if (sprite->y < m_h) m_bytes[YADDR(sprite->y) + sprite->x + i] |= (d << (sprite->y & 0x7)); if (uint8_t(sprite->y + 8) < m_h) m_bytes[YADDR(uint8_t(sprite->y + 8)) + sprite->x + i] |= (d >> (8 - (sprite->y & 0x7))); } } void NanoCanvas::blt(uint8_t x, uint8_t y) { ssd1306_drawBuffer(x, y, m_w, m_h, m_bytes); } void NanoCanvas::invert() { for(uint16_t i=0; i<m_w* (m_h >> 3); i++) m_bytes[i] = ~m_bytes[i]; } void NanoCanvas::flipH() { for (uint8_t y=0; y<(m_h>>3); y++) for (uint8_t x=0; x<m_w>>1; x++) { uint8_t temp = m_bytes[YADDR(y) + x]; m_bytes[YADDR(y) + x] = m_bytes[YADDR(y) + m_w - x -1]; m_bytes[YADDR(y) + m_w - x -1] = temp; } } <|endoftext|>
<commit_before>/** * @file decision_stump_impl.hpp * @author Udit Saxena * * Implementation of DecisionStump class. */ #ifndef __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP #define __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP // In case it hasn't been included yet. #include "decision_stump.hpp" namespace mlpack { namespace decision_stump { /** * Constructor. Train on the provided data. Generate a decision stump from data. * * @param data Input, training data. * @param labels Labels of data. * @param classes Number of distinct classes in labels. * @param bucketSize Minimum size of bucket when splitting. */ template<typename MatType> DecisionStump<MatType>::DecisionStump(const MatType& data, const arma::Row<size_t>& labels, const size_t classes, const size_t bucketSize) : classes(classes), bucketSize(bucketSize) { arma::rowvec weights; Train<false>(data, labels, weights); } /** * Empty constructor. */ template<typename MatType> DecisionStump<MatType>::DecisionStump() : classes(1), bucketSize(0), splitDimension(0), split(1), binLabels(1) { split[0] = DBL_MAX; binLabels[0] = 0; } /** * Train on the given data and labels. */ template<typename MatType> void DecisionStump<MatType>::Train(const MatType& data, const arma::Row<size_t>& labels, const size_t classes, const size_t bucketSize) { this->classes = classes; this->bucketSize = bucketSize; // Pass to unweighted training function. arma::rowvec weights; Train<false>(data, labels, weights); } /** * Train the decision stump on the given data and labels. * * @param data Dataset to train on. * @param labels Labels for dataset. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights> void DecisionStump<MatType>::Train(const MatType& data, const arma::Row<size_t>& labels, const arma::rowvec& weights) { this->classes = classes; this->bucketSize = bucketSize; // If classLabels are not all identical, proceed with training. size_t bestDim = 0; double entropy; const double rootEntropy = CalculateEntropy<UseWeights>(labels, weights); double gain, bestGain = 0.0; for (size_t i = 0; i < data.n_rows; i++) { // Go through each dimension of the data. if (IsDistinct(data.row(i))) { // For each dimension with non-identical values, treat it as a potential // splitting dimension and calculate entropy if split on it. entropy = SetupSplitDimension<UseWeights>(data.row(i), labels, weights); gain = rootEntropy - entropy; // Find the dimension with the best entropy so that the gain is // maximized. // We are maximizing gain, which is what is returned from // SetupSplitDimension(). if (gain < bestGain) { bestDim = i; bestGain = gain; } } } splitDimension = bestDim; // Once the splitting column/dimension has been decided, train on it. TrainOnDim(data.row(splitDimension), labels); } /** * Classification function. After training, classify test, and put the predicted * classes in predictedLabels. * * @param test Testing data or data to classify. * @param predictedLabels Vector to store the predicted classes after * classifying test */ template<typename MatType> void DecisionStump<MatType>::Classify(const MatType& test, arma::Row<size_t>& predictedLabels) { predictedLabels.set_size(test.n_cols); for (size_t i = 0; i < test.n_cols; i++) { // Determine which bin the test point falls into. // Assume first that it falls into the first bin, then proceed through the // bins until it is known which bin it falls into. size_t bin = 0; const double val = test(splitDimension, i); while (bin < split.n_elem - 1) { if (val < split(bin + 1)) break; ++bin; } predictedLabels(i) = binLabels(bin); } } /** * Alternate constructor which copies parameters bucketSize and numClasses * from an already initiated decision stump, other. It appropriately * sets the Weight vector. * * @param other The other initiated Decision Stump object from * which we copy the values from. * @param data The data on which to train this object on. * @param D Weight vector to use while training. For boosting purposes. * @param labels The labels of data. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> DecisionStump<MatType>::DecisionStump(const DecisionStump<>& other, const MatType& data, const arma::Row<size_t>& labels, const arma::rowvec& weights) : classes(other.classes), bucketSize(other.bucketSize) { Train<true>(data, labels, weights); } /** * Serialize the decision stump. */ template<typename MatType> template<typename Archive> void DecisionStump<MatType>::Serialize(Archive& ar, const unsigned int /* version */) { using data::CreateNVP; // This is straightforward; just serialize all of the members of the class. // None need special handling. ar & CreateNVP(classes, "classes"); ar & CreateNVP(bucketSize, "bucketSize"); ar & CreateNVP(splitDimension, "splitDimension"); ar & CreateNVP(split, "split"); ar & CreateNVP(binLabels, "binLabels"); } /** * Sets up dimension as if it were splitting on it and finds entropy when * splitting on dimension. * * @param dimension A row from the training data, which might be a candidate for * the splitting dimension. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights> double DecisionStump<MatType>::SetupSplitDimension( const arma::rowvec& dimension, const arma::Row<size_t>& labels, const arma::rowvec& weights) { size_t i, count, begin, end; double entropy = 0.0; // Sort the dimension in order to calculate splitting ranges. arma::rowvec sortedDim = arma::sort(dimension); // Store the indices of the sorted dimension to build a vector of sorted // labels. This sort is stable. arma::uvec sortedIndexDim = arma::stable_sort_index(dimension.t()); arma::Row<size_t> sortedLabels(dimension.n_elem); arma::rowvec sortedWeights(dimension.n_elem); for (i = 0; i < dimension.n_elem; i++) { sortedLabels(i) = labels(sortedIndexDim(i)); // Apply weights if necessary. if (UseWeights) sortedWeights(i) = weights(sortedIndexDim(i)); } i = 0; count = 0; // This splits the sorted data into buckets of size greater than or equal to // bucketSize. while (i < sortedLabels.n_elem) { count++; if (i == sortedLabels.n_elem - 1) { // If we're at the end, then don't worry about the bucket size; just take // this as the last bin. begin = i - count + 1; end = i; // Use ratioEl to calculate the ratio of elements in this split. const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); entropy += ratioEl * CalculateEntropy<UseWeights>( sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); i++; } else if (sortedLabels(i) != sortedLabels(i + 1)) { // If we're not at the last element of sortedLabels, then check whether // count is less than the current bucket size. if (count < bucketSize) { // If it is, then take the minimum bucket size anyways. // This is where the inpBucketSize comes into use. // This makes sure there isn't a bucket for every change in labels. begin = i - count + 1; end = begin + bucketSize - 1; if (end > sortedLabels.n_elem - 1) end = sortedLabels.n_elem - 1; } else { // If it is not, then take the bucket size as the value of count. begin = i - count + 1; end = i; } const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); entropy += ratioEl * CalculateEntropy<UseWeights>( sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); i = end + 1; count = 0; } else i++; } return entropy; } /** * After having decided the dimension on which to split, train on that * dimension. * * @param dimension Dimension is the dimension decided by the constructor on * which we now train the decision stump. */ template<typename MatType> template<typename VecType> void DecisionStump<MatType>::TrainOnDim(const VecType& dimension, const arma::Row<size_t>& labels) { size_t i, count, begin, end; arma::rowvec sortedSplitDim = arma::sort(dimension); arma::uvec sortedSplitIndexDim = arma::stable_sort_index(dimension.t()); arma::Row<size_t> sortedLabels(dimension.n_elem); sortedLabels.fill(0); for (i = 0; i < dimension.n_elem; i++) sortedLabels(i) = labels(sortedSplitIndexDim(i)); arma::rowvec subCols; double mostFreq; i = 0; count = 0; while (i < sortedLabels.n_elem) { count++; if (i == sortedLabels.n_elem - 1) { begin = i - count + 1; end = i; mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); split.resize(split.n_elem + 1); split(split.n_elem - 1) = sortedSplitDim(begin); binLabels.resize(binLabels.n_elem + 1); binLabels(binLabels.n_elem - 1) = mostFreq; i++; } else if (sortedLabels(i) != sortedLabels(i + 1)) { if (count < bucketSize) { // Test for different values of bucketSize, especially extreme cases. begin = i - count + 1; end = begin + bucketSize - 1; if (end > sortedLabels.n_elem - 1) end = sortedLabels.n_elem - 1; } else { begin = i - count + 1; end = i; } // Find the most frequent element in subCols so as to assign a label to // the bucket of subCols. mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); split.resize(split.n_elem + 1); split(split.n_elem - 1) = sortedSplitDim(begin); binLabels.resize(binLabels.n_elem + 1); binLabels(binLabels.n_elem - 1) = mostFreq; i = end + 1; count = 0; } else i++; } // Now trim the split matrix so that buckets one after the after which point // to the same classLabel are merged as one big bucket. MergeRanges(); } /** * After the "split" matrix has been set up, merge ranges with identical class * labels. */ template<typename MatType> void DecisionStump<MatType>::MergeRanges() { for (size_t i = 1; i < split.n_rows; i++) { if (binLabels(i) == binLabels(i - 1)) { // Remove this row, as it has the same label as the previous bucket. binLabels.shed_row(i); split.shed_row(i); // Go back to previous row. i--; } } } template<typename MatType> template<typename VecType> double DecisionStump<MatType>::CountMostFreq(const VecType& subCols) { // We'll create a map of elements and the number of times that each element is // seen. std::map<double, size_t> countMap; for (size_t i = 0; i < subCols.n_elem; ++i) { if (countMap.count(subCols[i]) == 0) countMap[subCols[i]] = 1; else ++countMap[subCols[i]]; } // Now find the maximum value. typename std::map<double, size_t>::iterator it = countMap.begin(); double mostFreq = it->first; size_t mostFreqCount = it->second; while (it != countMap.end()) { if (it->second >= mostFreqCount) { mostFreq = it->first; mostFreqCount = it->second; } ++it; } return mostFreq; } /** * Returns 1 if all the values of featureRow are not the same. * * @param featureRow The dimension which is checked for identical values. */ template<typename MatType> template<typename VecType> int DecisionStump<MatType>::IsDistinct(const VecType& featureRow) { typename VecType::elem_type val = featureRow(0); for (size_t i = 1; i < featureRow.n_elem; ++i) if (val != featureRow(i)) return 1; return 0; } /** * Calculate entropy of dimension. * * @param labels Corresponding labels of the dimension. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights, typename VecType, typename WeightVecType> double DecisionStump<MatType>::CalculateEntropy( const VecType& labels, const WeightVecType& weights) { double entropy = 0.0; size_t j; arma::Row<size_t> numElem(classes); numElem.fill(0); // Variable to accumulate the weight in this subview_row. double accWeight = 0.0; // Populate numElem; they are used as helpers to calculate entropy. if (UseWeights) { for (j = 0; j < labels.n_elem; j++) { numElem(labels(j)) += weights(j); accWeight += weights(j); } for (j = 0; j < classes; j++) { const double p1 = ((double) numElem(j) / accWeight); // Instead of using log2(), which is C99 and may not exist on some // compilers, use std::log(), then use the change-of-base formula to make // the result correct. entropy += (p1 == 0) ? 0 : p1 * std::log(p1); } } else { for (j = 0; j < labels.n_elem; j++) numElem(labels(j))++; for (j = 0; j < classes; j++) { const double p1 = ((double) numElem(j) / labels.n_elem); // Instead of using log2(), which is C99 and may not exist on some // compilers, use std::log(), then use the change-of-base formula to make // the result correct. entropy += (p1 == 0) ? 0 : p1 * std::log(p1); } } return entropy / std::log(2.0); } } // namespace decision_stump } // namespace mlpack #endif <commit_msg>Use double, not size_t.<commit_after>/** * @file decision_stump_impl.hpp * @author Udit Saxena * * Implementation of DecisionStump class. */ #ifndef __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP #define __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP // In case it hasn't been included yet. #include "decision_stump.hpp" namespace mlpack { namespace decision_stump { /** * Constructor. Train on the provided data. Generate a decision stump from data. * * @param data Input, training data. * @param labels Labels of data. * @param classes Number of distinct classes in labels. * @param bucketSize Minimum size of bucket when splitting. */ template<typename MatType> DecisionStump<MatType>::DecisionStump(const MatType& data, const arma::Row<size_t>& labels, const size_t classes, const size_t bucketSize) : classes(classes), bucketSize(bucketSize) { arma::rowvec weights; Train<false>(data, labels, weights); } /** * Empty constructor. */ template<typename MatType> DecisionStump<MatType>::DecisionStump() : classes(1), bucketSize(0), splitDimension(0), split(1), binLabels(1) { split[0] = DBL_MAX; binLabels[0] = 0; } /** * Train on the given data and labels. */ template<typename MatType> void DecisionStump<MatType>::Train(const MatType& data, const arma::Row<size_t>& labels, const size_t classes, const size_t bucketSize) { this->classes = classes; this->bucketSize = bucketSize; // Pass to unweighted training function. arma::rowvec weights; Train<false>(data, labels, weights); } /** * Train the decision stump on the given data and labels. * * @param data Dataset to train on. * @param labels Labels for dataset. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights> void DecisionStump<MatType>::Train(const MatType& data, const arma::Row<size_t>& labels, const arma::rowvec& weights) { this->classes = classes; this->bucketSize = bucketSize; // If classLabels are not all identical, proceed with training. size_t bestDim = 0; double entropy; const double rootEntropy = CalculateEntropy<UseWeights>(labels, weights); double gain, bestGain = 0.0; for (size_t i = 0; i < data.n_rows; i++) { // Go through each dimension of the data. if (IsDistinct(data.row(i))) { // For each dimension with non-identical values, treat it as a potential // splitting dimension and calculate entropy if split on it. entropy = SetupSplitDimension<UseWeights>(data.row(i), labels, weights); gain = rootEntropy - entropy; // Find the dimension with the best entropy so that the gain is // maximized. // We are maximizing gain, which is what is returned from // SetupSplitDimension(). if (gain < bestGain) { bestDim = i; bestGain = gain; } } } splitDimension = bestDim; // Once the splitting column/dimension has been decided, train on it. TrainOnDim(data.row(splitDimension), labels); } /** * Classification function. After training, classify test, and put the predicted * classes in predictedLabels. * * @param test Testing data or data to classify. * @param predictedLabels Vector to store the predicted classes after * classifying test */ template<typename MatType> void DecisionStump<MatType>::Classify(const MatType& test, arma::Row<size_t>& predictedLabels) { predictedLabels.set_size(test.n_cols); for (size_t i = 0; i < test.n_cols; i++) { // Determine which bin the test point falls into. // Assume first that it falls into the first bin, then proceed through the // bins until it is known which bin it falls into. size_t bin = 0; const double val = test(splitDimension, i); while (bin < split.n_elem - 1) { if (val < split(bin + 1)) break; ++bin; } predictedLabels(i) = binLabels(bin); } } /** * Alternate constructor which copies parameters bucketSize and numClasses * from an already initiated decision stump, other. It appropriately * sets the Weight vector. * * @param other The other initiated Decision Stump object from * which we copy the values from. * @param data The data on which to train this object on. * @param D Weight vector to use while training. For boosting purposes. * @param labels The labels of data. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> DecisionStump<MatType>::DecisionStump(const DecisionStump<>& other, const MatType& data, const arma::Row<size_t>& labels, const arma::rowvec& weights) : classes(other.classes), bucketSize(other.bucketSize) { Train<true>(data, labels, weights); } /** * Serialize the decision stump. */ template<typename MatType> template<typename Archive> void DecisionStump<MatType>::Serialize(Archive& ar, const unsigned int /* version */) { using data::CreateNVP; // This is straightforward; just serialize all of the members of the class. // None need special handling. ar & CreateNVP(classes, "classes"); ar & CreateNVP(bucketSize, "bucketSize"); ar & CreateNVP(splitDimension, "splitDimension"); ar & CreateNVP(split, "split"); ar & CreateNVP(binLabels, "binLabels"); } /** * Sets up dimension as if it were splitting on it and finds entropy when * splitting on dimension. * * @param dimension A row from the training data, which might be a candidate for * the splitting dimension. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights> double DecisionStump<MatType>::SetupSplitDimension( const arma::rowvec& dimension, const arma::Row<size_t>& labels, const arma::rowvec& weights) { size_t i, count, begin, end; double entropy = 0.0; // Sort the dimension in order to calculate splitting ranges. arma::rowvec sortedDim = arma::sort(dimension); // Store the indices of the sorted dimension to build a vector of sorted // labels. This sort is stable. arma::uvec sortedIndexDim = arma::stable_sort_index(dimension.t()); arma::Row<size_t> sortedLabels(dimension.n_elem); arma::rowvec sortedWeights(dimension.n_elem); for (i = 0; i < dimension.n_elem; i++) { sortedLabels(i) = labels(sortedIndexDim(i)); // Apply weights if necessary. if (UseWeights) sortedWeights(i) = weights(sortedIndexDim(i)); } i = 0; count = 0; // This splits the sorted data into buckets of size greater than or equal to // bucketSize. while (i < sortedLabels.n_elem) { count++; if (i == sortedLabels.n_elem - 1) { // If we're at the end, then don't worry about the bucket size; just take // this as the last bin. begin = i - count + 1; end = i; // Use ratioEl to calculate the ratio of elements in this split. const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); entropy += ratioEl * CalculateEntropy<UseWeights>( sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); i++; } else if (sortedLabels(i) != sortedLabels(i + 1)) { // If we're not at the last element of sortedLabels, then check whether // count is less than the current bucket size. if (count < bucketSize) { // If it is, then take the minimum bucket size anyways. // This is where the inpBucketSize comes into use. // This makes sure there isn't a bucket for every change in labels. begin = i - count + 1; end = begin + bucketSize - 1; if (end > sortedLabels.n_elem - 1) end = sortedLabels.n_elem - 1; } else { // If it is not, then take the bucket size as the value of count. begin = i - count + 1; end = i; } const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); entropy += ratioEl * CalculateEntropy<UseWeights>( sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); i = end + 1; count = 0; } else i++; } return entropy; } /** * After having decided the dimension on which to split, train on that * dimension. * * @param dimension Dimension is the dimension decided by the constructor on * which we now train the decision stump. */ template<typename MatType> template<typename VecType> void DecisionStump<MatType>::TrainOnDim(const VecType& dimension, const arma::Row<size_t>& labels) { size_t i, count, begin, end; arma::rowvec sortedSplitDim = arma::sort(dimension); arma::uvec sortedSplitIndexDim = arma::stable_sort_index(dimension.t()); arma::Row<size_t> sortedLabels(dimension.n_elem); sortedLabels.fill(0); for (i = 0; i < dimension.n_elem; i++) sortedLabels(i) = labels(sortedSplitIndexDim(i)); arma::rowvec subCols; double mostFreq; i = 0; count = 0; while (i < sortedLabels.n_elem) { count++; if (i == sortedLabels.n_elem - 1) { begin = i - count + 1; end = i; mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); split.resize(split.n_elem + 1); split(split.n_elem - 1) = sortedSplitDim(begin); binLabels.resize(binLabels.n_elem + 1); binLabels(binLabels.n_elem - 1) = mostFreq; i++; } else if (sortedLabels(i) != sortedLabels(i + 1)) { if (count < bucketSize) { // Test for different values of bucketSize, especially extreme cases. begin = i - count + 1; end = begin + bucketSize - 1; if (end > sortedLabels.n_elem - 1) end = sortedLabels.n_elem - 1; } else { begin = i - count + 1; end = i; } // Find the most frequent element in subCols so as to assign a label to // the bucket of subCols. mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); split.resize(split.n_elem + 1); split(split.n_elem - 1) = sortedSplitDim(begin); binLabels.resize(binLabels.n_elem + 1); binLabels(binLabels.n_elem - 1) = mostFreq; i = end + 1; count = 0; } else i++; } // Now trim the split matrix so that buckets one after the after which point // to the same classLabel are merged as one big bucket. MergeRanges(); } /** * After the "split" matrix has been set up, merge ranges with identical class * labels. */ template<typename MatType> void DecisionStump<MatType>::MergeRanges() { for (size_t i = 1; i < split.n_rows; i++) { if (binLabels(i) == binLabels(i - 1)) { // Remove this row, as it has the same label as the previous bucket. binLabels.shed_row(i); split.shed_row(i); // Go back to previous row. i--; } } } template<typename MatType> template<typename VecType> double DecisionStump<MatType>::CountMostFreq(const VecType& subCols) { // We'll create a map of elements and the number of times that each element is // seen. std::map<double, size_t> countMap; for (size_t i = 0; i < subCols.n_elem; ++i) { if (countMap.count(subCols[i]) == 0) countMap[subCols[i]] = 1; else ++countMap[subCols[i]]; } // Now find the maximum value. typename std::map<double, size_t>::iterator it = countMap.begin(); double mostFreq = it->first; size_t mostFreqCount = it->second; while (it != countMap.end()) { if (it->second >= mostFreqCount) { mostFreq = it->first; mostFreqCount = it->second; } ++it; } return mostFreq; } /** * Returns 1 if all the values of featureRow are not the same. * * @param featureRow The dimension which is checked for identical values. */ template<typename MatType> template<typename VecType> int DecisionStump<MatType>::IsDistinct(const VecType& featureRow) { typename VecType::elem_type val = featureRow(0); for (size_t i = 1; i < featureRow.n_elem; ++i) if (val != featureRow(i)) return 1; return 0; } /** * Calculate entropy of dimension. * * @param labels Corresponding labels of the dimension. * @param UseWeights Whether we need to run a weighted Decision Stump. */ template<typename MatType> template<bool UseWeights, typename VecType, typename WeightVecType> double DecisionStump<MatType>::CalculateEntropy( const VecType& labels, const WeightVecType& weights) { double entropy = 0.0; size_t j; arma::rowvec numElem(classes); numElem.fill(0); // Variable to accumulate the weight in this subview_row. double accWeight = 0.0; // Populate numElem; they are used as helpers to calculate entropy. if (UseWeights) { for (j = 0; j < labels.n_elem; j++) { numElem(labels(j)) += weights(j); accWeight += weights(j); } for (j = 0; j < classes; j++) { const double p1 = ((double) numElem(j) / accWeight); // Instead of using log2(), which is C99 and may not exist on some // compilers, use std::log(), then use the change-of-base formula to make // the result correct. entropy += (p1 == 0) ? 0 : p1 * std::log(p1); } } else { for (j = 0; j < labels.n_elem; j++) numElem(labels(j))++; for (j = 0; j < classes; j++) { const double p1 = ((double) numElem(j) / labels.n_elem); // Instead of using log2(), which is C99 and may not exist on some // compilers, use std::log(), then use the change-of-base formula to make // the result correct. entropy += (p1 == 0) ? 0 : p1 * std::log(p1); } } return entropy / std::log(2.0); } } // namespace decision_stump } // namespace mlpack #endif <|endoftext|>
<commit_before>#ifndef ORM_DATETIMEFIELD_HPP #define ORM_DATETIMEFIELD_HPP #include <ORM/fields/private/Attr.hpp> namespace orm { class DateTimeField : public Attr<std::string> { public: /** * \brief Make a Attr * * \param value value to store * \param column Column in bdd **/ DateTimeField(const std::string& value,const std::string& column); /** * \brief Make a Attr * default value is empty string. * \param column Column in bdd **/ DateTimeField(const std::string& column); DateTimeField(const DateTimeField&) = delete; DateTimeField& operator=(const DateTimeField&) = delete; DateTimeField(DateTimeField&&) = default; DateTimeField& operator=(DateTimeField&&) = default; /*using Attr<std::string>::operator=; using Attr<std::string>::operator+; using Attr<std::string>::operator==; using Attr<std::string>::operator!=; using Attr<std::string>::operator>; using Attr<std::string>::operator<; using Attr<std::string>::operator>=; using Attr<std::string>::operator<=; using Attr<std::string>::operator+=;*/ using Attr<std::string>::operator std::string; static DateTimeField now(); protected: /** * \brief create the attr column */ virtual std::string create(const Bdd& bdd) const; }; } #endif <commit_msg>add datetime<commit_after>#ifndef ORM_DATETIMEFIELD_HPP #define ORM_DATETIMEFIELD_HPP #include <ORM/fields/private/Attr.hpp> namespace orm { /** * \todo this DateTimeField class */ class DateTimeField : public Attr<std::string> { public: /** * \brief Make a Attr * * \param value value to store * \param column Column in bdd **/ DateTimeField(const std::string& value,const std::string& column); /** * \brief Make a Attr * default value is empty string. * \param column Column in bdd **/ DateTimeField(const std::string& column); DateTimeField(const DateTimeField&) = delete; DateTimeField& operator=(const DateTimeField&) = delete; DateTimeField(DateTimeField&&) = default; DateTimeField& operator=(DateTimeField&&) = default; /*using Attr<std::string>::operator=; using Attr<std::string>::operator+; using Attr<std::string>::operator==; using Attr<std::string>::operator!=; using Attr<std::string>::operator>; using Attr<std::string>::operator<; using Attr<std::string>::operator>=; using Attr<std::string>::operator<=; using Attr<std::string>::operator+=;*/ using Attr<std::string>::operator std::string; static DateTimeField now(); protected: /** * \brief create the attr column */ virtual std::string create(const Bdd& bdd) const; }; } #endif <|endoftext|>
<commit_before>/// /// @file Li.cpp /// @brief Logarithmic integral and Riemann R functions. /// /// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <generate.hpp> #include <int128_t.hpp> #include <stdint.h> #include <algorithm> #include <cmath> #include <limits> using namespace std; namespace primecount { /// Calculate the logarithmic integral using /// Ramanujan's formula: /// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation /// long double li(long double x) { long double gamma = 0.57721566490153286061; long double sum = 0; long double inner_sum = 0; long double factorial = 1; long double p = -1; long double q = 0; long double power2 = 1; int k = 0; if (x < 1.001) return 0; for (int n = 1; n < 200; n++) { p *= -log(x); factorial *= n; q = factorial * power2; power2 *= 2; for (; k <= (n - 1) / 2; k++) inner_sum += 1.0L / (2 * k + 1); long double old = sum; sum += (p / q) * inner_sum; if (abs(sum - old) < numeric_limits<double>::epsilon()) break; } return gamma + log(log(x)) + sqrt(x) * sum; } /// Calculate the offset logarithmic integral which is a very /// accurate approximation of the number of primes <= x. /// Li(x) > pi(x) for 24 <= x <= ~ 10^316 /// long double Li(long double x) { long double li2 = 1.04516378011749278484; if (x < 1.001) return 0; return li(x) - li2; } /// Calculate the inverse offset logarithmic integral which /// is a very accurate approximation of the nth prime. /// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316 /// long double Li_inverse(long double x) { long double t = x * log(x); if (x < 2) return 0; for (int i = 0; i < 100; i++) { long double old = t; t -= (Li(t) - x) * log(t); if (abs(t - old) < numeric_limits<double>::epsilon() * max(abs(t), abs(old))) break; } return t; } /// Calculate the Riemann R function which is a very accurate /// approximation of the number of primes below x. /// long double Ri(long double x) { int terms = 200; auto mu = generate_moebius(terms); long double sum = 0; if (x < 0) return 0; for (int n = 1; n < terms; n++) { long double root = pow(x, 1.0L / n); long double Li_root = Li(root); sum += (Li_root * mu[n]) / n; if (abs(Li_root) < numeric_limits<double>::epsilon()) break; } return sum; } /// Calculate the inverse Riemann R function which is a very /// accurate approximation of the nth prime. /// long double Ri_inverse(long double x) { long double t = x * log(x); if (x < 2) return 0; for (int i = 0; i < 100; i++) { long double old = t; t -= (Ri(t) - x) * log(t); if (abs(t - old) < numeric_limits<double>::epsilon() * max(abs(t), abs(old))) break; } return t; } int64_t Li(int64_t x) { return (int64_t) Li((long double) x); } int64_t Li_inverse(int64_t x) { return (int64_t) Li_inverse((long double) x); } #ifdef HAVE_INT128_T int128_t Li(int128_t x) { return (int128_t) Li((long double) x); } int128_t Li_inverse(int128_t x) { return (int128_t) Li_inverse((long double) x); } #endif int64_t Ri(int64_t x) { return (int64_t) Ri((long double) x); } int64_t Ri_inverse(int64_t x) { return (int64_t) Ri_inverse((long double) x); } #ifdef HAVE_INT128_T int128_t Ri(int128_t x) { return (int128_t) Ri((long double) x); } int128_t Ri_inverse(int128_t x) { return (int128_t) Ri_inverse((long double) x); } #endif } // namespace <commit_msg>Speed up Ri(x) and Ri_inverse(x)<commit_after>/// /// @file Li.cpp /// @brief Logarithmic integral and Riemann R functions. /// /// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <generate.hpp> #include <int128_t.hpp> #include <stdint.h> #include <algorithm> #include <cassert> #include <cmath> #include <limits> using namespace std; namespace primecount { /// Calculate the logarithmic integral using /// Ramanujan's formula: /// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation /// long double li(long double x) { assert(x >= 2); long double gamma = 0.57721566490153286061; long double sum = 0; long double inner_sum = 0; long double factorial = 1; long double p = -1; long double q = 0; long double power2 = 1; long double term; int k = 0; for (int n = 1; n < 200; n++) { p *= -log(x); factorial *= n; q = factorial * power2; power2 *= 2; for (; k <= (n - 1) / 2; k++) inner_sum += 1.0L / (2 * k + 1); term = (p / q) * inner_sum; sum += term; if (abs(term) < numeric_limits<double>::epsilon()) break; } return gamma + log(log(x)) + sqrt(x) * sum; } /// Calculate the offset logarithmic integral which is a very /// accurate approximation of the number of primes <= x. /// Li(x) > pi(x) for 24 <= x <= ~ 10^316 /// long double Li(long double x) { if (x < 2) return 0; long double li2 = 1.04516378011749278484; return li(x) - li2; } /// Calculate the inverse offset logarithmic integral which /// is a very accurate approximation of the nth prime. /// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316 /// long double Li_inverse(long double x) { if (x < 2) return 0; long double t = x * log(x); for (int i = 0; i < 100; i++) { long double old = t; t -= (Li(t) - x) * log(t); if (abs(t - old) < numeric_limits<double>::epsilon() * max(abs(t), abs(old))) break; } return t; } /// Calculate the Riemann R function which is a very accurate /// approximation of the number of primes below x. /// long double Ri(long double x) { if (x < 2) return 0; int terms = 200; auto mu = generate_moebius(terms); long double sum = 0; long double root; long double term; for (int n = 1; n < terms; n++) { if (mu[n]) { root = pow(x, 1.0L / n); term = (Li(root) * mu[n]) / n; sum += term; if (abs(term) < numeric_limits<double>::epsilon()) break; } } return sum; } /// Calculate the inverse Riemann R function which is a very /// accurate approximation of the nth prime. /// long double Ri_inverse(long double x) { if (x < 2) return 0; long double t = x * log(x); for (int i = 0; i < 100; i++) { long double old = t; t -= (Ri(t) - x) * log(t); if (abs(t - old) < numeric_limits<double>::epsilon() * max(abs(t), abs(old))) break; } return t; } int64_t Li(int64_t x) { return (int64_t) Li((long double) x); } int64_t Li_inverse(int64_t x) { return (int64_t) Li_inverse((long double) x); } #ifdef HAVE_INT128_T int128_t Li(int128_t x) { return (int128_t) Li((long double) x); } int128_t Li_inverse(int128_t x) { return (int128_t) Li_inverse((long double) x); } #endif int64_t Ri(int64_t x) { return (int64_t) Ri((long double) x); } int64_t Ri_inverse(int64_t x) { return (int64_t) Ri_inverse((long double) x); } #ifdef HAVE_INT128_T int128_t Ri(int128_t x) { return (int128_t) Ri((long double) x); } int128_t Ri_inverse(int128_t x) { return (int128_t) Ri_inverse((long double) x); } #endif } // namespace <|endoftext|>
<commit_before>#pragma once #include "fft2d/data.hpp" #include "fft2d/Converter.hpp" <commit_msg>Update includer<commit_after>#pragma once #include "fft2d/data.hpp" #include "fft2d/pb.hpp" #include "fft2d/plan.hpp" #include "fft2d/algorithm.hpp" <|endoftext|>
<commit_before>#include "sitkRecursiveGaussianImageFilter.h" namespace itk { namespace simple { //---------------------------------------------------------------------------- // // Default constructor that initializes parameters // RecursiveGaussianImageFilter::RecursiveGaussianImageFilter () { this->m_Sigma = 1.0; this->m_Order = ZeroOrder; this->m_NormalizeAcrossScale = false; this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) ); this->m_MemberFactory->RegisterMemberFunctions< PixelTypeList, 3 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelTypeList, 2 > (); } // // ToString // std::string RecursiveGaussianImageFilter::ToString() const { std::ostringstream out; out << "itk::simple::RecursiveGaussianImageFilter\n" << "\tSigma: " << this->m_Sigma << "\n" << "\tOrder: " << this->m_Order << "\n" << "\tNormalizeAcrossScale: " << this->m_NormalizeAcrossScale << "\n"; return out.str(); } // // Execute // Image::Pointer RecursiveGaussianImageFilter::Execute ( Image::Pointer image ) { ImageDataType type = image->GetDataType(); unsigned int dimension = image->GetDimension(); return this->m_MemberFactory->GetMemberFunction( type, dimension )( image ); } //---------------------------------------------------------------------------- // // ExecuteInternal // template <class TImageType> Image::Pointer RecursiveGaussianImageFilter::ExecuteInternal ( Image::Pointer inImage ) { typedef TImageType InputImageType; typedef itk::Image<float,InputImageType::ImageDimension> OutputImageType; typename InputImageType::Pointer image = dynamic_cast <InputImageType*> ( inImage->GetImageBase().GetPointer() ); if ( image.IsNull() ) { // Take some action return NULL; } typedef itk::RecursiveGaussianImageFilter<InputImageType, OutputImageType> GaussianFilterType; typename GaussianFilterType::Pointer filter = GaussianFilterType::New(); filter->SetInput ( image ); filter->SetSigma ( this->m_Sigma ); filter->SetNormalizeAcrossScale ( this->m_NormalizeAcrossScale ); // cast the order parameter to the type from the itk filter typename GaussianFilterType::OrderEnumType internalOrder = static_cast<typename GaussianFilterType::OrderEnumType>(this->m_Order); filter->SetOrder ( internalOrder ); filter->Update(); Image::Pointer out = new Image( filter->GetOutput() ); filter->GetOutput()->DisconnectPipeline(); return out; } } // end namespace simple } // end namespace itk <commit_msg>ENH: Simplified type declarations.<commit_after>#include "sitkRecursiveGaussianImageFilter.h" namespace itk { namespace simple { //---------------------------------------------------------------------------- // // Default constructor that initializes parameters // RecursiveGaussianImageFilter::RecursiveGaussianImageFilter () { this->m_Sigma = 1.0; this->m_Order = ZeroOrder; this->m_NormalizeAcrossScale = false; this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) ); this->m_MemberFactory->RegisterMemberFunctions< PixelTypeList, 3 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelTypeList, 2 > (); } // // ToString // std::string RecursiveGaussianImageFilter::ToString() const { std::ostringstream out; out << "itk::simple::RecursiveGaussianImageFilter\n" << "\tSigma: " << this->m_Sigma << "\n" << "\tOrder: " << this->m_Order << "\n" << "\tNormalizeAcrossScale: " << this->m_NormalizeAcrossScale << "\n"; return out.str(); } // // Execute // Image::Pointer RecursiveGaussianImageFilter::Execute ( Image::Pointer image ) { ImageDataType type = image->GetDataType(); unsigned int dimension = image->GetDimension(); return this->m_MemberFactory->GetMemberFunction( type, dimension )( image ); } //---------------------------------------------------------------------------- // // ExecuteInternal // template <class TImageType> Image::Pointer RecursiveGaussianImageFilter::ExecuteInternal ( Image::Pointer inImage ) { typedef TImageType InputImageType; typedef itk::Image<float,InputImageType::ImageDimension> OutputImageType; typename InputImageType::Pointer image = dynamic_cast <InputImageType*> ( inImage->GetImageBase().GetPointer() ); if ( image.IsNull() ) { // Take some action return NULL; } typedef itk::RecursiveGaussianImageFilter<InputImageType, OutputImageType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput ( image ); filter->SetSigma ( this->m_Sigma ); filter->SetNormalizeAcrossScale ( this->m_NormalizeAcrossScale ); // cast the order parameter to the type from the itk filter typename FilterType::OrderEnumType internalOrder = static_cast<typename FilterType::OrderEnumType>(this->m_Order); filter->SetOrder ( internalOrder ); filter->Update(); Image::Pointer out = new Image( filter->GetOutput() ); filter->GetOutput()->DisconnectPipeline(); return out; } } // end namespace simple } // end namespace itk <|endoftext|>
<commit_before>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com 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 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. #pragma once #include <unordered_map> #include <unordered_set> #include <distributions/common.hpp> #include <distributions/random.hpp> #include <distributions/vector.hpp> #include <distributions/trivial_hash.hpp> #include <distributions/mixture.hpp> namespace distributions { // This is explicitly instantiated for: // - int32_t // To add datatypes, edit the bottom of src/clustering.cc template<class count_t> struct Clustering { //---------------------------------------------------------------------------- // Assignments typedef std::unordered_map<count_t, count_t, TrivialHash<count_t>> Assignments; static std::vector<count_t> count_assignments ( const Assignments & assignments); //---------------------------------------------------------------------------- // Pitman-Yor Model struct PitmanYor { float alpha; float d; std::vector<count_t> sample_assignments ( count_t size, rng_t & rng) const; float score_counts ( const std::vector<count_t> & counts) const; float score_add_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { // What is the probability (score) of adding a customer // to a table which currently has: // // group_size people sitting at it (can be zero) // nonempty_group_count tables that have people sitting at them // sample_size people seated total // // In particular, if group_size == 0, this is the prob of sitting // at a new table. In that case, nonempty_group_count does not // include this "new" table, as it is obviously unoccupied. if (group_size == 0) { float numer = alpha + d * nonempty_group_count; float denom = (sample_size + alpha) * empty_group_count; return fast_log(numer / denom); } else { return fast_log((group_size - d) / (sample_size + alpha)); } } float score_remove_value( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { group_size -= 1; if (group_size == 0) { nonempty_group_count -= 1; //empty_group_count += 1; // FIXME is this right? } sample_size -= 1; return -score_add_value( group_size, nonempty_group_count, sample_size, empty_group_count); } // HACK gcc doesn't want Mixture defined outside of PitmanYor class Mixture { public: typedef PitmanYor Model; typedef typename MixtureDriver<PitmanYor, count_t>::IdSet IdSet; const std::vector<count_t> & counts () const { return driver_.counts(); } count_t counts (size_t groupid) const { return driver_.counts(groupid); } const IdSet & empty_groupids () const { return driver_.empty_groupids(); } size_t sample_size () const { return driver_.sample_size(); } void init (const Model & model, const std::vector<count_t> & counts) { driver_.init(model, counts); const size_t group_count = driver_.counts().size(); shifted_scores_.resize(group_count); for (size_t i = 0; i < group_count; ++i) { if (driver_.counts(i)) { _update_nonempty_group(model, i); } } _update_empty_groups(model); } bool add_value ( const Model & model, size_t groupid, count_t count = 1) { const bool add_group = driver_.add_value(model, groupid, count); if (DIST_UNLIKELY(add_group)) { _update_empty_groups(model); } return add_group; } bool remove_value ( const Model & model, size_t groupid, count_t count = 1) { const bool remove_group = driver_.remove_value(model, groupid, count); if (DIST_UNLIKELY(remove_group)) { _update_empty_groups(model); } else { _update_nonempty_group(model, groupid); } return remove_group; } void score (const Model & model, VectorFloat & scores) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_EQ(scores.size(), counts().size()); } const size_t size = counts().size(); const float shift = -fast_log(sample_size() + model.alpha); const float * __restrict__ in = VectorFloat_data(shifted_scores_); float * __restrict__ out = VectorFloat_data(scores); for (size_t i = 0; i < size; ++i) { out[i] = in[i] + shift; } } private: void _update_nonempty_group (const Model & model, size_t groupid) { const auto group_size = counts()[groupid]; DIST_ASSERT2(group_size, "expected nonempty group"); shifted_scores_[groupid] = fast_log(group_size - model.d); } void _update_empty_groups (const Model & model) { size_t empty_group_count = empty_groupids().size(); size_t nonempty_group_count = counts().size() - empty_group_count; float numer = model.alpha + model.d * nonempty_group_count; float denom = empty_group_count; const float shifted_score = fast_log(numer / denom); for (size_t i : empty_groupids()) { shifted_scores_[i] = shifted_score; } } MixtureDriver<PitmanYor, count_t> driver_; VectorFloat shifted_scores_; }; }; //---------------------------------------------------------------------------- // Low-Entropy Model struct LowEntropy { count_t dataset_size; std::vector<count_t> sample_assignments ( count_t sample_size, rng_t & rng) const; float score_counts (const std::vector<count_t> & counts) const; float score_add_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_LT(sample_size, dataset_size); DIST_ASSERT_LT(0, empty_group_count); } if (group_size == 0) { float score = -fast_log(empty_group_count); if (sample_size + 1 < dataset_size) { score += _approximate_postpred_correction(sample_size + 1); } return score; } // see `python derivations/clustering.py fastlog` const count_t very_large = 10000; float bigger = 1.f + group_size; if (group_size > very_large) { return 1.f + fast_log(bigger); } else { return fast_log(bigger / group_size) * group_size + fast_log(bigger); } } float score_remove_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_LT(0, sample_size); } group_size -= 1; return -score_add_value( group_size, nonempty_group_count, sample_size, empty_group_count); } float log_partition_function (count_t sample_size) const; typedef MixtureDriver<LowEntropy, count_t> Mixture; private: // ad hoc approximation, // see `python derivations/clustering.py postpred` // see `python derivations/clustering.py approximations` float _approximate_postpred_correction (float sample_size) const { if (DIST_DEBUG_LEVEL >= 2) { DIST_ASSERT_LT(0, sample_size); DIST_ASSERT_LT(sample_size, dataset_size); } float exponent = 0.45f - 0.1f / sample_size - 0.1f / dataset_size; float scale = dataset_size / sample_size; return fast_log(scale) * exponent; } float _approximate_dataprob_correction(count_t sample_size) const; }; }; // struct Clustering<count_t> } // namespace distributions <commit_msg>Fix bug in PitmanYor::Mixture<commit_after>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com 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 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. #pragma once #include <unordered_map> #include <unordered_set> #include <distributions/common.hpp> #include <distributions/random.hpp> #include <distributions/vector.hpp> #include <distributions/trivial_hash.hpp> #include <distributions/mixture.hpp> namespace distributions { // This is explicitly instantiated for: // - int32_t // To add datatypes, edit the bottom of src/clustering.cc template<class count_t> struct Clustering { //---------------------------------------------------------------------------- // Assignments typedef std::unordered_map<count_t, count_t, TrivialHash<count_t>> Assignments; static std::vector<count_t> count_assignments ( const Assignments & assignments); //---------------------------------------------------------------------------- // Pitman-Yor Model struct PitmanYor { float alpha; float d; std::vector<count_t> sample_assignments ( count_t size, rng_t & rng) const; float score_counts ( const std::vector<count_t> & counts) const; float score_add_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { // What is the probability (score) of adding a customer // to a table which currently has: // // group_size people sitting at it (can be zero) // nonempty_group_count tables that have people sitting at them // sample_size people seated total // // In particular, if group_size == 0, this is the prob of sitting // at a new table. In that case, nonempty_group_count does not // include this "new" table, as it is obviously unoccupied. if (group_size == 0) { float numer = alpha + d * nonempty_group_count; float denom = (sample_size + alpha) * empty_group_count; return fast_log(numer / denom); } else { return fast_log((group_size - d) / (sample_size + alpha)); } } float score_remove_value( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { group_size -= 1; if (group_size == 0) { nonempty_group_count -= 1; //empty_group_count += 1; // FIXME is this right? } sample_size -= 1; return -score_add_value( group_size, nonempty_group_count, sample_size, empty_group_count); } // HACK gcc doesn't want Mixture defined outside of PitmanYor class Mixture { public: typedef PitmanYor Model; typedef typename MixtureDriver<PitmanYor, count_t>::IdSet IdSet; const std::vector<count_t> & counts () const { return driver_.counts(); } count_t counts (size_t groupid) const { return driver_.counts(groupid); } const IdSet & empty_groupids () const { return driver_.empty_groupids(); } size_t sample_size () const { return driver_.sample_size(); } void init (const Model & model, const std::vector<count_t> & counts) { driver_.init(model, counts); const size_t group_count = driver_.counts().size(); shifted_scores_.resize(group_count); for (size_t i = 0; i < group_count; ++i) { if (driver_.counts(i)) { _update_nonempty_group(model, i); } } _update_empty_groups(model); } bool add_value ( const Model & model, size_t groupid, count_t count = 1) { const bool add_group = driver_.add_value(model, groupid, count); if (DIST_UNLIKELY(add_group)) { shifted_scores_.push_back(0); _update_empty_groups(model); } return add_group; } bool remove_value ( const Model & model, size_t groupid, count_t count = 1) { const bool remove_group = driver_.remove_value(model, groupid, count); if (DIST_UNLIKELY(remove_group)) { _update_empty_groups(model); shifted_scores_.pop_back(); } else { _update_nonempty_group(model, groupid); } return remove_group; } void score (const Model & model, VectorFloat & scores) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_EQ(scores.size(), counts().size()); } const size_t size = counts().size(); const float shift = -fast_log(sample_size() + model.alpha); const float * __restrict__ in = VectorFloat_data(shifted_scores_); float * __restrict__ out = VectorFloat_data(scores); for (size_t i = 0; i < size; ++i) { out[i] = in[i] + shift; } } private: void _update_nonempty_group (const Model & model, size_t groupid) { const auto group_size = counts()[groupid]; DIST_ASSERT2(group_size, "expected nonempty group"); shifted_scores_[groupid] = fast_log(group_size - model.d); } void _update_empty_groups (const Model & model) { size_t empty_group_count = empty_groupids().size(); size_t nonempty_group_count = counts().size() - empty_group_count; float numer = model.alpha + model.d * nonempty_group_count; float denom = empty_group_count; const float shifted_score = fast_log(numer / denom); for (size_t i : empty_groupids()) { shifted_scores_[i] = shifted_score; } } MixtureDriver<PitmanYor, count_t> driver_; VectorFloat shifted_scores_; }; }; //---------------------------------------------------------------------------- // Low-Entropy Model struct LowEntropy { count_t dataset_size; std::vector<count_t> sample_assignments ( count_t sample_size, rng_t & rng) const; float score_counts (const std::vector<count_t> & counts) const; float score_add_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_LT(sample_size, dataset_size); DIST_ASSERT_LT(0, empty_group_count); } if (group_size == 0) { float score = -fast_log(empty_group_count); if (sample_size + 1 < dataset_size) { score += _approximate_postpred_correction(sample_size + 1); } return score; } // see `python derivations/clustering.py fastlog` const count_t very_large = 10000; float bigger = 1.f + group_size; if (group_size > very_large) { return 1.f + fast_log(bigger); } else { return fast_log(bigger / group_size) * group_size + fast_log(bigger); } } float score_remove_value ( count_t group_size, count_t nonempty_group_count, count_t sample_size, count_t empty_group_count = 1) const { if (DIST_DEBUG_LEVEL >= 1) { DIST_ASSERT_LT(0, sample_size); } group_size -= 1; return -score_add_value( group_size, nonempty_group_count, sample_size, empty_group_count); } float log_partition_function (count_t sample_size) const; typedef MixtureDriver<LowEntropy, count_t> Mixture; private: // ad hoc approximation, // see `python derivations/clustering.py postpred` // see `python derivations/clustering.py approximations` float _approximate_postpred_correction (float sample_size) const { if (DIST_DEBUG_LEVEL >= 2) { DIST_ASSERT_LT(0, sample_size); DIST_ASSERT_LT(sample_size, dataset_size); } float exponent = 0.45f - 0.1f / sample_size - 0.1f / dataset_size; float scale = dataset_size / sample_size; return fast_log(scale) * exponent; } float _approximate_dataprob_correction(count_t sample_size) const; }; }; // struct Clustering<count_t> } // namespace distributions <|endoftext|>
<commit_before>/// /// @file Pk.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "pi_bsearch.hpp" #include "pmath.hpp" #include <primesieve.hpp> #include <stdint.h> #include <vector> #ifdef _OPENMP #include <omp.h> #include "get_omp_threads.hpp" #endif namespace primecount { /// 2nd partial sieve function. /// P2(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. /// Space complexity: O(x^0.5). /// int64_t P2(int64_t x, int64_t a, int threads) { std::vector<int32_t> primes; std::vector<int64_t> counts; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); counts.resize(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; // This uses a clever trick, instead of calculating // pi(x / primes[i+1]) for a < i <= b it only counts the primes // between adjacent values [x/primes[i+1], x/primes[i]]. // When finished pi(x / primes[i+1]) can quickly be calculated // by backwards summing up the counts. // #ifdef _OPENMP #pragma omp parallel for num_threads(get_omp_threads(threads)) \ schedule(dynamic) #endif for (int64_t i = b; i > a; i--) { int64_t prev = (i != b) ? x / primes[i + 1] + 1 : 0; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } return sum; } /// 3rd partial sieve function. /// P3(x, a) counts the numbers <= x that have exactly 3 prime /// factors each exceeding the a-th prime. /// Space complexity: O(x^0.5). /// int64_t P3(int64_t x, int64_t a, int threads) { std::vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); int64_t c = pi_bsearch(primes, iroot<3>(x)); int64_t sum = 0; #ifdef _OPENMP #pragma omp parallel for num_threads(get_omp_threads(threads)) \ schedule(dynamic) reduction(+: sum) #endif for (int64_t i = a + 1; i <= c; i++) { int64_t xi = x / primes[i]; int64_t bi = pi_bsearch(primes, isqrt(xi)); for (int64_t j = i; j <= bi; j++) { int64_t xij = xi / primes[j]; sum += pi_bsearch(primes, xij) - (j - 1); } } return sum; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file Pk.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "pi_bsearch.hpp" #include "pmath.hpp" #include <primesieve.hpp> #include <stdint.h> #include <vector> #ifdef _OPENMP #include <omp.h> #include "get_omp_threads.hpp" #endif using std::vector; namespace primecount { /// 2nd partial sieve function. /// P2(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. /// Space complexity: O(x^0.5). /// int64_t P2(int64_t x, int64_t a, int threads) { vector<int32_t> primes; vector<int64_t> counts; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); counts.resize(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; // This uses a clever trick, instead of calculating // pi(x / primes[i+1]) for a < i <= b it only counts the primes // between adjacent values [x/primes[i+1], x/primes[i]]. // When finished pi(x / primes[i+1]) can quickly be calculated // by backwards summing up the counts. // #ifdef _OPENMP #pragma omp parallel for num_threads(get_omp_threads(threads)) \ schedule(dynamic) #endif for (int64_t i = b; i > a; i--) { int64_t prev = (i == b) ? 0 : x / primes[i + 1] + 1; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } return sum; } /// 3rd partial sieve function. /// P3(x, a) counts the numbers <= x that have exactly 3 prime /// factors each exceeding the a-th prime. /// Space complexity: O(x^0.5). /// int64_t P3(int64_t x, int64_t a, int threads) { vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); int64_t y = iroot<3>(x); int64_t pi_y = pi_bsearch(primes, y); int64_t sum = 0; #ifdef _OPENMP #pragma omp parallel for num_threads(get_omp_threads(threads)) \ schedule(dynamic) reduction(+: sum) #endif for (int64_t i = a + 1; i <= pi_y; i++) { int64_t xi = x / primes[i]; int64_t bi = pi_bsearch(primes, isqrt(xi)); for (int64_t j = i; j <= bi; j++) sum += pi_bsearch(primes, xi / primes[j]) - (j - 1); } return sum; } } // namespace primecount <|endoftext|>
<commit_before>#include "RS.h" #include <cmath> #include <vector> #include "Math.h" using namespace TexturalAnalysis; std::vector<Point> RS::calculatePoints(const Image& image, const int x1, const int y1, const int x2, const int y2) { const int deltaX = std::abs(x2 - x1); const int deltaY = std::abs(y2 - y1); const int signX = x1 < x2 ? 1 : -1; const int signY = y1 < y2 ? 1 : -1; const int N = deltaX > deltaY ? deltaX + 1 : deltaY + 1; std::vector<double> h(N); int count = 0; h[count] = image.get(y2, x2); int error = deltaX - deltaY; double currentX = x1; double currentY = y1; while ((currentX != x2) || (currentY != y2)) { count++; h[count] = image.get(currentY, currentX); int error2 = error * 2; if(error2 > -deltaY) { error -= deltaY; currentX += signX; } if(error2 < deltaX) { error += deltaX; currentY += signY; } } std::vector<double> H(h.size()); H[0] = h[0]; for (int i = 1; i < h.size(); i++) { H[i] = H[i - 1] + h[i]; } std::vector<double> averageH(H.size()); for (int i = 0; i < H.size(); i++) { averageH[i] = H[i] / (i + 1); } std::vector<double> r(h.size()); r[0] = 0; for (int n = 1; n < h.size(); n++) { for (int k = 0; k < n; k++) { double sum = 0; double Max = 0; double Min = 0; for (int i = 0; i <= k; i++) { sum += h[i] - averageH[n]; if (sum < Min) { Min = sum; } if (sum > Max) { Max = sum; } } r[n] = Max - Min; } } std::vector<double> s(h.size()); for (int n = 0; n < h.size(); n++) { double sum = 0; for (int i = 0; i < n; i++){ sum += pow(h[i] - averageH[n], 2.0); } s[n] = sqrt(sum / (n + 1)); } std::vector<double> rs(h.size()); rs[0] = 0; for (int i = 1; i < r.size(); i++) { rs[i] = r[i] / s[i]; } std::vector<Point> points(rs.size()); for (int i = 1; i < rs.size(); i++) { double pointX = Math::ln(i); double pointY = Math::ln(rs[i]); points[i] = Point(pointX, pointY); } return points; } HirstValues RS::calculateHirstValues(const std::vector<Point>& rsPoints) { double c1 = 0; double c2 = 0; double g1 = 0; double g2 = 0; for (int i = 0; i < rsPoints.size(); i++) { Point point = rsPoints[i]; c1 += pow(point.x(), 2.0); c2 += point.x(); g1 += point.x() * point.y(); g2 += point.y(); } int size = rsPoints.size(); HirstValues hirstValues; hirstValues.coefficient = ((size - 1) * g1 - c2 * g2) / ((size - 1) * c1 - pow(c2, 2.0)); hirstValues.offset = (1.0 / (size - 1)) * (g2 - hirstValues.coefficient * c2); return hirstValues; }<commit_msg>Issue #13. Адаптировала алгоритм в RS-анализе на использование алгоритма Брезенхема.<commit_after>#include "RS.h" #include <cmath> #include <vector> #include "Math.h" #include "Bresenham.h" using namespace TexturalAnalysis; std::vector<Point> RS::calculatePoints(const Image& image, const int x1, const int y1, const int x2, const int y2) { std::vector<double> h = Bresenham::determinePoints(image, x1, y1, x2, y2); std::vector<double> H(h.size()); H[0] = h[0]; for (int i = 1; i < h.size(); i++) { H[i] = H[i - 1] + h[i]; } std::vector<double> averageH(H.size()); for (int i = 0; i < H.size(); i++) { averageH[i] = H[i] / (i + 1); } std::vector<double> r(h.size()); r[0] = 0; for (int n = 1; n < h.size(); n++) { for (int k = 0; k < n; k++) { double sum = 0; double Max = 0; double Min = 0; for (int i = 0; i <= k; i++) { sum += h[i] - averageH[n]; if (sum < Min) { Min = sum; } if (sum > Max) { Max = sum; } } r[n] = Max - Min; } } std::vector<double> s(h.size()); for (int n = 0; n < h.size(); n++) { double sum = 0; for (int i = 0; i < n; i++){ sum += pow(h[i] - averageH[n], 2.0); } s[n] = sqrt(sum / (n + 1)); } std::vector<double> rs(h.size()); rs[0] = 0; for (int i = 1; i < r.size(); i++) { rs[i] = r[i] / s[i]; } std::vector<Point> points(rs.size()); for (int i = 1; i < rs.size(); i++) { double pointX = Math::ln(i); double pointY = Math::ln(rs[i]); points[i] = Point(pointX, pointY); } return points; } HirstValues RS::calculateHirstValues(const std::vector<Point>& rsPoints) { double c1 = 0; double c2 = 0; double g1 = 0; double g2 = 0; for (int i = 0; i < rsPoints.size(); i++) { Point point = rsPoints[i]; c1 += pow(point.x(), 2.0); c2 += point.x(); g1 += point.x() * point.y(); g2 += point.y(); } int size = rsPoints.size(); HirstValues hirstValues; hirstValues.coefficient = ((size - 1) * g1 - c2 * g2) / ((size - 1) * c1 - pow(c2, 2.0)); hirstValues.offset = (1.0 / (size - 1)) * (g2 - hirstValues.coefficient * c2); return hirstValues; }<|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 "chrome/browser/extensions/api/feedback_private/feedback_private_api.h" #include "base/lazy_instance.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/extensions/api/feedback_private/feedback_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/feedback/tracing_manager.h" #include "extensions/browser/event_router.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "url/url_util.h" namespace { // Getting the filename of a blob prepends a "C:\fakepath" to the filename. // This is undesirable, strip it if it exists. std::string StripFakepath(const std::string& path) { const char kFakePathStr[] = "C:\\fakepath\\"; if (StartsWithASCII(path, kFakePathStr, false)) return path.substr(arraysize(kFakePathStr) - 1); return path; } } // namespace namespace extensions { namespace feedback_private = api::feedback_private; using feedback_private::SystemInformation; using feedback_private::FeedbackInfo; char kFeedbackExtensionId[] = "gfdkimpbcpahaombhbimeihdjnejgicl"; static base::LazyInstance<ProfileKeyedAPIFactory<FeedbackPrivateAPI> > g_factory = LAZY_INSTANCE_INITIALIZER; // static ProfileKeyedAPIFactory<FeedbackPrivateAPI>* FeedbackPrivateAPI::GetFactoryInstance() { return &g_factory.Get(); } FeedbackPrivateAPI::FeedbackPrivateAPI(Profile* profile) : profile_(profile), service_(FeedbackService::CreateInstance()) { } FeedbackPrivateAPI::~FeedbackPrivateAPI() { delete service_; service_ = NULL; } FeedbackService* FeedbackPrivateAPI::GetService() const { return service_; } void FeedbackPrivateAPI::RequestFeedback( const std::string& description_template, const std::string& category_tag, const GURL& page_url) { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: Feedback requested."; if (profile_ && ExtensionSystem::Get(profile_)->event_router()) { FeedbackInfo info; info.description = description_template; info.category_tag = make_scoped_ptr(new std::string(category_tag)); info.page_url = make_scoped_ptr(new std::string(page_url.spec())); info.system_information.reset(new SystemInformationList); // The manager is only available if tracing is enabled. if (TracingManager* manager = TracingManager::Get()) { info.trace_id.reset(new int(manager->RequestTrace())); } scoped_ptr<base::ListValue> args(new base::ListValue()); args->Append(info.ToValue().release()); scoped_ptr<Event> event(new Event( feedback_private::OnFeedbackRequested::kEventName, args.Pass())); // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: Dispatching onFeedbackRequested event."; ExtensionSystem::Get(profile_)->event_router()->DispatchEventToExtension( kFeedbackExtensionId, event.Pass()); } } // static base::Closure* FeedbackPrivateGetStringsFunction::test_callback_ = NULL; bool FeedbackPrivateGetStringsFunction::RunImpl() { base::DictionaryValue* dict = new base::DictionaryValue(); SetResult(dict); #define SET_STRING(id, idr) \ dict->SetString(id, l10n_util::GetStringUTF16(idr)) SET_STRING("page-title", IDS_FEEDBACK_REPORT_PAGE_TITLE); SET_STRING("page-url", IDS_FEEDBACK_REPORT_URL_LABEL); SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL); SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL); #if defined(OS_CHROMEOS) SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX); #else SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_CHKBOX); #endif SET_STRING("attach-file-label", IDS_FEEDBACK_ATTACH_FILE_LABEL); SET_STRING("attach-file-note", IDS_FEEDBACK_ATTACH_FILE_NOTE); SET_STRING("attach-file-to-big", IDS_FEEDBACK_ATTACH_FILE_TO_BIG); SET_STRING("reading-file", IDS_FEEDBACK_READING_FILE); SET_STRING("send-report", IDS_FEEDBACK_SEND_REPORT); SET_STRING("cancel", IDS_CANCEL); SET_STRING("no-description", IDS_FEEDBACK_NO_DESCRIPTION); SET_STRING("privacy-note", IDS_FEEDBACK_PRIVACY_NOTE); SET_STRING("performance-trace", IDS_FEEDBACK_INCLUDE_PERFORMANCE_TRACE_CHECKBOX); #undef SET_STRING webui::SetFontAndTextDirection(dict); if (test_callback_ && !test_callback_->is_null()) test_callback_->Run(); return true; } bool FeedbackPrivateGetUserEmailFunction::RunImpl() { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: User e-mail requested."; FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); SetResult(new base::StringValue(service->GetUserEmail())); return true; } bool FeedbackPrivateGetSystemInformationFunction::RunImpl() { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: System information requested."; FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); service->GetSystemInformation( base::Bind( &FeedbackPrivateGetSystemInformationFunction::OnCompleted, this)); return true; } void FeedbackPrivateGetSystemInformationFunction::OnCompleted( const SystemInformationList& sys_info) { results_ = feedback_private::GetSystemInformation::Results::Create( sys_info); SendResponse(true); } bool FeedbackPrivateSendFeedbackFunction::RunImpl() { scoped_ptr<feedback_private::SendFeedback::Params> params( feedback_private::SendFeedback::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const FeedbackInfo &feedback_info = params->feedback; std::string attached_file_uuid; if (feedback_info.attached_file_blob_uuid.get() && !feedback_info.attached_file_blob_uuid->empty()) attached_file_uuid = *feedback_info.attached_file_blob_uuid; std::string screenshot_uuid; if (feedback_info.screenshot_blob_uuid.get() && !feedback_info.screenshot_blob_uuid->empty()) screenshot_uuid = *feedback_info.screenshot_blob_uuid; // Populate feedback data. scoped_refptr<FeedbackData> feedback_data(new FeedbackData()); feedback_data->set_profile(GetProfile()); feedback_data->set_description(feedback_info.description); if (feedback_info.category_tag.get()) feedback_data->set_category_tag(*feedback_info.category_tag.get()); if (feedback_info.page_url.get()) feedback_data->set_page_url(*feedback_info.page_url.get()); if (feedback_info.email.get()) feedback_data->set_user_email(*feedback_info.email.get()); if (!attached_file_uuid.empty()) { feedback_data->set_attached_filename( StripFakepath((*feedback_info.attached_file.get()).name)); feedback_data->set_attached_file_uuid(attached_file_uuid); } if (!screenshot_uuid.empty()) feedback_data->set_screenshot_uuid(screenshot_uuid); if (feedback_info.trace_id.get()) { feedback_data->set_trace_id(*feedback_info.trace_id.get()); } scoped_ptr<FeedbackData::SystemLogsMap> sys_logs( new FeedbackData::SystemLogsMap); SystemInformationList* sys_info = feedback_info.system_information.get(); if (sys_info) { for (SystemInformationList::iterator it = sys_info->begin(); it != sys_info->end(); ++it) (*sys_logs.get())[it->get()->key] = it->get()->value; } feedback_data->SetAndCompressSystemInfo(sys_logs.Pass()); FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); if (feedback_info.send_histograms) { scoped_ptr<std::string> histograms(new std::string); service->GetHistograms(histograms.get()); if (!histograms->empty()) feedback_data->SetAndCompressHistograms(histograms.Pass()); } service->SendFeedback( GetProfile(), feedback_data, base::Bind(&FeedbackPrivateSendFeedbackFunction::OnCompleted, this)); return true; } void FeedbackPrivateSendFeedbackFunction::OnCompleted( bool success) { results_ = feedback_private::SendFeedback::Results::Create( success ? feedback_private::STATUS_SUCCESS : feedback_private::STATUS_DELAYED); SendResponse(true); } } // namespace extensions <commit_msg>Set restrict_to_browser_context parameter for feedback API events<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 "chrome/browser/extensions/api/feedback_private/feedback_private_api.h" #include "base/lazy_instance.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/extensions/api/feedback_private/feedback_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/feedback/tracing_manager.h" #include "extensions/browser/event_router.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "url/url_util.h" namespace { // Getting the filename of a blob prepends a "C:\fakepath" to the filename. // This is undesirable, strip it if it exists. std::string StripFakepath(const std::string& path) { const char kFakePathStr[] = "C:\\fakepath\\"; if (StartsWithASCII(path, kFakePathStr, false)) return path.substr(arraysize(kFakePathStr) - 1); return path; } } // namespace namespace extensions { namespace feedback_private = api::feedback_private; using feedback_private::SystemInformation; using feedback_private::FeedbackInfo; char kFeedbackExtensionId[] = "gfdkimpbcpahaombhbimeihdjnejgicl"; static base::LazyInstance<ProfileKeyedAPIFactory<FeedbackPrivateAPI> > g_factory = LAZY_INSTANCE_INITIALIZER; // static ProfileKeyedAPIFactory<FeedbackPrivateAPI>* FeedbackPrivateAPI::GetFactoryInstance() { return &g_factory.Get(); } FeedbackPrivateAPI::FeedbackPrivateAPI(Profile* profile) : profile_(profile), service_(FeedbackService::CreateInstance()) { } FeedbackPrivateAPI::~FeedbackPrivateAPI() { delete service_; service_ = NULL; } FeedbackService* FeedbackPrivateAPI::GetService() const { return service_; } void FeedbackPrivateAPI::RequestFeedback( const std::string& description_template, const std::string& category_tag, const GURL& page_url) { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: Feedback requested."; if (profile_ && ExtensionSystem::Get(profile_)->event_router()) { FeedbackInfo info; info.description = description_template; info.category_tag = make_scoped_ptr(new std::string(category_tag)); info.page_url = make_scoped_ptr(new std::string(page_url.spec())); info.system_information.reset(new SystemInformationList); // The manager is only available if tracing is enabled. if (TracingManager* manager = TracingManager::Get()) { info.trace_id.reset(new int(manager->RequestTrace())); } scoped_ptr<base::ListValue> args(new base::ListValue()); args->Append(info.ToValue().release()); scoped_ptr<Event> event(new Event( feedback_private::OnFeedbackRequested::kEventName, args.Pass())); event->restrict_to_browser_context = profile_; // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: Dispatching onFeedbackRequested event."; ExtensionSystem::Get(profile_)->event_router()->DispatchEventToExtension( kFeedbackExtensionId, event.Pass()); } } // static base::Closure* FeedbackPrivateGetStringsFunction::test_callback_ = NULL; bool FeedbackPrivateGetStringsFunction::RunImpl() { base::DictionaryValue* dict = new base::DictionaryValue(); SetResult(dict); #define SET_STRING(id, idr) \ dict->SetString(id, l10n_util::GetStringUTF16(idr)) SET_STRING("page-title", IDS_FEEDBACK_REPORT_PAGE_TITLE); SET_STRING("page-url", IDS_FEEDBACK_REPORT_URL_LABEL); SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL); SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL); #if defined(OS_CHROMEOS) SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX); #else SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_CHKBOX); #endif SET_STRING("attach-file-label", IDS_FEEDBACK_ATTACH_FILE_LABEL); SET_STRING("attach-file-note", IDS_FEEDBACK_ATTACH_FILE_NOTE); SET_STRING("attach-file-to-big", IDS_FEEDBACK_ATTACH_FILE_TO_BIG); SET_STRING("reading-file", IDS_FEEDBACK_READING_FILE); SET_STRING("send-report", IDS_FEEDBACK_SEND_REPORT); SET_STRING("cancel", IDS_CANCEL); SET_STRING("no-description", IDS_FEEDBACK_NO_DESCRIPTION); SET_STRING("privacy-note", IDS_FEEDBACK_PRIVACY_NOTE); SET_STRING("performance-trace", IDS_FEEDBACK_INCLUDE_PERFORMANCE_TRACE_CHECKBOX); #undef SET_STRING webui::SetFontAndTextDirection(dict); if (test_callback_ && !test_callback_->is_null()) test_callback_->Run(); return true; } bool FeedbackPrivateGetUserEmailFunction::RunImpl() { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: User e-mail requested."; FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); SetResult(new base::StringValue(service->GetUserEmail())); return true; } bool FeedbackPrivateGetSystemInformationFunction::RunImpl() { // TODO(rkc): Remove logging once crbug.com/284662 is closed. LOG(WARNING) << "FEEDBACK_DEBUG: System information requested."; FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); service->GetSystemInformation( base::Bind( &FeedbackPrivateGetSystemInformationFunction::OnCompleted, this)); return true; } void FeedbackPrivateGetSystemInformationFunction::OnCompleted( const SystemInformationList& sys_info) { results_ = feedback_private::GetSystemInformation::Results::Create( sys_info); SendResponse(true); } bool FeedbackPrivateSendFeedbackFunction::RunImpl() { scoped_ptr<feedback_private::SendFeedback::Params> params( feedback_private::SendFeedback::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const FeedbackInfo &feedback_info = params->feedback; std::string attached_file_uuid; if (feedback_info.attached_file_blob_uuid.get() && !feedback_info.attached_file_blob_uuid->empty()) attached_file_uuid = *feedback_info.attached_file_blob_uuid; std::string screenshot_uuid; if (feedback_info.screenshot_blob_uuid.get() && !feedback_info.screenshot_blob_uuid->empty()) screenshot_uuid = *feedback_info.screenshot_blob_uuid; // Populate feedback data. scoped_refptr<FeedbackData> feedback_data(new FeedbackData()); feedback_data->set_profile(GetProfile()); feedback_data->set_description(feedback_info.description); if (feedback_info.category_tag.get()) feedback_data->set_category_tag(*feedback_info.category_tag.get()); if (feedback_info.page_url.get()) feedback_data->set_page_url(*feedback_info.page_url.get()); if (feedback_info.email.get()) feedback_data->set_user_email(*feedback_info.email.get()); if (!attached_file_uuid.empty()) { feedback_data->set_attached_filename( StripFakepath((*feedback_info.attached_file.get()).name)); feedback_data->set_attached_file_uuid(attached_file_uuid); } if (!screenshot_uuid.empty()) feedback_data->set_screenshot_uuid(screenshot_uuid); if (feedback_info.trace_id.get()) { feedback_data->set_trace_id(*feedback_info.trace_id.get()); } scoped_ptr<FeedbackData::SystemLogsMap> sys_logs( new FeedbackData::SystemLogsMap); SystemInformationList* sys_info = feedback_info.system_information.get(); if (sys_info) { for (SystemInformationList::iterator it = sys_info->begin(); it != sys_info->end(); ++it) (*sys_logs.get())[it->get()->key] = it->get()->value; } feedback_data->SetAndCompressSystemInfo(sys_logs.Pass()); FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() ->GetForProfile(GetProfile()) ->GetService(); DCHECK(service); if (feedback_info.send_histograms) { scoped_ptr<std::string> histograms(new std::string); service->GetHistograms(histograms.get()); if (!histograms->empty()) feedback_data->SetAndCompressHistograms(histograms.Pass()); } service->SendFeedback( GetProfile(), feedback_data, base::Bind(&FeedbackPrivateSendFeedbackFunction::OnCompleted, this)); return true; } void FeedbackPrivateSendFeedbackFunction::OnCompleted( bool success) { results_ = feedback_private::SendFeedback::Results::Create( success ? feedback_private::STATUS_SUCCESS : feedback_private::STATUS_DELAYED); SendResponse(true); } } // namespace extensions <|endoftext|>
<commit_before>/*! @file api.cc * @brief Speech Feature Extraction interface implementation. * @author Markovtsev Vadim <v.markovtsev@samsung.com> * @version 1.0 * * @section Notes * This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>. * * @section Copyright * Copyright 2013 Samsung R&D Institute Russia */ #include <SoundFeatureExtraction/api.h> #include <assert.h> #include <omp.h> #include <stddef.h> #include "src/features_parser.h" #include "src/make_unique.h" #include "src/transform_tree.h" #include "src/transform_registry.h" using SoundFeatureExtraction::Transform; using SoundFeatureExtraction::TransformFactory; using SoundFeatureExtraction::ChainNameAlreadyExistsException; using SoundFeatureExtraction::TransformNotRegisteredException; using SoundFeatureExtraction::ChainAlreadyExistsException; using SoundFeatureExtraction::IncompatibleTransformFormatException; using SoundFeatureExtraction::RawFeaturesMap; using SoundFeatureExtraction::Features::ParseFeaturesException; using SoundFeatureExtraction::TransformTree; using SoundFeatureExtraction::Formats::RawFormat16; using SoundFeatureExtraction::Formats::Raw16; using SoundFeatureExtraction::BuffersBase; using SoundFeatureExtraction::Buffers; extern "C" { struct FeaturesConfiguration { std::unique_ptr<TransformTree> Tree; }; #define BLAME(x) fprintf(stderr, "Error: " #x " is null (function %s, " \ "line %i)\n", \ __FUNCTION__, __LINE__) #define CHECK_NULL(x) do { if (x == nullptr) { \ BLAME(x); \ return; \ } } while(0) #define CHECK_NULL_RET(x, ret) do { if (x == nullptr) { \ BLAME(x); \ return ret; \ } } while(0) void copy_string(const std::string& str, char **ptr) { size_t size = str.size() + 1; *ptr = new char[size]; memcpy(*ptr, str.c_str(), size); } void query_transforms_list(char ***names, int *listSize) { CHECK_NULL(names); CHECK_NULL(listSize); int i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { continue; } i += tc.second.size(); } *listSize = i; *names = new char*[*listSize]; i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { continue; } if (tc.second.size() == 1) { copy_string(tc.first, *names + i); i++; } else { for (auto tfc : tc.second) { std::string fullName(tc.first); fullName += " ("; fullName += tfc.first; fullName += ")"; copy_string(fullName, *names + i); i++; } } } } void destroy_transforms_list(char **names, int listSize) { CHECK_NULL(names); for (int i = 0; i < listSize; i++) { delete[] names[i]; } delete[] names; } void query_format_converters_list(char ***inputFormats, char*** outputFormats, int *listSize) { CHECK_NULL(inputFormats); CHECK_NULL(outputFormats); CHECK_NULL(listSize); int i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { i++; } } *listSize = i; *inputFormats = new char*[*listSize]; *outputFormats = new char*[*listSize]; i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { auto transform = tc.second.begin()->second(); copy_string(transform->InputFormat()->Id(), *inputFormats + i); copy_string(transform->OutputFormat()->Id(), *outputFormats + i); i++; } } } void destroy_format_converters_list(char **inputFormats, char** outputFormats, int listSize) { CHECK_NULL(inputFormats); CHECK_NULL(outputFormats); for (int i = 0; i < listSize; i++) { delete[] inputFormats[i]; delete[] outputFormats[i]; } delete[] inputFormats; delete[] outputFormats; } void query_transform_details(const char *name, char **description, char **inputFormat, char **outputFormat, char ***parameterNames, char ***parameterDescriptions, char ***parameterDefaultValues, int *parametersCount) { CHECK_NULL(name); CHECK_NULL(description); CHECK_NULL(parameterNames); CHECK_NULL(parameterDescriptions); CHECK_NULL(parameterDefaultValues); CHECK_NULL(parametersCount); std::string fullName(name); std::string transformName(fullName); std::string formatName; auto bracePos = fullName.find('('); if (bracePos != fullName.npos) { transformName = fullName.substr(0, bracePos - 1); formatName = fullName.substr(bracePos + 1); formatName.resize(formatName.size() - 1); } auto tit = TransformFactory::Instance().Map().find(transformName); if (tit == TransformFactory::Instance().Map().end()) { fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str()); return; } std::shared_ptr<Transform> transformInstance; if (formatName == "") { transformInstance = tit->second.begin()->second(); } else { auto tfit = tit->second.find(formatName); if (tfit == tit->second.end()) { fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str()); return; } transformInstance = tfit->second(); } copy_string(transformInstance->Description(), description); copy_string(transformInstance->InputFormat()->Id(), inputFormat); copy_string(transformInstance->OutputFormat()->Id(), outputFormat); int pCount = transformInstance->SupportedParameters().size(); *parametersCount = pCount; *parameterNames = new char*[pCount]; *parameterDescriptions = new char*[pCount]; *parameterDefaultValues = new char*[pCount]; int i = 0; for (auto prop : transformInstance->SupportedParameters()) { copy_string(prop.first, *parameterNames + i); copy_string(prop.second.Description, *parameterDescriptions + i); copy_string(prop.second.DefaultValue, *parameterDefaultValues + i); i++; } } void destroy_transform_details(char *description, char *inputFormat, char *outputFormat, char **parameterNames, char **parameterDescriptions, char **parameterDefaultValues, int parametersCount) { CHECK_NULL(description); CHECK_NULL(parameterNames); CHECK_NULL(parameterDescriptions); CHECK_NULL(parameterDefaultValues); delete[] description; delete[] inputFormat; delete[] outputFormat; for (int i = 0; i < parametersCount; i++) { delete[] parameterNames[i]; delete[] parameterDescriptions[i]; delete[] parameterDefaultValues[i]; } delete[] parameterNames; delete[] parameterDescriptions; delete[] parameterDefaultValues; } FeaturesConfiguration *setup_features_extraction( const char *const *features, int featuresCount, size_t bufferSize, int samplingRate) { CHECK_NULL_RET(features, nullptr); if (featuresCount < 0) { fprintf(stderr, "Error: featuresCount is negative (%i)\n", featuresCount); return nullptr; } if (featuresCount > MAX_FEATURES_COUNT) { fprintf(stderr, "Error: featuresCount is too big " "(%i > MAX_FEATURES_COUNT=%i)\n", featuresCount, MAX_FEATURES_COUNT); return nullptr; } std::vector<std::string> lines; for (int i = 0; i < featuresCount; i++) { if (features[i] == nullptr) { fprintf(stderr, "Error: features[%i] is null\n", i); return nullptr; } lines.push_back(features[i]); } RawFeaturesMap featmap; try { featmap = SoundFeatureExtraction::Features::Parse(lines); } catch(const ParseFeaturesException& pfe) { fprintf(stderr, "Failed to parse features. %s\n", pfe.what()); return nullptr; } auto format = std::make_shared<RawFormat16>(bufferSize, samplingRate); auto config = new FeaturesConfiguration(); config->Tree = std::make_unique<TransformTree>(format); for (auto featpair : featmap) { try { config->Tree->AddFeature(featpair.first, featpair.second); } catch(const ChainNameAlreadyExistsException& cnaee) { fprintf(stderr, "Failed to construct the transform tree. %s\n", cnaee.what()); return nullptr; } catch(const TransformNotRegisteredException& tnre) { fprintf(stderr, "Failed to construct the transform tree. %s\n", tnre.what()); return nullptr; } catch(const ChainAlreadyExistsException& caee) { fprintf(stderr, "Failed to construct the transform tree. %s\n", caee.what()); return nullptr; } catch(const IncompatibleTransformFormatException& itfe) { fprintf(stderr, "Failed to construct the transform tree. %s\n", itfe.what()); return nullptr; } } config->Tree->PrepareForExecution(); #ifdef DEBUG config->Tree->SetValidateAfterEachTransform(true); #endif return config; } FeatureExtractionResult extract_speech_features( const FeaturesConfiguration *fc, int16_t *buffer, char ***featureNames, void ***results, int **resultLengths) { CHECK_NULL_RET(fc, FEATURE_EXTRACTION_RESULT_ERROR); CHECK_NULL_RET(buffer, FEATURE_EXTRACTION_RESULT_ERROR); CHECK_NULL_RET(results, FEATURE_EXTRACTION_RESULT_ERROR); std::unordered_map<std::string, std::shared_ptr<Buffers>> retmap; try { retmap = fc->Tree->Execute(Raw16(buffer)); } catch (const std::exception& ex) { fprintf(stderr, "Caught an exception with message \"%s\".\n", ex.what()); return FEATURE_EXTRACTION_RESULT_ERROR; } *featureNames = new char*[retmap.size()]; *results = new void*[retmap.size()]; *resultLengths = new int[retmap.size()]; int i = 0; for (auto res : retmap) { copy_string(res.first, *featureNames + i); size_t sizeEach = res.second->Format()->PayloadSizeInBytes(); assert(sizeEach > 0); size_t size = sizeEach * res.second->Size(); (*resultLengths)[i] = size; (*results)[i] = new char[size]; for (int j = 0; j < static_cast<int>(res.second->Size()); j++) { memcpy(reinterpret_cast<char *>((*results)[i]) + j * sizeEach, res.second->Format()->PayloadPointer((*res.second)[j]), sizeEach); } i++; } return FEATURE_EXTRACTION_RESULT_OK; } void report_extraction_time(const FeaturesConfiguration *fc, char ***transformNames, float **values, int *length) { CHECK_NULL(fc); CHECK_NULL(transformNames); CHECK_NULL(values); CHECK_NULL(length); auto report = fc->Tree->ExecutionTimeReport(); *length = report.size(); *transformNames = new char*[*length]; *values = new float[*length]; int i = 0; for (auto pair : report) { copy_string(pair.first, *transformNames + i); (*values)[i] = pair.second; i++; } } void destroy_extraction_time_report(char **transformNames, float *values, int length) { CHECK_NULL(transformNames); CHECK_NULL(values); delete[] values; for (int i = 0; i < length; i++) { delete[] transformNames[i]; } delete[] transformNames; } void report_extraction_graph(const FeaturesConfiguration *fc, const char *fileName) { CHECK_NULL(fc); CHECK_NULL(fileName); fc->Tree->Dump(fileName); } void destroy_features_configuration(FeaturesConfiguration* fc) { CHECK_NULL(fc); delete fc; } void free_results(int featuresCount, char **featureNames, void **results, int *resultLengths) { if(featuresCount <= 0) { fprintf(stderr, "Warning: free_results() was called with featuresCount" " <= 0, skipped\n"); return; } for (int i = 0; i < featuresCount; i++) { if (featureNames != nullptr) { delete[] featureNames[i]; } if (results != nullptr) { delete[] reinterpret_cast<char*>(results[i]); } } if (featureNames != nullptr) { delete[] featureNames; } if (resultLengths != nullptr) { delete[] resultLengths; } if (results != nullptr) { delete[] results; } } void get_set_omp_transforms_max_threads_num(int *value, bool get) { static int threads_num = omp_get_max_threads(); if (get) { *value = threads_num; } else { int max = omp_get_max_threads(); if (*value > max) { fprintf(stderr, "Warning: can not set the maximal number of threads to " "%i (the limit is %i), so set to %i\n", *value, max, max); threads_num = max; } else if (*value < 1) { fprintf(stderr, "Warning: can not set the maximal number of threads to " "%i. The value remains the same (%i)\n", *value, threads_num); } else { threads_num = *value; } } } int get_omp_transforms_max_threads_num() { int res; get_set_omp_transforms_max_threads_num(&res, true); return res; } void set_omp_transforms_max_threads_num(int value) { get_set_omp_transforms_max_threads_num(&value, false); } } <commit_msg>Set FFTF num_threads to API num_threads<commit_after>/*! @file api.cc * @brief Speech Feature Extraction interface implementation. * @author Markovtsev Vadim <v.markovtsev@samsung.com> * @version 1.0 * * @section Notes * This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>. * * @section Copyright * Copyright 2013 Samsung R&D Institute Russia */ #include <SoundFeatureExtraction/api.h> #include <assert.h> #include <omp.h> #include <stddef.h> #include <fftf/api.h> #include "src/features_parser.h" #include "src/make_unique.h" #include "src/transform_tree.h" #include "src/transform_registry.h" using SoundFeatureExtraction::Transform; using SoundFeatureExtraction::TransformFactory; using SoundFeatureExtraction::ChainNameAlreadyExistsException; using SoundFeatureExtraction::TransformNotRegisteredException; using SoundFeatureExtraction::ChainAlreadyExistsException; using SoundFeatureExtraction::IncompatibleTransformFormatException; using SoundFeatureExtraction::RawFeaturesMap; using SoundFeatureExtraction::Features::ParseFeaturesException; using SoundFeatureExtraction::TransformTree; using SoundFeatureExtraction::Formats::RawFormat16; using SoundFeatureExtraction::Formats::Raw16; using SoundFeatureExtraction::BuffersBase; using SoundFeatureExtraction::Buffers; extern "C" { struct FeaturesConfiguration { std::unique_ptr<TransformTree> Tree; }; #define BLAME(x) fprintf(stderr, "Error: " #x " is null (function %s, " \ "line %i)\n", \ __FUNCTION__, __LINE__) #define CHECK_NULL(x) do { if (x == nullptr) { \ BLAME(x); \ return; \ } } while(0) #define CHECK_NULL_RET(x, ret) do { if (x == nullptr) { \ BLAME(x); \ return ret; \ } } while(0) void copy_string(const std::string& str, char **ptr) { size_t size = str.size() + 1; *ptr = new char[size]; memcpy(*ptr, str.c_str(), size); } void query_transforms_list(char ***names, int *listSize) { CHECK_NULL(names); CHECK_NULL(listSize); int i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { continue; } i += tc.second.size(); } *listSize = i; *names = new char*[*listSize]; i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { continue; } if (tc.second.size() == 1) { copy_string(tc.first, *names + i); i++; } else { for (auto tfc : tc.second) { std::string fullName(tc.first); fullName += " ("; fullName += tfc.first; fullName += ")"; copy_string(fullName, *names + i); i++; } } } } void destroy_transforms_list(char **names, int listSize) { CHECK_NULL(names); for (int i = 0; i < listSize; i++) { delete[] names[i]; } delete[] names; } void query_format_converters_list(char ***inputFormats, char*** outputFormats, int *listSize) { CHECK_NULL(inputFormats); CHECK_NULL(outputFormats); CHECK_NULL(listSize); int i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { i++; } } *listSize = i; *inputFormats = new char*[*listSize]; *outputFormats = new char*[*listSize]; i = 0; for (auto tc : TransformFactory::Instance().Map()) { if (tc.first.find("->") != std::string::npos) { auto transform = tc.second.begin()->second(); copy_string(transform->InputFormat()->Id(), *inputFormats + i); copy_string(transform->OutputFormat()->Id(), *outputFormats + i); i++; } } } void destroy_format_converters_list(char **inputFormats, char** outputFormats, int listSize) { CHECK_NULL(inputFormats); CHECK_NULL(outputFormats); for (int i = 0; i < listSize; i++) { delete[] inputFormats[i]; delete[] outputFormats[i]; } delete[] inputFormats; delete[] outputFormats; } void query_transform_details(const char *name, char **description, char **inputFormat, char **outputFormat, char ***parameterNames, char ***parameterDescriptions, char ***parameterDefaultValues, int *parametersCount) { CHECK_NULL(name); CHECK_NULL(description); CHECK_NULL(parameterNames); CHECK_NULL(parameterDescriptions); CHECK_NULL(parameterDefaultValues); CHECK_NULL(parametersCount); std::string fullName(name); std::string transformName(fullName); std::string formatName; auto bracePos = fullName.find('('); if (bracePos != fullName.npos) { transformName = fullName.substr(0, bracePos - 1); formatName = fullName.substr(bracePos + 1); formatName.resize(formatName.size() - 1); } auto tit = TransformFactory::Instance().Map().find(transformName); if (tit == TransformFactory::Instance().Map().end()) { fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str()); return; } std::shared_ptr<Transform> transformInstance; if (formatName == "") { transformInstance = tit->second.begin()->second(); } else { auto tfit = tit->second.find(formatName); if (tfit == tit->second.end()) { fprintf(stderr, "Error: transform %s was not found.\n", fullName.c_str()); return; } transformInstance = tfit->second(); } copy_string(transformInstance->Description(), description); copy_string(transformInstance->InputFormat()->Id(), inputFormat); copy_string(transformInstance->OutputFormat()->Id(), outputFormat); int pCount = transformInstance->SupportedParameters().size(); *parametersCount = pCount; *parameterNames = new char*[pCount]; *parameterDescriptions = new char*[pCount]; *parameterDefaultValues = new char*[pCount]; int i = 0; for (auto prop : transformInstance->SupportedParameters()) { copy_string(prop.first, *parameterNames + i); copy_string(prop.second.Description, *parameterDescriptions + i); copy_string(prop.second.DefaultValue, *parameterDefaultValues + i); i++; } } void destroy_transform_details(char *description, char *inputFormat, char *outputFormat, char **parameterNames, char **parameterDescriptions, char **parameterDefaultValues, int parametersCount) { CHECK_NULL(description); CHECK_NULL(parameterNames); CHECK_NULL(parameterDescriptions); CHECK_NULL(parameterDefaultValues); delete[] description; delete[] inputFormat; delete[] outputFormat; for (int i = 0; i < parametersCount; i++) { delete[] parameterNames[i]; delete[] parameterDescriptions[i]; delete[] parameterDefaultValues[i]; } delete[] parameterNames; delete[] parameterDescriptions; delete[] parameterDefaultValues; } FeaturesConfiguration *setup_features_extraction( const char *const *features, int featuresCount, size_t bufferSize, int samplingRate) { CHECK_NULL_RET(features, nullptr); if (featuresCount < 0) { fprintf(stderr, "Error: featuresCount is negative (%i)\n", featuresCount); return nullptr; } if (featuresCount > MAX_FEATURES_COUNT) { fprintf(stderr, "Error: featuresCount is too big " "(%i > MAX_FEATURES_COUNT=%i)\n", featuresCount, MAX_FEATURES_COUNT); return nullptr; } std::vector<std::string> lines; for (int i = 0; i < featuresCount; i++) { if (features[i] == nullptr) { fprintf(stderr, "Error: features[%i] is null\n", i); return nullptr; } lines.push_back(features[i]); } RawFeaturesMap featmap; try { featmap = SoundFeatureExtraction::Features::Parse(lines); } catch(const ParseFeaturesException& pfe) { fprintf(stderr, "Failed to parse features. %s\n", pfe.what()); return nullptr; } auto format = std::make_shared<RawFormat16>(bufferSize, samplingRate); auto config = new FeaturesConfiguration(); config->Tree = std::make_unique<TransformTree>(format); for (auto featpair : featmap) { try { config->Tree->AddFeature(featpair.first, featpair.second); } catch(const ChainNameAlreadyExistsException& cnaee) { fprintf(stderr, "Failed to construct the transform tree. %s\n", cnaee.what()); return nullptr; } catch(const TransformNotRegisteredException& tnre) { fprintf(stderr, "Failed to construct the transform tree. %s\n", tnre.what()); return nullptr; } catch(const ChainAlreadyExistsException& caee) { fprintf(stderr, "Failed to construct the transform tree. %s\n", caee.what()); return nullptr; } catch(const IncompatibleTransformFormatException& itfe) { fprintf(stderr, "Failed to construct the transform tree. %s\n", itfe.what()); return nullptr; } } config->Tree->PrepareForExecution(); #ifdef DEBUG config->Tree->SetValidateAfterEachTransform(true); #endif return config; } FeatureExtractionResult extract_speech_features( const FeaturesConfiguration *fc, int16_t *buffer, char ***featureNames, void ***results, int **resultLengths) { CHECK_NULL_RET(fc, FEATURE_EXTRACTION_RESULT_ERROR); CHECK_NULL_RET(buffer, FEATURE_EXTRACTION_RESULT_ERROR); CHECK_NULL_RET(results, FEATURE_EXTRACTION_RESULT_ERROR); std::unordered_map<std::string, std::shared_ptr<Buffers>> retmap; try { retmap = fc->Tree->Execute(Raw16(buffer)); } catch (const std::exception& ex) { fprintf(stderr, "Caught an exception with message \"%s\".\n", ex.what()); return FEATURE_EXTRACTION_RESULT_ERROR; } *featureNames = new char*[retmap.size()]; *results = new void*[retmap.size()]; *resultLengths = new int[retmap.size()]; int i = 0; for (auto res : retmap) { copy_string(res.first, *featureNames + i); size_t sizeEach = res.second->Format()->PayloadSizeInBytes(); assert(sizeEach > 0); size_t size = sizeEach * res.second->Size(); (*resultLengths)[i] = size; (*results)[i] = new char[size]; for (int j = 0; j < static_cast<int>(res.second->Size()); j++) { memcpy(reinterpret_cast<char *>((*results)[i]) + j * sizeEach, res.second->Format()->PayloadPointer((*res.second)[j]), sizeEach); } i++; } return FEATURE_EXTRACTION_RESULT_OK; } void report_extraction_time(const FeaturesConfiguration *fc, char ***transformNames, float **values, int *length) { CHECK_NULL(fc); CHECK_NULL(transformNames); CHECK_NULL(values); CHECK_NULL(length); auto report = fc->Tree->ExecutionTimeReport(); *length = report.size(); *transformNames = new char*[*length]; *values = new float[*length]; int i = 0; for (auto pair : report) { copy_string(pair.first, *transformNames + i); (*values)[i] = pair.second; i++; } } void destroy_extraction_time_report(char **transformNames, float *values, int length) { CHECK_NULL(transformNames); CHECK_NULL(values); delete[] values; for (int i = 0; i < length; i++) { delete[] transformNames[i]; } delete[] transformNames; } void report_extraction_graph(const FeaturesConfiguration *fc, const char *fileName) { CHECK_NULL(fc); CHECK_NULL(fileName); fc->Tree->Dump(fileName); } void destroy_features_configuration(FeaturesConfiguration* fc) { CHECK_NULL(fc); delete fc; } void free_results(int featuresCount, char **featureNames, void **results, int *resultLengths) { if(featuresCount <= 0) { fprintf(stderr, "Warning: free_results() was called with featuresCount" " <= 0, skipped\n"); return; } for (int i = 0; i < featuresCount; i++) { if (featureNames != nullptr) { delete[] featureNames[i]; } if (results != nullptr) { delete[] reinterpret_cast<char*>(results[i]); } } if (featureNames != nullptr) { delete[] featureNames; } if (resultLengths != nullptr) { delete[] resultLengths; } if (results != nullptr) { delete[] results; } } void get_set_omp_transforms_max_threads_num(int *value, bool get) { static int threads_num = omp_get_max_threads(); if (get) { *value = threads_num; } else { int max = omp_get_max_threads(); if (*value > max) { fprintf(stderr, "Warning: can not set the maximal number of threads to " "%i (the limit is %i), so set to %i\n", *value, max, max); threads_num = max; } else if (*value < 1) { fprintf(stderr, "Warning: can not set the maximal number of threads to " "%i. The value remains the same (%i)\n", *value, threads_num); } else { threads_num = *value; } } } int get_omp_transforms_max_threads_num() { int res; get_set_omp_transforms_max_threads_num(&res, true); return res; } void set_omp_transforms_max_threads_num(int value) { get_set_omp_transforms_max_threads_num(&value, false); fftf_set_openmp_num_threads(get_omp_transforms_max_threads_num()); } } <|endoftext|>
<commit_before>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/directory.h" #include "include/dart_api.h" #include "platform/assert.h" #include "vm/isolate.h" #include "vm/thread.h" #include "vm/unit_test.h" namespace dart { UNIT_TEST_CASE(DirectoryCurrentNoScope) { char* current_dir = dart::bin::Directory::CurrentNoScope(); EXPECT_NOTNULL(current_dir); free(current_dir); } TEST_CASE(DirectoryCurrent) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); } TEST_CASE(DirectoryExists) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(current); EXPECT_EQ(dart::bin::Directory::EXISTS, r); } TEST_CASE(DirectorySystemTemp) { const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); } TEST_CASE(DirectorySystemTempExists) { const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(system_temp); EXPECT_EQ(dart::bin::Directory::EXISTS, r); } TEST_CASE(DirectoryCreateTemp) { const char* kTempPrefix = "test_prefix"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const char* temp_dir = dart::bin::Directory::CreateTemp(kTempPrefix); EXPECT_NOTNULL(temp_dir); // Make sure temp_dir contains test_prefix. EXPECT_NOTNULL(strstr(temp_dir, kTempPrefix)); // Cleanup. EXPECT(dart::bin::Directory::Delete(temp_dir, false)); } TEST_CASE(DirectorySetCurrent) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); EXPECT(dart::bin::Directory::SetCurrent(system_temp)); const char* new_current = dart::bin::Directory::Current(); EXPECT_NOTNULL(new_current); EXPECT_NOTNULL(strstr(new_current, system_temp)); EXPECT(dart::bin::Directory::SetCurrent(current)); } TEST_CASE(DirectoryCreateDelete) { const char* kTempDirName = "test_name"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const intptr_t name_len = snprintf(NULL, 0, "%s/%s", system_temp, kTempDirName); ASSERT(name_len > 0); char* name = new char[name_len + 1]; snprintf(name, name_len + 1, "%s/%s", system_temp, kTempDirName); // Make a directory. EXPECT(dart::bin::Directory::Create(name)); // Make sure it exists. dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); // Cleanup. EXPECT(dart::bin::Directory::Delete(name, false)); delete[] name; } TEST_CASE(DirectoryRename) { const char* kTempDirName = "test_name"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const intptr_t name_len = snprintf(NULL, 0, "%s/%s", system_temp, kTempDirName); ASSERT(name_len > 0); char* name = new char[name_len + 1]; snprintf(name, name_len + 1, "%s/%s", system_temp, kTempDirName); // Make a directory. EXPECT(dart::bin::Directory::Create(name)); // Make sure it exists. dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); const intptr_t new_name_len = snprintf(NULL, 0, "%s/%snewname", system_temp, kTempDirName); ASSERT(new_name_len > 0); char* new_name = new char[new_name_len + 1]; snprintf(new_name, new_name_len + 1, "%s/%snewname", system_temp, kTempDirName); EXPECT(dart::bin::Directory::Rename(name, new_name)); r = dart::bin::Directory::Exists(new_name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::DOES_NOT_EXIST, r); EXPECT(dart::bin::Directory::Delete(new_name, false)); delete[] name; delete[] new_name; } } // namespace dart <commit_msg>Use different directory names in directory tests<commit_after>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/directory.h" #include "include/dart_api.h" #include "platform/assert.h" #include "vm/isolate.h" #include "vm/thread.h" #include "vm/unit_test.h" namespace dart { UNIT_TEST_CASE(DirectoryCurrentNoScope) { char* current_dir = dart::bin::Directory::CurrentNoScope(); EXPECT_NOTNULL(current_dir); free(current_dir); } TEST_CASE(DirectoryCurrent) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); } TEST_CASE(DirectoryExists) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(current); EXPECT_EQ(dart::bin::Directory::EXISTS, r); } TEST_CASE(DirectorySystemTemp) { const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); } TEST_CASE(DirectorySystemTempExists) { const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(system_temp); EXPECT_EQ(dart::bin::Directory::EXISTS, r); } TEST_CASE(DirectoryCreateTemp) { const char* kTempPrefix = "test_prefix"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const char* temp_dir = dart::bin::Directory::CreateTemp(kTempPrefix); EXPECT_NOTNULL(temp_dir); // Make sure temp_dir contains test_prefix. EXPECT_NOTNULL(strstr(temp_dir, kTempPrefix)); // Cleanup. EXPECT(dart::bin::Directory::Delete(temp_dir, false)); } TEST_CASE(DirectorySetCurrent) { const char* current = dart::bin::Directory::Current(); EXPECT_NOTNULL(current); const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); EXPECT(dart::bin::Directory::SetCurrent(system_temp)); const char* new_current = dart::bin::Directory::Current(); EXPECT_NOTNULL(new_current); EXPECT_NOTNULL(strstr(new_current, system_temp)); EXPECT(dart::bin::Directory::SetCurrent(current)); } TEST_CASE(DirectoryCreateDelete) { const char* kTempDirName = "create_delete_test_name"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const intptr_t name_len = snprintf(NULL, 0, "%s/%s", system_temp, kTempDirName); ASSERT(name_len > 0); char* name = new char[name_len + 1]; snprintf(name, name_len + 1, "%s/%s", system_temp, kTempDirName); // Make a directory. EXPECT(dart::bin::Directory::Create(name)); // Make sure it exists. dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); // Cleanup. EXPECT(dart::bin::Directory::Delete(name, false)); delete[] name; } TEST_CASE(DirectoryRename) { const char* kTempDirName = "rename_test_name"; const char* system_temp = dart::bin::Directory::SystemTemp(); EXPECT_NOTNULL(system_temp); const intptr_t name_len = snprintf(NULL, 0, "%s/%s", system_temp, kTempDirName); ASSERT(name_len > 0); char* name = new char[name_len + 1]; snprintf(name, name_len + 1, "%s/%s", system_temp, kTempDirName); // Make a directory. EXPECT(dart::bin::Directory::Create(name)); // Make sure it exists. dart::bin::Directory::ExistsResult r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); const intptr_t new_name_len = snprintf(NULL, 0, "%s/%snewname", system_temp, kTempDirName); ASSERT(new_name_len > 0); char* new_name = new char[new_name_len + 1]; snprintf(new_name, new_name_len + 1, "%s/%snewname", system_temp, kTempDirName); EXPECT(dart::bin::Directory::Rename(name, new_name)); r = dart::bin::Directory::Exists(new_name); EXPECT_EQ(dart::bin::Directory::EXISTS, r); r = dart::bin::Directory::Exists(name); EXPECT_EQ(dart::bin::Directory::DOES_NOT_EXIST, r); EXPECT(dart::bin::Directory::Delete(new_name, false)); delete[] name; delete[] new_name; } } // namespace dart <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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_SCALE_DENOMINATOR_HPP #define MAPNIK_SCALE_DENOMINATOR_HPP // mapnik #include <mapnik/config.hpp> namespace mapnik { class Map; MAPNIK_DECL double scale_denominator(double map_scale, bool geographic); } #endif // MAPNIK_SCALE_DENOMINATOR_HPP <commit_msg>+ no need to fwd decl mapnik::Map<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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_SCALE_DENOMINATOR_HPP #define MAPNIK_SCALE_DENOMINATOR_HPP // mapnik #include <mapnik/config.hpp> namespace mapnik { MAPNIK_DECL double scale_denominator(double map_scale, bool geographic); } #endif // MAPNIK_SCALE_DENOMINATOR_HPP <|endoftext|>
<commit_before>/********************************************************************* * * Copyright (C) 2008, Simon Kagstrom * * Filename: exceptions.hh * Author: Simon Kagstrom <simon.kagstrom@gmail.com> * Description: Impl. of exception builtins * * $Id:$ * ********************************************************************/ #ifndef __EXCEPTIONS_HH__ #define __EXCEPTIONS_HH__ #include <builtins.hh> #include <emit.hh> extern Instruction *tryInstruction; class ExceptionBuiltinBase : public Builtin { public: bool pass1(Instruction *insn) { insn->setBranchTarget(); return true; } int fillDestinations(int *p) { return this->addToRegisterUsage(R_EAR, p) + this->addToRegisterUsage(R_ECB, p); }; }; class ExcetpionBuiltinTry : ExceptionBuiltinBase { public: int fillSources(int *p) { return this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p); }; bool pass2(Instruction *insn) { emit->bc_pushregister(R_A0); emit->bc_popregister(R_ECB); emit->bc_pushregister(R_A1); emit->bc_popregister(R_EAR); tryInstruction = insn; return true; } }; #endif /* !__EXCEPTIONS_HH__ */ <commit_msg>Actually implemented now, seems to work<commit_after>/********************************************************************* * * Copyright (C) 2008, Simon Kagstrom * * Filename: exceptions.hh * Author: Simon Kagstrom <simon.kagstrom@gmail.com> * Description: Impl. of exception builtins * * $Id:$ * ********************************************************************/ #ifndef __EXCEPTIONS_HH__ #define __EXCEPTIONS_HH__ #include <javamethod.hh> #include <controller.hh> #include <builtins.hh> #include <emit.hh> extern Instruction *tryInstruction; class ExceptionBuiltinBase : public Builtin { public: ExceptionBuiltinBase(const char *name) : Builtin(name) { } bool pass1(Instruction *insn) { insn->setBranchTarget(); return true; } int fillDestinations(int *p) { return this->addToRegisterUsage(R_EAR, p) + this->addToRegisterUsage(R_ECB, p); }; }; class ExceptionBuiltinTry : public ExceptionBuiltinBase { public: ExceptionBuiltinTry() : ExceptionBuiltinBase("__NOPH_try") { } int fillSources(int *p) { return this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p); }; bool pass2(Instruction *insn) { emit->bc_pushregister(R_A0); emit->bc_popregister(R_ECB); emit->bc_pushregister(R_A1); emit->bc_popregister(R_EAR); tryInstruction = insn; return true; } }; class ExceptionBuiltinCatch : public ExceptionBuiltinBase { public: ExceptionBuiltinCatch() : ExceptionBuiltinBase("__NOPH_catch") { } int fillSources(int *p) { return this->addToRegisterUsage(R_SP, p); /* ECB, EAR in try */ }; bool pass2(Instruction *insn) { JavaMethod *method = controller->getMethodByAddress(insn->getAddress()); uint32_t start = tryInstruction->getAddress(); uint32_t end = insn->getAddress(); const char *handler = method->addExceptionHandler(start, end); emit->bc_generic(".catch all from L_%x to L_%x using %s\n", start, end, handler); return true; } }; #endif /* !__EXCEPTIONS_HH__ */ <|endoftext|>
<commit_before>#include "ReedSolomonEncoder.h" #include <zxing/Exception.h> #include <stdio.h> #include <string.h> namespace zxing { ReedSolomonEncoder::ReedSolomonEncoder(Ref<GenericGF> field) : field_(field), cachedGenerators_() { ArrayRef<int> arrayRef(1); //will this work? arrayRef[0] = 1; Ref< GenericGFPoly > tmpGeneratorRef(new GenericGFPoly(field, arrayRef)); cachedGenerators_.push_back(tmpGeneratorRef); } Ref<GenericGFPoly> ReedSolomonEncoder::buildGenerator(int degree) { if (degree >= cachedGenerators_.size()) { Ref<GenericGFPoly> lastGenerator = cachedGenerators_.at(cachedGenerators_.size() - 1); for (int d = cachedGenerators_.size(); d <= degree; d++) { ArrayRef<int> arrayRef(2); //will this work? arrayRef[0] = 1; arrayRef[1] = field_->exp(d - 1 + field_->getGeneratorBase()); Ref<GenericGFPoly> tmpGFRef(new GenericGFPoly(field_, arrayRef)); Ref<GenericGFPoly> nextGenerator = (*lastGenerator).multiply(tmpGFRef); cachedGenerators_.push_back(nextGenerator); lastGenerator = nextGenerator; } } return cachedGenerators_.at(degree); // ??? wont this through exception? } void ReedSolomonEncoder::encode(std::vector<byte> &toEncode, int ecBytes) { if (ecBytes == 0) { throw Exception("No error correction bytes"); } int dataBytes = toEncode.size();// - ecBytes; toEncode.resize(toEncode.size()+ecBytes); if (dataBytes <= 0) { throw Exception("No data bytes provided"); } Ref<GenericGFPoly> generator = buildGenerator(ecBytes); ArrayRef<int> infoCoefficients(dataBytes); //to-do optimize the following loop for(int i=0; i< dataBytes; i++) infoCoefficients[i] = toEncode[i]; Ref<GenericGFPoly> info(new GenericGFPoly(field_, infoCoefficients)); info = info->multiplyByMonomial(ecBytes, 1); Ref<GenericGFPoly> remainder = info->divide(generator)[1]; ArrayRef<int> coefficients = remainder->getCoefficients(); int numZeroCoefficients = ecBytes - coefficients->size(); for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } for (size_t i = 0; i < coefficients->size(); i++) toEncode[dataBytes + numZeroCoefficients + i] = coefficients[i]; } } <commit_msg>Fixed warnings in ReedSolomonEncoder.cpp<commit_after>#include "ReedSolomonEncoder.h" #include <zxing/Exception.h> #include <stdio.h> #include <string.h> namespace zxing { ReedSolomonEncoder::ReedSolomonEncoder(Ref<GenericGF> field) : field_(field), cachedGenerators_() { ArrayRef<int> arrayRef(1); //will this work? arrayRef[0] = 1; Ref< GenericGFPoly > tmpGeneratorRef(new GenericGFPoly(field, arrayRef)); cachedGenerators_.push_back(tmpGeneratorRef); } Ref<GenericGFPoly> ReedSolomonEncoder::buildGenerator(int degree) { if (degree >= int(cachedGenerators_.size())) { Ref<GenericGFPoly> lastGenerator = cachedGenerators_.at(cachedGenerators_.size() - 1); for (int d = int(cachedGenerators_.size()); d <= degree; d++) { ArrayRef<int> arrayRef(2); //will this work? arrayRef[0] = 1; arrayRef[1] = field_->exp(d - 1 + field_->getGeneratorBase()); Ref<GenericGFPoly> tmpGFRef(new GenericGFPoly(field_, arrayRef)); Ref<GenericGFPoly> nextGenerator = (*lastGenerator).multiply(tmpGFRef); cachedGenerators_.push_back(nextGenerator); lastGenerator = nextGenerator; } } // ??? wont this through exception? // No the elements up to index degree are added above return cachedGenerators_.at(size_t(degree)); } void ReedSolomonEncoder::encode(std::vector<byte> &toEncode, int ecBytes) { if (ecBytes == 0) { throw Exception("No error correction bytes"); } int dataBytes = int(toEncode.size());// - ecBytes; toEncode.resize(toEncode.size() + size_t(ecBytes)); if (dataBytes <= 0) { throw Exception("No data bytes provided"); } Ref<GenericGFPoly> generator = buildGenerator(ecBytes); ArrayRef<int> infoCoefficients(dataBytes); //to-do optimize the following loop for(int i=0; i< dataBytes; i++) infoCoefficients[i] = toEncode[size_t(i)]; Ref<GenericGFPoly> info(new GenericGFPoly(field_, infoCoefficients)); info = info->multiplyByMonomial(ecBytes, 1); Ref<GenericGFPoly> remainder = info->divide(generator)[1]; ArrayRef<int> coefficients = remainder->getCoefficients(); int numZeroCoefficients = ecBytes - coefficients->size(); for (int i = 0; i < numZeroCoefficients; i++) { toEncode[size_t(dataBytes + i)] = 0; } for (int i = 0; i < coefficients->size(); i++) toEncode[size_t(dataBytes + numZeroCoefficients + i)] = byte(coefficients[int(i)]); } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "base/message_loop.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/l10n_util.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/resource_bundle.h" #include "chrome/renderer/render_process.h" #include "chrome/test/injection_test_dll.h" #include "sandbox/src/sandbox.h" #include "chromium_strings.h" #include "generated_resources.h" // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); title += L" renderer"; // makes attaching to process easier MessageBox(NULL, L"renderer starting...", title.c_str(), MB_OK | MB_SETFOREGROUND); } } // mainline routine for running as the Rendererer process int RendererMain(CommandLine &parsed_command_line, int show_command, sandbox::TargetServices* target_services) { StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); // The main thread of the renderer services IO. MessageLoopForIO main_message_loop; std::wstring app_name = chrome::kBrowserAppName; PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str()); CoInitialize(NULL); DLOG(INFO) << "Started renderer with " << parsed_command_line.command_line_string(); HMODULE sandbox_test_module = NULL; bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); if (target_services && !no_sandbox) { // The command line might specify a test dll to load. if (parsed_command_line.HasSwitch(switches::kTestSandbox)) { std::wstring test_dll_name = parsed_command_line.GetSwitchValue(switches::kTestSandbox); sandbox_test_module = LoadLibrary(test_dll_name.c_str()); DCHECK(sandbox_test_module); } } HandleRendererErrorTestParameters(parsed_command_line); std::wstring channel_name = parsed_command_line.GetSwitchValue(switches::kProcessChannelID); if (RenderProcess::GlobalInit(channel_name)) { bool run_loop = true; if (!no_sandbox) { if (target_services) { target_services->LowerToken(); } else { run_loop = false; } } if (sandbox_test_module) { RunRendererTests run_security_tests = reinterpret_cast<RunRendererTests>(GetProcAddress(sandbox_test_module, kRenderTestCall)); DCHECK(run_security_tests); if (run_security_tests) { int test_count = 0; DLOG(INFO) << "Running renderer security tests"; BOOL result = run_security_tests(&test_count); DCHECK(result) << "Test number " << test_count << " has failed."; // If we are in release mode, debug or crash the process. if (!result) __debugbreak(); } } startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { // Load the accelerator table from the browser executable and tell the // message loop to use it when translating messages. MessageLoop::current()->Run(); } } RenderProcess::GlobalCleanup(); CoUninitialize(); return 0; } <commit_msg>Don't crash on chrome.exe --type=renderer. Don't try to GlobalCleanup() if GlobalInit() wasn't successful. Review URL: http://codereview.chromium.org/10247<commit_after>// Copyright (c) 2006-2008 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 "base/message_loop.h" #include "base/path_service.h" #include "base/platform_thread.h" #include "base/string_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/l10n_util.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/resource_bundle.h" #include "chrome/renderer/render_process.h" #include "chrome/test/injection_test_dll.h" #include "sandbox/src/sandbox.h" #include "chromium_strings.h" #include "generated_resources.h" // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME); title += L" renderer"; // makes attaching to process easier MessageBox(NULL, L"renderer starting...", title.c_str(), MB_OK | MB_SETFOREGROUND); } } // mainline routine for running as the Rendererer process int RendererMain(CommandLine &parsed_command_line, int show_command, sandbox::TargetServices* target_services) { StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); // The main thread of the renderer services IO. MessageLoopForIO main_message_loop; std::wstring app_name = chrome::kBrowserAppName; PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str()); CoInitialize(NULL); DLOG(INFO) << "Started renderer with " << parsed_command_line.command_line_string(); HMODULE sandbox_test_module = NULL; bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); if (target_services && !no_sandbox) { // The command line might specify a test dll to load. if (parsed_command_line.HasSwitch(switches::kTestSandbox)) { std::wstring test_dll_name = parsed_command_line.GetSwitchValue(switches::kTestSandbox); sandbox_test_module = LoadLibrary(test_dll_name.c_str()); DCHECK(sandbox_test_module); } } HandleRendererErrorTestParameters(parsed_command_line); std::wstring channel_name = parsed_command_line.GetSwitchValue(switches::kProcessChannelID); if (RenderProcess::GlobalInit(channel_name)) { bool run_loop = true; if (!no_sandbox) { if (target_services) { target_services->LowerToken(); } else { run_loop = false; } } if (sandbox_test_module) { RunRendererTests run_security_tests = reinterpret_cast<RunRendererTests>(GetProcAddress(sandbox_test_module, kRenderTestCall)); DCHECK(run_security_tests); if (run_security_tests) { int test_count = 0; DLOG(INFO) << "Running renderer security tests"; BOOL result = run_security_tests(&test_count); DCHECK(result) << "Test number " << test_count << " has failed."; // If we are in release mode, debug or crash the process. if (!result) __debugbreak(); } } startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { // Load the accelerator table from the browser executable and tell the // message loop to use it when translating messages. MessageLoop::current()->Run(); } RenderProcess::GlobalCleanup(); } CoUninitialize(); return 0; } <|endoftext|>
<commit_before>#pragma once #ifndef NIFTY_GRAPH_SIMPLE_GRAPH_HXX #define NIFTY_GRAPH_SIMPLE_GRAPH_HXX #include <vector> #include <boost/version.hpp> // for strange reason travis does not find the boost flat set #ifdef WITHIN_TRAVIS #include <set> #define __setimpl std::set #else #include <boost/container/flat_set.hpp> #define __setimpl boost::container::flat_set #endif #include <boost/iterator/counting_iterator.hpp> #include "nifty/container/flat_set.hxx" #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/undirected_graph_base.hxx" #include "nifty/graph/detail/adjacency.hxx" #include "nifty/graph/graph_tags.hxx" namespace nifty{ namespace graph{ namespace detail_graph{ template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > struct UndirectedGraphTypeHelper{ typedef EDGE_INTERANL_TYPE EdgeInternalType; typedef NODE_INTERNAL_TYPE NodeInteralType; typedef detail_graph::UndirectedAdjacency<int64_t,int64_t,NodeInteralType,EdgeInternalType> NodeAdjacency; //typedef std::set<NodeAdjacency > NodeStorage; typedef nifty::container::FlatSet <NodeAdjacency> NodeStorage; typedef std::pair<NodeInteralType,NodeInteralType> EdgeStorage; typedef boost::counting_iterator<int64_t> NodeIter; typedef boost::counting_iterator<int64_t> EdgeIter; typedef typename NodeStorage::const_iterator AdjacencyIter; }; class SimpleGraphNodeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; class SimpleGraphEdgeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; }; template<class EDGE_INTERANL_TYPE = int64_t, class NODE_INTERNAL_TYPE = int64_t> class UndirectedGraph : public UndirectedGraphBase< UndirectedGraph<EDGE_INTERANL_TYPE,NODE_INTERNAL_TYPE>, detail_graph::SimpleGraphNodeIter, detail_graph::SimpleGraphEdgeIter, typename detail_graph::UndirectedGraphTypeHelper<EDGE_INTERANL_TYPE,NODE_INTERNAL_TYPE>::AdjacencyIter > { protected: typedef EDGE_INTERANL_TYPE EdgeInternalType; typedef NODE_INTERNAL_TYPE NodeInteralType; typedef detail_graph::UndirectedAdjacency<int64_t,int64_t,NodeInteralType,EdgeInternalType> NodeAdjacency; typedef nifty::container::FlatSet<NodeAdjacency> NodeStorage; typedef std::pair<EdgeInternalType,EdgeInternalType> EdgeStorage; public: typedef detail_graph::SimpleGraphNodeIter NodeIter; typedef boost::counting_iterator<int64_t> EdgeIter; typedef typename NodeStorage::const_iterator AdjacencyIter; typedef ContiguousTag EdgeIdTag; typedef ContiguousTag NodeIdTag; typedef SortedTag EdgeIdOrderTag; typedef SortedTag NodeIdOrderTag; // constructors UndirectedGraph(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0; void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0); int64_t insertEdge(const int64_t u, const int64_t v); // MUST IMPL INTERFACE int64_t u(const int64_t e)const; int64_t v(const int64_t e)const; int64_t findEdge(const int64_t u, const int64_t v)const; int64_t nodeIdUpperBound() const; int64_t edgeIdUpperBound() const; uint64_t numberOfEdges() const; uint64_t numberOfNodes() const; NodeIter nodesBegin()const; NodeIter nodesEnd()const; EdgeIter edgesBegin()const; EdgeIter edgesEnd()const; AdjacencyIter adjacencyBegin(const int64_t node)const; } AdjacencyIter adjacencyEnd(const int64_t node)const; AdjacencyIter adjacencyOutBegin(const int64_t node)const; // optional (with default impl in base) std::pair<int64_t,int64_t> uv(const int64_t e)const; template<class F> void forEachEdge(F && f)const; std::vector<NodeStorage> nodes_; std::vector<EdgeStorage> edges_; }; template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: UndirectedGraph(const uint64_t numberOfNodes , const uint64_t reserveNumberOfEdges ) : nodes_(numberOfNodes), edges_() { edges_.reserve(reserveNumberOfEdges); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > void UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: assign(const uint64_t numberOfNodes , const uint64_t reserveNumberOfEdges ){ nodes_.clear(); edges_.clear(); nodes_.resize(numberOfNodes); edges_.reserve(reserveNumberOfEdges); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: insertEdge(const int64_t u, const int64_t v){ const auto fres = nodes_[u].find(NodeAdjacency(v)); if(fres != nodes_[u].end()) return fres->edge(); else{ const auto uu = std::min(u,v); const auto vv = std::max(u,v); auto e = EdgeStorage(uu, vv); auto ei = edges_.size(); edges_.push_back(e); nodes_[u].insert(NodeAdjacency(v,ei)); nodes_[v].insert(NodeAdjacency(u,ei)); return ei; } } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: u(const int64_t e)const{ NIFTY_ASSERT_OP(e,<,numberOfEdges()); return edges_[e].first; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: v(const int64_t e)const{ NIFTY_ASSERT_OP(e,<,numberOfEdges()); return edges_[e].second; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: findEdge(const int64_t u, const int64_t v)const{ NIFTY_ASSERT_OP(u,<,numberOfNodes()); NIFTY_ASSERT_OP(v,<,numberOfNodes()); const auto fres = nodes_[u].find(NodeAdjacency(v)); if(fres != nodes_[u].end()) return fres->edge(); else return -1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodeIdUpperBound() const{ return numberOfNodes() == 0 ? 0 : numberOfNodes()-1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgeIdUpperBound() const{ return numberOfEdges() == 0 ? 0 : numberOfEdges()-1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > uint64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: numberOfEdges() const { return edges_.size(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > uint64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: numberOfNodes() const{ return nodes_.size(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::NodeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodesBegin()const{ return NodeIter(0); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::NodeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodesEnd()const{ return NodeIter(this->numberOfNodes()); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::EdgeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgesBegin()const{ return EdgeIter(0); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::EdgeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgesEnd()const{ return EdgeIter(this->numberOfEdges()); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyBegin(const int64_t node)const{ NIFTY_ASSERT_OP(node,<,numberOfNodes()); return nodes_[node].begin(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyEnd(const int64_t node)const{ NIFTY_ASSERT_OP(node,<,numberOfNodes()); return nodes_[node].end(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyOutBegin(const int64_t node)const{ return adjacencyBegin(node); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > std::pair<int64_t,int64_t> UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: uv(const int64_t e)const{ const auto _uv = edges_[e]; return std::pair<int64_t,int64_t>(_uv.first, _uv.second); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > template<class F> void UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: forEachEdge(F && f)const{ for(uint64_t edge=0; edge< numberOfEdges(); ++edge){ f(edge); } } } // namespace nifty::graph } // namespace nifty #endif // NIFTY_GRAPH_SIMPLE_GRAPH_HXX <commit_msg>changed libhdf5-dev to the serial version<commit_after>#pragma once #ifndef NIFTY_GRAPH_SIMPLE_GRAPH_HXX #define NIFTY_GRAPH_SIMPLE_GRAPH_HXX #include <vector> #include <boost/version.hpp> // for strange reason travis does not find the boost flat set #ifdef WITHIN_TRAVIS #include <set> #define __setimpl std::set #else #include <boost/container/flat_set.hpp> #define __setimpl boost::container::flat_set #endif #include <boost/iterator/counting_iterator.hpp> #include "nifty/container/flat_set.hxx" #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/undirected_graph_base.hxx" #include "nifty/graph/detail/adjacency.hxx" #include "nifty/graph/graph_tags.hxx" namespace nifty{ namespace graph{ namespace detail_graph{ template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > struct UndirectedGraphTypeHelper{ typedef EDGE_INTERANL_TYPE EdgeInternalType; typedef NODE_INTERNAL_TYPE NodeInteralType; typedef detail_graph::UndirectedAdjacency<int64_t,int64_t,NodeInteralType,EdgeInternalType> NodeAdjacency; //typedef std::set<NodeAdjacency > NodeStorage; typedef nifty::container::FlatSet <NodeAdjacency> NodeStorage; typedef std::pair<NodeInteralType,NodeInteralType> EdgeStorage; typedef boost::counting_iterator<int64_t> NodeIter; typedef boost::counting_iterator<int64_t> EdgeIter; typedef typename NodeStorage::const_iterator AdjacencyIter; }; class SimpleGraphNodeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; class SimpleGraphEdgeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; }; template<class EDGE_INTERANL_TYPE = int64_t, class NODE_INTERNAL_TYPE = int64_t> class UndirectedGraph : public UndirectedGraphBase< UndirectedGraph<EDGE_INTERANL_TYPE,NODE_INTERNAL_TYPE>, detail_graph::SimpleGraphNodeIter, detail_graph::SimpleGraphEdgeIter, typename detail_graph::UndirectedGraphTypeHelper<EDGE_INTERANL_TYPE,NODE_INTERNAL_TYPE>::AdjacencyIter > { protected: typedef EDGE_INTERANL_TYPE EdgeInternalType; typedef NODE_INTERNAL_TYPE NodeInteralType; typedef detail_graph::UndirectedAdjacency<int64_t,int64_t,NodeInteralType,EdgeInternalType> NodeAdjacency; typedef nifty::container::FlatSet<NodeAdjacency> NodeStorage; typedef std::pair<EdgeInternalType,EdgeInternalType> EdgeStorage; public: typedef detail_graph::SimpleGraphNodeIter NodeIter; typedef boost::counting_iterator<int64_t> EdgeIter; typedef typename NodeStorage::const_iterator AdjacencyIter; typedef ContiguousTag EdgeIdTag; typedef ContiguousTag NodeIdTag; typedef SortedTag EdgeIdOrderTag; typedef SortedTag NodeIdOrderTag; // constructors UndirectedGraph(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0); void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0); int64_t insertEdge(const int64_t u, const int64_t v); // MUST IMPL INTERFACE int64_t u(const int64_t e)const; int64_t v(const int64_t e)const; int64_t findEdge(const int64_t u, const int64_t v)const; int64_t nodeIdUpperBound() const; int64_t edgeIdUpperBound() const; uint64_t numberOfEdges() const; uint64_t numberOfNodes() const; NodeIter nodesBegin()const; NodeIter nodesEnd()const; EdgeIter edgesBegin()const; EdgeIter edgesEnd()const; AdjacencyIter adjacencyBegin(const int64_t node)const; AdjacencyIter adjacencyEnd(const int64_t node)const; AdjacencyIter adjacencyOutBegin(const int64_t node)const; // optional (with default impl in base) std::pair<int64_t,int64_t> uv(const int64_t e)const; template<class F> void forEachEdge(F && f)const; std::vector<NodeStorage> nodes_; std::vector<EdgeStorage> edges_; }; template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: UndirectedGraph(const uint64_t numberOfNodes , const uint64_t reserveNumberOfEdges ) : nodes_(numberOfNodes), edges_() { edges_.reserve(reserveNumberOfEdges); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > void UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: assign(const uint64_t numberOfNodes , const uint64_t reserveNumberOfEdges ){ nodes_.clear(); edges_.clear(); nodes_.resize(numberOfNodes); edges_.reserve(reserveNumberOfEdges); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: insertEdge(const int64_t u, const int64_t v){ const auto fres = nodes_[u].find(NodeAdjacency(v)); if(fres != nodes_[u].end()) return fres->edge(); else{ const auto uu = std::min(u,v); const auto vv = std::max(u,v); auto e = EdgeStorage(uu, vv); auto ei = edges_.size(); edges_.push_back(e); nodes_[u].insert(NodeAdjacency(v,ei)); nodes_[v].insert(NodeAdjacency(u,ei)); return ei; } } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: u(const int64_t e)const{ NIFTY_ASSERT_OP(e,<,numberOfEdges()); return edges_[e].first; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: v(const int64_t e)const{ NIFTY_ASSERT_OP(e,<,numberOfEdges()); return edges_[e].second; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: findEdge(const int64_t u, const int64_t v)const{ NIFTY_ASSERT_OP(u,<,numberOfNodes()); NIFTY_ASSERT_OP(v,<,numberOfNodes()); const auto fres = nodes_[u].find(NodeAdjacency(v)); if(fres != nodes_[u].end()) return fres->edge(); else return -1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodeIdUpperBound() const{ return numberOfNodes() == 0 ? 0 : numberOfNodes()-1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > int64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgeIdUpperBound() const{ return numberOfEdges() == 0 ? 0 : numberOfEdges()-1; } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > uint64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: numberOfEdges() const { return edges_.size(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > uint64_t UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: numberOfNodes() const{ return nodes_.size(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::NodeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodesBegin()const{ return NodeIter(0); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::NodeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: nodesEnd()const{ return NodeIter(this->numberOfNodes()); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::EdgeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgesBegin()const{ return EdgeIter(0); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::EdgeIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: edgesEnd()const{ return EdgeIter(this->numberOfEdges()); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyBegin(const int64_t node)const{ NIFTY_ASSERT_OP(node,<,numberOfNodes()); return nodes_[node].begin(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyEnd(const int64_t node)const{ NIFTY_ASSERT_OP(node,<,numberOfNodes()); return nodes_[node].end(); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > typename UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>::AdjacencyIter UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: adjacencyOutBegin(const int64_t node)const{ return adjacencyBegin(node); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > std::pair<int64_t,int64_t> UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: uv(const int64_t e)const{ const auto _uv = edges_[e]; return std::pair<int64_t,int64_t>(_uv.first, _uv.second); } template<class EDGE_INTERANL_TYPE, class NODE_INTERNAL_TYPE > template<class F> void UndirectedGraph<EDGE_INTERANL_TYPE, NODE_INTERNAL_TYPE>:: forEachEdge(F && f)const{ for(uint64_t edge=0; edge< numberOfEdges(); ++edge){ f(edge); } } } // namespace nifty::graph } // namespace nifty #endif // NIFTY_GRAPH_SIMPLE_GRAPH_HXX <|endoftext|>
<commit_before><commit_msg>coverity#708671 Uninitialized scalar field<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:08:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <svx/sdr/contact/objectcontactofpageview.hxx> #include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx> #include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include "svdomedia.hxx" #include "svdpagv.hxx" #include <vcl/outdev.hxx> #include <vcl/window.hxx> #include <avmedia/mediaitem.hxx> #include "sdrmediawindow.hxx" namespace sdr { namespace contact { // ---------------------------------- // - ViewObjectContactOfSdrMediaObj - // ---------------------------------- ViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact, ViewContact& rViewContact, const ::avmedia::MediaItem& rMediaItem ) : ViewObjectContact( rObjectContact, rViewContact ), mpMediaWindow( NULL ) { Window* pWindow = getWindow(); if( pWindow ) { mpMediaWindow = new SdrMediaWindow( pWindow, *this ); executeMediaItem( rMediaItem ); mpMediaWindow->show(); } } // ------------------------------------------------------------------------------ ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj() { DBG_ASSERT( !mpMediaWindow, "ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL" ); } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::PrepareDelete() { ViewObjectContact::PrepareDelete(); delete mpMediaWindow; mpMediaWindow = NULL; } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo) { SdrObject* pObj = GetViewContact().TryToGetSdrObject(); ViewObjectContact::PaintObject( rDisplayInfo ); if( pObj ) { Rectangle aPaintRect( pObj->GetCurrentBoundRect() ); OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice(); sal_Int32 nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() ); bool bWasPainted = false; aPaintRect.Left() += nOffset; aPaintRect.Top() += nOffset; aPaintRect.Right() -= nOffset; aPaintRect.Bottom() -= nOffset; if( !mpMediaWindow ) { OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice(); if( pOutDev && ( aPaintRect.Left() < aPaintRect.Right() && aPaintRect.Top() < aPaintRect.Bottom() ) ) { const Color aBackgroundColor( 67, 67, 67 ); pOutDev->SetLineColor( aBackgroundColor ); pOutDev->SetFillColor( aBackgroundColor ); pOutDev->DrawRect( aPaintRect ); if( pObj->ISA( SdrMediaObj ) ) { const Graphic& rGraphic = static_cast< SdrMediaObj* >( pObj )->getGraphic(); if( rGraphic.GetType() != GRAPHIC_NONE ) { rGraphic.Draw( pOutDev, aPaintRect.TopLeft(), aPaintRect.GetSize() ); } } bWasPainted = true; } } else { const Rectangle aPaintRectPixel( pOutDev->LogicToPixel( aPaintRect.TopLeft() ), pOutDev->LogicToPixel( aPaintRect.GetSize() ) ); mpMediaWindow->setPosSize( aPaintRectPixel ); Window* pWindow = mpMediaWindow->getWindow(); if( pWindow ) pWindow->Invalidate(); bWasPainted = true; } if( bWasPainted ) { mbIsPainted = sal_True; mbIsInvalidated = sal_False; maPaintedRectangle = pObj->GetCurrentBoundRect(); } } } // ------------------------------------------------------------------------------ Window* ViewObjectContactOfSdrMediaObj::getWindow() const { ObjectContactOfPageView* pOC = dynamic_cast< ObjectContactOfPageView* >( &GetObjectContact() ); if( pOC) { OutputDevice& rOutDev = pOC->GetPageViewWindow().GetOutputDevice(); return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL ); } return NULL; } // ------------------------------------------------------------------------------ bool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const { return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() ); } // ------------------------------------------------------------------------------ Size ViewObjectContactOfSdrMediaObj::getPreferredSize() const { Size aRet; if( mpMediaWindow ) aRet = mpMediaWindow->getPreferredSize(); return aRet; } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const { if( mpMediaWindow ) mpMediaWindow->updateMediaItem( rItem ); } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem ) { if( mpMediaWindow ) { ::avmedia::MediaItem aUpdatedItem; mpMediaWindow->executeMediaItem( rItem ); // query new properties after trying to set the new properties updateMediaItem( aUpdatedItem ); static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem ); } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.7.218); FILE MERGED 2006/02/21 16:41:12 aw 1.7.218.1: #i55991# Adaptions to warning free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:29:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <svx/sdr/contact/objectcontactofpageview.hxx> #include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx> #include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include "svdomedia.hxx" #include "svdpagv.hxx" #include <vcl/outdev.hxx> #include <vcl/window.hxx> #include <avmedia/mediaitem.hxx> #include "sdrmediawindow.hxx" namespace sdr { namespace contact { // ---------------------------------- // - ViewObjectContactOfSdrMediaObj - // ---------------------------------- ViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact, ViewContact& rViewContact, const ::avmedia::MediaItem& rMediaItem ) : ViewObjectContact( rObjectContact, rViewContact ), mpMediaWindow( NULL ) { Window* pWindow = getWindow(); if( pWindow ) { mpMediaWindow = new SdrMediaWindow( pWindow, *this ); executeMediaItem( rMediaItem ); mpMediaWindow->show(); } } // ------------------------------------------------------------------------------ ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj() { DBG_ASSERT( !mpMediaWindow, "ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL" ); } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::PrepareDelete() { ViewObjectContact::PrepareDelete(); delete mpMediaWindow; mpMediaWindow = NULL; } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo) { SdrObject* pObj = GetViewContact().TryToGetSdrObject(); ViewObjectContact::PaintObject( rDisplayInfo ); if( pObj ) { Rectangle aPaintRect( pObj->GetCurrentBoundRect() ); OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice(); sal_Int32 nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() ); bool bWasPainted = false; aPaintRect.Left() += nOffset; aPaintRect.Top() += nOffset; aPaintRect.Right() -= nOffset; aPaintRect.Bottom() -= nOffset; if( !mpMediaWindow ) { //OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice(); if( pOutDev && ( aPaintRect.Left() < aPaintRect.Right() && aPaintRect.Top() < aPaintRect.Bottom() ) ) { const Color aBackgroundColor( 67, 67, 67 ); pOutDev->SetLineColor( aBackgroundColor ); pOutDev->SetFillColor( aBackgroundColor ); pOutDev->DrawRect( aPaintRect ); if( pObj->ISA( SdrMediaObj ) ) { const Graphic& rGraphic = static_cast< SdrMediaObj* >( pObj )->getGraphic(); if( rGraphic.GetType() != GRAPHIC_NONE ) { rGraphic.Draw( pOutDev, aPaintRect.TopLeft(), aPaintRect.GetSize() ); } } bWasPainted = true; } } else { const Rectangle aPaintRectPixel( pOutDev->LogicToPixel( aPaintRect.TopLeft() ), pOutDev->LogicToPixel( aPaintRect.GetSize() ) ); mpMediaWindow->setPosSize( aPaintRectPixel ); Window* pWindow = mpMediaWindow->getWindow(); if( pWindow ) pWindow->Invalidate(); bWasPainted = true; } if( bWasPainted ) { mbIsPainted = sal_True; mbIsInvalidated = sal_False; maPaintedRectangle = pObj->GetCurrentBoundRect(); } } } // ------------------------------------------------------------------------------ Window* ViewObjectContactOfSdrMediaObj::getWindow() const { ObjectContactOfPageView* pOC = dynamic_cast< ObjectContactOfPageView* >( &GetObjectContact() ); if( pOC) { OutputDevice& rOutDev = pOC->GetPageViewWindow().GetOutputDevice(); return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL ); } return NULL; } // ------------------------------------------------------------------------------ bool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const { return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() ); } // ------------------------------------------------------------------------------ Size ViewObjectContactOfSdrMediaObj::getPreferredSize() const { Size aRet; if( mpMediaWindow ) aRet = mpMediaWindow->getPreferredSize(); return aRet; } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const { if( mpMediaWindow ) mpMediaWindow->updateMediaItem( rItem ); } // ------------------------------------------------------------------------------ void ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem ) { if( mpMediaWindow ) { ::avmedia::MediaItem aUpdatedItem; mpMediaWindow->executeMediaItem( rItem ); // query new properties after trying to set the new properties updateMediaItem( aUpdatedItem ); static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem ); } } } } <|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 "content/browser/browser_plugin/browser_plugin_web_contents_observer.h" #include "base/lazy_instance.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/browser_plugin_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "ppapi/proxy/ppapi_messages.h" namespace content { BrowserPluginWebContentsObserver::BrowserPluginWebContentsObserver( TabContents* tab_contents) : WebContentsObserver(tab_contents), host_(NULL), instance_id_(0) { registrar_.Add(this, NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderViewHost>( tab_contents->GetRenderViewHost())); } BrowserPluginWebContentsObserver::~BrowserPluginWebContentsObserver() { } bool BrowserPluginWebContentsObserver::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(BrowserPluginWebContentsObserver, message) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_ChannelCreated, OnRendererPluginChannelCreated) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_OpenChannel, OnOpenChannelToBrowserPlugin) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_GuestReady, OnGuestReady) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_ResizeGuest, OnResizeGuest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() return handled; } void BrowserPluginWebContentsObserver::OnGuestReady() { // We only care about handling this message on guests. if (!host()) return; // The renderer is now ready to receive ppapi messages. // Let's tell it create a channel with the embedder/host. BrowserPluginMsg_CreateChannel* msg = new BrowserPluginMsg_CreateChannel( host()->GetRenderProcessHost()->GetHandle(), host()->GetRenderProcessHost()->GetID()); msg->set_routing_id(web_contents()->GetRenderViewHost()->GetRoutingID()); // TODO(fsamuel): If we aren't able to successfully send this message // to the guest then that probably means it crashed. Is there anything // we can do that's cleaner than failing a check? CHECK(Send(msg)); } void BrowserPluginWebContentsObserver::OnResizeGuest( int width, int height) { // Tell the RenderWidgetHostView to adjust its size. web_contents()->GetRenderViewHost()->GetView()->SetSize( gfx::Size(width, height)); } void BrowserPluginWebContentsObserver::OnOpenChannelToBrowserPlugin( int instance_id, long long frame_id, const std::string& src, const gfx::Size& size) { BrowserContext* browser_context = web_contents()->GetRenderViewHost()->GetProcess()->GetBrowserContext(); DCHECK(browser_context); GURL url(src); SiteInstance* site_instance = SiteInstance::CreateForURL( browser_context, url); TabContents* guest_tab_contents = static_cast<TabContents*>( WebContents::Create( browser_context, site_instance, MSG_ROUTING_NONE, NULL, // base tab contents NULL // session storage namespace )); // TODO(fsamuel): Set the WebContentsDelegate here. RenderViewHostImpl* guest_render_view_host = static_cast<RenderViewHostImpl*>( guest_tab_contents->GetRenderViewHost()); // We need to make sure that the RenderViewHost knows that it's // hosting a guest RenderView so that it informs the RenderView // on a ViewMsg_New. Guest RenderViews will avoid compositing // until a guest-to-host channel has been initialized. guest_render_view_host->set_guest(true); guest_tab_contents->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_HOME_PAGE, std::string()); guest_render_view_host->GetView()->SetSize(size); BrowserPluginWebContentsObserver* guest_observer = guest_tab_contents->browser_plugin_web_contents_observer(); guest_observer->set_host(static_cast<TabContents*>(web_contents())); guest_observer->set_instance_id(instance_id); AddGuest(guest_tab_contents, frame_id); } void BrowserPluginWebContentsObserver::OnRendererPluginChannelCreated( const IPC::ChannelHandle& channel_handle) { DCHECK(host()); // Prepare the handle to send to the renderer. base::ProcessHandle plugin_process = web_contents()->GetRenderProcessHost()->GetHandle(); #if defined(OS_WIN) base::ProcessHandle renderer_process = host()->GetRenderProcessHost()->GetHandle(); int renderer_id = host()->GetRenderProcessHost()->GetID(); base::ProcessHandle renderers_plugin_handle = NULL; ::DuplicateHandle(::GetCurrentProcess(), plugin_process, renderer_process, &renderers_plugin_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); #elif defined(OS_POSIX) // Don't need to duplicate anything on POSIX since it's just a PID. base::ProcessHandle renderers_plugin_handle = plugin_process; #endif // Tell the BrowserPLuginPlaceholder in the host that we're done // and that it can begin using the guest renderer. host()->GetRenderProcessHost()->Send( new BrowserPluginMsg_GuestReady_ACK( host()->GetRenderViewHost()->GetRoutingID(), instance_id(), renderers_plugin_handle, channel_handle)); } void BrowserPluginWebContentsObserver::AddGuest( TabContents* guest, int64 frame_id) { guests_[guest] = frame_id; } void BrowserPluginWebContentsObserver::RemoveGuest(TabContents* guest) { guests_.erase(guest); } void BrowserPluginWebContentsObserver::DestroyGuests() { for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { const TabContents* contents = it->first; delete contents; } guests_.clear(); } void BrowserPluginWebContentsObserver::DidCommitProvisionalLoadForFrame( int64 frame_id, bool is_main_frame, const GURL& url, PageTransition transition_type) { typedef std::set<TabContents*> GuestSet; GuestSet guests_to_delete; for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { TabContents* contents = it->first; if (it->second == frame_id) { guests_to_delete.insert(contents); } } for (GuestSet::const_iterator it = guests_to_delete.begin(); it != guests_to_delete.end(); ++it) { delete *it; guests_.erase(*it); } } void BrowserPluginWebContentsObserver::RenderViewDeleted( RenderViewHost* render_view_host) { DestroyGuests(); } void BrowserPluginWebContentsObserver::RenderViewGone( base::TerminationStatus status) { DestroyGuests(); } void BrowserPluginWebContentsObserver::WebContentsDestroyed( WebContents* web_contents) { DestroyGuests(); } void BrowserPluginWebContentsObserver::Observe( int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED); bool visible = *Details<bool>(details).ptr(); // If the host is hidden we need to hide the guests as well. for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { TabContents* contents = it->first; if (visible) contents->ShowContents(); else contents->HideContents(); } } } // namespace content <commit_msg>Fix typo from r131054.<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 "content/browser/browser_plugin/browser_plugin_web_contents_observer.h" #include "base/lazy_instance.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/browser_plugin_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "ppapi/proxy/ppapi_messages.h" namespace content { BrowserPluginWebContentsObserver::BrowserPluginWebContentsObserver( TabContents* tab_contents) : WebContentsObserver(tab_contents), host_(NULL), instance_id_(0) { registrar_.Add(this, NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderViewHost>( tab_contents->GetRenderViewHost())); } BrowserPluginWebContentsObserver::~BrowserPluginWebContentsObserver() { } bool BrowserPluginWebContentsObserver::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(BrowserPluginWebContentsObserver, message) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_ChannelCreated, OnRendererPluginChannelCreated) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_OpenChannel, OnOpenChannelToBrowserPlugin) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_GuestReady, OnGuestReady) IPC_MESSAGE_HANDLER(BrowserPluginHostMsg_ResizeGuest, OnResizeGuest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void BrowserPluginWebContentsObserver::OnGuestReady() { // We only care about handling this message on guests. if (!host()) return; // The renderer is now ready to receive ppapi messages. // Let's tell it create a channel with the embedder/host. BrowserPluginMsg_CreateChannel* msg = new BrowserPluginMsg_CreateChannel( host()->GetRenderProcessHost()->GetHandle(), host()->GetRenderProcessHost()->GetID()); msg->set_routing_id(web_contents()->GetRenderViewHost()->GetRoutingID()); // TODO(fsamuel): If we aren't able to successfully send this message // to the guest then that probably means it crashed. Is there anything // we can do that's cleaner than failing a check? CHECK(Send(msg)); } void BrowserPluginWebContentsObserver::OnResizeGuest( int width, int height) { // Tell the RenderWidgetHostView to adjust its size. web_contents()->GetRenderViewHost()->GetView()->SetSize( gfx::Size(width, height)); } void BrowserPluginWebContentsObserver::OnOpenChannelToBrowserPlugin( int instance_id, long long frame_id, const std::string& src, const gfx::Size& size) { BrowserContext* browser_context = web_contents()->GetRenderViewHost()->GetProcess()->GetBrowserContext(); DCHECK(browser_context); GURL url(src); SiteInstance* site_instance = SiteInstance::CreateForURL( browser_context, url); TabContents* guest_tab_contents = static_cast<TabContents*>( WebContents::Create( browser_context, site_instance, MSG_ROUTING_NONE, NULL, // base tab contents NULL // session storage namespace )); // TODO(fsamuel): Set the WebContentsDelegate here. RenderViewHostImpl* guest_render_view_host = static_cast<RenderViewHostImpl*>( guest_tab_contents->GetRenderViewHost()); // We need to make sure that the RenderViewHost knows that it's // hosting a guest RenderView so that it informs the RenderView // on a ViewMsg_New. Guest RenderViews will avoid compositing // until a guest-to-host channel has been initialized. guest_render_view_host->set_guest(true); guest_tab_contents->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_HOME_PAGE, std::string()); guest_render_view_host->GetView()->SetSize(size); BrowserPluginWebContentsObserver* guest_observer = guest_tab_contents->browser_plugin_web_contents_observer(); guest_observer->set_host(static_cast<TabContents*>(web_contents())); guest_observer->set_instance_id(instance_id); AddGuest(guest_tab_contents, frame_id); } void BrowserPluginWebContentsObserver::OnRendererPluginChannelCreated( const IPC::ChannelHandle& channel_handle) { DCHECK(host()); // Prepare the handle to send to the renderer. base::ProcessHandle plugin_process = web_contents()->GetRenderProcessHost()->GetHandle(); #if defined(OS_WIN) base::ProcessHandle renderer_process = host()->GetRenderProcessHost()->GetHandle(); int renderer_id = host()->GetRenderProcessHost()->GetID(); base::ProcessHandle renderers_plugin_handle = NULL; ::DuplicateHandle(::GetCurrentProcess(), plugin_process, renderer_process, &renderers_plugin_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); #elif defined(OS_POSIX) // Don't need to duplicate anything on POSIX since it's just a PID. base::ProcessHandle renderers_plugin_handle = plugin_process; #endif // Tell the BrowserPLuginPlaceholder in the host that we're done // and that it can begin using the guest renderer. host()->GetRenderProcessHost()->Send( new BrowserPluginMsg_GuestReady_ACK( host()->GetRenderViewHost()->GetRoutingID(), instance_id(), renderers_plugin_handle, channel_handle)); } void BrowserPluginWebContentsObserver::AddGuest( TabContents* guest, int64 frame_id) { guests_[guest] = frame_id; } void BrowserPluginWebContentsObserver::RemoveGuest(TabContents* guest) { guests_.erase(guest); } void BrowserPluginWebContentsObserver::DestroyGuests() { for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { const TabContents* contents = it->first; delete contents; } guests_.clear(); } void BrowserPluginWebContentsObserver::DidCommitProvisionalLoadForFrame( int64 frame_id, bool is_main_frame, const GURL& url, PageTransition transition_type) { typedef std::set<TabContents*> GuestSet; GuestSet guests_to_delete; for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { TabContents* contents = it->first; if (it->second == frame_id) { guests_to_delete.insert(contents); } } for (GuestSet::const_iterator it = guests_to_delete.begin(); it != guests_to_delete.end(); ++it) { delete *it; guests_.erase(*it); } } void BrowserPluginWebContentsObserver::RenderViewDeleted( RenderViewHost* render_view_host) { DestroyGuests(); } void BrowserPluginWebContentsObserver::RenderViewGone( base::TerminationStatus status) { DestroyGuests(); } void BrowserPluginWebContentsObserver::WebContentsDestroyed( WebContents* web_contents) { DestroyGuests(); } void BrowserPluginWebContentsObserver::Observe( int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED); bool visible = *Details<bool>(details).ptr(); // If the host is hidden we need to hide the guests as well. for (GuestMap::const_iterator it = guests_.begin(); it != guests_.end(); ++it) { TabContents* contents = it->first; if (visible) contents->ShowContents(); else contents->HideContents(); } } } // namespace content <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: staticmb.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:01:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ <commit_msg>INTEGRATION: CWS changefileheader (1.2.62); FILE MERGED 2008/03/31 07:25:46 rt 1.2.62.1: #i87441# Change license header to LPGL v3.<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: staticmb.cxx,v $ * $Revision: 1.3 $ * * 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. * ************************************************************************/ <|endoftext|>
<commit_before>// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_JOINTINDEX_F35DB555_HPP #define POMDOG_JOINTINDEX_F35DB555_HPP #include "Pomdog/Utility/Assert.hpp" #include <cstdint> #include <type_traits> #include <limits> namespace Pomdog { namespace Detail { namespace SkeletalAnimation2D { template <typename T> class OptionalUnsigned final { public: static_assert(std::is_unsigned<T>::value, "T is unsigned integer type."); T Data; // Constructors: constexpr OptionalUnsigned() : Data(std::numeric_limits<T>::max()) {} constexpr OptionalUnsigned(T v) : Data(v) {} // Binary operators: constexpr bool operator==(OptionalUnsigned const& v) const { return POMDOG_CONSTEXPR_ASSERT(Data != std::numeric_limits<T>::max()), Data == v.Data; } constexpr bool operator!=(OptionalUnsigned const& v) const { return POMDOG_CONSTEXPR_ASSERT(Data != std::numeric_limits<T>::max()), Data != v.Data; } T const& operator*() const { POMDOG_ASSERT(Data != std::numeric_limits<T>::max()); return Data; } T & operator*() { POMDOG_ASSERT(Data != std::numeric_limits<T>::max()); return Data; } constexpr explicit operator bool() const noexcept { return Data != std::numeric_limits<T>::max(); } }; }// namespace SkeletalAnimation2D }// namespace Detail using JointIndex = Detail::SkeletalAnimation2D::OptionalUnsigned<std::uint8_t>; }// namespace Pomdog #endif // POMDOG_JOINTINDEX_F35DB555_HPP <commit_msg>Update JointIndex<commit_after>// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_JOINTINDEX_F35DB555_HPP #define POMDOG_JOINTINDEX_F35DB555_HPP #include "Pomdog/Utility/Assert.hpp" #include <cstdint> #include <type_traits> #include <limits> namespace Pomdog { namespace Detail { namespace SkeletalAnimation2D { template <typename T> class OptionalUnsigned final { public: static_assert(std::is_unsigned<T>::value, "T is unsigned integer type."); T Data; constexpr OptionalUnsigned() noexcept : Data(std::numeric_limits<T>::max()) {} constexpr OptionalUnsigned(T v) noexcept : Data(v) {} constexpr bool operator==(OptionalUnsigned const& v) const noexcept { return POMDOG_CONSTEXPR_ASSERT(Data != std::numeric_limits<T>::max()), Data == v.Data; } constexpr bool operator!=(OptionalUnsigned const& v) const noexcept { return POMDOG_CONSTEXPR_ASSERT(Data != std::numeric_limits<T>::max()), Data != v.Data; } T const& operator*() const { POMDOG_ASSERT(Data != std::numeric_limits<T>::max()); return Data; } T & operator*() { POMDOG_ASSERT(Data != std::numeric_limits<T>::max()); return Data; } constexpr explicit operator bool() const noexcept { return Data != std::numeric_limits<T>::max(); } }; } // namespace SkeletalAnimation2D } // namespace Detail using JointIndex = Detail::SkeletalAnimation2D::OptionalUnsigned<std::uint8_t>; } // namespace Pomdog #endif // POMDOG_JOINTINDEX_F35DB555_HPP <|endoftext|>
<commit_before>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkComposeShader.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkImageRef_GlobalPool.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkBlurDrawLooper.h" #include "SkColorMatrixFilter.h" static void drawmarshmallow(SkCanvas* canvas) { SkBitmap bitmap; SkPaint paint; SkRect r; SkMatrix m; SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap); SkShader* s = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); paint.setShader(s)->unref(); m.setTranslate(SkIntToScalar(250), SkIntToScalar(134)); s->setLocalMatrix(m); r.set(SkIntToScalar(250), SkIntToScalar(134), SkIntToScalar(250 + 449), SkIntToScalar(134 + 701)); paint.setFlags(2); canvas->drawRect(r, paint); } static void DrawRoundRect(SkCanvas& canvas) { bool ret = false; SkPaint paint; SkBitmap bitmap; SkMatrix matrix; matrix.reset(); bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812); bitmap.allocPixels(); #if 0 SkCanvas canvas; canvas.setBitmapDevice(bitmap); #endif // set up clipper SkRect skclip; skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708)); // ret = canvas.clipRect(skclip); // SkASSERT(ret); matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28)); matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50)); matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171)); matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043)); matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968)); matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876)); matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0)); matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0)); ret = canvas.concat(matrix); paint.setAntiAlias(true); paint.setColor(0xb2202020); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkFloatToFixed(68.13)); SkRect r; r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541)); canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint); } static bool SetImageRef(SkBitmap* bitmap, SkStream* stream, SkBitmap::Config pref, const char name[] = NULL) { #if 0 // test buffer streams SkStream* str = new SkBufferStream(stream, 717); stream->unref(); stream = str; #endif SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1); ref->setURI(name); if (!ref->getInfo(bitmap)) { delete ref; return false; } bitmap->setPixelRef(ref)->unref(); return true; } //#define SPECIFIC_IMAGE "/skimages/72.jpg" #define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg" #define IMAGE_DIR "/skimages/" #define IMAGE_SUFFIX ".gif" class ImageDirView : public SkView { public: SkBitmap* fBitmaps; SkString* fStrings; int fBitmapCount; int fCurrIndex; SkScalar fSaturation; SkScalar fAngle; ImageDirView() { SkImageRef_GlobalPool::SetRAMBudget(320 * 1024); #ifdef SPECIFIC_IMAGE fBitmaps = new SkBitmap[3]; fStrings = new SkString[3]; fBitmapCount = 3; const SkBitmap::Config configs[] = { SkBitmap::kARGB_8888_Config, SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config }; for (int i = 0; i < fBitmapCount; i++) { #if 1 SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE); SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE); stream->unref(); #else SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]); #endif } #else int i, N = 0; SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX); SkString name; while (iter.next(&name)) { N += 1; } fBitmaps = new SkBitmap[N]; fStrings = new SkString[N]; iter.reset(IMAGE_DIR, IMAGE_SUFFIX); for (i = 0; i < N; i++) { iter.next(&name); SkString path(IMAGE_DIR); path.append(name); SkStream* stream = new SkFILEStream(path.c_str()); SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config, name.c_str()); stream->unref(); fStrings[i] = name; } fBitmapCount = N; #endif fCurrIndex = 0; fDX = fDY = 0; fSaturation = SK_Scalar1; fAngle = 0; fScale = SK_Scalar1; } virtual ~ImageDirView() { delete[] fBitmaps; delete[] fStrings; SkImageRef_GlobalPool::DumpPool(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("ImageDir: "); #ifdef SPECIFIC_IMAGE str.append(SPECIFIC_IMAGE); #else str.append(IMAGE_DIR); #endif SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { // canvas->drawColor(0xFFDDDDDD); canvas->drawColor(SK_ColorGRAY); canvas->drawColor(SK_ColorWHITE); } SkScalar fScale; virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); if (true) { canvas->scale(SkIntToScalar(2), SkIntToScalar(2)); drawmarshmallow(canvas); return; } if (false) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p); p.setAntiAlias(true); canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p); } if (false) { SkScalar cx = this->width()/2; SkScalar cy = this->height()/2; canvas->translate(cx, cy); canvas->scale(fScale, fScale); canvas->translate(-cx, -cy); DrawRoundRect(*canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32); SkPaint paint; #if 0 for (int i = 0; i < fBitmapCount; i++) { SkPaint p; #if 1 const SkScalar cm[] = { SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255), 0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255), 0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255), 0, 0, 0, SkIntToScalar(1), 0 }; SkColorFilter* cf = new SkColorMatrixFilter(cm); p.setColorFilter(cf)->unref(); #endif canvas->drawBitmap(fBitmaps[i], x, y, &p); x += SkIntToScalar(fBitmaps[i].width() + 10); } return; #endif canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint); #ifndef SPECIFIC_IMAGE if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) { fCurrIndex = 0; } this->inval(NULL); } #endif } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) fCurrIndex = 0; this->inval(NULL); } return new Click(this); } virtual bool onClick(Click* click) { SkScalar center = this->width()/2; fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2); center = this->height()/2; fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180; fDX += click->fCurr.fX - click->fPrev.fX; fDY += click->fCurr.fY - click->fPrev.fY; fScale = SkScalarDiv(click->fCurr.fX, this->width()); this->inval(NULL); return true; return this->INHERITED::onClick(click); } private: SkScalar fDX, fDY; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new ImageDirView; } static SkViewRegister reg(MyFactory); <commit_msg>notice if the bitmap failed to load<commit_after>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkComposeShader.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkImageRef_GlobalPool.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkBlurDrawLooper.h" #include "SkColorMatrixFilter.h" static void drawmarshmallow(SkCanvas* canvas) { SkBitmap bitmap; SkPaint paint; SkRect r; SkMatrix m; SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap); if (!bitmap.pixelRef()) { return; } SkShader* s = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); paint.setShader(s)->unref(); m.setTranslate(SkIntToScalar(250), SkIntToScalar(134)); s->setLocalMatrix(m); r.set(SkIntToScalar(250), SkIntToScalar(134), SkIntToScalar(250 + 449), SkIntToScalar(134 + 701)); paint.setFlags(2); canvas->drawRect(r, paint); } static void DrawRoundRect(SkCanvas& canvas) { bool ret = false; SkPaint paint; SkBitmap bitmap; SkMatrix matrix; matrix.reset(); bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812); bitmap.allocPixels(); #if 0 SkCanvas canvas; canvas.setBitmapDevice(bitmap); #endif // set up clipper SkRect skclip; skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708)); // ret = canvas.clipRect(skclip); // SkASSERT(ret); matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28)); matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50)); matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171)); matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043)); matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968)); matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876)); matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0)); matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0)); ret = canvas.concat(matrix); paint.setAntiAlias(true); paint.setColor(0xb2202020); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkFloatToFixed(68.13)); SkRect r; r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541)); canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint); } static bool SetImageRef(SkBitmap* bitmap, SkStream* stream, SkBitmap::Config pref, const char name[] = NULL) { #if 0 // test buffer streams SkStream* str = new SkBufferStream(stream, 717); stream->unref(); stream = str; #endif SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1); ref->setURI(name); if (!ref->getInfo(bitmap)) { delete ref; return false; } bitmap->setPixelRef(ref)->unref(); return true; } //#define SPECIFIC_IMAGE "/skimages/72.jpg" #define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg" #define IMAGE_DIR "/skimages/" #define IMAGE_SUFFIX ".gif" class ImageDirView : public SkView { public: SkBitmap* fBitmaps; SkString* fStrings; int fBitmapCount; int fCurrIndex; SkScalar fSaturation; SkScalar fAngle; ImageDirView() { SkImageRef_GlobalPool::SetRAMBudget(320 * 1024); #ifdef SPECIFIC_IMAGE fBitmaps = new SkBitmap[3]; fStrings = new SkString[3]; fBitmapCount = 3; const SkBitmap::Config configs[] = { SkBitmap::kARGB_8888_Config, SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config }; for (int i = 0; i < fBitmapCount; i++) { #if 1 SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE); SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE); stream->unref(); #else SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]); #endif } #else int i, N = 0; SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX); SkString name; while (iter.next(&name)) { N += 1; } fBitmaps = new SkBitmap[N]; fStrings = new SkString[N]; iter.reset(IMAGE_DIR, IMAGE_SUFFIX); for (i = 0; i < N; i++) { iter.next(&name); SkString path(IMAGE_DIR); path.append(name); SkStream* stream = new SkFILEStream(path.c_str()); SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config, name.c_str()); stream->unref(); fStrings[i] = name; } fBitmapCount = N; #endif fCurrIndex = 0; fDX = fDY = 0; fSaturation = SK_Scalar1; fAngle = 0; fScale = SK_Scalar1; } virtual ~ImageDirView() { delete[] fBitmaps; delete[] fStrings; SkImageRef_GlobalPool::DumpPool(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("ImageDir: "); #ifdef SPECIFIC_IMAGE str.append(SPECIFIC_IMAGE); #else str.append(IMAGE_DIR); #endif SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { // canvas->drawColor(0xFFDDDDDD); canvas->drawColor(SK_ColorGRAY); canvas->drawColor(SK_ColorWHITE); } SkScalar fScale; virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); if (true) { canvas->scale(SkIntToScalar(2), SkIntToScalar(2)); drawmarshmallow(canvas); return; } if (false) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p); p.setAntiAlias(true); canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p); } if (false) { SkScalar cx = this->width()/2; SkScalar cy = this->height()/2; canvas->translate(cx, cy); canvas->scale(fScale, fScale); canvas->translate(-cx, -cy); DrawRoundRect(*canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32); SkPaint paint; #if 0 for (int i = 0; i < fBitmapCount; i++) { SkPaint p; #if 1 const SkScalar cm[] = { SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255), 0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255), 0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255), 0, 0, 0, SkIntToScalar(1), 0 }; SkColorFilter* cf = new SkColorMatrixFilter(cm); p.setColorFilter(cf)->unref(); #endif canvas->drawBitmap(fBitmaps[i], x, y, &p); x += SkIntToScalar(fBitmaps[i].width() + 10); } return; #endif canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint); #ifndef SPECIFIC_IMAGE if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) { fCurrIndex = 0; } this->inval(NULL); } #endif } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) fCurrIndex = 0; this->inval(NULL); } return new Click(this); } virtual bool onClick(Click* click) { SkScalar center = this->width()/2; fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2); center = this->height()/2; fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180; fDX += click->fCurr.fX - click->fPrev.fX; fDY += click->fCurr.fY - click->fPrev.fY; fScale = SkScalarDiv(click->fCurr.fX, this->width()); this->inval(NULL); return true; return this->INHERITED::onClick(click); } private: SkScalar fDX, fDY; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new ImageDirView; } static SkViewRegister reg(MyFactory); <|endoftext|>
<commit_before>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkComposeShader.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkImageRef_GlobalPool.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkBlurDrawLooper.h" #include "SkColorMatrixFilter.h" static void drawmarshmallow(SkCanvas* canvas) { SkBitmap bitmap; SkPaint paint; SkRect r; SkMatrix m; SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap); SkShader* s = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); paint.setShader(s)->unref(); m.setTranslate(SkIntToScalar(250), SkIntToScalar(134)); s->setLocalMatrix(m); r.set(SkIntToScalar(250), SkIntToScalar(134), SkIntToScalar(250 + 449), SkIntToScalar(134 + 701)); paint.setFlags(2); canvas->drawRect(r, paint); } static void DrawRoundRect(SkCanvas& canvas) { bool ret = false; SkPaint paint; SkBitmap bitmap; SkMatrix matrix; matrix.reset(); bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812); bitmap.allocPixels(); #if 0 SkCanvas canvas; canvas.setBitmapDevice(bitmap); #endif // set up clipper SkRect skclip; skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708)); // ret = canvas.clipRect(skclip); // SkASSERT(ret); matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28)); matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50)); matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171)); matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043)); matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968)); matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876)); matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0)); matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0)); ret = canvas.concat(matrix); paint.setAntiAlias(true); paint.setColor(0xb2202020); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkFloatToFixed(68.13)); SkRect r; r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541)); canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint); } static bool SetImageRef(SkBitmap* bitmap, SkStream* stream, SkBitmap::Config pref, const char name[] = NULL) { #if 0 // test buffer streams SkStream* str = new SkBufferStream(stream, 717); stream->unref(); stream = str; #endif SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1); ref->setURI(name); if (!ref->getInfo(bitmap)) { delete ref; return false; } bitmap->setPixelRef(ref)->unref(); return true; } //#define SPECIFIC_IMAGE "/skimages/72.jpg" #define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg" #define IMAGE_DIR "/skimages/" #define IMAGE_SUFFIX ".gif" class ImageDirView : public SkView { public: SkBitmap* fBitmaps; SkString* fStrings; int fBitmapCount; int fCurrIndex; SkScalar fSaturation; SkScalar fAngle; ImageDirView() { SkImageRef_GlobalPool::SetRAMBudget(320 * 1024); #ifdef SPECIFIC_IMAGE fBitmaps = new SkBitmap[3]; fStrings = new SkString[3]; fBitmapCount = 3; const SkBitmap::Config configs[] = { SkBitmap::kARGB_8888_Config, SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config }; for (int i = 0; i < fBitmapCount; i++) { #if 1 SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE); SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE); stream->unref(); #else SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]); #endif } #else int i, N = 0; SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX); SkString name; while (iter.next(&name)) { N += 1; } fBitmaps = new SkBitmap[N]; fStrings = new SkString[N]; iter.reset(IMAGE_DIR, IMAGE_SUFFIX); for (i = 0; i < N; i++) { iter.next(&name); SkString path(IMAGE_DIR); path.append(name); SkStream* stream = new SkFILEStream(path.c_str()); SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config, name.c_str()); stream->unref(); fStrings[i] = name; } fBitmapCount = N; #endif fCurrIndex = 0; fDX = fDY = 0; fSaturation = SK_Scalar1; fAngle = 0; fScale = SK_Scalar1; } virtual ~ImageDirView() { delete[] fBitmaps; delete[] fStrings; SkImageRef_GlobalPool::DumpPool(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("ImageDir: "); #ifdef SPECIFIC_IMAGE str.append(SPECIFIC_IMAGE); #else str.append(IMAGE_DIR); #endif SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { // canvas->drawColor(0xFFDDDDDD); canvas->drawColor(SK_ColorGRAY); canvas->drawColor(SK_ColorWHITE); } SkScalar fScale; virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); if (true) { canvas->scale(SkIntToScalar(2), SkIntToScalar(2)); drawmarshmallow(canvas); return; } if (false) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p); p.setAntiAlias(true); canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p); } if (false) { SkScalar cx = this->width()/2; SkScalar cy = this->height()/2; canvas->translate(cx, cy); canvas->scale(fScale, fScale); canvas->translate(-cx, -cy); DrawRoundRect(*canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32); SkPaint paint; #if 0 for (int i = 0; i < fBitmapCount; i++) { SkPaint p; #if 1 const SkScalar cm[] = { SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255), 0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255), 0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255), 0, 0, 0, SkIntToScalar(1), 0 }; SkColorFilter* cf = new SkColorMatrixFilter(cm); p.setColorFilter(cf)->unref(); #endif canvas->drawBitmap(fBitmaps[i], x, y, &p); x += SkIntToScalar(fBitmaps[i].width() + 10); } return; #endif canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint); #ifndef SPECIFIC_IMAGE if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) { fCurrIndex = 0; } this->inval(NULL); } #endif } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) fCurrIndex = 0; this->inval(NULL); } return new Click(this); } virtual bool onClick(Click* click) { SkScalar center = this->width()/2; fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2); center = this->height()/2; fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180; fDX += click->fCurr.fX - click->fPrev.fX; fDY += click->fCurr.fY - click->fPrev.fY; fScale = SkScalarDiv(click->fCurr.fX, this->width()); this->inval(NULL); return true; return this->INHERITED::onClick(click); } private: SkScalar fDX, fDY; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new ImageDirView; } static SkViewRegister reg(MyFactory); <commit_msg>notice if the bitmap failed to load<commit_after>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkComposeShader.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkImageRef_GlobalPool.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkBlurDrawLooper.h" #include "SkColorMatrixFilter.h" static void drawmarshmallow(SkCanvas* canvas) { SkBitmap bitmap; SkPaint paint; SkRect r; SkMatrix m; SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap); if (!bitmap.pixelRef()) { return; } SkShader* s = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); paint.setShader(s)->unref(); m.setTranslate(SkIntToScalar(250), SkIntToScalar(134)); s->setLocalMatrix(m); r.set(SkIntToScalar(250), SkIntToScalar(134), SkIntToScalar(250 + 449), SkIntToScalar(134 + 701)); paint.setFlags(2); canvas->drawRect(r, paint); } static void DrawRoundRect(SkCanvas& canvas) { bool ret = false; SkPaint paint; SkBitmap bitmap; SkMatrix matrix; matrix.reset(); bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812); bitmap.allocPixels(); #if 0 SkCanvas canvas; canvas.setBitmapDevice(bitmap); #endif // set up clipper SkRect skclip; skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708)); // ret = canvas.clipRect(skclip); // SkASSERT(ret); matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28)); matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50)); matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171)); matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043)); matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968)); matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876)); matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0)); matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0)); ret = canvas.concat(matrix); paint.setAntiAlias(true); paint.setColor(0xb2202020); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkFloatToFixed(68.13)); SkRect r; r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541)); canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint); } static bool SetImageRef(SkBitmap* bitmap, SkStream* stream, SkBitmap::Config pref, const char name[] = NULL) { #if 0 // test buffer streams SkStream* str = new SkBufferStream(stream, 717); stream->unref(); stream = str; #endif SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1); ref->setURI(name); if (!ref->getInfo(bitmap)) { delete ref; return false; } bitmap->setPixelRef(ref)->unref(); return true; } //#define SPECIFIC_IMAGE "/skimages/72.jpg" #define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg" #define IMAGE_DIR "/skimages/" #define IMAGE_SUFFIX ".gif" class ImageDirView : public SkView { public: SkBitmap* fBitmaps; SkString* fStrings; int fBitmapCount; int fCurrIndex; SkScalar fSaturation; SkScalar fAngle; ImageDirView() { SkImageRef_GlobalPool::SetRAMBudget(320 * 1024); #ifdef SPECIFIC_IMAGE fBitmaps = new SkBitmap[3]; fStrings = new SkString[3]; fBitmapCount = 3; const SkBitmap::Config configs[] = { SkBitmap::kARGB_8888_Config, SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config }; for (int i = 0; i < fBitmapCount; i++) { #if 1 SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE); SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE); stream->unref(); #else SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]); #endif } #else int i, N = 0; SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX); SkString name; while (iter.next(&name)) { N += 1; } fBitmaps = new SkBitmap[N]; fStrings = new SkString[N]; iter.reset(IMAGE_DIR, IMAGE_SUFFIX); for (i = 0; i < N; i++) { iter.next(&name); SkString path(IMAGE_DIR); path.append(name); SkStream* stream = new SkFILEStream(path.c_str()); SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config, name.c_str()); stream->unref(); fStrings[i] = name; } fBitmapCount = N; #endif fCurrIndex = 0; fDX = fDY = 0; fSaturation = SK_Scalar1; fAngle = 0; fScale = SK_Scalar1; } virtual ~ImageDirView() { delete[] fBitmaps; delete[] fStrings; SkImageRef_GlobalPool::DumpPool(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("ImageDir: "); #ifdef SPECIFIC_IMAGE str.append(SPECIFIC_IMAGE); #else str.append(IMAGE_DIR); #endif SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { // canvas->drawColor(0xFFDDDDDD); canvas->drawColor(SK_ColorGRAY); canvas->drawColor(SK_ColorWHITE); } SkScalar fScale; virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); if (true) { canvas->scale(SkIntToScalar(2), SkIntToScalar(2)); drawmarshmallow(canvas); return; } if (false) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p); p.setAntiAlias(true); canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p); } if (false) { SkScalar cx = this->width()/2; SkScalar cy = this->height()/2; canvas->translate(cx, cy); canvas->scale(fScale, fScale); canvas->translate(-cx, -cy); DrawRoundRect(*canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32); SkPaint paint; #if 0 for (int i = 0; i < fBitmapCount; i++) { SkPaint p; #if 1 const SkScalar cm[] = { SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255), 0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255), 0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255), 0, 0, 0, SkIntToScalar(1), 0 }; SkColorFilter* cf = new SkColorMatrixFilter(cm); p.setColorFilter(cf)->unref(); #endif canvas->drawBitmap(fBitmaps[i], x, y, &p); x += SkIntToScalar(fBitmaps[i].width() + 10); } return; #endif canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint); #ifndef SPECIFIC_IMAGE if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) { fCurrIndex = 0; } this->inval(NULL); } #endif } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { if (true) { fCurrIndex += 1; if (fCurrIndex >= fBitmapCount) fCurrIndex = 0; this->inval(NULL); } return new Click(this); } virtual bool onClick(Click* click) { SkScalar center = this->width()/2; fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2); center = this->height()/2; fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180; fDX += click->fCurr.fX - click->fPrev.fX; fDY += click->fCurr.fY - click->fPrev.fY; fScale = SkScalarDiv(click->fCurr.fX, this->width()); this->inval(NULL); return true; return this->INHERITED::onClick(click); } private: SkScalar fDX, fDY; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new ImageDirView; } static SkViewRegister reg(MyFactory); <|endoftext|>
<commit_before>#define SHA1_CHECKSUM #include "framework/serialization/providers/providerwithchecksum.h" #include "framework/configfile.h" #include "framework/logger.h" #include "framework/trace.h" #include "library/strings.h" #include "library/strings_format.h" #include <sstream> #include "dependencies/pugixml/src/pugixml.hpp" #include <boost/crc.hpp> #include <boost/version.hpp> #if BOOST_VERSION >= 106600 #include <boost/uuid/detail/sha1.hpp> #else #include <boost/uuid/sha1.hpp> #endif #include <boost/uuid/uuid.hpp> namespace OpenApoc { ConfigOptionBool useCRCChecksum("Framework.Serialization", "CRC", "use a CRC checksum when saving files", true); ConfigOptionBool useSHA1Checksum("Framework.Serialization", "SHA1", "use a SHA1 checksum when saving files", false); static UString calculateSHA1Checksum(const std::string &str) { TRACE_FN; UString hashString; boost::uuids::detail::sha1 sha; sha.process_bytes(str.c_str(), str.size()); unsigned int hash[5]; sha.get_digest(hash); for (int i = 0; i < 5; i++) { unsigned int v = hash[i]; for (int j = 0; j < 4; j++) { // FIXME: Probably need to do the reverse for big endian? unsigned int byteHex = v & 0xff000000; byteHex >>= 24; hashString += format("%02x", byteHex).str(); v <<= 8; } } return hashString; } static UString calculateCRCChecksum(const std::string &str) { TRACE_FN; UString hashString; boost::crc_32_type crc; crc.process_bytes(str.c_str(), str.size()); auto hash = crc.checksum(); hashString = format("%08x", hash); return hashString; } static UString calculateChecksum(const UString &type, const std::string &str) { if (type == "CRC") { return calculateCRCChecksum(str); } else if (type == "SHA1") { return calculateSHA1Checksum(str); } else { LogWarning("Unknown checksum type \"%s\"", type); return ""; } } std::string ProviderWithChecksum::serializeManifest() { pugi::xml_document manifestDoc; auto decl = manifestDoc.prepend_child(pugi::node_declaration); decl.append_attribute("version") = "1.0"; decl.append_attribute("encoding") = "UTF-8"; auto root = manifestDoc.root().append_child(); root.set_name("checksums"); for (auto &p : checksums) { auto node = root.append_child(); node.set_name("file"); node.text().set(p.first.cStr()); for (auto &csum : p.second) { auto checksumNode = node.append_child(); checksumNode.set_name(csum.first.cStr()); checksumNode.text().set(csum.second.cStr()); } } std::stringstream ss; manifestDoc.save(ss, " "); return ss.str(); } bool ProviderWithChecksum::parseManifest(const std::string &manifestData) { std::stringstream ss(manifestData); pugi::xml_document manifestDoc; auto parse_result = manifestDoc.load(ss); if (!parse_result) { LogWarning("Failed to parse checksum.xml : \"%s\" at \"%llu\"", parse_result.description(), (unsigned long long)parse_result.offset); return false; } auto rootNode = manifestDoc.child("checksums"); if (!rootNode) { LogWarning("checksum.xml has invalid root node"); return false; } auto fileNode = rootNode.child("file"); while (fileNode) { UString fileName = fileNode.text().get(); if (this->checksums.find(fileName) != this->checksums.end()) { LogWarning("Multiple manifest entries for path \"%s\"", fileName); } this->checksums[fileName] = {}; auto checksumNode = fileNode.first_child(); while (checksumNode) { if (checksumNode.type() == pugi::xml_node_type::node_element) { UString checksumType = checksumNode.name(); this->checksums[fileName][checksumType] = checksumNode.text().get(); } checksumNode = checksumNode.next_sibling(); } fileNode = fileNode.next_sibling("file"); } return true; } bool ProviderWithChecksum::openArchive(const UString &path, bool write) { if (!inner->openArchive(path, write)) { return false; } if (!write) { UString result; if (!inner->readDocument("checksum.xml", result)) { LogInfo("Missing manifest file in \"%s\"", path); return true; } parseManifest(result.str()); } return true; } bool ProviderWithChecksum::readDocument(const UString &path, UString &result) { if (inner->readDocument(path, result)) { for (auto &csum : checksums[path.str()]) { auto expectedCSum = csum.second; auto calculatedCSum = calculateChecksum(csum.first, result.str()); if (expectedCSum != calculatedCSum) { LogWarning("File \"%s\" has incorrect \"%s\" checksum \"%s\", expected \"%s\"", path, csum.first, calculatedCSum, expectedCSum); } else { LogDebug("File \"%s\" matches \"%s\" checksum \"%s\"", path, csum.first, calculatedCSum); } } return true; } return false; } bool ProviderWithChecksum::saveDocument(const UString &path, const UString &contents) { if (inner->saveDocument(path, contents)) { if (this->checksums.find(path) != this->checksums.end()) { LogWarning("Multiple document entries for path \"%s\"", path); } this->checksums[path.str()] = {}; if (useCRCChecksum.get()) this->checksums[path.str()]["CRC"] = calculateChecksum("CRC", contents.str()).str(); if (useSHA1Checksum.get()) this->checksums[path.str()]["SHA1"] = calculateChecksum("SHA1", contents.str()).str(); return true; } return false; } bool ProviderWithChecksum::finalizeSave() { UString manifest = serializeManifest(); inner->saveDocument("checksum.xml", manifest); return inner->finalizeSave(); } } // namespace OpenApoc <commit_msg>Disable gamestate CRC checksums by default<commit_after>#define SHA1_CHECKSUM #include "framework/serialization/providers/providerwithchecksum.h" #include "framework/configfile.h" #include "framework/logger.h" #include "framework/trace.h" #include "library/strings.h" #include "library/strings_format.h" #include <sstream> #include "dependencies/pugixml/src/pugixml.hpp" #include <boost/crc.hpp> #include <boost/version.hpp> #if BOOST_VERSION >= 106600 #include <boost/uuid/detail/sha1.hpp> #else #include <boost/uuid/sha1.hpp> #endif #include <boost/uuid/uuid.hpp> namespace OpenApoc { ConfigOptionBool useCRCChecksum("Framework.Serialization", "CRC", "use a CRC checksum when saving files", false); ConfigOptionBool useSHA1Checksum("Framework.Serialization", "SHA1", "use a SHA1 checksum when saving files", false); static UString calculateSHA1Checksum(const std::string &str) { TRACE_FN; UString hashString; boost::uuids::detail::sha1 sha; sha.process_bytes(str.c_str(), str.size()); unsigned int hash[5]; sha.get_digest(hash); for (int i = 0; i < 5; i++) { unsigned int v = hash[i]; for (int j = 0; j < 4; j++) { // FIXME: Probably need to do the reverse for big endian? unsigned int byteHex = v & 0xff000000; byteHex >>= 24; hashString += format("%02x", byteHex).str(); v <<= 8; } } return hashString; } static UString calculateCRCChecksum(const std::string &str) { TRACE_FN; UString hashString; boost::crc_32_type crc; crc.process_bytes(str.c_str(), str.size()); auto hash = crc.checksum(); hashString = format("%08x", hash); return hashString; } static UString calculateChecksum(const UString &type, const std::string &str) { if (type == "CRC") { return calculateCRCChecksum(str); } else if (type == "SHA1") { return calculateSHA1Checksum(str); } else { LogWarning("Unknown checksum type \"%s\"", type); return ""; } } std::string ProviderWithChecksum::serializeManifest() { pugi::xml_document manifestDoc; auto decl = manifestDoc.prepend_child(pugi::node_declaration); decl.append_attribute("version") = "1.0"; decl.append_attribute("encoding") = "UTF-8"; auto root = manifestDoc.root().append_child(); root.set_name("checksums"); for (auto &p : checksums) { auto node = root.append_child(); node.set_name("file"); node.text().set(p.first.cStr()); for (auto &csum : p.second) { auto checksumNode = node.append_child(); checksumNode.set_name(csum.first.cStr()); checksumNode.text().set(csum.second.cStr()); } } std::stringstream ss; manifestDoc.save(ss, " "); return ss.str(); } bool ProviderWithChecksum::parseManifest(const std::string &manifestData) { std::stringstream ss(manifestData); pugi::xml_document manifestDoc; auto parse_result = manifestDoc.load(ss); if (!parse_result) { LogWarning("Failed to parse checksum.xml : \"%s\" at \"%llu\"", parse_result.description(), (unsigned long long)parse_result.offset); return false; } auto rootNode = manifestDoc.child("checksums"); if (!rootNode) { LogWarning("checksum.xml has invalid root node"); return false; } auto fileNode = rootNode.child("file"); while (fileNode) { UString fileName = fileNode.text().get(); if (this->checksums.find(fileName) != this->checksums.end()) { LogWarning("Multiple manifest entries for path \"%s\"", fileName); } this->checksums[fileName] = {}; auto checksumNode = fileNode.first_child(); while (checksumNode) { if (checksumNode.type() == pugi::xml_node_type::node_element) { UString checksumType = checksumNode.name(); this->checksums[fileName][checksumType] = checksumNode.text().get(); } checksumNode = checksumNode.next_sibling(); } fileNode = fileNode.next_sibling("file"); } return true; } bool ProviderWithChecksum::openArchive(const UString &path, bool write) { if (!inner->openArchive(path, write)) { return false; } if (!write) { UString result; if (!inner->readDocument("checksum.xml", result)) { LogInfo("Missing manifest file in \"%s\"", path); return true; } parseManifest(result.str()); } return true; } bool ProviderWithChecksum::readDocument(const UString &path, UString &result) { if (inner->readDocument(path, result)) { for (auto &csum : checksums[path.str()]) { auto expectedCSum = csum.second; auto calculatedCSum = calculateChecksum(csum.first, result.str()); if (expectedCSum != calculatedCSum) { LogWarning("File \"%s\" has incorrect \"%s\" checksum \"%s\", expected \"%s\"", path, csum.first, calculatedCSum, expectedCSum); } else { LogDebug("File \"%s\" matches \"%s\" checksum \"%s\"", path, csum.first, calculatedCSum); } } return true; } return false; } bool ProviderWithChecksum::saveDocument(const UString &path, const UString &contents) { if (inner->saveDocument(path, contents)) { if (this->checksums.find(path) != this->checksums.end()) { LogWarning("Multiple document entries for path \"%s\"", path); } this->checksums[path.str()] = {}; if (useCRCChecksum.get()) this->checksums[path.str()]["CRC"] = calculateChecksum("CRC", contents.str()).str(); if (useSHA1Checksum.get()) this->checksums[path.str()]["SHA1"] = calculateChecksum("SHA1", contents.str()).str(); return true; } return false; } bool ProviderWithChecksum::finalizeSave() { UString manifest = serializeManifest(); inner->saveDocument("checksum.xml", manifest); return inner->finalizeSave(); } } // namespace OpenApoc <|endoftext|>
<commit_before>/* Copyright 2019 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/lite/delegates/gpu/cl/kernels/max_unpooling.h" #include <string> #include "tensorflow/lite/delegates/gpu/cl/kernels/util.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h" namespace tflite { namespace gpu { namespace cl { namespace { std::string GetMaxUnoolingKernelCode( const OperationDef& op_def, const CLDevice& device, const std::vector<ElementwiseOperation*>& linked_operations) { TensorCodeGenerator src("src_data", "src_size", op_def.src_tensors[0]); TensorCodeGenerator src_ind("src_data_indices", "src_size", op_def.src_tensors[1]); TensorCodeGenerator dst("dst_data", "dst_size", op_def.dst_tensors[0]); const auto address_mode = GetFastestZeroMode(device); std::string code = GetCommonDefines(op_def.precision); code += "__kernel void main_function(\n"; code += src.GetDeclaration(AccessType::READ) + ",\n"; code += src_ind.GetDeclaration(AccessType::READ); code += GetArgsDeclaration(linked_operations); code += dst.GetDeclaration(AccessType::WRITE) + ",\n"; code += " int4 src_size, \n"; code += " int4 dst_size, \n"; code += " int2 kernel_size, \n"; code += " int2 padding, \n"; code += " int2 stride \n"; code += ") {\n"; code += " int X = get_global_id(0);\n"; code += " int Y = get_global_id(1);\n"; code += " int Z = get_global_id(2);\n"; code += " if (X >= dst_size.x || Y >= dst_size.y || Z >= dst_size.w) return; \n"; code += " int src_x = (X + padding.x) / stride.x;\n"; code += " int src_y = (Y + padding.y) / stride.y;\n"; code += " " + src.GetAddress("src_adr", "src_x", "src_y", "Z") + "\n"; if (op_def.src_tensors[0].storage_type == TensorStorageType::BUFFER) { code += " bool outside = src_x < 0 || src_y < 0 ||"; code += " src_x >= src_size.x || src_y >= src_size.y;\n"; code += " FLT4 src = (FLT4)(0.0f);\n"; code += " int4 ind = (int4)(0);\n"; code += " if (!outside) {\n"; code += " src = " + src.Read("src_adr", TextureAddressMode::DONT_CARE) + ";\n"; code += " ind = convert_int4(" + src_ind.Read("src_adr", TextureAddressMode::DONT_CARE) + ");\n"; code += " }\n"; } else { code += " FLT4 src = " + src.Read("src_adr", address_mode) + ";\n"; code += " int4 ind = convert_int4(" + src_ind.Read("src_adr", address_mode) + ");\n"; } code += " int t_x = X - (src_x * stride.x - padding.x);\n"; code += " int t_y = Y - (src_y * stride.y - padding.y);\n"; code += " int t_index = t_y * kernel_size.x + t_x;\n"; code += " FLT4 result;\n"; const std::string channels[] = {".x", ".y", ".z", ".w"}; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; code += " result" + s + "= t_index == ind" + s + "? src" + s + ": 0.0f;\n"; } const LinkingContext context{"result", "X", "Y", "Z"}; code += PostProcess(linked_operations, context); code += " " + dst.Write3D("result", "X", "Y", "Z"); code += "}\n"; return code; } } // namespace MaxUnpooling::MaxUnpooling(const OperationDef& definition, const MaxUnpooling2DAttributes& attr) : GPUOperation(definition), stride_(attr.strides.w, attr.strides.h), padding_(attr.padding.appended.w, attr.padding.appended.h), kernel_size_(attr.kernel.w, attr.kernel.h) {} MaxUnpooling::MaxUnpooling(MaxUnpooling&& kernel) : GPUOperation(std::move(kernel)), stride_(kernel.stride_), padding_(kernel.padding_), kernel_size_(kernel.kernel_size_), kernel_(std::move(kernel.kernel_)), work_group_size_(kernel.work_group_size_) {} MaxUnpooling& MaxUnpooling::operator=(MaxUnpooling&& kernel) { if (this != &kernel) { std::swap(stride_, kernel.stride_); std::swap(padding_, kernel.padding_); std::swap(kernel_size_, kernel.kernel_size_); kernel_ = std::move(kernel.kernel_); std::swap(work_group_size_, kernel.work_group_size_); GPUOperation::operator=(std::move(kernel)); } return *this; } Status MaxUnpooling::Compile(const CreationContext& creation_context) { const auto code = GetMaxUnoolingKernelCode( definition_, *creation_context.device, linked_operations_); return creation_context.cache->GetOrCreateCLKernel( code, "main_function", *creation_context.context, *creation_context.device, &kernel_); } Status MaxUnpooling::BindArguments() { kernel_.ResetBindingCounter(); RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[0]->GetMemoryPtr())); RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[1]->GetMemoryPtr())); RETURN_IF_ERROR(BindArgs(&kernel_, linked_operations_)); RETURN_IF_ERROR(kernel_.SetMemoryAuto(dst_[0]->GetMemoryPtrForWriting())); RETURN_IF_ERROR(kernel_.SetBytesAuto(src_[0]->GetSizeWithDepth())); RETURN_IF_ERROR(kernel_.SetBytesAuto(dst_[0]->GetSizeWithDepth())); RETURN_IF_ERROR(kernel_.SetBytesAuto(kernel_size_)); RETURN_IF_ERROR(kernel_.SetBytesAuto(padding_)); RETURN_IF_ERROR(kernel_.SetBytesAuto(stride_)); return OkStatus(); } int3 MaxUnpooling::GetGridSize() const { const int grid_x = dst_[0]->Width(); const int grid_y = dst_[0]->Height(); const int grid_z = dst_[0]->Depth(); return int3(grid_x, grid_y, grid_z); } Status MaxUnpooling::Tune(const TuningParameters& params) { RETURN_IF_ERROR(BindArguments()); return GetBestWorkGroup(params, kernel_, GetGridSize(), &work_group_size_); } Status MaxUnpooling::AddToQueue(CLCommandQueue* queue) { RETURN_IF_ERROR(BindArguments()); return queue->DispatchImplicit(kernel_, GetGridSize(), work_group_size_); } MaxUnpooling CreateMaxUnpooling(const OperationDef& definition, const MaxUnpooling2DAttributes& attr) { return MaxUnpooling(definition, attr); } } // namespace cl } // namespace gpu } // namespace tflite <commit_msg>Batch support for MaxUnpooling.<commit_after>/* Copyright 2019 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/lite/delegates/gpu/cl/kernels/max_unpooling.h" #include <string> #include "tensorflow/lite/delegates/gpu/cl/kernels/util.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h" namespace tflite { namespace gpu { namespace cl { namespace { std::string GetMaxUnoolingKernelCode( const OperationDef& op_def, const CLDevice& device, const std::vector<ElementwiseOperation*>& linked_operations) { TensorCodeGenerator src("src_data", {"src_size.x", "src_size.y", "src_size.z"}, op_def.src_tensors[0]); TensorCodeGenerator src_ind("src_data_indices", {"src_size.x", "src_size.y", "src_size.z"}, op_def.src_tensors[1]); TensorCodeGenerator dst("dst_data", {"dst_size.x", "dst_size.y", "dst_size.z"}, op_def.dst_tensors[0]); const auto address_mode = GetFastestZeroMode(device); std::string c = GetCommonDefines(op_def.precision); c += "__kernel void main_function(\n"; c += src.GetDeclaration(AccessType::READ) + ",\n"; c += src_ind.GetDeclaration(AccessType::READ); c += GetArgsDeclaration(linked_operations); c += dst.GetDeclaration(AccessType::WRITE) + ",\n"; c += " int4 src_size, \n"; c += " int4 dst_size, \n"; c += " int2 kernel_size, \n"; c += " int2 padding, \n"; c += " int2 stride \n"; c += ") {\n"; c += " int X = get_global_id(0);\n"; c += " int Y = get_global_id(1);\n"; c += " int Z = get_global_id(2);\n"; c += " if (X >= dst_size.x || Y >= dst_size.y || Z >= dst_size.z) return;\n"; if (op_def.batch_support) { c += " int B = get_global_id(0) % dst_size.w;\n"; c += " int X0 = get_global_id(0) / dst_size.w;\n"; c += " int src_x0 = (X0 + padding.x) / stride.x;\n"; c += " int src_x = src_x0 * dst_size.w + B;\n"; } else { c += " int src_x = (X + padding.x) / stride.x;\n"; } c += " int src_y = (Y + padding.y) / stride.y;\n"; c += " " + src.GetAddress("src_adr", "src_x", "src_y", "Z") + "\n"; if (op_def.src_tensors[0].storage_type == TensorStorageType::BUFFER) { c += " bool outside = src_x < 0 || src_y < 0 ||"; c += " src_x >= src_size.x || src_y >= src_size.y;\n"; c += " FLT4 src = (FLT4)(0.0f);\n"; c += " int4 ind = (int4)(0);\n"; c += " if (!outside) {\n"; c += " src = " + src.Read("src_adr", TextureAddressMode::DONT_CARE) + ";\n"; c += " ind = convert_int4(" + src_ind.Read("src_adr", TextureAddressMode::DONT_CARE) + ");\n"; c += " }\n"; } else { c += " FLT4 src = " + src.Read("src_adr", address_mode) + ";\n"; c += " int4 ind = convert_int4(" + src_ind.Read("src_adr", address_mode) + ");\n"; } if (op_def.batch_support) { c += " int t_x = X0 - (src_x0 * stride.x - padding.x);\n"; } else { c += " int t_x = X - (src_x * stride.x - padding.x);\n"; } c += " int t_y = Y - (src_y * stride.y - padding.y);\n"; c += " int t_index = t_y * kernel_size.x + t_x;\n"; c += " FLT4 result;\n"; const std::string channels[] = {".x", ".y", ".z", ".w"}; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; c += " result" + s + "= t_index == ind" + s + "? src" + s + ": 0.0f;\n"; } c += PostProcess(linked_operations, {"result", "X", "Y", "Z"}); c += " " + dst.Write3D("result", "X", "Y", "Z"); c += "}\n"; return c; } } // namespace MaxUnpooling::MaxUnpooling(const OperationDef& definition, const MaxUnpooling2DAttributes& attr) : GPUOperation(definition), stride_(attr.strides.w, attr.strides.h), padding_(attr.padding.appended.w, attr.padding.appended.h), kernel_size_(attr.kernel.w, attr.kernel.h) {} MaxUnpooling::MaxUnpooling(MaxUnpooling&& kernel) : GPUOperation(std::move(kernel)), stride_(kernel.stride_), padding_(kernel.padding_), kernel_size_(kernel.kernel_size_), kernel_(std::move(kernel.kernel_)), work_group_size_(kernel.work_group_size_) {} MaxUnpooling& MaxUnpooling::operator=(MaxUnpooling&& kernel) { if (this != &kernel) { std::swap(stride_, kernel.stride_); std::swap(padding_, kernel.padding_); std::swap(kernel_size_, kernel.kernel_size_); kernel_ = std::move(kernel.kernel_); std::swap(work_group_size_, kernel.work_group_size_); GPUOperation::operator=(std::move(kernel)); } return *this; } Status MaxUnpooling::Compile(const CreationContext& creation_context) { const auto code = GetMaxUnoolingKernelCode( definition_, *creation_context.device, linked_operations_); return creation_context.cache->GetOrCreateCLKernel( code, "main_function", *creation_context.context, *creation_context.device, &kernel_); } Status MaxUnpooling::BindArguments() { kernel_.ResetBindingCounter(); RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[0]->GetMemoryPtr())); RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[1]->GetMemoryPtr())); RETURN_IF_ERROR(BindArgs(&kernel_, linked_operations_)); RETURN_IF_ERROR(kernel_.SetMemoryAuto(dst_[0]->GetMemoryPtrForWriting())); RETURN_IF_ERROR(kernel_.SetBytesAuto(src_[0]->GetWBatchedHDB())); RETURN_IF_ERROR(kernel_.SetBytesAuto(dst_[0]->GetWBatchedHDB())); RETURN_IF_ERROR(kernel_.SetBytesAuto(kernel_size_)); RETURN_IF_ERROR(kernel_.SetBytesAuto(padding_)); RETURN_IF_ERROR(kernel_.SetBytesAuto(stride_)); return OkStatus(); } int3 MaxUnpooling::GetGridSize() const { const int grid_x = dst_[0]->Width() * dst_[0]->Batch(); const int grid_y = dst_[0]->Height(); const int grid_z = dst_[0]->Depth(); return int3(grid_x, grid_y, grid_z); } Status MaxUnpooling::Tune(const TuningParameters& params) { RETURN_IF_ERROR(BindArguments()); return GetBestWorkGroup(params, kernel_, GetGridSize(), &work_group_size_); } Status MaxUnpooling::AddToQueue(CLCommandQueue* queue) { RETURN_IF_ERROR(BindArguments()); return queue->DispatchImplicit(kernel_, GetGridSize(), work_group_size_); } MaxUnpooling CreateMaxUnpooling(const OperationDef& definition, const MaxUnpooling2DAttributes& attr) { return MaxUnpooling(definition, attr); } } // namespace cl } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>/* Video Core Copyright (c) 2014 James G. Hurley 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. */ #ifndef videocore_IAudioMixer_hpp #define videocore_IAudioMixer_hpp #include <videocore/system/Buffer.hpp> #include <videocore/mixers/IMixer.hpp> #include <videocore/transforms/IMetadata.hpp> namespace videocore { /*! Enum values for the AudioBufferMetadata tuple */ enum { kAudioMetadataFrequencyInHz, /*!< Specifies the sampling rate of the buffer */ kAudioMetadataBitsPerChannel, /*!< Specifies the number of bits per channel */ kAudioMetadataChannelCount, /*!< Specifies the number of channels */ kAudioMetadataFlags, /*!< Specifies the audio flags */ kAudioMetadataBytesPerFrame, /*!< Specifies the number of bytes per frame */ kAudioMetadataNumberFrames, /*!< Number of sample frames in the buffer. */ kAudioMetadataUsesOSStruct, /*!< Indicates that the audio is not raw but instead uses a platform-specific struct */ kAudioMetadataLoops, /*!< Indicates whether or not the buffer should loop. Currently ignored. */ kAudioMetadataSource /*!< A smart pointer to the source. */ }; /*! * Specifies the properties of the incoming audio buffer. */ typedef MetaData<'soun', int, int, int, int, int, int, bool, bool, std::weak_ptr<ISource> > AudioBufferMetadata; class ISource; /*! IAudioMixer interface. Defines the required interface methods for Audio mixers. */ class IAudioMixer : public IMixer { public: /*! Virtual destructor */ virtual ~IAudioMixer() {}; /*! * Set the output gain of the specified source. * * \param source A smart pointer to the source to be modified * \param gain A value between 0 and 1 representing the desired gain. */ virtual void setSourceGain(std::weak_ptr<ISource> source, float gain) = 0; /*! * Set the channel count. * * \param channelCount The number of audio channels. */ virtual void setChannelCount(int channelCount) = 0; /*! * Set the channel count. * * \param frequencyInHz The audio sample frequency in Hz. */ virtual void setFrequencyInHz(float frequencyInHz) = 0; /*! * Set the amount of time to buffer before emitting mixed samples. * * \param duration The duration, in seconds, to buffer. */ virtual void setMinimumBufferDuration(const double duration) = 0; }; } #endif <commit_msg>fixed typo IMetaData<commit_after>/* Video Core Copyright (c) 2014 James G. Hurley 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. */ #ifndef videocore_IAudioMixer_hpp #define videocore_IAudioMixer_hpp #include <videocore/system/Buffer.hpp> #include <videocore/mixers/IMixer.hpp> #include <videocore/transforms/IMetaData.hpp> namespace videocore { /*! Enum values for the AudioBufferMetadata tuple */ enum { kAudioMetadataFrequencyInHz, /*!< Specifies the sampling rate of the buffer */ kAudioMetadataBitsPerChannel, /*!< Specifies the number of bits per channel */ kAudioMetadataChannelCount, /*!< Specifies the number of channels */ kAudioMetadataFlags, /*!< Specifies the audio flags */ kAudioMetadataBytesPerFrame, /*!< Specifies the number of bytes per frame */ kAudioMetadataNumberFrames, /*!< Number of sample frames in the buffer. */ kAudioMetadataUsesOSStruct, /*!< Indicates that the audio is not raw but instead uses a platform-specific struct */ kAudioMetadataLoops, /*!< Indicates whether or not the buffer should loop. Currently ignored. */ kAudioMetadataSource /*!< A smart pointer to the source. */ }; /*! * Specifies the properties of the incoming audio buffer. */ typedef MetaData<'soun', int, int, int, int, int, int, bool, bool, std::weak_ptr<ISource> > AudioBufferMetadata; class ISource; /*! IAudioMixer interface. Defines the required interface methods for Audio mixers. */ class IAudioMixer : public IMixer { public: /*! Virtual destructor */ virtual ~IAudioMixer() {}; /*! * Set the output gain of the specified source. * * \param source A smart pointer to the source to be modified * \param gain A value between 0 and 1 representing the desired gain. */ virtual void setSourceGain(std::weak_ptr<ISource> source, float gain) = 0; /*! * Set the channel count. * * \param channelCount The number of audio channels. */ virtual void setChannelCount(int channelCount) = 0; /*! * Set the channel count. * * \param frequencyInHz The audio sample frequency in Hz. */ virtual void setFrequencyInHz(float frequencyInHz) = 0; /*! * Set the amount of time to buffer before emitting mixed samples. * * \param duration The duration, in seconds, to buffer. */ virtual void setMinimumBufferDuration(const double duration) = 0; }; } #endif <|endoftext|>
<commit_before>#ifndef VIENNAMETA_ALGORITHM_HPP #define VIENNAMETA_ALGORITHM_HPP #include "collection.hpp" #include "container_collection.hpp" #include "view.hpp" #include "viennagrid/meta/algorithm.hpp" namespace viennagrid { namespace storage { namespace collection { template<typename collection_type, typename functor> struct for_each_functor { for_each_functor(collection_type & _collection, functor _f) : collection(_collection), f(_f) {} template<typename type> void operator()( viennameta::tag<type> ) { f( viennagrid::storage::collection::get<type>(collection) ); } collection_type & collection; functor f; }; template<typename collection_type, typename functor> void for_each(collection_type & collection, functor f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each< typename viennagrid::storage::container_collection::result_of::container_typelist<collection_type>::type >(ff); } template<typename typelist, typename collection_type, typename functor> void for_each_typelist(collection_type & collection, functor & f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each<typelist>(ff); } } namespace container_collection { template<typename collection_type, typename functor> class for_each_functor { public: for_each_functor(collection_type & _collection, functor _f) : collection(_collection), f(_f) {} template<typename type> void operator()( viennameta::tag<type> ) { f( viennagrid::storage::container_collection::get<type>(collection) ); } private: collection_type & collection; functor f; }; template<typename typelist, typename collection_type, typename functor> void for_each_typelist(collection_type & collection, functor f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each<typelist>(ff); } template<typename collection_type_1, typename collection_type_2, typename functor> class dual_for_each_functor { public: dual_for_each_functor( collection_type_1 & _container_collection_1, collection_type_2 & _container_collection_2, functor _f) : container_collection_1(_container_collection_1), container_collection_2(_container_collection_2), f(_f) {} template<typename type> void operator() ( viennameta::tag<type> ) { f( viennagrid::storage::container_collection::get<type>(container_collection_1), viennagrid::storage::container_collection::get<type>(container_collection_2) ); } private: collection_type_1 & container_collection_1; collection_type_2 & container_collection_2; functor f; }; template<typename predicate> class copy_functor { public: copy_functor(predicate _pred) : pred(_pred) {} template<typename src_container_type, typename dst_container_type> void operator() (src_container_type & src_container, dst_container_type & dst_container) { for (typename src_container_type::iterator it = src_container.begin(); it != src_container.end(); ++it) if (pred(*it)) viennagrid::storage::container::insert(dst_container, *it); } template<typename src_container_type, typename dst_container_type> void operator() (const src_container_type & src_container, dst_container_type & dst_container) { for (typename src_container_type::const_iterator it = src_container.begin(); it != src_container.end(); ++it) if (pred(*it)) viennagrid::storage::container::insert(dst_container, *it); } private: predicate pred; }; template<typename src_container_typelist, typename dst_container_typelist> void copy(const collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst) { dual_for_each_functor< const collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<viennameta::true_predicate> > functor(src, dst, copy_functor<viennameta::true_predicate>(viennameta::true_predicate())); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename src_container_typelist, typename dst_container_typelist, typename predicate> void copy_if(const collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst, predicate pred) { dual_for_each_functor< const collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<predicate> > functor(src, dst, copy_functor<predicate>(pred)); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename src_container_typelist, typename dst_container_typelist> void reference(collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst) { dual_for_each_functor< collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<viennameta::true_predicate> > functor(src, dst, copy_functor<viennameta::true_predicate>(viennameta::true_predicate())); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename src_container_typelist, typename dst_container_typelist, typename predicate> void reference_if(collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst, predicate pred) { dual_for_each_functor< collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<predicate> > functor(src, dst, copy_functor<predicate>(pred)); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } } } } #endif <commit_msg>added support for hooks seperate hook() implementaion<commit_after>#ifndef VIENNAMETA_ALGORITHM_HPP #define VIENNAMETA_ALGORITHM_HPP #include "collection.hpp" #include "container_collection.hpp" #include "view.hpp" #include "viennagrid/meta/algorithm.hpp" namespace viennagrid { namespace storage { namespace collection { template<typename collection_type, typename functor> struct for_each_functor { for_each_functor(collection_type & _collection, functor _f) : collection(_collection), f(_f) {} template<typename type> void operator()( viennameta::tag<type> ) { f( viennagrid::storage::collection::get<type>(collection) ); } collection_type & collection; functor f; }; template<typename collection_type, typename functor> void for_each(collection_type & collection, functor f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each< typename viennagrid::storage::container_collection::result_of::container_typelist<collection_type>::type >(ff); } template<typename typelist, typename collection_type, typename functor> void for_each_typelist(collection_type & collection, functor & f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each<typelist>(ff); } } namespace container_collection { template<typename collection_type, typename functor> class for_each_functor { public: for_each_functor(collection_type & _collection, functor _f) : collection(_collection), f(_f) {} template<typename type> void operator()( viennameta::tag<type> ) { f( viennagrid::storage::container_collection::get<type>(collection) ); } private: collection_type & collection; functor f; }; template<typename typelist, typename collection_type, typename functor> void for_each_typelist(collection_type & collection, functor f) { for_each_functor<collection_type, functor> ff(collection, f); viennameta::typelist::for_each<typelist>(ff); } template<typename collection_type_1, typename collection_type_2, typename functor> class dual_for_each_functor { public: dual_for_each_functor( collection_type_1 & _container_collection_1, collection_type_2 & _container_collection_2, functor _f) : container_collection_1(_container_collection_1), container_collection_2(_container_collection_2), f(_f) {} template<typename type> void operator() ( viennameta::tag<type> ) { f( viennagrid::storage::container_collection::get<type>(container_collection_1), viennagrid::storage::container_collection::get<type>(container_collection_2) ); } private: collection_type_1 & container_collection_1; collection_type_2 & container_collection_2; functor f; }; template<typename predicate> class copy_functor { public: copy_functor(predicate _pred) : pred(_pred) {} template<typename src_container_type, typename dst_container_type> void operator() (const src_container_type & src_container, dst_container_type & dst_container) { for (typename src_container_type::const_iterator it = src_container.begin(); it != src_container.end(); ++it) if (pred(*it)) dst_container.insert( *it ); //viennagrid::storage::container::insert(dst_container, *it); //viennagrid::storage::container::insert_helper<dst_container_type>::insert_noreturn(dst_container, *it); } private: predicate pred; }; template<typename src_container_typelist, typename dst_container_typelist> void copy(const collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst) { dual_for_each_functor< const collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<viennameta::true_predicate> > functor(src, dst, copy_functor<viennameta::true_predicate>(viennameta::true_predicate())); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename src_container_typelist, typename dst_container_typelist, typename predicate> void copy_if(const collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst, predicate pred) { dual_for_each_functor< const collection_t<src_container_typelist>, collection_t<dst_container_typelist>, copy_functor<predicate> > functor(src, dst, copy_functor<predicate>(pred)); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename predicate> class hook_functor { public: hook_functor(predicate _pred) : pred(_pred) {} template<typename container_type, typename base_container_type, typename hook_tag, typename hook_container_tag> void operator() (container_type & src_container, view_t<base_container_type, hook_tag, hook_container_tag> & dst_view) { for (typename container_type::hook_iterator it = src_container.hook_begin(); it != src_container.hook_end(); ++it) if (pred( src_container.dereference_hook(*it) )) dst_view.insert_hook( *it ); } private: predicate pred; }; template<typename src_container_typelist, typename dst_container_typelist> void hook(collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst) { dual_for_each_functor< collection_t<src_container_typelist>, collection_t<dst_container_typelist>, hook_functor<viennameta::true_predicate> > functor(src, dst, hook_functor<viennameta::true_predicate>(viennameta::true_predicate())); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } template<typename src_container_typelist, typename dst_container_typelist, typename predicate> void hook_if(collection_t<src_container_typelist> & src, collection_t<dst_container_typelist> & dst, predicate pred) { dual_for_each_functor< collection_t<src_container_typelist>, collection_t<dst_container_typelist>, hook_functor<predicate> > functor(src, dst, hook_functor<predicate>(pred)); typedef typename viennagrid::storage::result_of::common_values< collection_t<src_container_typelist>, collection_t<dst_container_typelist> >::type typelist; viennameta::typelist::for_each<typelist>(functor); } } } } #endif <|endoftext|>
<commit_before>//===- Symbols.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Symbols.h" #include "Config.h" #include "InputChunks.h" #include "InputFiles.h" #include "InputGlobal.h" #include "OutputSegment.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Strings.h" #define DEBUG_TYPE "lld" using namespace llvm; using namespace llvm::wasm; using namespace lld; using namespace lld::wasm; DefinedFunction *WasmSym::CallCtors; DefinedData *WasmSym::DsoHandle; DefinedData *WasmSym::DataEnd; DefinedData *WasmSym::HeapBase; DefinedGlobal *WasmSym::StackPointer; WasmSymbolType Symbol::getWasmType() const { if (isa<FunctionSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION; if (isa<DataSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_DATA; if (isa<GlobalSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL; llvm_unreachable("invalid symbol kind"); } InputChunk *Symbol::getChunk() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function; if (auto *D = dyn_cast<DefinedData>(this)) return D->Segment; return nullptr; } bool Symbol::isLive() const { if (auto *G = dyn_cast<DefinedGlobal>(this)) return G->Global->Live; if (InputChunk *C = getChunk()) return C->Live; return Referenced; } void Symbol::markLive() { if (auto *G = dyn_cast<DefinedGlobal>(this)) G->Global->Live = true; if (InputChunk *C = getChunk()) C->Live = true; Referenced = true; } uint32_t Symbol::getOutputSymbolIndex() const { assert(OutputSymbolIndex != INVALID_INDEX); return OutputSymbolIndex; } void Symbol::setOutputSymbolIndex(uint32_t Index) { DEBUG(dbgs() << "setOutputSymbolIndex " << Name << " -> " << Index << "\n"); assert(OutputSymbolIndex == INVALID_INDEX); OutputSymbolIndex = Index; } bool Symbol::isWeak() const { return (Flags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK; } bool Symbol::isLocal() const { return (Flags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_LOCAL; } bool Symbol::isHidden() const { return (Flags & WASM_SYMBOL_VISIBILITY_MASK) == WASM_SYMBOL_VISIBILITY_HIDDEN; } void Symbol::setHidden(bool IsHidden) { DEBUG(dbgs() << "setHidden: " << Name << " -> " << IsHidden << "\n"); Flags &= ~WASM_SYMBOL_VISIBILITY_MASK; if (IsHidden) Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; else Flags |= WASM_SYMBOL_VISIBILITY_DEFAULT; } uint32_t FunctionSymbol::getFunctionIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->getFunctionIndex(); assert(FunctionIndex != INVALID_INDEX); return FunctionIndex; } void FunctionSymbol::setFunctionIndex(uint32_t Index) { DEBUG(dbgs() << "setFunctionIndex " << Name << " -> " << Index << "\n"); assert(FunctionIndex == INVALID_INDEX); FunctionIndex = Index; } bool FunctionSymbol::hasFunctionIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->hasFunctionIndex(); return FunctionIndex != INVALID_INDEX; } uint32_t FunctionSymbol::getTableIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->getTableIndex(); assert(TableIndex != INVALID_INDEX); return TableIndex; } bool FunctionSymbol::hasTableIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->hasTableIndex(); return TableIndex != INVALID_INDEX; } void FunctionSymbol::setTableIndex(uint32_t Index) { // For imports, we set the table index here on the Symbol; for defined // functions we set the index on the InputFunction so that we don't export // the same thing twice (keeps the table size down). if (auto *F = dyn_cast<DefinedFunction>(this)) { F->Function->setTableIndex(Index); return; } DEBUG(dbgs() << "setTableIndex " << Name << " -> " << Index << "\n"); assert(TableIndex == INVALID_INDEX); TableIndex = Index; } DefinedFunction::DefinedFunction(StringRef Name, uint32_t Flags, InputFile *F, InputFunction *Function) : FunctionSymbol(Name, DefinedFunctionKind, Flags, F, Function ? &Function->Signature : nullptr), Function(Function) {} uint32_t DefinedData::getVirtualAddress() const { DEBUG(dbgs() << "getVirtualAddress: " << getName() << "\n"); if (Segment) return Segment->OutputSeg->StartVA + Segment->OutputSegmentOffset + Offset; return Offset; } void DefinedData::setVirtualAddress(uint32_t Value) { DEBUG(dbgs() << "setVirtualAddress " << Name << " -> " << Value << "\n"); assert(!Segment); Offset = Value; } uint32_t DefinedData::getOutputSegmentOffset() const { DEBUG(dbgs() << "getOutputSegmentOffset: " << getName() << "\n"); return Segment->OutputSegmentOffset + Offset; } uint32_t DefinedData::getOutputSegmentIndex() const { DEBUG(dbgs() << "getOutputSegmentIndex: " << getName() << "\n"); return Segment->OutputSeg->Index; } uint32_t GlobalSymbol::getGlobalIndex() const { if (auto *F = dyn_cast<DefinedGlobal>(this)) return F->Global->getGlobalIndex(); assert(GlobalIndex != INVALID_INDEX); return GlobalIndex; } void GlobalSymbol::setGlobalIndex(uint32_t Index) { DEBUG(dbgs() << "setGlobalIndex " << Name << " -> " << Index << "\n"); assert(GlobalIndex == INVALID_INDEX); GlobalIndex = Index; } bool GlobalSymbol::hasGlobalIndex() const { if (auto *F = dyn_cast<DefinedGlobal>(this)) return F->Global->hasGlobalIndex(); return GlobalIndex != INVALID_INDEX; } DefinedGlobal::DefinedGlobal(StringRef Name, uint32_t Flags, InputFile *File, InputGlobal *Global) : GlobalSymbol(Name, DefinedGlobalKind, Flags, File, Global ? &Global->getType() : nullptr), Global(Global) {} void LazySymbol::fetch() { cast<ArchiveFile>(File)->addMember(&ArchiveSymbol); } std::string lld::toString(const wasm::Symbol &Sym) { if (Config->Demangle) if (Optional<std::string> S = demangleItanium(Sym.getName())) return *S; return Sym.getName(); } std::string lld::toString(wasm::Symbol::Kind Kind) { switch (Kind) { case wasm::Symbol::DefinedFunctionKind: return "DefinedFunction"; case wasm::Symbol::DefinedDataKind: return "DefinedData"; case wasm::Symbol::DefinedGlobalKind: return "DefinedGlobal"; case wasm::Symbol::UndefinedFunctionKind: return "UndefinedFunction"; case wasm::Symbol::UndefinedDataKind: return "UndefinedData"; case wasm::Symbol::UndefinedGlobalKind: return "UndefinedGlobal"; case wasm::Symbol::LazyKind: return "LazyKind"; } llvm_unreachable("invalid symbol kind"); } std::string lld::toString(WasmSymbolType Type) { switch (Type) { case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION: return "Function"; case llvm::wasm::WASM_SYMBOL_TYPE_DATA: return "Data"; case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL: return "Global"; } llvm_unreachable("invalid symbol type"); } <commit_msg>[LLD][WASM] Handle WASM_SYMBOL_TYPE_SECTION in toString().<commit_after>//===- Symbols.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Symbols.h" #include "Config.h" #include "InputChunks.h" #include "InputFiles.h" #include "InputGlobal.h" #include "OutputSegment.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Strings.h" #define DEBUG_TYPE "lld" using namespace llvm; using namespace llvm::wasm; using namespace lld; using namespace lld::wasm; DefinedFunction *WasmSym::CallCtors; DefinedData *WasmSym::DsoHandle; DefinedData *WasmSym::DataEnd; DefinedData *WasmSym::HeapBase; DefinedGlobal *WasmSym::StackPointer; WasmSymbolType Symbol::getWasmType() const { if (isa<FunctionSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION; if (isa<DataSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_DATA; if (isa<GlobalSymbol>(this)) return llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL; llvm_unreachable("invalid symbol kind"); } InputChunk *Symbol::getChunk() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function; if (auto *D = dyn_cast<DefinedData>(this)) return D->Segment; return nullptr; } bool Symbol::isLive() const { if (auto *G = dyn_cast<DefinedGlobal>(this)) return G->Global->Live; if (InputChunk *C = getChunk()) return C->Live; return Referenced; } void Symbol::markLive() { if (auto *G = dyn_cast<DefinedGlobal>(this)) G->Global->Live = true; if (InputChunk *C = getChunk()) C->Live = true; Referenced = true; } uint32_t Symbol::getOutputSymbolIndex() const { assert(OutputSymbolIndex != INVALID_INDEX); return OutputSymbolIndex; } void Symbol::setOutputSymbolIndex(uint32_t Index) { DEBUG(dbgs() << "setOutputSymbolIndex " << Name << " -> " << Index << "\n"); assert(OutputSymbolIndex == INVALID_INDEX); OutputSymbolIndex = Index; } bool Symbol::isWeak() const { return (Flags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK; } bool Symbol::isLocal() const { return (Flags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_LOCAL; } bool Symbol::isHidden() const { return (Flags & WASM_SYMBOL_VISIBILITY_MASK) == WASM_SYMBOL_VISIBILITY_HIDDEN; } void Symbol::setHidden(bool IsHidden) { DEBUG(dbgs() << "setHidden: " << Name << " -> " << IsHidden << "\n"); Flags &= ~WASM_SYMBOL_VISIBILITY_MASK; if (IsHidden) Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN; else Flags |= WASM_SYMBOL_VISIBILITY_DEFAULT; } uint32_t FunctionSymbol::getFunctionIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->getFunctionIndex(); assert(FunctionIndex != INVALID_INDEX); return FunctionIndex; } void FunctionSymbol::setFunctionIndex(uint32_t Index) { DEBUG(dbgs() << "setFunctionIndex " << Name << " -> " << Index << "\n"); assert(FunctionIndex == INVALID_INDEX); FunctionIndex = Index; } bool FunctionSymbol::hasFunctionIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->hasFunctionIndex(); return FunctionIndex != INVALID_INDEX; } uint32_t FunctionSymbol::getTableIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->getTableIndex(); assert(TableIndex != INVALID_INDEX); return TableIndex; } bool FunctionSymbol::hasTableIndex() const { if (auto *F = dyn_cast<DefinedFunction>(this)) return F->Function->hasTableIndex(); return TableIndex != INVALID_INDEX; } void FunctionSymbol::setTableIndex(uint32_t Index) { // For imports, we set the table index here on the Symbol; for defined // functions we set the index on the InputFunction so that we don't export // the same thing twice (keeps the table size down). if (auto *F = dyn_cast<DefinedFunction>(this)) { F->Function->setTableIndex(Index); return; } DEBUG(dbgs() << "setTableIndex " << Name << " -> " << Index << "\n"); assert(TableIndex == INVALID_INDEX); TableIndex = Index; } DefinedFunction::DefinedFunction(StringRef Name, uint32_t Flags, InputFile *F, InputFunction *Function) : FunctionSymbol(Name, DefinedFunctionKind, Flags, F, Function ? &Function->Signature : nullptr), Function(Function) {} uint32_t DefinedData::getVirtualAddress() const { DEBUG(dbgs() << "getVirtualAddress: " << getName() << "\n"); if (Segment) return Segment->OutputSeg->StartVA + Segment->OutputSegmentOffset + Offset; return Offset; } void DefinedData::setVirtualAddress(uint32_t Value) { DEBUG(dbgs() << "setVirtualAddress " << Name << " -> " << Value << "\n"); assert(!Segment); Offset = Value; } uint32_t DefinedData::getOutputSegmentOffset() const { DEBUG(dbgs() << "getOutputSegmentOffset: " << getName() << "\n"); return Segment->OutputSegmentOffset + Offset; } uint32_t DefinedData::getOutputSegmentIndex() const { DEBUG(dbgs() << "getOutputSegmentIndex: " << getName() << "\n"); return Segment->OutputSeg->Index; } uint32_t GlobalSymbol::getGlobalIndex() const { if (auto *F = dyn_cast<DefinedGlobal>(this)) return F->Global->getGlobalIndex(); assert(GlobalIndex != INVALID_INDEX); return GlobalIndex; } void GlobalSymbol::setGlobalIndex(uint32_t Index) { DEBUG(dbgs() << "setGlobalIndex " << Name << " -> " << Index << "\n"); assert(GlobalIndex == INVALID_INDEX); GlobalIndex = Index; } bool GlobalSymbol::hasGlobalIndex() const { if (auto *F = dyn_cast<DefinedGlobal>(this)) return F->Global->hasGlobalIndex(); return GlobalIndex != INVALID_INDEX; } DefinedGlobal::DefinedGlobal(StringRef Name, uint32_t Flags, InputFile *File, InputGlobal *Global) : GlobalSymbol(Name, DefinedGlobalKind, Flags, File, Global ? &Global->getType() : nullptr), Global(Global) {} void LazySymbol::fetch() { cast<ArchiveFile>(File)->addMember(&ArchiveSymbol); } std::string lld::toString(const wasm::Symbol &Sym) { if (Config->Demangle) if (Optional<std::string> S = demangleItanium(Sym.getName())) return *S; return Sym.getName(); } std::string lld::toString(wasm::Symbol::Kind Kind) { switch (Kind) { case wasm::Symbol::DefinedFunctionKind: return "DefinedFunction"; case wasm::Symbol::DefinedDataKind: return "DefinedData"; case wasm::Symbol::DefinedGlobalKind: return "DefinedGlobal"; case wasm::Symbol::UndefinedFunctionKind: return "UndefinedFunction"; case wasm::Symbol::UndefinedDataKind: return "UndefinedData"; case wasm::Symbol::UndefinedGlobalKind: return "UndefinedGlobal"; case wasm::Symbol::LazyKind: return "LazyKind"; } llvm_unreachable("invalid symbol kind"); } std::string lld::toString(WasmSymbolType Type) { switch (Type) { case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION: return "Function"; case llvm::wasm::WASM_SYMBOL_TYPE_DATA: return "Data"; case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL: return "Global"; case llvm::wasm::WASM_SYMBOL_TYPE_SECTION: return "Section"; } llvm_unreachable("invalid symbol type"); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ResampleVolumesToBeIsotropic.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkIdentityTransform.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkIntensityWindowingImageFilter.h" int main( int argc, char * argv[] ) { if( argc < 5 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile lower upper " << std::endl; return 1; } const unsigned int Dimension = 3; typedef unsigned short InputPixelType; typedef float InternalPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } InputImageType::ConstPointer inputImage = reader->GetOutput(); const double * inputSpacing = inputImage->GetSpacing(); const double isoSpacing = sqrt( inputSpacing[2] * inputSpacing[0] ); typedef itk::IntensityWindowingImageFilter< InputImageType, InternalImageType > IntensityFilterType; IntensityFilterType::Pointer intensityWindowing = IntensityFilterType::New(); intensityWindowing->SetWindowMinimum( atoi( argv[3] ) ); intensityWindowing->SetWindowMaximum( atoi( argv[4] ) ); intensityWindowing->SetOutputMinimum( 0.0 ); intensityWindowing->SetOutputMaximum( 255.0 ); // floats but in the range of chars. typedef itk::RecursiveGaussianImageFilter< InternalImageType, InternalImageType > GaussianFilterType; GaussianFilterType::Pointer smootherX = GaussianFilterType::New(); GaussianFilterType::Pointer smootherY = GaussianFilterType::New(); intensityWindowing->SetInput( reader->GetOutput() ); smootherX->SetInput( intensityWindowing->GetOutput() ); smootherY->SetInput( smootherX->GetOutput() ); smootherX->SetSigma( isoSpacing ); smootherY->SetSigma( isoSpacing ); smootherX->SetDirection( 0 ); smootherY->SetDirection( 1 ); smootherX->SetNormalizeAcrossScale( true ); smootherY->SetNormalizeAcrossScale( true ); try { smootherY->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput(); typedef itk::ResampleImageFilter< InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; typedef itk::LinearInterpolateImageFunction< InternalImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator( interpolator ); resampler->SetDefaultPixelValue( 1000 ); // highlight regions without source double spacing[ Dimension ]; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); // Use the same origin resampler->SetOutputOrigin( inputImage->GetOrigin() ); InputImageType::SizeType inputSize = inputImage->GetLargestPossibleRegion().GetSize(); InputImageType::SizeType size; size[0] = inputSize[0] * inputSpacing[0] / isoSpacing; size[1] = inputSize[1] * inputSpacing[1] / isoSpacing; size[2] = ( inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing; resampler->SetSize( size ); resampler->SetInput( smoothedImage ); writer->SetInput( resampler->GetOutput() ); TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } return 0; } <commit_msg>ERR: warnings.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ResampleVolumesToBeIsotropic.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkIdentityTransform.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkIntensityWindowingImageFilter.h" int main( int argc, char * argv[] ) { if( argc < 5 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile lower upper " << std::endl; return 1; } const unsigned int Dimension = 3; typedef unsigned short InputPixelType; typedef float InternalPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } InputImageType::ConstPointer inputImage = reader->GetOutput(); const double * inputSpacing = inputImage->GetSpacing(); const double isoSpacing = sqrt( inputSpacing[2] * inputSpacing[0] ); typedef itk::IntensityWindowingImageFilter< InputImageType, InternalImageType > IntensityFilterType; IntensityFilterType::Pointer intensityWindowing = IntensityFilterType::New(); intensityWindowing->SetWindowMinimum( atoi( argv[3] ) ); intensityWindowing->SetWindowMaximum( atoi( argv[4] ) ); intensityWindowing->SetOutputMinimum( 0.0 ); intensityWindowing->SetOutputMaximum( 255.0 ); // floats but in the range of chars. typedef itk::RecursiveGaussianImageFilter< InternalImageType, InternalImageType > GaussianFilterType; GaussianFilterType::Pointer smootherX = GaussianFilterType::New(); GaussianFilterType::Pointer smootherY = GaussianFilterType::New(); intensityWindowing->SetInput( reader->GetOutput() ); smootherX->SetInput( intensityWindowing->GetOutput() ); smootherY->SetInput( smootherX->GetOutput() ); smootherX->SetSigma( isoSpacing ); smootherY->SetSigma( isoSpacing ); smootherX->SetDirection( 0 ); smootherY->SetDirection( 1 ); smootherX->SetNormalizeAcrossScale( true ); smootherY->SetNormalizeAcrossScale( true ); try { smootherY->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput(); typedef itk::ResampleImageFilter< InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; typedef itk::LinearInterpolateImageFunction< InternalImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator( interpolator ); resampler->SetDefaultPixelValue( 255 ); // highlight regions without source double spacing[ Dimension ]; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); // Use the same origin resampler->SetOutputOrigin( inputImage->GetOrigin() ); InputImageType::SizeType inputSize = inputImage->GetLargestPossibleRegion().GetSize(); typedef InputImageType::SizeType::SizeValueType SizeValueType; InputImageType::SizeType size; size[0] = static_cast<SizeValueType>(inputSize[0] * inputSpacing[0] / isoSpacing); size[1] = static_cast<SizeValueType>(inputSize[1] * inputSpacing[1] / isoSpacing); size[2] = static_cast<SizeValueType>((inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing); resampler->SetSize( size ); resampler->SetInput( smoothedImage ); writer->SetInput( resampler->GetOutput() ); TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception catched !" << std::endl; std::cerr << excep << std::endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "CellularTests.h" #ifndef CELLULAR_DEVICE #error [NOT_SUPPORTED] CELLULAR_DEVICE must be defined for this test #endif EventQueue queue(32 * EVENTS_EVENT_SIZE); Thread t; CELLULAR_DEVICE cellularDevice(queue); UARTSerial serial(MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE); CellularNetwork *network = NULL; CellularPower *pwr = NULL; CellularSIM *sim = NULL; CellularSMS *sms = NULL; using namespace utest::v1; // using namespace mbed; utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } Case cases[] = { // power test Case("Create power", test_create_power, greentea_failure_handler), #ifdef MBED_CONF_APP_CELLULAR_SIM_PIN // sim test Case("test get SIM state", test_get_sim_state, greentea_failure_handler), Case("SIM set pin", test_set_pin, greentea_failure_handler), Case("SIM change pin", test_change_pin, greentea_failure_handler), #endif // network tests Case("attach", test_attach, greentea_failure_handler), // SMS tests Case("SMS init", test_sms_init, greentea_failure_handler), // network tests Case("connect", test_connect, greentea_failure_handler), Case("get_ip_address", test_get_ip_address, greentea_failure_handler), // stack tests Case("open", test_socket_open, greentea_failure_handler), Case("bind", test_socket_bind, greentea_failure_handler), // Case("set socket blocking", test_socket_set_blocking, greentea_failure_handler), // Case("socket send receive in blocking mode", test_socket_send_receive_blocking, greentea_failure_handler), Case("set socket non blocking", test_socket_set_non_blocking, greentea_failure_handler), Case("socket send receive in non blocking mode", test_socket_send_receive_non_blocking, greentea_failure_handler), Case("close", test_socket_close, greentea_failure_handler), // network tests Case("disconnect", test_disconnect, greentea_failure_handler), // test closing of all interface, must be the last test case Case("Close all Interfaces", test_close_interfaces, greentea_failure_handler) }; utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(300, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Specification specification(test_setup, cases); void test_close_interfaces() { // SMS is already closed in it's test cellularDevice.close_network(); cellularDevice.close_sim(); cellularDevice.close_power(); } int main() { #if defined (MDMRTS) && defined (MDMCTS) serial.set_flow_control(SerialBase::RTSCTS, MDMRTS, MDMCTS); #endif pwr = cellularDevice.open_power(&serial); sim = cellularDevice.open_sim(&serial); sms = cellularDevice.open_sms(&serial); network = cellularDevice.open_network(&serial); t.start(callback(&queue, &EventQueue::dispatch_forever)); return Harness::run(specification); } <commit_msg>Fixed travis-ci.<commit_after>/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "CellularTests.h" #if !defined(MBED_CONF_NSAPI_PRESENT) #error [NOT_SUPPORTED] A json configuration file is needed. Skipping this build. #endif #ifndef CELLULAR_DEVICE #error [NOT_SUPPORTED] CELLULAR_DEVICE must be defined for this test #endif EventQueue queue(32 * EVENTS_EVENT_SIZE); Thread t; CELLULAR_DEVICE cellularDevice(queue); UARTSerial serial(MDMTXD, MDMRXD, MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE); CellularNetwork *network = NULL; CellularPower *pwr = NULL; CellularSIM *sim = NULL; CellularSMS *sms = NULL; using namespace utest::v1; // using namespace mbed; utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } Case cases[] = { // power test Case("Create power", test_create_power, greentea_failure_handler), #ifdef MBED_CONF_APP_CELLULAR_SIM_PIN // sim test Case("test get SIM state", test_get_sim_state, greentea_failure_handler), Case("SIM set pin", test_set_pin, greentea_failure_handler), Case("SIM change pin", test_change_pin, greentea_failure_handler), #endif // network tests Case("attach", test_attach, greentea_failure_handler), // SMS tests Case("SMS init", test_sms_init, greentea_failure_handler), // network tests Case("connect", test_connect, greentea_failure_handler), Case("get_ip_address", test_get_ip_address, greentea_failure_handler), // stack tests Case("open", test_socket_open, greentea_failure_handler), Case("bind", test_socket_bind, greentea_failure_handler), // Case("set socket blocking", test_socket_set_blocking, greentea_failure_handler), // Case("socket send receive in blocking mode", test_socket_send_receive_blocking, greentea_failure_handler), Case("set socket non blocking", test_socket_set_non_blocking, greentea_failure_handler), Case("socket send receive in non blocking mode", test_socket_send_receive_non_blocking, greentea_failure_handler), Case("close", test_socket_close, greentea_failure_handler), // network tests Case("disconnect", test_disconnect, greentea_failure_handler), // test closing of all interface, must be the last test case Case("Close all Interfaces", test_close_interfaces, greentea_failure_handler) }; utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(300, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Specification specification(test_setup, cases); void test_close_interfaces() { // SMS is already closed in it's test cellularDevice.close_network(); cellularDevice.close_sim(); cellularDevice.close_power(); } int main() { #if defined (MDMRTS) && defined (MDMCTS) serial.set_flow_control(SerialBase::RTSCTS, MDMRTS, MDMCTS); #endif pwr = cellularDevice.open_power(&serial); sim = cellularDevice.open_sim(&serial); sms = cellularDevice.open_sms(&serial); network = cellularDevice.open_network(&serial); t.start(callback(&queue, &EventQueue::dispatch_forever)); return Harness::run(specification); } <|endoftext|>
<commit_before>/* * Copyright (c) 2018-2019 Inria * 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 the copyright holders 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. * * Authors: Daniel Carvalho */ /** @file * Implementation of a dictionary based cache compressor. */ #ifndef __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ #define __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ #include <algorithm> #include "debug/CacheComp.hh" #include "mem/cache/compressors/dictionary_compressor.hh" #include "params/BaseDictionaryCompressor.hh" template <class T> DictionaryCompressor<T>::CompData::CompData() : CompressionData() { } template <class T> void DictionaryCompressor<T>::CompData::addEntry(std::unique_ptr<Pattern> pattern) { // Increase size setSizeBits(getSizeBits() + pattern->getSizeBits()); // Push new entry to list entries.push_back(std::move(pattern)); } template <class T> DictionaryCompressor<T>::DictionaryCompressor(const Params *p) : BaseDictionaryCompressor(p) { dictionary.resize(dictionarySize); resetDictionary(); } template <class T> void DictionaryCompressor<T>::resetDictionary() { // Reset number of valid entries numEntries = 0; // Set all entries as 0 std::fill(dictionary.begin(), dictionary.end(), toDictionaryEntry(0)); } template <typename T> std::unique_ptr<typename DictionaryCompressor<T>::Pattern> DictionaryCompressor<T>::compressValue(const T data) { // Split data in bytes const DictionaryEntry bytes = toDictionaryEntry(data); // Start as a no-match pattern. A negative match location is used so that // patterns that depend on the dictionary entry don't match std::unique_ptr<Pattern> pattern = getPattern(bytes, toDictionaryEntry(0), -1); // Search for word on dictionary for (std::size_t i = 0; i < numEntries; i++) { // Try matching input with possible patterns std::unique_ptr<Pattern> temp_pattern = getPattern(bytes, dictionary[i], i); // Check if found pattern is better than previous if (temp_pattern->getSizeBits() < pattern->getSizeBits()) { pattern = std::move(temp_pattern); } } // Update stats patternStats[pattern->getPatternNumber()]++; // Push into dictionary if (pattern->shouldAllocate()) { addToDictionary(bytes); } return pattern; } template <class T> std::unique_ptr<BaseCacheCompressor::CompressionData> DictionaryCompressor<T>::compress(const uint64_t* data) { std::unique_ptr<CompData> comp_data = std::unique_ptr<CompData>(new CompData()); // Reset dictionary resetDictionary(); // Compress every value sequentially const std::vector<T> values((T*)data, (T*)data + blkSize / sizeof(T)); for (const auto& value : values) { std::unique_ptr<Pattern> pattern = compressValue(value); DPRINTF(CacheComp, "Compressed %016x to %s\n", value, pattern->print()); comp_data->addEntry(std::move(pattern)); } // Return compressed line return std::move(comp_data); } template <class T> T DictionaryCompressor<T>::decompressValue(const Pattern* pattern) { // Search for matching entry auto entry_it = dictionary.begin(); std::advance(entry_it, pattern->getMatchLocation()); // Decompress the match. If the decompressed value must be added to // the dictionary, do it const DictionaryEntry data = pattern->decompress(*entry_it); if (pattern->shouldAllocate()) { addToDictionary(data); } // Return value return fromDictionaryEntry(data); } template <class T> void DictionaryCompressor<T>::decompress(const CompressionData* comp_data, uint64_t* data) { const CompData* casted_comp_data = static_cast<const CompData*>(comp_data); // Reset dictionary resetDictionary(); // Decompress every entry sequentially std::vector<T> decomp_values; for (const auto& entry : casted_comp_data->entries) { const T value = decompressValue(&*entry); decomp_values.push_back(value); DPRINTF(CacheComp, "Decompressed %s to %x\n", entry->print(), value); } // Concatenate the decompressed values to generate the original data for (std::size_t i = 0; i < blkSize/8; i++) { data[i] = 0; const std::size_t values_per_entry = sizeof(uint64_t)/sizeof(T); for (int j = values_per_entry - 1; j >= 0; j--) { data[i] |= static_cast<uint64_t>(decomp_values[values_per_entry*i+j]) << (j*8*sizeof(T)); } } } template <class T> typename DictionaryCompressor<T>::DictionaryEntry DictionaryCompressor<T>::toDictionaryEntry(T value) { DictionaryEntry entry; for (int i = 0; i < sizeof(T); i++) { entry[i] = value & 0xFF; value >>= 8; } return entry; } template <class T> T DictionaryCompressor<T>::fromDictionaryEntry(const DictionaryEntry& entry) { T value = 0; for (int i = sizeof(T) - 1; i >= 0; i--) { value <<= 8; value |= entry[i]; } return value; } #endif //__MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ <commit_msg>mem-cache: Modify compressor to appease newer compilers<commit_after>/* * Copyright (c) 2018-2019 Inria * 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 the copyright holders 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. * * Authors: Daniel Carvalho */ /** @file * Implementation of a dictionary based cache compressor. */ #ifndef __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ #define __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ #include <algorithm> #include "debug/CacheComp.hh" #include "mem/cache/compressors/dictionary_compressor.hh" #include "params/BaseDictionaryCompressor.hh" template <class T> DictionaryCompressor<T>::CompData::CompData() : CompressionData() { } template <class T> void DictionaryCompressor<T>::CompData::addEntry(std::unique_ptr<Pattern> pattern) { // Increase size setSizeBits(getSizeBits() + pattern->getSizeBits()); // Push new entry to list entries.push_back(std::move(pattern)); } template <class T> DictionaryCompressor<T>::DictionaryCompressor(const Params *p) : BaseDictionaryCompressor(p) { dictionary.resize(dictionarySize); resetDictionary(); } template <class T> void DictionaryCompressor<T>::resetDictionary() { // Reset number of valid entries numEntries = 0; // Set all entries as 0 std::fill(dictionary.begin(), dictionary.end(), toDictionaryEntry(0)); } template <typename T> std::unique_ptr<typename DictionaryCompressor<T>::Pattern> DictionaryCompressor<T>::compressValue(const T data) { // Split data in bytes const DictionaryEntry bytes = toDictionaryEntry(data); // Start as a no-match pattern. A negative match location is used so that // patterns that depend on the dictionary entry don't match std::unique_ptr<Pattern> pattern = getPattern(bytes, toDictionaryEntry(0), -1); // Search for word on dictionary for (std::size_t i = 0; i < numEntries; i++) { // Try matching input with possible patterns std::unique_ptr<Pattern> temp_pattern = getPattern(bytes, dictionary[i], i); // Check if found pattern is better than previous if (temp_pattern->getSizeBits() < pattern->getSizeBits()) { pattern = std::move(temp_pattern); } } // Update stats patternStats[pattern->getPatternNumber()]++; // Push into dictionary if (pattern->shouldAllocate()) { addToDictionary(bytes); } return pattern; } template <class T> std::unique_ptr<BaseCacheCompressor::CompressionData> DictionaryCompressor<T>::compress(const uint64_t* data) { std::unique_ptr<BaseCacheCompressor::CompressionData> comp_data = std::unique_ptr<CompData>(new CompData()); // Reset dictionary resetDictionary(); // Compress every value sequentially CompData* const comp_data_ptr = static_cast<CompData*>(comp_data.get()); const std::vector<T> values((T*)data, (T*)data + blkSize / sizeof(T)); for (const auto& value : values) { std::unique_ptr<Pattern> pattern = compressValue(value); DPRINTF(CacheComp, "Compressed %016x to %s\n", value, pattern->print()); comp_data_ptr->addEntry(std::move(pattern)); } // Return compressed line return comp_data; } template <class T> T DictionaryCompressor<T>::decompressValue(const Pattern* pattern) { // Search for matching entry auto entry_it = dictionary.begin(); std::advance(entry_it, pattern->getMatchLocation()); // Decompress the match. If the decompressed value must be added to // the dictionary, do it const DictionaryEntry data = pattern->decompress(*entry_it); if (pattern->shouldAllocate()) { addToDictionary(data); } // Return value return fromDictionaryEntry(data); } template <class T> void DictionaryCompressor<T>::decompress(const CompressionData* comp_data, uint64_t* data) { const CompData* casted_comp_data = static_cast<const CompData*>(comp_data); // Reset dictionary resetDictionary(); // Decompress every entry sequentially std::vector<T> decomp_values; for (const auto& entry : casted_comp_data->entries) { const T value = decompressValue(&*entry); decomp_values.push_back(value); DPRINTF(CacheComp, "Decompressed %s to %x\n", entry->print(), value); } // Concatenate the decompressed values to generate the original data for (std::size_t i = 0; i < blkSize/8; i++) { data[i] = 0; const std::size_t values_per_entry = sizeof(uint64_t)/sizeof(T); for (int j = values_per_entry - 1; j >= 0; j--) { data[i] |= static_cast<uint64_t>(decomp_values[values_per_entry*i+j]) << (j*8*sizeof(T)); } } } template <class T> typename DictionaryCompressor<T>::DictionaryEntry DictionaryCompressor<T>::toDictionaryEntry(T value) { DictionaryEntry entry; for (int i = 0; i < sizeof(T); i++) { entry[i] = value & 0xFF; value >>= 8; } return entry; } template <class T> T DictionaryCompressor<T>::fromDictionaryEntry(const DictionaryEntry& entry) { T value = 0; for (int i = sizeof(T) - 1; i >= 0; i--) { value <<= 8; value |= entry[i]; } return value; } #endif //__MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_IMPL_HH__ <|endoftext|>
<commit_before>/** * @file positive_definite_constraint.hpp * @author Ryan Curtin * * Restricts a covariance matrix to being positive definite. */ #ifndef __MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP #define __MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP #include <mlpack/core.hpp> namespace mlpack { namespace gmm { /** * Given a covariance matrix, force the matrix to be positive definite. */ class PositiveDefiniteConstraint { public: /** * Apply the positive definiteness constraint to the given covariance matrix. * * @param covariance Covariance matrix. */ static void ApplyConstraint(arma::mat& covariance) { // Realistically, all we care about is that we can perform a Cholesky // decomposition of the matrix, so that FactorCovariance() doesn't fail // later. Therefore, that's what we'll do to check for positive // definiteness... // // Note that other techniques like checking the determinant *could* work, // but floating-point errors mean that various decompositions may start to // fail when the matrix gets close to being indefinite. This is why we test // with chol() and not something else, since that's what will be used later. // // We also need to make sure that the errors go to nowhere, so we have to // call set_stream_err2()... std::ostringstream oss; std::ostream& originalStream = arma::get_stream_err2(); arma::set_stream_err2(oss); // Thus, errors won't be displayed. arma::mat covLower; #if (ARMA_VERSION_MAJOR < 4) || \ ((ARMA_VERSION_MAJOR == 4) && (ARMA_VERSION_MINOR < 500)) if (!arma::chol(covLower, covariance)) #else if (!arma::chol(covLower, covariance, "lower")) #endif { Log::Debug << "Covariance matrix is not positive definite. Adding " << "perturbation." << std::endl; double perturbation = 1e-15; #if (ARMA_VERSION_MAJOR < 4) || \ ((ARMA_VERSION_MAJOR == 4) && (ARMA_VERSION_MAJOR < 500)) while (!arma::chol(covLower, covariance)) #else while (!arma::chol(covLower, covariance, "lower")) #endif { covariance.diag() += perturbation; perturbation *= 10; } } // Restore the original stream state. arma::set_stream_err2(originalStream); } //! Serialize the constraint (which stores nothing, so, nothing to do). template<typename Archive> static void Serialize(Archive& /* ar */, const unsigned int /* version */) { } }; } // namespace gmm } // namespace mlpack #endif <commit_msg>Force a minimum value on the diagonal.<commit_after>/** * @file positive_definite_constraint.hpp * @author Ryan Curtin * * Restricts a covariance matrix to being positive definite. */ #ifndef __MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP #define __MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP #include <mlpack/core.hpp> namespace mlpack { namespace gmm { /** * Given a covariance matrix, force the matrix to be positive definite. Also * force a minimum value on the diagonal, so that even if the matrix is * invertible, it doesn't */ class PositiveDefiniteConstraint { public: /** * Apply the positive definiteness constraint to the given covariance matrix, * and ensure each value on the diagonal is at least 1e-50. * * @param covariance Covariance matrix. */ static void ApplyConstraint(arma::mat& covariance) { // Make sure each diagonal element is at least 1e-50. for (size_t i = 0; i < covariance.n_cols; ++i) if (std::abs(covariance(i, i)) < 1e-50) covariance(i, i) = 1e-50; // Realistically, all we care about is that we can perform a Cholesky // decomposition of the matrix, so that FactorCovariance() doesn't fail // later. Therefore, that's what we'll do to check for positive // definiteness... // // Note that other techniques like checking the determinant *could* work, // but floating-point errors mean that various decompositions may start to // fail when the matrix gets close to being indefinite. This is why we test // with chol() and not something else, since that's what will be used later. // // We also need to make sure that the errors go to nowhere, so we have to // call set_stream_err2()... std::ostringstream oss; std::ostream& originalStream = arma::get_stream_err2(); arma::set_stream_err2(oss); // Thus, errors won't be displayed. arma::mat covLower; #if (ARMA_VERSION_MAJOR < 4) || \ ((ARMA_VERSION_MAJOR == 4) && (ARMA_VERSION_MINOR < 500)) if (!arma::chol(covLower, covariance)) #else if (!arma::chol(covLower, covariance, "lower")) #endif { Log::Debug << "Covariance matrix is not positive definite. Adding " << "perturbation." << std::endl; double perturbation = 1e-15; #if (ARMA_VERSION_MAJOR < 4) || \ ((ARMA_VERSION_MAJOR == 4) && (ARMA_VERSION_MAJOR < 500)) while (!arma::chol(covLower, covariance)) #else while (!arma::chol(covLower, covariance, "lower")) #endif { covariance.diag() += perturbation; perturbation *= 10; } } // Restore the original stream state. arma::set_stream_err2(originalStream); } //! Serialize the constraint (which stores nothing, so, nothing to do). template<typename Archive> static void Serialize(Archive& /* ar */, const unsigned int /* version */) { } }; } // namespace gmm } // namespace mlpack #endif <|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "base/logging.hpp" #include "indexer/classificator_loader.hpp" #include "generator/osm2meta.hpp" #include "coding/writer.hpp" #include "coding/reader.hpp" UNIT_TEST(Metadata_ValidateAndFormat_stars) { FeatureParams params; MetadataTagProcessor p(params); // ignore incorrect values p("stars", "0"); TEST(params.GetMetadata().Empty(), ()); p("stars", "-1"); TEST(params.GetMetadata().Empty(), ()); p("stars", "aasdasdas"); TEST(params.GetMetadata().Empty(), ()); p("stars", "8"); TEST(params.GetMetadata().Empty(), ()); p("stars", "10"); TEST(params.GetMetadata().Empty(), ()); p("stars", "910"); TEST(params.GetMetadata().Empty(), ()); p("stars", "100"); TEST(params.GetMetadata().Empty(), ()); // check correct values p("stars", "1"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "1", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "2"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "2", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "3"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "3", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "4"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "4", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "5"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "5", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "6"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "6", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "7"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "7", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); // check almost correct values p("stars", "4+"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "4", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); p("stars", "5s"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_STARS), "5", ()) params.GetMetadata().Drop(feature::Metadata::FMD_STARS); } UNIT_TEST(Metadata_ValidateAndFormat_operator) { classificator::Load(); Classificator const & c = classif(); uint32_t const type_atm = c.GetTypeByPath({ "amenity", "atm" }); uint32_t const type_fuel = c.GetTypeByPath({ "amenity", "fuel" }); FeatureParams params; MetadataTagProcessor p(params); // ignore tag 'operator' if feature have inappropriate type p("operator", "Some"); TEST(params.GetMetadata().Empty(), ()); params.SetType(type_atm); p("operator", "Some"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_OPERATOR), "Some", ()); params.GetMetadata().Drop(feature::Metadata::FMD_OPERATOR); params.SetType(type_fuel); p("operator", "Some"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_OPERATOR), "Some", ()); params.GetMetadata().Drop(feature::Metadata::FMD_OPERATOR); params.SetType(type_atm); params.AddType(type_fuel); p("operator", "Some"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_OPERATOR), "Some", ()); params.GetMetadata().Drop(feature::Metadata::FMD_OPERATOR); } UNIT_TEST(Metadata_ValidateAndFormat_ele) { classificator::Load(); Classificator const & c = classif(); uint32_t const type_peak = c.GetTypeByPath({ "natural", "peak" }); FeatureParams params; MetadataTagProcessor p(params); // ignore tag 'operator' if feature have inappropriate type p("ele", "123"); TEST(params.GetMetadata().Empty(), ()); params.SetType(type_peak); p("ele", "0"); TEST(params.GetMetadata().Empty(), ()); params.SetType(type_peak); p("ele", "0,0000"); TEST(params.GetMetadata().Empty(), ()); params.SetType(type_peak); p("ele", "0.0"); TEST(params.GetMetadata().Empty(), ()); params.SetType(type_peak); p("ele", "123"); TEST_EQUAL(params.GetMetadata().Get(feature::Metadata::FMD_ELE), "123", ()); params.GetMetadata().Drop(feature::Metadata::FMD_ELE); } UNIT_TEST(Metadata_ValidateAndFormat_wikipedia) { using feature::Metadata; char const * kWikiKey = "wikipedia"; FeatureParams params; MetadataTagProcessor p(params); p(kWikiKey, "en:Bad %20Data"); TEST_EQUAL(params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA), "en:Bad %20Data", ()); TEST_EQUAL(params.GetMetadata().GetWikiURL(), "https://en.m.wikipedia.org/wiki/Bad_%2520Data", ()); params.GetMetadata().Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "ru:Тест_with % sign"); TEST_EQUAL(params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA), "ru:Тест with % sign", ()); TEST_EQUAL(params.GetMetadata().GetWikiURL(), "https://ru.m.wikipedia.org/wiki/Тест_with_%25_sign", ()); params.GetMetadata().Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "https://be-tarask.wikipedia.org/wiki/Вялікае_Княства_Літоўскае"); TEST_EQUAL(params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA), "be-tarask:Вялікае Княства Літоўскае", ()); TEST_EQUAL(params.GetMetadata().GetWikiURL(), "https://be-tarask.m.wikipedia.org/wiki/Вялікае_Княства_Літоўскае", ()); params.GetMetadata().Drop(Metadata::FMD_WIKIPEDIA); // Final link points to https and mobile version. p(kWikiKey, "http://en.wikipedia.org/wiki/A"); TEST_EQUAL(params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA), "en:A", ()); TEST_EQUAL(params.GetMetadata().GetWikiURL(), "https://en.m.wikipedia.org/wiki/A", ()); params.GetMetadata().Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "invalid_input_without_language_and_colon"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "https://en.wikipedia.org/wiki/"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://wikipedia.org/wiki/Article"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://somesite.org"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://www.spamsitewithaslash.com/"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://.wikipedia.org/wiki/Article"); TEST(params.GetMetadata().Empty(), (params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA))); // Ignore incorrect prefixes. p(kWikiKey, "ht.tps://en.wikipedia.org/wiki/Whuh"); TEST_EQUAL(params.GetMetadata().Get(Metadata::FMD_WIKIPEDIA), "en:Whuh", ()); params.GetMetadata().Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "http://ru.google.com/wiki/wutlol"); TEST(params.GetMetadata().Empty(), ("Not a wikipedia site.")); } <commit_msg>Minor tests formatting to improve readability.<commit_after>#include "testing/testing.hpp" #include "base/logging.hpp" #include "indexer/classificator_loader.hpp" #include "generator/osm2meta.hpp" #include "coding/writer.hpp" #include "coding/reader.hpp" using feature::Metadata; UNIT_TEST(Metadata_ValidateAndFormat_stars) { FeatureParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // ignore incorrect values p("stars", "0"); TEST(md.Empty(), ()); p("stars", "-1"); TEST(md.Empty(), ()); p("stars", "aasdasdas"); TEST(md.Empty(), ()); p("stars", "8"); TEST(md.Empty(), ()); p("stars", "10"); TEST(md.Empty(), ()); p("stars", "910"); TEST(md.Empty(), ()); p("stars", "100"); TEST(md.Empty(), ()); // check correct values p("stars", "1"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "1", ()) md.Drop(Metadata::FMD_STARS); p("stars", "2"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "2", ()) md.Drop(Metadata::FMD_STARS); p("stars", "3"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "3", ()) md.Drop(Metadata::FMD_STARS); p("stars", "4"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()) md.Drop(Metadata::FMD_STARS); p("stars", "5"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()) md.Drop(Metadata::FMD_STARS); p("stars", "6"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "6", ()) md.Drop(Metadata::FMD_STARS); p("stars", "7"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "7", ()) md.Drop(Metadata::FMD_STARS); // check almost correct values p("stars", "4+"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()) md.Drop(Metadata::FMD_STARS); p("stars", "5s"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()) md.Drop(Metadata::FMD_STARS); } UNIT_TEST(Metadata_ValidateAndFormat_operator) { classificator::Load(); Classificator const & c = classif(); uint32_t const type_atm = c.GetTypeByPath({ "amenity", "atm" }); uint32_t const type_fuel = c.GetTypeByPath({ "amenity", "fuel" }); FeatureParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // ignore tag 'operator' if feature have inappropriate type p("operator", "Some"); TEST(md.Empty(), ()); params.SetType(type_atm); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(type_fuel); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(type_atm); params.AddType(type_fuel); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); } UNIT_TEST(Metadata_ValidateAndFormat_ele) { classificator::Load(); Classificator const & c = classif(); uint32_t const type_peak = c.GetTypeByPath({ "natural", "peak" }); FeatureParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // ignore tag 'operator' if feature have inappropriate type p("ele", "123"); TEST(md.Empty(), ()); params.SetType(type_peak); p("ele", "0"); TEST(md.Empty(), ()); params.SetType(type_peak); p("ele", "0,0000"); TEST(md.Empty(), ()); params.SetType(type_peak); p("ele", "0.0"); TEST(md.Empty(), ()); params.SetType(type_peak); p("ele", "123"); TEST_EQUAL(md.Get(Metadata::FMD_ELE), "123", ()); md.Drop(Metadata::FMD_ELE); } UNIT_TEST(Metadata_ValidateAndFormat_wikipedia) { char const * kWikiKey = "wikipedia"; FeatureParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); p(kWikiKey, "en:Bad %20Data"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Bad %20Data", ()); TEST_EQUAL(md.GetWikiURL(), "https://en.m.wikipedia.org/wiki/Bad_%2520Data", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "ru:Тест_with % sign"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "ru:Тест with % sign", ()); TEST_EQUAL(md.GetWikiURL(), "https://ru.m.wikipedia.org/wiki/Тест_with_%25_sign", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "https://be-tarask.wikipedia.org/wiki/Вялікае_Княства_Літоўскае"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "be-tarask:Вялікае Княства Літоўскае", ()); TEST_EQUAL(md.GetWikiURL(), "https://be-tarask.m.wikipedia.org/wiki/Вялікае_Княства_Літоўскае", ()); md.Drop(Metadata::FMD_WIKIPEDIA); // Final link points to https and mobile version. p(kWikiKey, "http://en.wikipedia.org/wiki/A"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:A", ()); TEST_EQUAL(md.GetWikiURL(), "https://en.m.wikipedia.org/wiki/A", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "invalid_input_without_language_and_colon"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "https://en.wikipedia.org/wiki/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://somesite.org"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://www.spamsitewithaslash.com/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://.wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); // Ignore incorrect prefixes. p(kWikiKey, "ht.tps://en.wikipedia.org/wiki/Whuh"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Whuh", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "http://ru.google.com/wiki/wutlol"); TEST(md.Empty(), ("Not a wikipedia site.")); } <|endoftext|>
<commit_before>//===-- BenchmarkRunner.cpp -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <array> #include <string> #include "Assembler.h" #include "BenchmarkRunner.h" #include "MCInstrDescView.h" #include "PerfHelper.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Program.h" namespace llvm { namespace exegesis { BenchmarkFailure::BenchmarkFailure(const llvm::Twine &S) : llvm::StringError(S, llvm::inconvertibleErrorCode()) {} BenchmarkRunner::BenchmarkRunner(const LLVMState &State, InstructionBenchmark::ModeE Mode) : State(State), Mode(Mode), Scratch(llvm::make_unique<ScratchSpace>()) {} BenchmarkRunner::~BenchmarkRunner() = default; // Repeat the snippet until there are at least MinInstructions in the resulting // code. static std::vector<llvm::MCInst> GenerateInstructions(const BenchmarkCode &BC, const size_t MinInstructions) { if (BC.Instructions.empty()) return {}; std::vector<llvm::MCInst> Code = BC.Instructions; for (int I = 0; Code.size() < MinInstructions; ++I) Code.push_back(BC.Instructions[I % BC.Instructions.size()]); return Code; } namespace { class FunctionExecutorImpl : public BenchmarkRunner::FunctionExecutor { public: FunctionExecutorImpl(const LLVMState &State, llvm::object::OwningBinary<llvm::object::ObjectFile> Obj, BenchmarkRunner::ScratchSpace *Scratch) : Function(State.createTargetMachine(), std::move(Obj)), Scratch(Scratch) {} private: llvm::Expected<int64_t> runAndMeasure(const char *Counters) const override { // We sum counts when there are several counters for a single ProcRes // (e.g. P23 on SandyBridge). int64_t CounterValue = 0; llvm::SmallVector<llvm::StringRef, 2> CounterNames; llvm::StringRef(Counters).split(CounterNames, '+'); char *const ScratchPtr = Scratch->ptr(); for (auto &CounterName : CounterNames) { CounterName = CounterName.trim(); pfm::PerfEvent PerfEvent(CounterName); if (!PerfEvent.valid()) llvm::report_fatal_error(llvm::Twine("invalid perf event '") .concat(CounterName) .concat("'")); pfm::Counter Counter(PerfEvent); Scratch->clear(); { llvm::CrashRecoveryContext CRC; llvm::CrashRecoveryContext::Enable(); const bool Crashed = !CRC.RunSafely([this, &Counter, ScratchPtr]() { Counter.start(); this->Function(ScratchPtr); Counter.stop(); }); llvm::CrashRecoveryContext::Disable(); // FIXME: Better diagnosis. if (Crashed) return llvm::make_error<BenchmarkFailure>( "snippet crashed while running"); } CounterValue += Counter.read(); } return CounterValue; } const ExecutableFunction Function; BenchmarkRunner::ScratchSpace *const Scratch; }; } // namespace InstructionBenchmark BenchmarkRunner::runConfiguration(const BenchmarkCode &BC, unsigned NumRepetitions, bool DumpObjectToDisk) const { InstructionBenchmark InstrBenchmark; InstrBenchmark.Mode = Mode; InstrBenchmark.CpuName = State.getTargetMachine().getTargetCPU(); InstrBenchmark.LLVMTriple = State.getTargetMachine().getTargetTriple().normalize(); InstrBenchmark.NumRepetitions = NumRepetitions; InstrBenchmark.Info = BC.Info; const std::vector<llvm::MCInst> &Instructions = BC.Instructions; InstrBenchmark.Key.Instructions = Instructions; InstrBenchmark.Key.RegisterInitialValues = BC.RegisterInitialValues; // Assemble at least kMinInstructionsForSnippet instructions by repeating the // snippet for debug/analysis. This is so that the user clearly understands // that the inside instructions are repeated. constexpr const int kMinInstructionsForSnippet = 16; { auto ObjectFilePath = writeObjectFile( BC, GenerateInstructions(BC, kMinInstructionsForSnippet)); if (llvm::Error E = ObjectFilePath.takeError()) { InstrBenchmark.Error = llvm::toString(std::move(E)); return InstrBenchmark; } const ExecutableFunction EF(State.createTargetMachine(), getObjectFromFile(*ObjectFilePath)); const auto FnBytes = EF.getFunctionBytes(); InstrBenchmark.AssembledSnippet.assign(FnBytes.begin(), FnBytes.end()); } // Assemble NumRepetitions instructions repetitions of the snippet for // measurements. const auto Code = GenerateInstructions(BC, InstrBenchmark.NumRepetitions); llvm::object::OwningBinary<llvm::object::ObjectFile> ObjectFile; if (DumpObjectToDisk) { auto ObjectFilePath = writeObjectFile(BC, Code); if (llvm::Error E = ObjectFilePath.takeError()) { InstrBenchmark.Error = llvm::toString(std::move(E)); return InstrBenchmark; } llvm::outs() << "Check generated assembly with: /usr/bin/objdump -d " << *ObjectFilePath << "\n"; ObjectFile = getObjectFromFile(*ObjectFilePath); } else { llvm::SmallString<0> Buffer; llvm::raw_svector_ostream OS(Buffer); assembleToStream(State.getExegesisTarget(), State.createTargetMachine(), BC.LiveIns, BC.RegisterInitialValues, Code, OS); ObjectFile = getObjectFromBuffer(OS.str()); } const FunctionExecutorImpl Executor(State, std::move(ObjectFile), Scratch.get()); auto Measurements = runMeasurements(Executor); if (llvm::Error E = Measurements.takeError()) { InstrBenchmark.Error = llvm::toString(std::move(E)); return InstrBenchmark; } InstrBenchmark.Measurements = std::move(*Measurements); assert(InstrBenchmark.NumRepetitions > 0 && "invalid NumRepetitions"); for (BenchmarkMeasure &BM : InstrBenchmark.Measurements) { // Scale the measurements by instruction. BM.PerInstructionValue /= InstrBenchmark.NumRepetitions; // Scale the measurements by snippet. BM.PerSnippetValue *= static_cast<double>(BC.Instructions.size()) / InstrBenchmark.NumRepetitions; } return InstrBenchmark; } llvm::Expected<std::string> BenchmarkRunner::writeObjectFile(const BenchmarkCode &BC, llvm::ArrayRef<llvm::MCInst> Code) const { int ResultFD = 0; llvm::SmallString<256> ResultPath; if (llvm::Error E = llvm::errorCodeToError(llvm::sys::fs::createTemporaryFile( "snippet", "o", ResultFD, ResultPath))) return std::move(E); llvm::raw_fd_ostream OFS(ResultFD, true /*ShouldClose*/); assembleToStream(State.getExegesisTarget(), State.createTargetMachine(), BC.LiveIns, BC.RegisterInitialValues, Code, OFS); return ResultPath.str(); } BenchmarkRunner::FunctionExecutor::~FunctionExecutor() {} } // namespace exegesis } // namespace llvm <commit_msg>[llvm-exegesis] BenchmarkRunner::runConfiguration(): write small snippet to memory<commit_after>//===-- BenchmarkRunner.cpp -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <array> #include <string> #include "Assembler.h" #include "BenchmarkRunner.h" #include "MCInstrDescView.h" #include "PerfHelper.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Program.h" namespace llvm { namespace exegesis { BenchmarkFailure::BenchmarkFailure(const llvm::Twine &S) : llvm::StringError(S, llvm::inconvertibleErrorCode()) {} BenchmarkRunner::BenchmarkRunner(const LLVMState &State, InstructionBenchmark::ModeE Mode) : State(State), Mode(Mode), Scratch(llvm::make_unique<ScratchSpace>()) {} BenchmarkRunner::~BenchmarkRunner() = default; // Repeat the snippet until there are at least MinInstructions in the resulting // code. static std::vector<llvm::MCInst> GenerateInstructions(const BenchmarkCode &BC, const size_t MinInstructions) { if (BC.Instructions.empty()) return {}; std::vector<llvm::MCInst> Code = BC.Instructions; for (int I = 0; Code.size() < MinInstructions; ++I) Code.push_back(BC.Instructions[I % BC.Instructions.size()]); return Code; } namespace { class FunctionExecutorImpl : public BenchmarkRunner::FunctionExecutor { public: FunctionExecutorImpl(const LLVMState &State, llvm::object::OwningBinary<llvm::object::ObjectFile> Obj, BenchmarkRunner::ScratchSpace *Scratch) : Function(State.createTargetMachine(), std::move(Obj)), Scratch(Scratch) {} private: llvm::Expected<int64_t> runAndMeasure(const char *Counters) const override { // We sum counts when there are several counters for a single ProcRes // (e.g. P23 on SandyBridge). int64_t CounterValue = 0; llvm::SmallVector<llvm::StringRef, 2> CounterNames; llvm::StringRef(Counters).split(CounterNames, '+'); char *const ScratchPtr = Scratch->ptr(); for (auto &CounterName : CounterNames) { CounterName = CounterName.trim(); pfm::PerfEvent PerfEvent(CounterName); if (!PerfEvent.valid()) llvm::report_fatal_error(llvm::Twine("invalid perf event '") .concat(CounterName) .concat("'")); pfm::Counter Counter(PerfEvent); Scratch->clear(); { llvm::CrashRecoveryContext CRC; llvm::CrashRecoveryContext::Enable(); const bool Crashed = !CRC.RunSafely([this, &Counter, ScratchPtr]() { Counter.start(); this->Function(ScratchPtr); Counter.stop(); }); llvm::CrashRecoveryContext::Disable(); // FIXME: Better diagnosis. if (Crashed) return llvm::make_error<BenchmarkFailure>( "snippet crashed while running"); } CounterValue += Counter.read(); } return CounterValue; } const ExecutableFunction Function; BenchmarkRunner::ScratchSpace *const Scratch; }; } // namespace InstructionBenchmark BenchmarkRunner::runConfiguration(const BenchmarkCode &BC, unsigned NumRepetitions, bool DumpObjectToDisk) const { InstructionBenchmark InstrBenchmark; InstrBenchmark.Mode = Mode; InstrBenchmark.CpuName = State.getTargetMachine().getTargetCPU(); InstrBenchmark.LLVMTriple = State.getTargetMachine().getTargetTriple().normalize(); InstrBenchmark.NumRepetitions = NumRepetitions; InstrBenchmark.Info = BC.Info; const std::vector<llvm::MCInst> &Instructions = BC.Instructions; InstrBenchmark.Key.Instructions = Instructions; InstrBenchmark.Key.RegisterInitialValues = BC.RegisterInitialValues; // Assemble at least kMinInstructionsForSnippet instructions by repeating the // snippet for debug/analysis. This is so that the user clearly understands // that the inside instructions are repeated. constexpr const int kMinInstructionsForSnippet = 16; { llvm::SmallString<0> Buffer; llvm::raw_svector_ostream OS(Buffer); assembleToStream(State.getExegesisTarget(), State.createTargetMachine(), BC.LiveIns, BC.RegisterInitialValues, GenerateInstructions(BC, kMinInstructionsForSnippet), OS); const ExecutableFunction EF(State.createTargetMachine(), getObjectFromBuffer(OS.str())); const auto FnBytes = EF.getFunctionBytes(); InstrBenchmark.AssembledSnippet.assign(FnBytes.begin(), FnBytes.end()); } // Assemble NumRepetitions instructions repetitions of the snippet for // measurements. const auto Code = GenerateInstructions(BC, InstrBenchmark.NumRepetitions); llvm::object::OwningBinary<llvm::object::ObjectFile> ObjectFile; if (DumpObjectToDisk) { auto ObjectFilePath = writeObjectFile(BC, Code); if (llvm::Error E = ObjectFilePath.takeError()) { InstrBenchmark.Error = llvm::toString(std::move(E)); return InstrBenchmark; } llvm::outs() << "Check generated assembly with: /usr/bin/objdump -d " << *ObjectFilePath << "\n"; ObjectFile = getObjectFromFile(*ObjectFilePath); } else { llvm::SmallString<0> Buffer; llvm::raw_svector_ostream OS(Buffer); assembleToStream(State.getExegesisTarget(), State.createTargetMachine(), BC.LiveIns, BC.RegisterInitialValues, Code, OS); ObjectFile = getObjectFromBuffer(OS.str()); } const FunctionExecutorImpl Executor(State, std::move(ObjectFile), Scratch.get()); auto Measurements = runMeasurements(Executor); if (llvm::Error E = Measurements.takeError()) { InstrBenchmark.Error = llvm::toString(std::move(E)); return InstrBenchmark; } InstrBenchmark.Measurements = std::move(*Measurements); assert(InstrBenchmark.NumRepetitions > 0 && "invalid NumRepetitions"); for (BenchmarkMeasure &BM : InstrBenchmark.Measurements) { // Scale the measurements by instruction. BM.PerInstructionValue /= InstrBenchmark.NumRepetitions; // Scale the measurements by snippet. BM.PerSnippetValue *= static_cast<double>(BC.Instructions.size()) / InstrBenchmark.NumRepetitions; } return InstrBenchmark; } llvm::Expected<std::string> BenchmarkRunner::writeObjectFile(const BenchmarkCode &BC, llvm::ArrayRef<llvm::MCInst> Code) const { int ResultFD = 0; llvm::SmallString<256> ResultPath; if (llvm::Error E = llvm::errorCodeToError(llvm::sys::fs::createTemporaryFile( "snippet", "o", ResultFD, ResultPath))) return std::move(E); llvm::raw_fd_ostream OFS(ResultFD, true /*ShouldClose*/); assembleToStream(State.getExegesisTarget(), State.createTargetMachine(), BC.LiveIns, BC.RegisterInitialValues, Code, OFS); return ResultPath.str(); } BenchmarkRunner::FunctionExecutor::~FunctionExecutor() {} } // namespace exegesis } // namespace llvm <|endoftext|>
<commit_before>/* * Copyright (C) 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 "WebHelperPluginImpl.h" #include "PageWidgetDelegate.h" #include "WebDocument.h" #include "WebFrameImpl.h" #include "WebPlugin.h" #include "WebPluginContainerImpl.h" #include "WebViewClient.h" #include "WebViewImpl.h" #include "WebWidgetClient.h" #include "core/dom/NodeList.h" #include "core/html/HTMLPlugInElement.h" #include "core/loader/DocumentLoader.h" #include "core/loader/EmptyClients.h" #include "core/page/FocusController.h" #include "core/page/FrameView.h" #include "core/page/Page.h" #include "core/page/Settings.h" using namespace WebCore; namespace WebKit { #define addLiteral(literal, writer) writer.addData(literal, sizeof(literal) - 1) static inline void addString(const String& str, DocumentWriter& writer) { CString str8 = str.utf8(); writer.addData(str8.data(), str8.length()); } void writeDocument(const String& pluginType, const WebDocument& hostDocument, WebCore::DocumentWriter& writer) { // Give the new document the same URL as the hose document so that content // settings and other decisions can be made based on the correct origin. const WebURL& url = hostDocument.url(); writer.setMIMEType("text/html"); writer.setEncoding("UTF-8", false); writer.begin(url); addLiteral("<!DOCTYPE html><head><meta charset='UTF-8'></head><body>\n", writer); String objectTag = "<object type=\"" + pluginType + "\"></object>"; addString(objectTag, writer); addLiteral("</body>\n", writer); writer.end(); } class HelperPluginChromeClient : public EmptyChromeClient { WTF_MAKE_NONCOPYABLE(HelperPluginChromeClient); WTF_MAKE_FAST_ALLOCATED; public: explicit HelperPluginChromeClient(WebHelperPluginImpl* widget) : m_widget(widget) { ASSERT(m_widget->m_widgetClient); } private: virtual void closeWindowSoon() OVERRIDE { // This should never be called since the only way to close the // invisible page is via closeHelperPlugin(). ASSERT_NOT_REACHED(); m_widget->closeHelperPlugin(); } virtual void* webView() const OVERRIDE { return m_widget->m_webView; } WebHelperPluginImpl* m_widget; }; // WebHelperPluginImpl ---------------------------------------------------------------- WebHelperPluginImpl::WebHelperPluginImpl(WebWidgetClient* client) : m_widgetClient(client) , m_webView(0) { ASSERT(client); } WebHelperPluginImpl::~WebHelperPluginImpl() { ASSERT(!m_page); } bool WebHelperPluginImpl::initialize(const String& pluginType, const WebDocument& hostDocument, WebViewImpl* webView) { ASSERT(webView); m_webView = webView; return initializePage(pluginType, hostDocument); } void WebHelperPluginImpl::closeHelperPlugin() { if (m_page) { m_page->clearPageGroup(); m_page->mainFrame()->loader()->stopAllLoaders(); m_page->mainFrame()->loader()->stopLoading(UnloadEventPolicyNone); } // We must destroy the page now in case the host page is being destroyed, in // which case some of the objects the page depends on may have been // destroyed by the time this->close() is called asynchronously. destroyPage(); // m_widgetClient might be 0 because this widget might be already closed. if (m_widgetClient) { // closeWidgetSoon() will call this->close() later. m_widgetClient->closeWidgetSoon(); } } void WebHelperPluginImpl::initializeFrame(WebFrameClient* client) { ASSERT(m_page); RefPtr<WebFrameImpl> frame = WebFrameImpl::create(client); frame->initializeAsMainFrame(m_page.get()); } // Returns a pointer to the WebPlugin by finding the single <object> tag in the page. WebPlugin* WebHelperPluginImpl::getPlugin() { ASSERT(m_page); RefPtr<NodeList> objectElements = m_page->mainFrame()->document()->getElementsByTagName(WebCore::HTMLNames::objectTag.localName()); ASSERT(objectElements && objectElements->length() == 1); if (!objectElements || objectElements->length() < 1) return 0; Node* node = objectElements->item(0); ASSERT(node->hasTagName(WebCore::HTMLNames::objectTag)); WebCore::Widget* widget = toHTMLPlugInElement(node)->pluginWidget(); if (!widget) return 0; WebPlugin* plugin = static_cast<WebPluginContainerImpl*>(widget)->plugin(); ASSERT(plugin); // If the plugin is a placeholder, it is not useful to the caller, and it // could be replaced at any time. Therefore, do not return it. if (plugin->isPlaceholder()) return 0; // The plugin was instantiated and will outlive this object. return plugin; } bool WebHelperPluginImpl::initializePage(const String& pluginType, const WebDocument& hostDocument) { Page::PageClients pageClients; fillWithEmptyClients(pageClients); m_chromeClient = adoptPtr(new HelperPluginChromeClient(this)); pageClients.chromeClient = m_chromeClient.get(); m_page = adoptPtr(new Page(pageClients)); // Scripting must be enabled in ScriptController::windowScriptNPObject(). m_page->settings()->setScriptEnabled(true); m_page->settings()->setPluginsEnabled(true); unsigned layoutMilestones = DidFirstLayout | DidFirstVisuallyNonEmptyLayout; m_page->addLayoutMilestones(static_cast<LayoutMilestones>(layoutMilestones)); m_webView->client()->initializeHelperPluginWebFrame(this); // The page's main frame was set in initializeFrame() as a result of the above call. Frame* frame = m_page->mainFrame(); ASSERT(frame); frame->setView(FrameView::create(frame)); // No need to set a size or make it not transparent. DocumentWriter* writer = frame->loader()->activeDocumentLoader()->writer(); writeDocument(pluginType, hostDocument, *writer); return true; } void WebHelperPluginImpl::destroyPage() { if (!m_page) return; if (m_page->mainFrame()) m_page->mainFrame()->loader()->frameDetached(); m_page.clear(); } void WebHelperPluginImpl::layout() { PageWidgetDelegate::layout(m_page.get()); } void WebHelperPluginImpl::setFocus(bool) { ASSERT_NOT_REACHED(); } void WebHelperPluginImpl::close() { ASSERT(!m_page); // Should only be called via closePopup(). m_widgetClient = 0; deref(); } // WebHelperPlugin ---------------------------------------------------------------- WebHelperPlugin* WebHelperPlugin::create(WebWidgetClient* client) { if (!client) CRASH(); // A WebHelperPluginImpl instance usually has two references. // - One owned by the instance itself. It represents the visible widget. // - One owned by the hosting element. It's released when the hosting // element asks the WebHelperPluginImpl to close. // We need them because the closing operation is asynchronous and the widget // can be closed while the hosting element is unaware of it. return adoptRef(new WebHelperPluginImpl(client)).leakRef(); } } // namespace WebKit <commit_msg>Sandbox the Helper Plugin<commit_after>/* * Copyright (C) 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 "WebHelperPluginImpl.h" #include "PageWidgetDelegate.h" #include "WebDocument.h" #include "WebFrameImpl.h" #include "WebPlugin.h" #include "WebPluginContainerImpl.h" #include "WebViewClient.h" #include "WebViewImpl.h" #include "WebWidgetClient.h" #include "core/dom/NodeList.h" #include "core/html/HTMLPlugInElement.h" #include "core/loader/DocumentLoader.h" #include "core/loader/EmptyClients.h" #include "core/page/FocusController.h" #include "core/page/FrameView.h" #include "core/page/Page.h" #include "core/page/Settings.h" using namespace WebCore; namespace WebKit { #define addLiteral(literal, writer) writer.addData(literal, sizeof(literal) - 1) static inline void addString(const String& str, DocumentWriter& writer) { CString str8 = str.utf8(); writer.addData(str8.data(), str8.length()); } void writeDocument(const String& pluginType, const WebDocument& hostDocument, WebCore::DocumentWriter& writer) { // Give the new document the same URL as the hose document so that content // settings and other decisions can be made based on the correct origin. const WebURL& url = hostDocument.url(); writer.setMIMEType("text/html"); writer.setEncoding("UTF-8", false); writer.begin(url); addLiteral("<!DOCTYPE html><head><meta charset='UTF-8'></head><body>\n", writer); String objectTag = "<object type=\"" + pluginType + "\"></object>"; addString(objectTag, writer); addLiteral("</body>\n", writer); writer.end(); } class HelperPluginChromeClient : public EmptyChromeClient { WTF_MAKE_NONCOPYABLE(HelperPluginChromeClient); WTF_MAKE_FAST_ALLOCATED; public: explicit HelperPluginChromeClient(WebHelperPluginImpl* widget) : m_widget(widget) { ASSERT(m_widget->m_widgetClient); } private: virtual void closeWindowSoon() OVERRIDE { // This should never be called since the only way to close the // invisible page is via closeHelperPlugin(). ASSERT_NOT_REACHED(); m_widget->closeHelperPlugin(); } virtual void* webView() const OVERRIDE { return m_widget->m_webView; } WebHelperPluginImpl* m_widget; }; // WebHelperPluginImpl ---------------------------------------------------------------- WebHelperPluginImpl::WebHelperPluginImpl(WebWidgetClient* client) : m_widgetClient(client) , m_webView(0) { ASSERT(client); } WebHelperPluginImpl::~WebHelperPluginImpl() { ASSERT(!m_page); } bool WebHelperPluginImpl::initialize(const String& pluginType, const WebDocument& hostDocument, WebViewImpl* webView) { ASSERT(webView); m_webView = webView; return initializePage(pluginType, hostDocument); } void WebHelperPluginImpl::closeHelperPlugin() { if (m_page) { m_page->clearPageGroup(); m_page->mainFrame()->loader()->stopAllLoaders(); m_page->mainFrame()->loader()->stopLoading(UnloadEventPolicyNone); } // We must destroy the page now in case the host page is being destroyed, in // which case some of the objects the page depends on may have been // destroyed by the time this->close() is called asynchronously. destroyPage(); // m_widgetClient might be 0 because this widget might be already closed. if (m_widgetClient) { // closeWidgetSoon() will call this->close() later. m_widgetClient->closeWidgetSoon(); } } void WebHelperPluginImpl::initializeFrame(WebFrameClient* client) { ASSERT(m_page); RefPtr<WebFrameImpl> frame = WebFrameImpl::create(client); frame->initializeAsMainFrame(m_page.get()); } // Returns a pointer to the WebPlugin by finding the single <object> tag in the page. WebPlugin* WebHelperPluginImpl::getPlugin() { ASSERT(m_page); RefPtr<NodeList> objectElements = m_page->mainFrame()->document()->getElementsByTagName(WebCore::HTMLNames::objectTag.localName()); ASSERT(objectElements && objectElements->length() == 1); if (!objectElements || objectElements->length() < 1) return 0; Node* node = objectElements->item(0); ASSERT(node->hasTagName(WebCore::HTMLNames::objectTag)); WebCore::Widget* widget = toHTMLPlugInElement(node)->pluginWidget(); if (!widget) return 0; WebPlugin* plugin = static_cast<WebPluginContainerImpl*>(widget)->plugin(); ASSERT(plugin); // If the plugin is a placeholder, it is not useful to the caller, and it // could be replaced at any time. Therefore, do not return it. if (plugin->isPlaceholder()) return 0; // The plugin was instantiated and will outlive this object. return plugin; } bool WebHelperPluginImpl::initializePage(const String& pluginType, const WebDocument& hostDocument) { Page::PageClients pageClients; fillWithEmptyClients(pageClients); m_chromeClient = adoptPtr(new HelperPluginChromeClient(this)); pageClients.chromeClient = m_chromeClient.get(); m_page = adoptPtr(new Page(pageClients)); // Scripting must be enabled in ScriptController::windowScriptNPObject(). m_page->settings()->setScriptEnabled(true); m_page->settings()->setPluginsEnabled(true); unsigned layoutMilestones = DidFirstLayout | DidFirstVisuallyNonEmptyLayout; m_page->addLayoutMilestones(static_cast<LayoutMilestones>(layoutMilestones)); m_webView->client()->initializeHelperPluginWebFrame(this); // The page's main frame was set in initializeFrame() as a result of the above call. Frame* frame = m_page->mainFrame(); ASSERT(frame); frame->loader()->forceSandboxFlags(SandboxAll & ~SandboxPlugins & ~SandboxScripts); frame->setView(FrameView::create(frame)); // No need to set a size or make it not transparent. DocumentWriter* writer = frame->loader()->activeDocumentLoader()->writer(); writeDocument(pluginType, hostDocument, *writer); return true; } void WebHelperPluginImpl::destroyPage() { if (!m_page) return; if (m_page->mainFrame()) m_page->mainFrame()->loader()->frameDetached(); m_page.clear(); } void WebHelperPluginImpl::layout() { PageWidgetDelegate::layout(m_page.get()); } void WebHelperPluginImpl::setFocus(bool) { ASSERT_NOT_REACHED(); } void WebHelperPluginImpl::close() { ASSERT(!m_page); // Should only be called via closePopup(). m_widgetClient = 0; deref(); } // WebHelperPlugin ---------------------------------------------------------------- WebHelperPlugin* WebHelperPlugin::create(WebWidgetClient* client) { if (!client) CRASH(); // A WebHelperPluginImpl instance usually has two references. // - One owned by the instance itself. It represents the visible widget. // - One owned by the hosting element. It's released when the hosting // element asks the WebHelperPluginImpl to close. // We need them because the closing operation is asynchronous and the widget // can be closed while the hosting element is unaware of it. return adoptRef(new WebHelperPluginImpl(client)).leakRef(); } } // namespace WebKit <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ //RUN: %cling %s 'args(42,"AAA)BBB")' 2>&1 | FileCheck %s //RUN: %cling '.x %s(42,"AAA)BBB")' 2>&1 | FileCheck -check-prefix=CHECK-DOTX %s //CHECK-NOT: {{.*error|note:.*}} //CHECK-DOTX-NOT: {{.*error|note:.*}} extern "C" int printf(const char* fmt, ...); void args(int I, const char* R, const char* S = "ArgString") { printf("I=%d\n", I); // CHECK: I=42 // CHECK-DOTX: I=42 printf("S=%s\n", S); // CHECK: S=ArgString // CHECK-DOTX: S=ArgString printf("R=%s\n", R); // CHECK: R=AAA)BBB // CHECK-DOTX: R=AAA)BBB } <commit_msg>Adapt expectation to reality.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ //RUN: %cling %s 'args(42,"AAA)BBB")' 2>&1 | FileCheck %s //RUN: %cling '.x %s(42,"AAA)BBB")' 2>&1 | FileCheck -check-prefix=CHECK-DOTX %s // From .x-implicit args() call: //CHECK: input_line_4:2:2: error: no matching function for call to 'args' //CHECK-DOTX-NOT: {{.*error|note:.*}} extern "C" int printf(const char* fmt, ...); void args(int I, const char* R, const char* S = "ArgString") { printf("I=%d\n", I); // CHECK: I=42 // CHECK-DOTX: I=42 printf("S=%s\n", S); // CHECK: S=ArgString // CHECK-DOTX: S=ArgString printf("R=%s\n", R); // CHECK: R=AAA)BBB // CHECK-DOTX: R=AAA)BBB } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: delcodlg.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:20:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_DELCODLG_HXX #define SC_DELCODLG_HXX #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/imagebtn.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif //------------------------------------------------------------------------ class ScDeleteContentsDlg : public ModalDialog { private: FixedLine aFlFrame; CheckBox aBtnDelAll; CheckBox aBtnDelStrings; CheckBox aBtnDelNumbers; CheckBox aBtnDelDateTime; CheckBox aBtnDelFormulas; CheckBox aBtnDelNotes; CheckBox aBtnDelAttrs; CheckBox aBtnDelObjects; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; BOOL bObjectsDisabled; static BOOL bPreviousAllCheck; static USHORT nPreviousChecks; void DisableChecks( BOOL bDelAllChecked = TRUE ); DECL_LINK( DelAllHdl, void * ); public: ScDeleteContentsDlg( Window* pParent, USHORT nCheckDefaults = 0 ); ~ScDeleteContentsDlg(); void DisableObjects(); USHORT GetDelContentsCmdBits() const; }; #endif // SC_DELCODLG_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.700); FILE MERGED 2008/04/01 15:30:51 thb 1.3.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:45 thb 1.3.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:40 rt 1.3.700.1: #i87441# Change license header to LPGL v3.<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: delcodlg.hxx,v $ * $Revision: 1.4 $ * * 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. * ************************************************************************/ #ifndef SC_DELCODLG_HXX #define SC_DELCODLG_HXX #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <vcl/imagebtn.hxx> #include "global.hxx" //------------------------------------------------------------------------ class ScDeleteContentsDlg : public ModalDialog { private: FixedLine aFlFrame; CheckBox aBtnDelAll; CheckBox aBtnDelStrings; CheckBox aBtnDelNumbers; CheckBox aBtnDelDateTime; CheckBox aBtnDelFormulas; CheckBox aBtnDelNotes; CheckBox aBtnDelAttrs; CheckBox aBtnDelObjects; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; BOOL bObjectsDisabled; static BOOL bPreviousAllCheck; static USHORT nPreviousChecks; void DisableChecks( BOOL bDelAllChecked = TRUE ); DECL_LINK( DelAllHdl, void * ); public: ScDeleteContentsDlg( Window* pParent, USHORT nCheckDefaults = 0 ); ~ScDeleteContentsDlg(); void DisableObjects(); USHORT GetDelContentsCmdBits() const; }; #endif // SC_DELCODLG_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: solvrdlg.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:40:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SOLVRDLG_HXX #define SC_SOLVRDLG_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef SC_ANYREFDG_HXX #include "anyrefdg.hxx" #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif //---------------------------------------------------------------------------- enum ScSolverErr { SOLVERR_NOFORMULA, SOLVERR_INVALID_FORMULA, SOLVERR_INVALID_VARIABLE, SOLVERR_INVALID_TARGETVALUE }; //============================================================================ class ScSolverDlg : public ScAnyRefDlg { public: ScSolverDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pDocument, ScAddress aCursorPos ); ~ScSolverDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual BOOL IsRefInputMode() const; virtual void SetActive(); virtual BOOL Close(); private: FixedLine aFlVariables; FixedText aFtFormulaCell; ScRefEdit aEdFormulaCell; ScRefButton aRBFormulaCell; FixedText aFtTargetVal; Edit aEdTargetVal; FixedText aFtVariableCell; ScRefEdit aEdVariableCell; ScRefButton aRBVariableCell; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; ScAddress theFormulaCell; ScAddress theVariableCell; String theTargetValStr; ScDocument* pDoc; const SCTAB nCurTab; ScRefEdit* pEdActive; BOOL bDlgLostFocus; const String errMsgInvalidVar; const String errMsgInvalidForm; const String errMsgNoFormula; const String errMsgInvalidVal; #ifdef _SOLVRDLG_CXX void Init(); BOOL CheckTargetValue( String& rStrVal ); void RaiseError( ScSolverErr eError ); DECL_LINK( BtnHdl, PushButton* ); DECL_LINK( GetFocusHdl, Control* ); DECL_LINK( LoseFocusHdl, Control* ); #endif // _SOLVERDLG_CXX }; #endif // SC_SOLVRDLG_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.4.452); FILE MERGED 2005/09/05 15:05:50 rt 1.4.452.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: solvrdlg.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:51:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_SOLVRDLG_HXX #define SC_SOLVRDLG_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef SC_ANYREFDG_HXX #include "anyrefdg.hxx" #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif //---------------------------------------------------------------------------- enum ScSolverErr { SOLVERR_NOFORMULA, SOLVERR_INVALID_FORMULA, SOLVERR_INVALID_VARIABLE, SOLVERR_INVALID_TARGETVALUE }; //============================================================================ class ScSolverDlg : public ScAnyRefDlg { public: ScSolverDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pDocument, ScAddress aCursorPos ); ~ScSolverDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual BOOL IsRefInputMode() const; virtual void SetActive(); virtual BOOL Close(); private: FixedLine aFlVariables; FixedText aFtFormulaCell; ScRefEdit aEdFormulaCell; ScRefButton aRBFormulaCell; FixedText aFtTargetVal; Edit aEdTargetVal; FixedText aFtVariableCell; ScRefEdit aEdVariableCell; ScRefButton aRBVariableCell; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; ScAddress theFormulaCell; ScAddress theVariableCell; String theTargetValStr; ScDocument* pDoc; const SCTAB nCurTab; ScRefEdit* pEdActive; BOOL bDlgLostFocus; const String errMsgInvalidVar; const String errMsgInvalidForm; const String errMsgNoFormula; const String errMsgInvalidVal; #ifdef _SOLVRDLG_CXX void Init(); BOOL CheckTargetValue( String& rStrVal ); void RaiseError( ScSolverErr eError ); DECL_LINK( BtnHdl, PushButton* ); DECL_LINK( GetFocusHdl, Control* ); DECL_LINK( LoseFocusHdl, Control* ); #endif // _SOLVERDLG_CXX }; #endif // SC_SOLVRDLG_HXX <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <iostream> using std::cerr; using std::endl; #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include <virvo/vvbonjour/vvbonjourentry.h> #include <virvo/vvbonjour/vvbonjourregistrar.h> #include <virvo/vvdebugmsg.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvpthread.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendercontext.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvsocketio.h> #include <virvo/vvtcpserver.h> #include <virvo/vvtoolshed.h> #include <virvo/vvvirvo.h> #include <virvo/vvvoldesc.h> /** * Virvo Server main class. * * Server unit for remote rendering. * * Options -port: set port, else default will be used. * * @author Juergen Schulze (schulze@cs.brown.de) * @author Stavros Delisavas (stavros.delisavas@uni-koeln.de) */ class vvServer { private: /// Remote rendering type enum RemoteRenderingType { RR_NONE, RR_IMAGE, RR_IBR }; static const int DEFAULTSIZE; ///< default window size (width and height) in pixels static const int DEFAULT_PORT; ///< default port for socket connections static vvServer* ds; ///< one instance of vvServer is always present int winWidth, winHeight; ///< window size in pixels unsigned short port; ///< port the server renderer uses to listen for incoming connections public: vvServer(); ~vvServer(); int run(int, char**); private: void displayHelpInfo(); bool parseCommandLine(int argc, char *argv[]); void serverLoop(); static void * handleClient(void * attribs); }; const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; //---------------------------------------------------------------------------- /// Constructor vvServer::vvServer() { winWidth = winHeight = DEFAULTSIZE; port = vvServer::DEFAULT_PORT; } //---------------------------------------------------------------------------- /// Destructor. vvServer::~vvServer() { } void vvServer::serverLoop() { pthread_t thread; vvTcpServer tcpServ = vvTcpServer(port); if(!tcpServ.initStatus()) { cerr << "Failed to initialize server-socket on port " << port << "." << endl; return; } vvBonjourRegistrar regist; DNSServiceErrorType bonjErr = regist.registerService(*(new vvBonjourEntry("Virvo Server", "_vserver._tcp", "")), vvServer::DEFAULT_PORT); while (1) { cerr << "Listening on port " << port << endl; vvSocket *sock = NULL; while((sock = tcpServ.nextConnection()) == NULL) { // retry cerr << "Socket blocked, retry..." << endl; } if(sock == NULL) { cerr << "Failed to initialize server socket on port " << port << endl; delete sock; break; } else { pthread_create(&thread, NULL, handleClient, sock); int joined = pthread_join(thread, NULL); if (joined != 0) { std::cerr << "Couldn't join thread" << std::endl; } } } if(kDNSServiceErr_NoError == bonjErr) regist.unregisterService(); } void * vvServer::handleClient(void *attribs) { vvRenderContext::ContextOptions contextOptions; contextOptions.displayName = ""; contextOptions.height = DEFAULTSIZE; contextOptions.width = DEFAULTSIZE; contextOptions.type = vvRenderContext::VV_PBUFFER; vvRenderContext renderContext = vvRenderContext(&contextOptions); if (!renderContext.makeCurrent()) { std::cerr << "Couldn't make render context current" << std::endl; pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvGLTools::enableGLErrorBacktrace(); vvTcpSocket *sock = reinterpret_cast<vvTcpSocket*>(attribs); vvSocketIO *sockio = new vvSocketIO(sock); vvRemoteServer* server = NULL; int getType; sockio->getInt32(getType); RemoteRenderingType remoteType = RR_NONE; vvRenderer::RendererType rType = (vvRenderer::RendererType)getType; switch(rType) { case vvRenderer::REMOTE_IMAGE: server = new vvImageServer(sockio); remoteType = RR_IMAGE; break; case vvRenderer::REMOTE_IBR: server = new vvIbrServer(sockio); remoteType = RR_IBR; break; default: std::cerr << "Unknown remote rendering type " << rType << std::endl; break; } if(!server) { pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvVolDesc *vd = NULL; if (server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if (vd != NULL) { if (server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if (vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, remoteType==RR_IBR ? "rayrend" : "default", ""); if(remoteType == RR_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); while (1) { if (!server->processEvents(renderer)) { break; } // if (vvDebugMsg::getDebugLevel() > 0) // { // renderContext.swapBuffers(); // } } delete renderer; } // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). cleanup: delete server; server = NULL; sock->disconnectFromHost(); delete sock; sock = NULL; delete vd; vd = NULL; pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } //---------------------------------------------------------------------------- /// Display command usage help on the command line. void vvServer::displayHelpInfo() { vvDebugMsg::msg(1, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; cerr << "-size <width> <height>" << endl; cerr << " Set the window size to <width> * <height> pixels." << endl; cerr << " The default window size is " << DEFAULTSIZE << " * " << DEFAULTSIZE << " pixels" << endl; cerr << endl; cerr << "-debug" << endl; cerr << " Set debug level" << endl; cerr << endl; } //---------------------------------------------------------------------------- /** Parse command line arguments. @param argc,argv command line arguments @return true if parsing ok, false on error */ bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-debug")==0) { if ((++arg)>=argc) { cerr << "Debug level missing." << endl; return false; } int level = atoi(argv[arg]); if (level>=0 && level<=3) vvDebugMsg::setDebugLevel(level); else { cerr << "Invalid debug level." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-size")==0) { if ((++arg)>=argc) { cerr << "Window width missing." << endl; return false; } winWidth = atoi(argv[arg]); if ((++arg)>=argc) { cerr << "Window height missing." << endl; return false; } winHeight = atoi(argv[arg]); if (winWidth<1 || winHeight<1) { cerr << "Invalid window size." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified, defaulting to: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; return false; } else { int inport = atoi(argv[arg]); if(inport > 65535 || inport <= 0) { cerr << "Specified port is out of range. Falling back to default: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; } else port = inport; } } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } //---------------------------------------------------------------------------- /** Main Virvo server routine. @param argc,argv command line arguments @return 0 if the program finished ok, 1 if an error occurred */ int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze (schulze@cs.brown.edu)" << endl; cerr << "Brown University" << endl << endl; if (parseCommandLine(argc, argv) == false) return 1; serverLoop(); return 0; } //---------------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); vvServer vserver; int error = vserver.run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //============================================================================ // End of File //============================================================================ // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>vserver bugfix: announce correct port<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <iostream> using std::cerr; using std::endl; #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include <virvo/vvbonjour/vvbonjourentry.h> #include <virvo/vvbonjour/vvbonjourregistrar.h> #include <virvo/vvdebugmsg.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvpthread.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendercontext.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvsocketio.h> #include <virvo/vvtcpserver.h> #include <virvo/vvtoolshed.h> #include <virvo/vvvirvo.h> #include <virvo/vvvoldesc.h> /** * Virvo Server main class. * * Server unit for remote rendering. * * Options -port: set port, else default will be used. * * @author Juergen Schulze (schulze@cs.brown.de) * @author Stavros Delisavas (stavros.delisavas@uni-koeln.de) */ class vvServer { private: /// Remote rendering type enum RemoteRenderingType { RR_NONE, RR_IMAGE, RR_IBR }; static const int DEFAULTSIZE; ///< default window size (width and height) in pixels static const int DEFAULT_PORT; ///< default port for socket connections static vvServer* ds; ///< one instance of vvServer is always present int winWidth, winHeight; ///< window size in pixels unsigned short port; ///< port the server renderer uses to listen for incoming connections public: vvServer(); ~vvServer(); int run(int, char**); private: void displayHelpInfo(); bool parseCommandLine(int argc, char *argv[]); void serverLoop(); static void * handleClient(void * attribs); }; const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; //---------------------------------------------------------------------------- /// Constructor vvServer::vvServer() { winWidth = winHeight = DEFAULTSIZE; port = vvServer::DEFAULT_PORT; } //---------------------------------------------------------------------------- /// Destructor. vvServer::~vvServer() { } void vvServer::serverLoop() { pthread_t thread; vvTcpServer tcpServ = vvTcpServer(port); if(!tcpServ.initStatus()) { cerr << "Failed to initialize server-socket on port " << port << "." << endl; return; } vvBonjourRegistrar regist; DNSServiceErrorType bonjErr = regist.registerService(*(new vvBonjourEntry("Virvo Server", "_vserver._tcp", "")), port); while (1) { cerr << "Listening on port " << port << endl; vvSocket *sock = NULL; while((sock = tcpServ.nextConnection()) == NULL) { // retry cerr << "Socket blocked, retry..." << endl; } if(sock == NULL) { cerr << "Failed to initialize server socket on port " << port << endl; delete sock; break; } else { pthread_create(&thread, NULL, handleClient, sock); int joined = pthread_join(thread, NULL); if (joined != 0) { std::cerr << "Couldn't join thread" << std::endl; } } } if(kDNSServiceErr_NoError == bonjErr) regist.unregisterService(); } void * vvServer::handleClient(void *attribs) { vvRenderContext::ContextOptions contextOptions; contextOptions.displayName = ""; contextOptions.height = DEFAULTSIZE; contextOptions.width = DEFAULTSIZE; contextOptions.type = vvRenderContext::VV_PBUFFER; vvRenderContext renderContext = vvRenderContext(&contextOptions); if (!renderContext.makeCurrent()) { std::cerr << "Couldn't make render context current" << std::endl; pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvGLTools::enableGLErrorBacktrace(); vvTcpSocket *sock = reinterpret_cast<vvTcpSocket*>(attribs); vvSocketIO *sockio = new vvSocketIO(sock); vvRemoteServer* server = NULL; int getType; sockio->getInt32(getType); RemoteRenderingType remoteType = RR_NONE; vvRenderer::RendererType rType = (vvRenderer::RendererType)getType; switch(rType) { case vvRenderer::REMOTE_IMAGE: server = new vvImageServer(sockio); remoteType = RR_IMAGE; break; case vvRenderer::REMOTE_IBR: server = new vvIbrServer(sockio); remoteType = RR_IBR; break; default: std::cerr << "Unknown remote rendering type " << rType << std::endl; break; } if(!server) { pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvVolDesc *vd = NULL; if (server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if (vd != NULL) { if (server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if (vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, remoteType==RR_IBR ? "rayrend" : "default", ""); if(remoteType == RR_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); while (1) { if (!server->processEvents(renderer)) { break; } // if (vvDebugMsg::getDebugLevel() > 0) // { // renderContext.swapBuffers(); // } } delete renderer; } // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). cleanup: delete server; server = NULL; sock->disconnectFromHost(); delete sock; sock = NULL; delete vd; vd = NULL; pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } //---------------------------------------------------------------------------- /// Display command usage help on the command line. void vvServer::displayHelpInfo() { vvDebugMsg::msg(1, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; cerr << "-size <width> <height>" << endl; cerr << " Set the window size to <width> * <height> pixels." << endl; cerr << " The default window size is " << DEFAULTSIZE << " * " << DEFAULTSIZE << " pixels" << endl; cerr << endl; cerr << "-debug" << endl; cerr << " Set debug level" << endl; cerr << endl; } //---------------------------------------------------------------------------- /** Parse command line arguments. @param argc,argv command line arguments @return true if parsing ok, false on error */ bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-debug")==0) { if ((++arg)>=argc) { cerr << "Debug level missing." << endl; return false; } int level = atoi(argv[arg]); if (level>=0 && level<=3) vvDebugMsg::setDebugLevel(level); else { cerr << "Invalid debug level." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-size")==0) { if ((++arg)>=argc) { cerr << "Window width missing." << endl; return false; } winWidth = atoi(argv[arg]); if ((++arg)>=argc) { cerr << "Window height missing." << endl; return false; } winHeight = atoi(argv[arg]); if (winWidth<1 || winHeight<1) { cerr << "Invalid window size." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified, defaulting to: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; return false; } else { int inport = atoi(argv[arg]); if(inport > 65535 || inport <= 0) { cerr << "Specified port is out of range. Falling back to default: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; } else port = inport; } } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } //---------------------------------------------------------------------------- /** Main Virvo server routine. @param argc,argv command line arguments @return 0 if the program finished ok, 1 if an error occurred */ int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze (schulze@cs.brown.edu)" << endl; cerr << "Brown University" << endl << endl; if (parseCommandLine(argc, argv) == false) return 1; serverLoop(); return 0; } //---------------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); vvServer vserver; int error = vserver.run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //============================================================================ // End of File //============================================================================ // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before> #include "CCameraController.h" #include <ionWindow.h> #include <glm/gtc/matrix_transform.hpp> namespace ion { CCameraController::CCameraController(Scene::ICamera * Camera) { this->Camera = Camera; this->Phi = 0; this->Theta = 1.5708f; this->Tracking = false; this->MoveSpeed = 2.5f; this->LookSpeed = 0.005f; this->FocalLengthDelta = 1.1f; this->MaxAngleEpsilon = 0.01f; for (int i = 0; i < (int) ECommand::Count; ++ i) this->Commands[i] = false; } void CCameraController::OnEvent(IEvent & Event) { if (InstanceOf<SMouseEvent>(Event)) { SMouseEvent & MouseEvent = As<SMouseEvent>(Event); if (MouseEvent.Type == SMouseEvent::EType::Click && (MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right) Tracking = true; if (MouseEvent.Type == SMouseEvent::EType::Click && (! MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right) Tracking = false; if (MouseEvent.Type == SMouseEvent::EType::Move) { if (Tracking) { Theta += (MouseEvent.Movement.X) * LookSpeed; Phi -= (MouseEvent.Movement.Y) * LookSpeed; } } if (MouseEvent.Type == SMouseEvent::EType::Scroll) { Scene::CPerspectiveCamera * PerspectiveCamera = nullptr; if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera))) { f32 FocalLength = PerspectiveCamera->GetFocalLength(); s32 ticks = (s32) MouseEvent.Movement.Y; if (ticks > 0) while (ticks-- > 0) FocalLength *= FocalLengthDelta; else if (ticks < 0) while (ticks++ < 0) FocalLength /= FocalLengthDelta; PerspectiveCamera->SetFocalLength(FocalLength); } } } else if (InstanceOf<SKeyboardEvent>(Event)) { SKeyboardEvent & KeyboardEvent = As<SKeyboardEvent>(Event); if (KeyboardEvent.Key == EKey::W || KeyboardEvent.Key == EKey::Up) Commands[(int) ECommand::Forward] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::S || KeyboardEvent.Key == EKey::Down) Commands[(int) ECommand::Back] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::A || KeyboardEvent.Key == EKey::Left) Commands[(int) ECommand::Left] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::D || KeyboardEvent.Key == EKey::Right) Commands[(int) ECommand::Right] = KeyboardEvent.Pressed; if (! KeyboardEvent.Pressed) { if (KeyboardEvent.Key == EKey::Num0) SetVelocity(5000000.f); if (KeyboardEvent.Key == EKey::Num9) SetVelocity(500000.f); if (KeyboardEvent.Key == EKey::Num8) SetVelocity(50000.f); if (KeyboardEvent.Key == EKey::Num7) SetVelocity(5000.f); if (KeyboardEvent.Key == EKey::Num6) SetVelocity(500.f); if (KeyboardEvent.Key == EKey::Num5) SetVelocity(50.f); if (KeyboardEvent.Key == EKey::Num4) SetVelocity(10.f); if (KeyboardEvent.Key == EKey::Num3) SetVelocity(2.5f); if (KeyboardEvent.Key == EKey::Num2) SetVelocity(0.75f); if (KeyboardEvent.Key == EKey::Num1) SetVelocity(0.1f); } } else if (InstanceOf<CTimeManager::CUpdateTick>(Event)) { CTimeManager::CUpdateTick & UpdateTick = As<CTimeManager::CUpdateTick>(Event); Update(UpdateTick.GetElapsedTime()); } } void CCameraController::Update(f64 const TickTime) { if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon) Phi = Constants32::Pi / 2 - MaxAngleEpsilon; if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon) Phi = -Constants32::Pi / 2 + MaxAngleEpsilon; vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi)); vec3f const UpVector = Camera->GetUpVector(); vec3f Translation = Camera->GetPosition(); vec3f const W = -1 * LookDirection; vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized(); vec3f const U = V.CrossProduct(W).GetNormalized()*-1; f32 const MoveDelta = MoveSpeed * (f32) TickTime; if (Commands[(int) ECommand::Forward]) Translation += LookDirection * MoveDelta; if (Commands[(int) ECommand::Left]) Translation += V * MoveDelta; if (Commands[(int) ECommand::Right]) Translation -= V * MoveDelta; if (Commands[(int) ECommand::Back]) Translation -= LookDirection * MoveDelta; Camera->SetPosition(Translation); Camera->SetLookDirection(LookDirection); } vec3f const & CCameraController::GetPosition() const { return Camera->GetPosition(); } Scene::ICamera const * CCameraController::GetCamera() const { return Camera; } Scene::ICamera * CCameraController::GetCamera() { return Camera; } f32 CCameraController::GetVelocity() const { return MoveSpeed; } void CCameraController::SetVelocity(float const velocity) { MoveSpeed = velocity; } f32 CCameraController::GetPhi() const { return Phi; } void CCameraController::SetPhi(f32 const Phi) { this->Phi = Phi; } f32 CCameraController::GetTheta() const { return Theta; } void CCameraController::SetTheta(f32 const Theta) { this->Theta = Theta; } ////////////////////////////// // CGamePadCameraController // ////////////////////////////// CGamePadCameraController::CGamePadCameraController(Scene::ICamera * Camera) : CCameraController(Camera) {} void CGamePadCameraController::Update(f64 const TickTime) { GamePad->UpdateState(); f32 const RightMod = (1.f + 5.f * GamePad->GetRightTrigger()); f32 const LeftMod = (1.f / (1.f + 10.f * GamePad->GetLeftTrigger())); // Look - Right Axis f32 const LookMod = 512.f * LeftMod; Theta += (GamePad->GetRightStick().X) * LookMod * LookSpeed * (f32) TickTime; Phi += (GamePad->GetRightStick().Y) * LookMod * LookSpeed * (f32) TickTime; if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon) Phi = Constants32::Pi / 2 - MaxAngleEpsilon; if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon) Phi = -Constants32::Pi / 2 + MaxAngleEpsilon; vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi)); vec3f const UpVector = Camera->GetUpVector(); vec3f Translation = Camera->GetPosition(); vec3f const W = -1 * LookDirection; vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized(); vec3f const U = V.CrossProduct(W).GetNormalized()*-1; // Movement - Left Axis f32 const MoveDelta = MoveSpeed * (f32) TickTime * RightMod * LeftMod; Translation += LookDirection * MoveDelta * GamePad->GetLeftStick().Y; Translation -= V * MoveDelta * GamePad->GetLeftStick().X; if (GamePad->IsButtonPressed(EGamePadButton::LeftShoulder)) Translation.Y -= MoveDelta; if (GamePad->IsButtonPressed(EGamePadButton::RightShoulder)) Translation.Y += MoveDelta; Camera->SetPosition(Translation); // Camera Speed f32 const AccelerateSpeed = 32.f; if (GamePad->IsButtonPressed(EGamePadButton::DPadRight)) MoveSpeed += AccelerateSpeed * (f32) TickTime; if (GamePad->IsButtonPressed(EGamePadButton::DPadLeft)) MoveSpeed -= AccelerateSpeed * (f32) TickTime; // Focal Length - DPad f32 const ZoomSpeed = 100.f; f32 const ZoomMod = 1.01f; Scene::CPerspectiveCamera * PerspectiveCamera = nullptr; if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera))) { f32 FocalLength = PerspectiveCamera->GetFocalLength(); if (GamePad->IsButtonPressed(EGamePadButton::DPadUp)) FocalLengthAccumulator += ZoomSpeed * (f32) TickTime; if (GamePad->IsButtonPressed(EGamePadButton::DPadDown)) FocalLengthAccumulator -= ZoomSpeed * (f32) TickTime; if (FocalLengthAccumulator > 1) { while (FocalLengthAccumulator > 1) { FocalLengthAccumulator -= 1.f; FocalLength *= ZoomMod; } } else if (FocalLengthAccumulator < -1) { while (FocalLengthAccumulator < -1) { FocalLengthAccumulator += 1.f; FocalLength /= ZoomMod; } } PerspectiveCamera->SetFocalLength(FocalLength); } CCameraController::Update(TickTime); } } <commit_msg>[ionApplication] Improve gamepad camera controller vertical movement<commit_after> #include "CCameraController.h" #include <ionWindow.h> #include <glm/gtc/matrix_transform.hpp> namespace ion { CCameraController::CCameraController(Scene::ICamera * Camera) { this->Camera = Camera; this->Phi = 0; this->Theta = 1.5708f; this->Tracking = false; this->MoveSpeed = 2.5f; this->LookSpeed = 0.005f; this->FocalLengthDelta = 1.1f; this->MaxAngleEpsilon = 0.01f; for (int i = 0; i < (int) ECommand::Count; ++ i) this->Commands[i] = false; } void CCameraController::OnEvent(IEvent & Event) { if (InstanceOf<SMouseEvent>(Event)) { SMouseEvent & MouseEvent = As<SMouseEvent>(Event); if (MouseEvent.Type == SMouseEvent::EType::Click && (MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right) Tracking = true; if (MouseEvent.Type == SMouseEvent::EType::Click && (! MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right) Tracking = false; if (MouseEvent.Type == SMouseEvent::EType::Move) { if (Tracking) { Theta += (MouseEvent.Movement.X) * LookSpeed; Phi -= (MouseEvent.Movement.Y) * LookSpeed; } } if (MouseEvent.Type == SMouseEvent::EType::Scroll) { Scene::CPerspectiveCamera * PerspectiveCamera = nullptr; if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera))) { f32 FocalLength = PerspectiveCamera->GetFocalLength(); s32 ticks = (s32) MouseEvent.Movement.Y; if (ticks > 0) while (ticks-- > 0) FocalLength *= FocalLengthDelta; else if (ticks < 0) while (ticks++ < 0) FocalLength /= FocalLengthDelta; PerspectiveCamera->SetFocalLength(FocalLength); } } } else if (InstanceOf<SKeyboardEvent>(Event)) { SKeyboardEvent & KeyboardEvent = As<SKeyboardEvent>(Event); if (KeyboardEvent.Key == EKey::W || KeyboardEvent.Key == EKey::Up) Commands[(int) ECommand::Forward] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::S || KeyboardEvent.Key == EKey::Down) Commands[(int) ECommand::Back] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::A || KeyboardEvent.Key == EKey::Left) Commands[(int) ECommand::Left] = KeyboardEvent.Pressed; if (KeyboardEvent.Key == EKey::D || KeyboardEvent.Key == EKey::Right) Commands[(int) ECommand::Right] = KeyboardEvent.Pressed; if (! KeyboardEvent.Pressed) { if (KeyboardEvent.Key == EKey::Num0) SetVelocity(5000000.f); if (KeyboardEvent.Key == EKey::Num9) SetVelocity(500000.f); if (KeyboardEvent.Key == EKey::Num8) SetVelocity(50000.f); if (KeyboardEvent.Key == EKey::Num7) SetVelocity(5000.f); if (KeyboardEvent.Key == EKey::Num6) SetVelocity(500.f); if (KeyboardEvent.Key == EKey::Num5) SetVelocity(50.f); if (KeyboardEvent.Key == EKey::Num4) SetVelocity(10.f); if (KeyboardEvent.Key == EKey::Num3) SetVelocity(2.5f); if (KeyboardEvent.Key == EKey::Num2) SetVelocity(0.75f); if (KeyboardEvent.Key == EKey::Num1) SetVelocity(0.1f); } } else if (InstanceOf<CTimeManager::CUpdateTick>(Event)) { CTimeManager::CUpdateTick & UpdateTick = As<CTimeManager::CUpdateTick>(Event); Update(UpdateTick.GetElapsedTime()); } } void CCameraController::Update(f64 const TickTime) { if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon) Phi = Constants32::Pi / 2 - MaxAngleEpsilon; if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon) Phi = -Constants32::Pi / 2 + MaxAngleEpsilon; vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi)); vec3f const UpVector = Camera->GetUpVector(); vec3f Translation = Camera->GetPosition(); vec3f const W = -1 * LookDirection; vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized(); vec3f const U = V.CrossProduct(W).GetNormalized()*-1; f32 const MoveDelta = MoveSpeed * (f32) TickTime; if (Commands[(int) ECommand::Forward]) Translation += LookDirection * MoveDelta; if (Commands[(int) ECommand::Left]) Translation += V * MoveDelta; if (Commands[(int) ECommand::Right]) Translation -= V * MoveDelta; if (Commands[(int) ECommand::Back]) Translation -= LookDirection * MoveDelta; Camera->SetPosition(Translation); Camera->SetLookDirection(LookDirection); } vec3f const & CCameraController::GetPosition() const { return Camera->GetPosition(); } Scene::ICamera const * CCameraController::GetCamera() const { return Camera; } Scene::ICamera * CCameraController::GetCamera() { return Camera; } f32 CCameraController::GetVelocity() const { return MoveSpeed; } void CCameraController::SetVelocity(float const velocity) { MoveSpeed = velocity; } f32 CCameraController::GetPhi() const { return Phi; } void CCameraController::SetPhi(f32 const Phi) { this->Phi = Phi; } f32 CCameraController::GetTheta() const { return Theta; } void CCameraController::SetTheta(f32 const Theta) { this->Theta = Theta; } ////////////////////////////// // CGamePadCameraController // ////////////////////////////// CGamePadCameraController::CGamePadCameraController(Scene::ICamera * Camera) : CCameraController(Camera) {} void CGamePadCameraController::Update(f64 const TickTime) { GamePad->UpdateState(); f32 const RightMod = (1.f + 5.f * (GamePad->IsButtonPressed(EGamePadButton::RightShoulder) ? 1.f : 0.f)); f32 const LeftMod = (1.f / (1.f + 10.f * (GamePad->IsButtonPressed(EGamePadButton::LeftShoulder) ? 1.f : 0.f))); // Look - Right Axis f32 const LookMod = 512.f * LeftMod; Theta += (GamePad->GetRightStick().X) * LookMod * LookSpeed * (f32) TickTime; Phi += (GamePad->GetRightStick().Y) * LookMod * LookSpeed * (f32) TickTime; if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon) Phi = Constants32::Pi / 2 - MaxAngleEpsilon; if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon) Phi = -Constants32::Pi / 2 + MaxAngleEpsilon; vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi)); vec3f const UpVector = Camera->GetUpVector(); vec3f Translation = Camera->GetPosition(); vec3f const W = -1 * LookDirection; vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized(); vec3f const U = V.CrossProduct(W).GetNormalized()*-1; // Movement - Left Axis f32 const MoveDelta = MoveSpeed * (f32) TickTime * RightMod * LeftMod; Translation += LookDirection * MoveDelta * GamePad->GetLeftStick().Y; Translation -= V * MoveDelta * GamePad->GetLeftStick().X; Translation.Y -= MoveDelta * GamePad->GetLeftTrigger(); Translation.Y += MoveDelta * GamePad->GetRightTrigger(); Camera->SetPosition(Translation); // Camera Speed f32 const AccelerateSpeed = 32.f; if (GamePad->IsButtonPressed(EGamePadButton::DPadRight)) MoveSpeed += AccelerateSpeed * (f32) TickTime; if (GamePad->IsButtonPressed(EGamePadButton::DPadLeft)) MoveSpeed -= AccelerateSpeed * (f32) TickTime; // Focal Length - DPad f32 const ZoomSpeed = 100.f; f32 const ZoomMod = 1.01f; Scene::CPerspectiveCamera * PerspectiveCamera = nullptr; if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera))) { f32 FocalLength = PerspectiveCamera->GetFocalLength(); if (GamePad->IsButtonPressed(EGamePadButton::DPadUp)) FocalLengthAccumulator += ZoomSpeed * (f32) TickTime; if (GamePad->IsButtonPressed(EGamePadButton::DPadDown)) FocalLengthAccumulator -= ZoomSpeed * (f32) TickTime; if (FocalLengthAccumulator > 1) { while (FocalLengthAccumulator > 1) { FocalLengthAccumulator -= 1.f; FocalLength *= ZoomMod; } } else if (FocalLengthAccumulator < -1) { while (FocalLengthAccumulator < -1) { FocalLengthAccumulator += 1.f; FocalLength /= ZoomMod; } } PerspectiveCamera->SetFocalLength(FocalLength); } CCameraController::Update(TickTime); } } <|endoftext|>
<commit_before>// Copyright (c) 2017-2018 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "zpiv/accumulators.h" #include "chain.h" #include "zpiv/deterministicmint.h" #include "main.h" #include "stakeinput.h" #include "wallet.h" CZPivStake::CZPivStake(const libzerocoin::CoinSpend& spend) { this->nChecksum = spend.getAccumulatorChecksum(); this->denom = spend.getDenomination(); uint256 nSerial = spend.getCoinSerialNumber().getuint256(); this->hashSerial = Hash(nSerial.begin(), nSerial.end()); this->pindexFrom = nullptr; fMint = false; } int CZPivStake::GetChecksumHeightFromMint() { int nHeightChecksum = chainActive.Height() - Params().Zerocoin_RequiredStakeDepth(); //Need to return the first occurance of this checksum in order for the validation process to identify a specific //block height uint32_t nChecksum = 0; nChecksum = ParseChecksum(chainActive[nHeightChecksum]->nAccumulatorCheckpoint, denom); return GetChecksumHeight(nChecksum, denom); } int CZPivStake::GetChecksumHeightFromSpend() { return GetChecksumHeight(nChecksum, denom); } uint32_t CZPivStake::GetChecksum() { return nChecksum; } // The zPIV block index is the first appearance of the accumulator checksum that was used in the spend // note that this also means when staking that this checksum should be from a block that is beyond 60 minutes old and // 100 blocks deep. CBlockIndex* CZPivStake::GetIndexFrom() { if (pindexFrom) return pindexFrom; int nHeightChecksum = 0; if (fMint) nHeightChecksum = GetChecksumHeightFromMint(); else nHeightChecksum = GetChecksumHeightFromSpend(); if (nHeightChecksum < Params().Zerocoin_StartHeight() || nHeightChecksum > chainActive.Height()) { pindexFrom = nullptr; } else { //note that this will be a nullptr if the height DNE pindexFrom = chainActive[nHeightChecksum]; } return pindexFrom; } CAmount CZPivStake::GetValue() { return denom * COIN; } //Use the first accumulator checkpoint that occurs 60 minutes after the block being staked from // In case of regtest, next accumulator of 60 blocks after the block being staked from bool CZPivStake::GetModifier(uint64_t& nStakeModifier) { CBlockIndex* pindex = GetIndexFrom(); if (!pindex) return error("%s: failed to get index from", __func__); if(Params().NetworkID() == CBaseChainParams::REGTEST) { // Stake modifier is fixed for now, move it to 60 blocks after this pindex in the future.. nStakeModifier = pindexFrom->nStakeModifier; return true; } int64_t nTimeBlockFrom = pindex->GetBlockTime(); while (true) { if (pindex->GetBlockTime() - nTimeBlockFrom > 60 * 60) { nStakeModifier = pindex->nAccumulatorCheckpoint.Get64(); return true; } if (pindex->nHeight + 1 <= chainActive.Height()) pindex = chainActive.Next(pindex); else return false; } } CDataStream CZPivStake::GetUniqueness() { //The unique identifier for a zPIV is a hash of the serial CDataStream ss(SER_GETHASH, 0); ss << hashSerial; return ss; } bool CZPivStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) { CBlockIndex* pindexCheckpoint = GetIndexFrom(); if (!pindexCheckpoint) return error("%s: failed to find checkpoint block index", __func__); CZerocoinMint mint; if (!pwallet->GetMintFromStakeHash(hashSerial, mint)) return error("%s: failed to fetch mint associated with serial hash %s", __func__, hashSerial.GetHex()); if (libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < 2) return error("%s: serial extract is less than v2", __func__); CZerocoinSpendReceipt receipt; if (!pwallet->MintToTxIn(mint, hashTxOut, txIn, receipt, libzerocoin::SpendType::STAKE, GetIndexFrom())) return error("%s\n", receipt.GetStatusMessage()); return true; } bool CZPivStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal) { //Create an output returning the zPIV that was staked CTxOut outReward; libzerocoin::CoinDenomination denomStaked = libzerocoin::AmountToZerocoinDenomination(this->GetValue()); CDeterministicMint dMint; if (!pwallet->CreateZPIVOutPut(denomStaked, outReward, dMint)) return error("%s: failed to create zPIV output", __func__); vout.emplace_back(outReward); //Add new staked denom to our wallet if (!pwallet->DatabaseMint(dMint)) return error("%s: failed to database the staked zPIV", __func__); for (unsigned int i = 0; i < 3; i++) { CTxOut out; CDeterministicMint dMintReward; if (!pwallet->CreateZPIVOutPut(libzerocoin::CoinDenomination::ZQ_ONE, out, dMintReward)) return error("%s: failed to create zPIV output", __func__); vout.emplace_back(out); if (!pwallet->DatabaseMint(dMintReward)) return error("%s: failed to database mint reward", __func__); } return true; } bool CZPivStake::GetTxFrom(CTransaction& tx) { return false; } bool CZPivStake::MarkSpent(CWallet *pwallet, const uint256& txid) { CzPIVTracker* zpivTracker = pwallet->zpivTracker.get(); CMintMeta meta; if (!zpivTracker->GetMetaFromStakeHash(hashSerial, meta)) return error("%s: tracker does not have serialhash", __func__); zpivTracker->SetPubcoinUsed(meta.hashPubcoin, txid); return true; } //!PIV Stake bool CPivStake::SetInput(CTransaction txPrev, unsigned int n) { this->txFrom = txPrev; this->nPosition = n; return true; } bool CPivStake::GetTxFrom(CTransaction& tx) { tx = txFrom; return true; } bool CPivStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) { txIn = CTxIn(txFrom.GetHash(), nPosition); return true; } CAmount CPivStake::GetValue() { return txFrom.vout[nPosition].nValue; } bool CPivStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal) { vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyKernel = txFrom.vout[nPosition].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); return false; } if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) return false; // only support pay to public key and pay to address CScript scriptPubKey; if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKey key; CKeyID keyID = CKeyID(uint160(vSolutions[0])); if (!pwallet->GetKey(keyID, key)) return false; scriptPubKey << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKey = scriptPubKeyKernel; vout.emplace_back(CTxOut(0, scriptPubKey)); // Calculate if we need to split the output if (nTotal / 2 > (CAmount)(pwallet->nStakeSplitThreshold * COIN)) vout.emplace_back(CTxOut(0, scriptPubKey)); return true; } bool CPivStake::GetModifier(uint64_t& nStakeModifier) { int nStakeModifierHeight = 0; int64_t nStakeModifierTime = 0; GetIndexFrom(); if (!pindexFrom) return error("%s: failed to get index from", __func__); if (!GetKernelStakeModifier(pindexFrom->GetBlockHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, false)) return error("CheckStakeKernelHash(): failed to get kernel stake modifier \n"); return true; } CDataStream CPivStake::GetUniqueness() { //The unique identifier for a PIV stake is the outpoint CDataStream ss(SER_NETWORK, 0); ss << nPosition << txFrom.GetHash(); return ss; } //The block that the UTXO was added to the chain CBlockIndex* CPivStake::GetIndexFrom() { uint256 hashBlock = 0; CTransaction tx; if (GetTransaction(txFrom.GetHash(), tx, hashBlock, true)) { // If the index is in the chain, then set it as the "index from" if (mapBlockIndex.count(hashBlock)) { CBlockIndex* pindex = mapBlockIndex.at(hashBlock); if (chainActive.Contains(pindex)) pindexFrom = pindex; } } else { LogPrintf("%s : failed to find tx %s\n", __func__, txFrom.GetHash().GetHex()); } return pindexFrom; } <commit_msg>don't duplicate function call<commit_after>// Copyright (c) 2017-2018 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "zpiv/accumulators.h" #include "chain.h" #include "zpiv/deterministicmint.h" #include "main.h" #include "stakeinput.h" #include "wallet.h" CZPivStake::CZPivStake(const libzerocoin::CoinSpend& spend) { this->nChecksum = spend.getAccumulatorChecksum(); this->denom = spend.getDenomination(); uint256 nSerial = spend.getCoinSerialNumber().getuint256(); this->hashSerial = Hash(nSerial.begin(), nSerial.end()); this->pindexFrom = nullptr; fMint = false; } int CZPivStake::GetChecksumHeightFromMint() { int nHeightChecksum = chainActive.Height() - Params().Zerocoin_RequiredStakeDepth(); //Need to return the first occurance of this checksum in order for the validation process to identify a specific //block height uint32_t nChecksum = 0; nChecksum = ParseChecksum(chainActive[nHeightChecksum]->nAccumulatorCheckpoint, denom); return GetChecksumHeight(nChecksum, denom); } int CZPivStake::GetChecksumHeightFromSpend() { return GetChecksumHeight(nChecksum, denom); } uint32_t CZPivStake::GetChecksum() { return nChecksum; } // The zPIV block index is the first appearance of the accumulator checksum that was used in the spend // note that this also means when staking that this checksum should be from a block that is beyond 60 minutes old and // 100 blocks deep. CBlockIndex* CZPivStake::GetIndexFrom() { if (pindexFrom) return pindexFrom; int nHeightChecksum = 0; if (fMint) nHeightChecksum = GetChecksumHeightFromMint(); else nHeightChecksum = GetChecksumHeightFromSpend(); if (nHeightChecksum < Params().Zerocoin_StartHeight() || nHeightChecksum > chainActive.Height()) { pindexFrom = nullptr; } else { //note that this will be a nullptr if the height DNE pindexFrom = chainActive[nHeightChecksum]; } return pindexFrom; } CAmount CZPivStake::GetValue() { return denom * COIN; } //Use the first accumulator checkpoint that occurs 60 minutes after the block being staked from // In case of regtest, next accumulator of 60 blocks after the block being staked from bool CZPivStake::GetModifier(uint64_t& nStakeModifier) { CBlockIndex* pindex = GetIndexFrom(); if (!pindex) return error("%s: failed to get index from", __func__); if(Params().NetworkID() == CBaseChainParams::REGTEST) { // Stake modifier is fixed for now, move it to 60 blocks after this pindex in the future.. nStakeModifier = pindexFrom->nStakeModifier; return true; } int64_t nTimeBlockFrom = pindex->GetBlockTime(); while (true) { if (pindex->GetBlockTime() - nTimeBlockFrom > 60 * 60) { nStakeModifier = pindex->nAccumulatorCheckpoint.Get64(); return true; } if (pindex->nHeight + 1 <= chainActive.Height()) pindex = chainActive.Next(pindex); else return false; } } CDataStream CZPivStake::GetUniqueness() { //The unique identifier for a zPIV is a hash of the serial CDataStream ss(SER_GETHASH, 0); ss << hashSerial; return ss; } bool CZPivStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) { CBlockIndex* pindexCheckpoint = GetIndexFrom(); if (!pindexCheckpoint) return error("%s: failed to find checkpoint block index", __func__); CZerocoinMint mint; if (!pwallet->GetMintFromStakeHash(hashSerial, mint)) return error("%s: failed to fetch mint associated with serial hash %s", __func__, hashSerial.GetHex()); if (libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < 2) return error("%s: serial extract is less than v2", __func__); CZerocoinSpendReceipt receipt; if (!pwallet->MintToTxIn(mint, hashTxOut, txIn, receipt, libzerocoin::SpendType::STAKE, pindexCheckpoint)) return error("%s\n", receipt.GetStatusMessage()); return true; } bool CZPivStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal) { //Create an output returning the zPIV that was staked CTxOut outReward; libzerocoin::CoinDenomination denomStaked = libzerocoin::AmountToZerocoinDenomination(this->GetValue()); CDeterministicMint dMint; if (!pwallet->CreateZPIVOutPut(denomStaked, outReward, dMint)) return error("%s: failed to create zPIV output", __func__); vout.emplace_back(outReward); //Add new staked denom to our wallet if (!pwallet->DatabaseMint(dMint)) return error("%s: failed to database the staked zPIV", __func__); for (unsigned int i = 0; i < 3; i++) { CTxOut out; CDeterministicMint dMintReward; if (!pwallet->CreateZPIVOutPut(libzerocoin::CoinDenomination::ZQ_ONE, out, dMintReward)) return error("%s: failed to create zPIV output", __func__); vout.emplace_back(out); if (!pwallet->DatabaseMint(dMintReward)) return error("%s: failed to database mint reward", __func__); } return true; } bool CZPivStake::GetTxFrom(CTransaction& tx) { return false; } bool CZPivStake::MarkSpent(CWallet *pwallet, const uint256& txid) { CzPIVTracker* zpivTracker = pwallet->zpivTracker.get(); CMintMeta meta; if (!zpivTracker->GetMetaFromStakeHash(hashSerial, meta)) return error("%s: tracker does not have serialhash", __func__); zpivTracker->SetPubcoinUsed(meta.hashPubcoin, txid); return true; } //!PIV Stake bool CPivStake::SetInput(CTransaction txPrev, unsigned int n) { this->txFrom = txPrev; this->nPosition = n; return true; } bool CPivStake::GetTxFrom(CTransaction& tx) { tx = txFrom; return true; } bool CPivStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) { txIn = CTxIn(txFrom.GetHash(), nPosition); return true; } CAmount CPivStake::GetValue() { return txFrom.vout[nPosition].nValue; } bool CPivStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal) { vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyKernel = txFrom.vout[nPosition].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); return false; } if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) return false; // only support pay to public key and pay to address CScript scriptPubKey; if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKey key; CKeyID keyID = CKeyID(uint160(vSolutions[0])); if (!pwallet->GetKey(keyID, key)) return false; scriptPubKey << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKey = scriptPubKeyKernel; vout.emplace_back(CTxOut(0, scriptPubKey)); // Calculate if we need to split the output if (nTotal / 2 > (CAmount)(pwallet->nStakeSplitThreshold * COIN)) vout.emplace_back(CTxOut(0, scriptPubKey)); return true; } bool CPivStake::GetModifier(uint64_t& nStakeModifier) { int nStakeModifierHeight = 0; int64_t nStakeModifierTime = 0; GetIndexFrom(); if (!pindexFrom) return error("%s: failed to get index from", __func__); if (!GetKernelStakeModifier(pindexFrom->GetBlockHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, false)) return error("CheckStakeKernelHash(): failed to get kernel stake modifier \n"); return true; } CDataStream CPivStake::GetUniqueness() { //The unique identifier for a PIV stake is the outpoint CDataStream ss(SER_NETWORK, 0); ss << nPosition << txFrom.GetHash(); return ss; } //The block that the UTXO was added to the chain CBlockIndex* CPivStake::GetIndexFrom() { uint256 hashBlock = 0; CTransaction tx; if (GetTransaction(txFrom.GetHash(), tx, hashBlock, true)) { // If the index is in the chain, then set it as the "index from" if (mapBlockIndex.count(hashBlock)) { CBlockIndex* pindex = mapBlockIndex.at(hashBlock); if (chainActive.Contains(pindex)) pindexFrom = pindex; } } else { LogPrintf("%s : failed to find tx %s\n", __func__, txFrom.GetHash().GetHex()); } return pindexFrom; } <|endoftext|>
<commit_before>#include "parsegtf.hpp" #include "utility.hpp" class badline: public std::exception { virtual const char* what() const throw(){ return "Badly formatted line"; } } badline; using str_vec_iter = std::vector<std::string>::iterator; struct block_process { std::vector <std::string> operator() (str_vec_iter begin, str_vec_iter end, const GTFOptions &options) { std::vector <std::string> result_vector; for (auto it = begin; it != end ; it++) { result_vector.push_back( getGTFFields(*it, options) ); } return std::move(result_vector); } }; std::vector<std::string> parallel_parse(str_vec_iter begin, str_vec_iter end, const GTFOptions & options) { const size_t MIN_SIZE = 10000; size_t length = std::distance(begin, end); if (length < MIN_SIZE) { return block_process() (begin, end, std::ref(options)); } size_t num_threads = std::max((unsigned int)2, std::thread::hardware_concurrency()); size_t block_size = length / num_threads; str_vec_iter current_begin, current_end; current_begin = begin; std::vector< std::future<std::vector<std::string>>> handle_vector; for (size_t i=0 ; i < (num_threads - 1) ; i++) { current_end=current_begin; std::advance(current_end, block_size); handle_vector.push_back( std::async( std::launch::async, block_process(), current_begin, current_end, std::ref(options) ) ); current_begin = current_end; } handle_vector.push_back( std::async( std::launch::async, block_process(), current_begin, current_end, std::ref(options) ) ); std::vector<std::string> final_results; std::for_each(handle_vector.begin(), handle_vector.end(), [&final_results](auto &element){ auto result = element.get(); std::move(result.begin(), result.end(), std::back_inserter(final_results)); }); return std::move(final_results); } void readGTFFile(std::istream &input_stream, std::ostream &output_stream, const GTFOptions& options) { const size_t buffer_size = 262'144; std::string line; string_map att_map; std::vector <std::string> line_buffer, result_buffer; size_t line_count = 0; auto post_data = [&](){ result_buffer = parallel_parse( line_buffer.begin(), line_buffer.end(), options ); std::for_each(result_buffer.begin(), result_buffer.end() , [&output_stream](auto &element){ output_stream << element; }); line_buffer.clear(); }; while (getline(input_stream, line)) { line_count++; if (line[0] != '#') { line_buffer.push_back(std::move(line)); if (line_buffer.size() >= buffer_size) { post_data(); } } } if (line_buffer.size() > 0) { post_data(); } } std::string getGTFFields(const std::string &line, const GTFOptions& options){ std::vector <std::string> tokens; Tokenize(line, tokens, "\t"); if (tokens.size() < 9) { throw badline; } std::string output(""); if (options.feature_type.empty() || tokens[2] == options.feature_type) { for (size_t index = 0 ; index < options.field_list.size() ; index++) { output += tokens[options.field_list[index]]; output += "\t"; } string_map attribute = ParseGTFAttributes(tokens[8]); for(auto &element : options.attribute_list){ output += attribute[element]; output += "\t"; } if (!output.empty()) { output.pop_back(); output += "\n"; } } return output; } string_map ParseGTFAttributes(const std::string &line){ string_map att_map; int pos_name = 0; int size_name; int pos_value = 0; int size_value; std::string start_delims(" "); std::string mid_delims(" \""); std::string end_delims(" \";"); while (true) { pos_name = line.find_first_not_of(end_delims,pos_name); if (pos_name == -1) break; size_name = line.find_first_of(start_delims, pos_name) - pos_name; pos_value = pos_name + size_name; pos_value = line.find_first_not_of(mid_delims,pos_value); if (pos_value == -1) break; size_value = line.find_first_of("\"", pos_value) - pos_value; att_map[ line.substr(pos_name, size_name) ] = line.substr(pos_value, size_value); pos_name = pos_value + size_value; } return att_map; } <commit_msg>Fix data splitting for threads<commit_after>#include "parsegtf.hpp" #include "utility.hpp" class badline: public std::exception { virtual const char* what() const throw(){ return "Badly formatted line"; } } badline; using str_vec_iter = std::vector<std::string>::iterator; struct block_process { std::vector <std::string> operator() (str_vec_iter begin, str_vec_iter end, const GTFOptions &options) { std::vector <std::string> result_vector; for (auto it = begin; it != end ; it++) { result_vector.push_back( getGTFFields(*it, options) ); } return std::move(result_vector); } }; std::vector<std::string> parallel_parse(str_vec_iter begin, str_vec_iter end, const GTFOptions & options) { const size_t MIN_SIZE = 10000; size_t length = std::distance(begin, end); if (length < MIN_SIZE) { return block_process() (begin, end, std::ref(options)); } size_t num_threads = std::max((unsigned int)2, std::thread::hardware_concurrency()); size_t block_size = length / num_threads; str_vec_iter current_begin, current_end; current_begin = begin; std::vector< std::future<std::vector<std::string>>> handle_vector; for (size_t i=0 ; i < (num_threads - 1) ; i++) { current_end=current_begin; std::advance(current_end, block_size); handle_vector.push_back( std::async( std::launch::async, block_process(), current_begin, current_end, std::ref(options) ) ); current_begin = current_end; } handle_vector.push_back( std::async( std::launch::async, block_process(), current_begin, end, std::ref(options) ) ); std::vector<std::string> final_results; std::for_each(handle_vector.begin(), handle_vector.end(), [&final_results](auto &element){ auto result = element.get(); std::move(result.begin(), result.end(), std::back_inserter(final_results)); }); return std::move(final_results); } void readGTFFile(std::istream &input_stream, std::ostream &output_stream, const GTFOptions& options) { const size_t buffer_size = 262'144; std::string line; string_map att_map; std::vector <std::string> line_buffer, result_buffer; size_t line_count = 0; auto post_data = [&](){ result_buffer = parallel_parse( line_buffer.begin(), line_buffer.end(), options ); std::for_each(result_buffer.begin(), result_buffer.end() , [&output_stream](auto &element){ output_stream << element; }); line_buffer.clear(); }; while (getline(input_stream, line)) { line_count++; if (line[0] != '#') { line_buffer.push_back(std::move(line)); if (line_buffer.size() >= buffer_size) { post_data(); } } } if (line_buffer.size() > 0) { post_data(); } } std::string getGTFFields(const std::string &line, const GTFOptions& options){ std::vector <std::string> tokens; Tokenize(line, tokens, "\t"); if (tokens.size() < 9) { throw badline; } std::string output(""); if (options.feature_type.empty() || tokens[2] == options.feature_type) { for (size_t index = 0 ; index < options.field_list.size() ; index++) { output += tokens[options.field_list[index]]; output += "\t"; } string_map attribute = ParseGTFAttributes(tokens[8]); for(auto &element : options.attribute_list){ output += attribute[element]; output += "\t"; } if (!output.empty()) { output.pop_back(); output += "\n"; } } return output; } string_map ParseGTFAttributes(const std::string &line){ string_map att_map; int pos_name = 0; int size_name; int pos_value = 0; int size_value; std::string start_delims(" "); std::string mid_delims(" \""); std::string end_delims(" \";"); while (true) { pos_name = line.find_first_not_of(end_delims,pos_name); if (pos_name == -1) break; size_name = line.find_first_of(start_delims, pos_name) - pos_name; pos_value = pos_name + size_name; pos_value = line.find_first_not_of(mid_delims,pos_value); if (pos_value == -1) break; size_value = line.find_first_of("\"", pos_value) - pos_value; att_map[ line.substr(pos_name, size_name) ] = line.substr(pos_value, size_value); pos_name = pos_value + size_value; } return att_map; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hintwin.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-07-21 15:02:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes ----------------------------------------------------- // INCLUDE --------------------------------------------------------------- #include "hintwin.hxx" #include "global.hxx" #define HINT_LINESPACE 2 #define HINT_INDENT 3 #define HINT_MARGIN 4 //================================================================== ScHintWindow::ScHintWindow( Window* pParent, const String& rTit, const String& rMsg ) : Window( pParent, WinBits( WB_BORDER ) ), aTitle( rTit ), aMessage( rMsg ) { aMessage.ConvertLineEnd( LINEEND_CR ); // Hellgelb, wie Notizen in detfunc.cxx Color aYellow( 255,255,192 ); // hellgelb SetBackground( aYellow ); aTextFont = GetFont(); aTextFont.SetTransparent( TRUE ); aTextFont.SetWeight( WEIGHT_NORMAL ); aHeadFont = aTextFont; aHeadFont.SetWeight( WEIGHT_BOLD ); SetFont( aHeadFont ); Size aHeadSize( GetTextWidth( aTitle ), GetTextHeight() ); SetFont( aTextFont ); Size aTextSize; xub_StrLen nIndex = 0; while ( nIndex != STRING_NOTFOUND ) { String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex ); Size aLineSize( GetTextWidth( aLine ), GetTextHeight() ); nTextHeight = aLineSize.Height(); aTextSize.Height() += nTextHeight; if ( aLineSize.Width() > aTextSize.Width() ) aTextSize.Width() = aLineSize.Width(); } aTextSize.Width() += HINT_INDENT; aTextStart = Point( HINT_MARGIN + HINT_INDENT, aHeadSize.Height() + HINT_MARGIN + HINT_LINESPACE ); Size aWinSize( Max( aHeadSize.Width(), aTextSize.Width() ) + 2 * HINT_MARGIN + 1, aHeadSize.Height() + aTextSize.Height() + HINT_LINESPACE + 2 * HINT_MARGIN + 1 ); SetOutputSizePixel( aWinSize ); } ScHintWindow::~ScHintWindow() { } void __EXPORT ScHintWindow::Paint( const Rectangle& rRect ) { SetFont( aHeadFont ); DrawText( Point(HINT_MARGIN,HINT_MARGIN), aTitle ); SetFont( aTextFont ); xub_StrLen nIndex = 0; Point aLineStart = aTextStart; while ( nIndex != STRING_NOTFOUND ) { String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex ); DrawText( aLineStart, aLine ); aLineStart.Y() += nTextHeight; } } <commit_msg>INTEGRATION: CWS calcwarnings (1.4.110); FILE MERGED 2006/12/01 08:53:47 nn 1.4.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hintwin.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:53:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes ----------------------------------------------------- // INCLUDE --------------------------------------------------------------- #include "hintwin.hxx" #include "global.hxx" #define HINT_LINESPACE 2 #define HINT_INDENT 3 #define HINT_MARGIN 4 //================================================================== ScHintWindow::ScHintWindow( Window* pParent, const String& rTit, const String& rMsg ) : Window( pParent, WinBits( WB_BORDER ) ), aTitle( rTit ), aMessage( rMsg ) { aMessage.ConvertLineEnd( LINEEND_CR ); // Hellgelb, wie Notizen in detfunc.cxx Color aYellow( 255,255,192 ); // hellgelb SetBackground( aYellow ); aTextFont = GetFont(); aTextFont.SetTransparent( TRUE ); aTextFont.SetWeight( WEIGHT_NORMAL ); aHeadFont = aTextFont; aHeadFont.SetWeight( WEIGHT_BOLD ); SetFont( aHeadFont ); Size aHeadSize( GetTextWidth( aTitle ), GetTextHeight() ); SetFont( aTextFont ); Size aTextSize; xub_StrLen nIndex = 0; while ( nIndex != STRING_NOTFOUND ) { String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex ); Size aLineSize( GetTextWidth( aLine ), GetTextHeight() ); nTextHeight = aLineSize.Height(); aTextSize.Height() += nTextHeight; if ( aLineSize.Width() > aTextSize.Width() ) aTextSize.Width() = aLineSize.Width(); } aTextSize.Width() += HINT_INDENT; aTextStart = Point( HINT_MARGIN + HINT_INDENT, aHeadSize.Height() + HINT_MARGIN + HINT_LINESPACE ); Size aWinSize( Max( aHeadSize.Width(), aTextSize.Width() ) + 2 * HINT_MARGIN + 1, aHeadSize.Height() + aTextSize.Height() + HINT_LINESPACE + 2 * HINT_MARGIN + 1 ); SetOutputSizePixel( aWinSize ); } ScHintWindow::~ScHintWindow() { } void __EXPORT ScHintWindow::Paint( const Rectangle& /* rRect */ ) { SetFont( aHeadFont ); DrawText( Point(HINT_MARGIN,HINT_MARGIN), aTitle ); SetFont( aTextFont ); xub_StrLen nIndex = 0; Point aLineStart = aTextStart; while ( nIndex != STRING_NOTFOUND ) { String aLine = aMessage.GetToken( 0, CHAR_CR, nIndex ); DrawText( aLineStart, aLine ); aLineStart.Y() += nTextHeight; } } <|endoftext|>
<commit_before>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * 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 <QProcess> #include <QsLog.h> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl(brick)) , mMailbox(mailbox) , mState(ready) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::textInStdOut); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } mMainContext.evalScript("script.wait(0)"); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } } return true; } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);}); } void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } if (scriptFile.isFile()) { mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('" + scriptFile.canonicalPath() + "')"); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); } <commit_msg>Add explanation to comments<commit_after>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * 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 <QProcess> #include <QsLog.h> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl(brick)) , mMailbox(mailbox) , mState(ready) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::textInStdOut); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } // HACK: to avoid duplicate system.py try to check if basic feature like script.wait works. mMainContext.evalScript("script.wait(0)"); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } } return true; } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);}); } void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } if (scriptFile.isFile()) { mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('" + scriptFile.canonicalPath() + "')"); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); } <|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 "chrome/browser/chromeos/extensions/virtual_keyboard_browsertest.h" #include <vector> #include "ash/shell.h" #include "base/command_line.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "extensions/common/extension.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/input_method.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_switches.h" namespace { const base::FilePath::CharType kWebuiTestDir[] = FILE_PATH_LITERAL("webui"); const base::FilePath::CharType kMockController[] = FILE_PATH_LITERAL("mock_controller.js"); const base::FilePath::CharType kMockTimer[] = FILE_PATH_LITERAL("mock_timer.js"); const char kVirtualKeyboardTestDir[] = "chromeos/virtual_keyboard"; const char kBaseKeyboardTestFramework[] = "virtual_keyboard_test_base.js"; const char kExtensionId[] = "mppnpdlheglhdfmldimlhpnegondlapf"; // Loading the virtual keyboard with id=none suppresses asynchronous loading of // layout and configuration assets. This allows the javascript test code to be // injected ahead of the keyboard initialization. const char kVirtualKeyboardURL[] = "chrome://keyboard?id=none"; } // namespace VirtualKeyboardBrowserTestConfig::VirtualKeyboardBrowserTestConfig() : base_framework_(kBaseKeyboardTestFramework), extension_id_(kExtensionId), test_dir_(kVirtualKeyboardTestDir), url_(kVirtualKeyboardURL) { } VirtualKeyboardBrowserTestConfig::~VirtualKeyboardBrowserTestConfig() {}; void VirtualKeyboardBrowserTest::SetUpCommandLine( base::CommandLine* command_line) { command_line->AppendSwitch(keyboard::switches::kEnableVirtualKeyboard); } void VirtualKeyboardBrowserTest::RunTest( const base::FilePath& file, const VirtualKeyboardBrowserTestConfig& config) { ui_test_utils::NavigateToURL(browser(), GURL(config.url_)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); ASSERT_TRUE(web_contents); // Inject testing scripts. InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockController)); InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockTimer)); InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), base::FilePath(FILE_PATH_LITERAL(config.base_framework_))); InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), file); ASSERT_TRUE(content::ExecuteScript(web_contents, utf8_content_)); // Inject DOM-automation test harness and run tests. std::vector<int> resource_ids; EXPECT_TRUE(ExecuteWebUIResourceTest(web_contents, resource_ids)); } void VirtualKeyboardBrowserTest::ShowVirtualKeyboard() { aura::Window* window = ash::Shell::GetPrimaryRootWindow(); ui::InputMethod* input_method = window->GetHost()->GetInputMethod(); ASSERT_TRUE(input_method); input_method->ShowImeIfNeeded(); } content::RenderViewHost* VirtualKeyboardBrowserTest::GetKeyboardRenderViewHost( const std::string& id) { ShowVirtualKeyboard(); GURL url = extensions::Extension::GetBaseURLFromExtensionId(id); scoped_ptr<content::RenderWidgetHostIterator> widgets( content::RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { if (widget->IsRenderView()) { content::RenderViewHost* view = content::RenderViewHost::From(widget); if (url == view->GetSiteInstance()->GetSiteURL()) { content::WebContents* wc = content::WebContents::FromRenderViewHost(view); // Waits for virtual keyboard to load. EXPECT_TRUE(content::WaitForLoadStop(wc)); return view; } } } LOG(ERROR) << "Extension not found:" << url; return NULL; } void VirtualKeyboardBrowserTest::InjectJavascript(const base::FilePath& dir, const base::FilePath& file) { base::FilePath path = ui_test_utils::GetTestFilePath(dir, file); std::string library_content; ASSERT_TRUE(base::ReadFileToString(path, &library_content)) << path.value(); utf8_content_.append(library_content); utf8_content_.append(";\n"); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, TypingTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("typing_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, LayoutTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("layout_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, ModifierTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("modifier_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, HideKeyboardKeyTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("hide_keyboard_key_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, IsKeyboardLoaded) { content::RenderViewHost* keyboard_rvh = GetKeyboardRenderViewHost(kExtensionId); ASSERT_TRUE(keyboard_rvh); bool loaded = false; std::string script = "!!chrome.virtualKeyboardPrivate"; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( keyboard_rvh, "window.domAutomationController.send(" + script + ");", &loaded)); // Catches the regression in crbug.com/308653. ASSERT_TRUE(loaded); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, EndToEndTest) { // Get the virtual keyboard's render view host. content::RenderViewHost* keyboard_rvh = GetKeyboardRenderViewHost(kExtensionId); ASSERT_TRUE(keyboard_rvh); // Get the test page's render view host. content::RenderViewHost* browser_rvh = browser()->tab_strip_model()-> GetActiveWebContents()->GetRenderViewHost(); ASSERT_TRUE(browser_rvh); // Set up the test page. GURL url = ui_test_utils::GetTestUrl( base::FilePath(), base::FilePath(FILE_PATH_LITERAL( "chromeos/virtual_keyboard/end_to_end_test.html"))); ui_test_utils::NavigateToURL(browser(), url); // Press 'a' on keyboard. base::FilePath path = ui_test_utils::GetTestFilePath( base::FilePath(FILE_PATH_LITERAL(kVirtualKeyboardTestDir)), base::FilePath(FILE_PATH_LITERAL("end_to_end_test.js"))); std::string script; ASSERT_TRUE(base::ReadFileToString(path, &script)); EXPECT_TRUE(content::ExecuteScript(keyboard_rvh, script)); // Verify 'a' appeared on test page. bool success = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( browser_rvh, "success ? verifyInput('a') : waitForInput('a');", &success)); ASSERT_TRUE(success); } // TODO(kevers|rsadam|bshe): Add UI tests for remaining virtual keyboard // functionality. <commit_msg>Disable VirtualKeyboardBrowserTest.EndToEndTest; it's currently broken.<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 "chrome/browser/chromeos/extensions/virtual_keyboard_browsertest.h" #include <vector> #include "ash/shell.h" #include "base/command_line.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "extensions/common/extension.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/input_method.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_switches.h" namespace { const base::FilePath::CharType kWebuiTestDir[] = FILE_PATH_LITERAL("webui"); const base::FilePath::CharType kMockController[] = FILE_PATH_LITERAL("mock_controller.js"); const base::FilePath::CharType kMockTimer[] = FILE_PATH_LITERAL("mock_timer.js"); const char kVirtualKeyboardTestDir[] = "chromeos/virtual_keyboard"; const char kBaseKeyboardTestFramework[] = "virtual_keyboard_test_base.js"; const char kExtensionId[] = "mppnpdlheglhdfmldimlhpnegondlapf"; // Loading the virtual keyboard with id=none suppresses asynchronous loading of // layout and configuration assets. This allows the javascript test code to be // injected ahead of the keyboard initialization. const char kVirtualKeyboardURL[] = "chrome://keyboard?id=none"; } // namespace VirtualKeyboardBrowserTestConfig::VirtualKeyboardBrowserTestConfig() : base_framework_(kBaseKeyboardTestFramework), extension_id_(kExtensionId), test_dir_(kVirtualKeyboardTestDir), url_(kVirtualKeyboardURL) { } VirtualKeyboardBrowserTestConfig::~VirtualKeyboardBrowserTestConfig() {}; void VirtualKeyboardBrowserTest::SetUpCommandLine( base::CommandLine* command_line) { command_line->AppendSwitch(keyboard::switches::kEnableVirtualKeyboard); } void VirtualKeyboardBrowserTest::RunTest( const base::FilePath& file, const VirtualKeyboardBrowserTestConfig& config) { ui_test_utils::NavigateToURL(browser(), GURL(config.url_)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); ASSERT_TRUE(web_contents); // Inject testing scripts. InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockController)); InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockTimer)); InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), base::FilePath(FILE_PATH_LITERAL(config.base_framework_))); InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), file); ASSERT_TRUE(content::ExecuteScript(web_contents, utf8_content_)); // Inject DOM-automation test harness and run tests. std::vector<int> resource_ids; EXPECT_TRUE(ExecuteWebUIResourceTest(web_contents, resource_ids)); } void VirtualKeyboardBrowserTest::ShowVirtualKeyboard() { aura::Window* window = ash::Shell::GetPrimaryRootWindow(); ui::InputMethod* input_method = window->GetHost()->GetInputMethod(); ASSERT_TRUE(input_method); input_method->ShowImeIfNeeded(); } content::RenderViewHost* VirtualKeyboardBrowserTest::GetKeyboardRenderViewHost( const std::string& id) { ShowVirtualKeyboard(); GURL url = extensions::Extension::GetBaseURLFromExtensionId(id); scoped_ptr<content::RenderWidgetHostIterator> widgets( content::RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { if (widget->IsRenderView()) { content::RenderViewHost* view = content::RenderViewHost::From(widget); if (url == view->GetSiteInstance()->GetSiteURL()) { content::WebContents* wc = content::WebContents::FromRenderViewHost(view); // Waits for virtual keyboard to load. EXPECT_TRUE(content::WaitForLoadStop(wc)); return view; } } } LOG(ERROR) << "Extension not found:" << url; return NULL; } void VirtualKeyboardBrowserTest::InjectJavascript(const base::FilePath& dir, const base::FilePath& file) { base::FilePath path = ui_test_utils::GetTestFilePath(dir, file); std::string library_content; ASSERT_TRUE(base::ReadFileToString(path, &library_content)) << path.value(); utf8_content_.append(library_content); utf8_content_.append(";\n"); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, TypingTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("typing_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, LayoutTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("layout_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, ModifierTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("modifier_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, HideKeyboardKeyTest) { RunTest(base::FilePath(FILE_PATH_LITERAL("hide_keyboard_key_test.js")), VirtualKeyboardBrowserTestConfig()); } IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, IsKeyboardLoaded) { content::RenderViewHost* keyboard_rvh = GetKeyboardRenderViewHost(kExtensionId); ASSERT_TRUE(keyboard_rvh); bool loaded = false; std::string script = "!!chrome.virtualKeyboardPrivate"; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( keyboard_rvh, "window.domAutomationController.send(" + script + ");", &loaded)); // Catches the regression in crbug.com/308653. ASSERT_TRUE(loaded); } // Disabled; http://crbug.com/515596 IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_EndToEndTest) { // Get the virtual keyboard's render view host. content::RenderViewHost* keyboard_rvh = GetKeyboardRenderViewHost(kExtensionId); ASSERT_TRUE(keyboard_rvh); // Get the test page's render view host. content::RenderViewHost* browser_rvh = browser()->tab_strip_model()-> GetActiveWebContents()->GetRenderViewHost(); ASSERT_TRUE(browser_rvh); // Set up the test page. GURL url = ui_test_utils::GetTestUrl( base::FilePath(), base::FilePath(FILE_PATH_LITERAL( "chromeos/virtual_keyboard/end_to_end_test.html"))); ui_test_utils::NavigateToURL(browser(), url); // Press 'a' on keyboard. base::FilePath path = ui_test_utils::GetTestFilePath( base::FilePath(FILE_PATH_LITERAL(kVirtualKeyboardTestDir)), base::FilePath(FILE_PATH_LITERAL("end_to_end_test.js"))); std::string script; ASSERT_TRUE(base::ReadFileToString(path, &script)); EXPECT_TRUE(content::ExecuteScript(keyboard_rvh, script)); // Verify 'a' appeared on test page. bool success = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( browser_rvh, "success ? verifyInput('a') : waitForInput('a');", &success)); ASSERT_TRUE(success); } // TODO(kevers|rsadam|bshe): Add UI tests for remaining virtual keyboard // functionality. <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "tasnativeutils.h" #include <taslogger.h> #include <windows.h> #include <stdio.h> #include <psapi.h> int TasNativeUtils::pidOfActiveWindow(const QHash<QString, TasClient*> clients) { Q_UNUSED(clients); return -1; } int TasNativeUtils::bringAppToForeground(quint64 pid) { Q_UNUSED(pid); return -1; } void TasNativeUtils::changeOrientation(QString) {} bool TasNativeUtils::killProcess(quint64 pid) { HANDLE hProcess; hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, pid ); if( hProcess ){ TerminateProcess( hProcess, 0); CloseHandle(hProcess); return true; } return false; } bool TasNativeUtils::verifyProcess(quint64 pid) { bool running = false; HANDLE hProcess; hProcess = OpenProcess( READ_CONTROL, FALSE, pid ); if( hProcess ){ CloseHandle(hProcess); running = true; } return running; } bool TasNativeUtils::processExitStatus(quint64 pid, int &status) { bool stopped = true; HANDLE hProcess; hProcess = OpenProcess( READ_CONTROL, FALSE, pid ); if( hProcess ){ DWORD dwExitCode = 0; if(GetExitCodeProcess(hProcess, &dwExitCode)){ if(dwExitCode == STILL_ACTIVE){ stopped = false; } else{ status = dwExitCode; } } else{ TasLogger::logger()->debug("TasNativeUtils::processExitStatus could not get status"); //maybe no process since could not open status = 0; } CloseHandle(hProcess); } return stopped; } void TasNativeUtils::runningProcesses(TasObject& applist) { // Get the list of process identifiers. DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) { //return empty if fails return ; } cProcesses = cbNeeded / sizeof(DWORD); //get the details for ( i = 0; i < cProcesses; i++ ){ if( aProcesses[i] != 0 ){ DWORD processID = aProcesses[i]; HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processID ); if (NULL != hProcess ){ HMODULE hMod; DWORD cbNeeded; TCHAR szProcessName[MAX_PATH] = TEXT("unknown"); if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ){ GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) ); } QString processName; #ifdef UNICODE processName = QString::fromUtf16((ushort*)szProcessName); #else processName = QString::fromLocal8Bit(szProcessName); #endif TasObject& processDetails = applist.addNewObject(QString::number(processID), processName, "process"); //add mem PROCESS_MEMORY_COUNTERS pmc; if(GetProcessMemoryInfo(hProcess,&pmc, sizeof(pmc))){ processDetails.addAttribute("memUsage", (int)pmc.WorkingSetSize); } } CloseHandle( hProcess ); } } } <commit_msg>name fix<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "tasnativeutils.h" #include <taslogger.h> #include <windows.h> #include <stdio.h> #include <psapi.h> int TasNativeUtils::pidOfActiveWindow(const QHash<QString, TasClient*> clients) { Q_UNUSED(clients); return -1; } int TasNativeUtils::bringAppToForeground(quint64 pid) { Q_UNUSED(pid); return -1; } void TasNativeUtils::changeOrientation(QString) {} bool TasNativeUtils::killProcess(quint64 pid) { HANDLE hProcess; hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, pid ); if( hProcess ){ TerminateProcess( hProcess, 0); CloseHandle(hProcess); return true; } return false; } bool TasNativeUtils::verifyProcess(quint64 pid) { bool running = false; HANDLE hProcess; hProcess = OpenProcess( READ_CONTROL, FALSE, pid ); if( hProcess ){ CloseHandle(hProcess); running = true; } return running; } bool TasNativeUtils::processExitStatus(quint64 pid, int &status) { bool stopped = true; HANDLE hProcess; hProcess = OpenProcess( READ_CONTROL, FALSE, pid ); if( hProcess ){ DWORD dwExitCode = 0; if(GetExitCodeProcess(hProcess, &dwExitCode)){ if(dwExitCode == STILL_ACTIVE){ stopped = false; } else{ status = dwExitCode; } } else{ TasLogger::logger()->debug("TasNativeUtils::processExitStatus could not get status"); //maybe no process since could not open status = 0; } CloseHandle(hProcess); } return stopped; } void TasNativeUtils::runningProcesses(TasObject& applist) { // Get the list of process identifiers. DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) { //return empty if fails return ; } cProcesses = cbNeeded / sizeof(DWORD); //get the details for ( i = 0; i < cProcesses; i++ ){ if( aProcesses[i] != 0 ){ DWORD processID = aProcesses[i]; HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processID ); if (NULL != hProcess ){ HMODULE hMod; DWORD cbNeeded; TCHAR szProcessName[MAX_PATH] = TEXT("unknown"); if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ){ GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) ); } QString processName; #ifdef UNICODE processName = QString::fromUtf16((ushort*)szProcessName); #else processName = QString::fromLocal8Bit(szProcessName); #endif processName = processName.split(".exe").first(); TasObject& processDetails = applist.addNewObject(QString::number(processID), processName, "process"); //add mem PROCESS_MEMORY_COUNTERS pmc; if(GetProcessMemoryInfo(hProcess,&pmc, sizeof(pmc))){ processDetails.addAttribute("memUsage", (int)pmc.WorkingSetSize); } } CloseHandle( hProcess ); } } } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 <string> #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/web_cache_manager.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" class WebCacheManagerBrowserTest : public InProcessBrowserTest { }; // Regression test for http://crbug.com/12362. If a renderer crashes and the // user navigates to another tab and back, the browser doesn't crash. // TODO(jam): http://crbug.com/15288 disabled because it fails on the build bot. IN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, DISABLED_CrashOnceOnly) { const FilePath kTestDir(FILE_PATH_LITERAL("google")); const FilePath kTestFile(FILE_PATH_LITERAL("google.html")); GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile)); ui_test_utils::NavigateToURL(browser(), url); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(tab != NULL); base::KillProcess(tab->GetRenderProcessHost()->GetHandle(), base::PROCESS_END_KILLED_BY_USER, true); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); // We would have crashed at the above line with the bug. browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( WebCacheManager::GetInstance()->active_renderers_.size(), 1U); EXPECT_EQ( WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U); EXPECT_EQ( WebCacheManager::GetInstance()->stats_.size(), 1U); } <commit_msg>TTF: Re-enable WebCacheManagerBrowserTest.CrashOnceOnly by marking it flaky.<commit_after>// Copyright (c) 2009 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 <string> #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/web_cache_manager.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" class WebCacheManagerBrowserTest : public InProcessBrowserTest { }; // Regression test for http://crbug.com/12362. If a renderer crashes and the // user navigates to another tab and back, the browser doesn't crash. // Flaky, http://crbug.com/15288. IN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, FLAKY_CrashOnceOnly) { const FilePath kTestDir(FILE_PATH_LITERAL("google")); const FilePath kTestFile(FILE_PATH_LITERAL("google.html")); GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile)); ui_test_utils::NavigateToURL(browser(), url); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(tab != NULL); base::KillProcess(tab->GetRenderProcessHost()->GetHandle(), base::PROCESS_END_KILLED_BY_USER, true); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); // We would have crashed at the above line with the bug. browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( WebCacheManager::GetInstance()->active_renderers_.size(), 1U); EXPECT_EQ( WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U); EXPECT_EQ( WebCacheManager::GetInstance()->stats_.size(), 1U); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright © 2012-2014 Institut für Nachrichtentechnik, Universität Rostock * * Copyright © 2006-2012 Quality & Usability Lab, * * Telekom Innovation Laboratories, TU Berlin * * * * This file is part of the Audio Processing Framework (APF). * * * * The APF 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. * * * * The APF 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/>. * * * * http://AudioProcessingFramework.github.com * ******************************************************************************/ // A small example of the MimoProcessor with varying JACK output ports. // This is a stand-alone program. #include <vector> #include "apf/mimoprocessor.h" #include "apf/combine_channels.h" // for apf::CombineChannelsCopy #include "apf/jack_policy.h" #include "apf/dummy_thread_policy.h" class MyProcessor : public apf::MimoProcessor<MyProcessor , apf::jack_policy , apf::dummy_thread_policy> { public: using Input = MimoProcessorBase::DefaultInput; class Output : public MimoProcessorBase::DefaultOutput { public: explicit Output(const Params& p) : MimoProcessorBase::DefaultOutput(p) , _combiner(this->parent.get_input_list(), *this) {} APF_PROCESS(Output, MimoProcessorBase::DefaultOutput) { _combiner.process(select_all_inputs()); } private: struct select_all_inputs { apf::CombineChannelsResult::type select(const Input&) { return apf::CombineChannelsResult::constant; } }; apf::CombineChannelsCopy<rtlist_proxy<Input>, Output> _combiner; }; }; int main() { int out_channels = 20; MyProcessor engine; engine.add<MyProcessor::Input>(); engine.activate(); sleep(2); std::vector<MyProcessor::Output*> outputs; for (int i = 1; i <= out_channels; ++i) { MyProcessor::Output::Params p; p.set("id", i * 10); p.set("connect_to", "system:playback_1"); outputs.push_back(engine.add(p)); sleep(1); } sleep(2); // remove the outputs one by one ... while (outputs.begin() != outputs.end()) { engine.rem(outputs.front()); engine.wait_for_rt_thread(); outputs.erase(outputs.begin()); sleep(1); } sleep(2); engine.deactivate(); } // Settings for Vim (http://www.vim.org/), please do not remove: // vim:softtabstop=2:shiftwidth=2:expandtab:textwidth=80:cindent <commit_msg>(SSR) jack_dynamic_outputs: use POSIX instead of dummy thread policy<commit_after>/****************************************************************************** * Copyright © 2012-2014 Institut für Nachrichtentechnik, Universität Rostock * * Copyright © 2006-2012 Quality & Usability Lab, * * Telekom Innovation Laboratories, TU Berlin * * * * This file is part of the Audio Processing Framework (APF). * * * * The APF 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. * * * * The APF 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/>. * * * * http://AudioProcessingFramework.github.com * ******************************************************************************/ // A small example of the MimoProcessor with varying JACK output ports. // This is a stand-alone program. #include <vector> #include "apf/mimoprocessor.h" #include "apf/combine_channels.h" // for apf::CombineChannelsCopy #include "apf/jack_policy.h" #include "apf/posix_thread_policy.h" class MyProcessor : public apf::MimoProcessor<MyProcessor , apf::jack_policy , apf::posix_thread_policy> { public: using Input = MimoProcessorBase::DefaultInput; class Output : public MimoProcessorBase::DefaultOutput { public: explicit Output(const Params& p) : MimoProcessorBase::DefaultOutput(p) , _combiner(this->parent.get_input_list(), *this) {} APF_PROCESS(Output, MimoProcessorBase::DefaultOutput) { _combiner.process(select_all_inputs()); } private: struct select_all_inputs { apf::CombineChannelsResult::type select(const Input&) { return apf::CombineChannelsResult::constant; } }; apf::CombineChannelsCopy<rtlist_proxy<Input>, Output> _combiner; }; }; int main() { int out_channels = 20; MyProcessor engine; engine.add<MyProcessor::Input>(); engine.activate(); sleep(2); std::vector<MyProcessor::Output*> outputs; for (int i = 1; i <= out_channels; ++i) { MyProcessor::Output::Params p; p.set("id", i * 10); p.set("connect_to", "system:playback_1"); outputs.push_back(engine.add(p)); sleep(1); } sleep(2); // remove the outputs one by one ... while (outputs.begin() != outputs.end()) { engine.rem(outputs.front()); engine.wait_for_rt_thread(); outputs.erase(outputs.begin()); sleep(1); } sleep(2); engine.deactivate(); } // Settings for Vim (http://www.vim.org/), please do not remove: // vim:softtabstop=2:shiftwidth=2:expandtab:textwidth=80:cindent <|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/chromeos/policy/wildcard_login_checker.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "net/url_request/url_request_context_getter.h" namespace policy { namespace { // Presence of this key in the userinfo response indicates whether the user is // on a hosted domain. const char kHostedDomainKey[] = "hd"; // UMA histogram names. const char kUMADelayPolicyTokenFetch[] = "Enterprise.WildcardLoginCheck.DelayPolicyTokenFetch"; const char kUMADelayUserInfoFetch[] = "Enterprise.WildcardLoginCheck.DelayUserInfoFetch"; const char kUMADelayTotal[] = "Enterprise.WildcardLoginCheck.DelayTotal"; } // namespace WildcardLoginChecker::WildcardLoginChecker() {} WildcardLoginChecker::~WildcardLoginChecker() {} void WildcardLoginChecker::StartWithSigninContext( scoped_refptr<net::URLRequestContextGetter> signin_context, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); callback_ = callback; token_fetcher_.reset(new PolicyOAuth2TokenFetcher()); token_fetcher_->StartWithSigninContext( signin_context.get(), g_browser_process->system_request_context(), base::Bind(&WildcardLoginChecker::OnPolicyTokenFetched, base::Unretained(this))); } void WildcardLoginChecker::StartWithRefreshToken( const std::string& refresh_token, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); callback_ = callback; token_fetcher_.reset(new PolicyOAuth2TokenFetcher()); token_fetcher_->StartWithRefreshToken( refresh_token, g_browser_process->system_request_context(), base::Bind(&WildcardLoginChecker::OnPolicyTokenFetched, base::Unretained(this))); } void WildcardLoginChecker::StartWithAccessToken( const std::string& access_token, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); callback_ = callback; StartUserInfoFetcher(access_token); } void WildcardLoginChecker::OnGetUserInfoSuccess( const base::DictionaryValue* response) { if (!start_timestamp_.is_null()) { base::Time now = base::Time::Now(); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayUserInfoFetch, now - token_available_timestamp_); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayTotal, now - start_timestamp_); } OnCheckCompleted(response->HasKey(kHostedDomainKey) ? RESULT_ALLOWED : RESULT_BLOCKED); } void WildcardLoginChecker::OnGetUserInfoFailure( const GoogleServiceAuthError& error) { LOG(ERROR) << "Failed to fetch user info " << error.ToString(); OnCheckCompleted(RESULT_FAILED); } void WildcardLoginChecker::OnPolicyTokenFetched( const std::string& access_token, const GoogleServiceAuthError& error) { if (error.state() != GoogleServiceAuthError::NONE) { LOG(ERROR) << "Failed to fetch policy token " << error.ToString(); OnCheckCompleted(RESULT_FAILED); return; } if (!start_timestamp_.is_null()) { token_available_timestamp_ = base::Time::Now(); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayPolicyTokenFetch, token_available_timestamp_ - start_timestamp_); } token_fetcher_.reset(); StartUserInfoFetcher(access_token); } void WildcardLoginChecker::StartUserInfoFetcher( const std::string& access_token) { user_info_fetcher_.reset( new UserInfoFetcher(this, g_browser_process->system_request_context())); user_info_fetcher_->Start(access_token); } void WildcardLoginChecker::OnCheckCompleted(Result result) { if (!callback_.is_null()) callback_.Run(result); } } // namespace policy <commit_msg>Set start timestamp in StartWithAccessToken.<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/chromeos/policy/wildcard_login_checker.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "net/url_request/url_request_context_getter.h" namespace policy { namespace { // Presence of this key in the userinfo response indicates whether the user is // on a hosted domain. const char kHostedDomainKey[] = "hd"; // UMA histogram names. const char kUMADelayPolicyTokenFetch[] = "Enterprise.WildcardLoginCheck.DelayPolicyTokenFetch"; const char kUMADelayUserInfoFetch[] = "Enterprise.WildcardLoginCheck.DelayUserInfoFetch"; const char kUMADelayTotal[] = "Enterprise.WildcardLoginCheck.DelayTotal"; } // namespace WildcardLoginChecker::WildcardLoginChecker() {} WildcardLoginChecker::~WildcardLoginChecker() {} void WildcardLoginChecker::StartWithSigninContext( scoped_refptr<net::URLRequestContextGetter> signin_context, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); callback_ = callback; token_fetcher_.reset(new PolicyOAuth2TokenFetcher()); token_fetcher_->StartWithSigninContext( signin_context.get(), g_browser_process->system_request_context(), base::Bind(&WildcardLoginChecker::OnPolicyTokenFetched, base::Unretained(this))); } void WildcardLoginChecker::StartWithRefreshToken( const std::string& refresh_token, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); callback_ = callback; token_fetcher_.reset(new PolicyOAuth2TokenFetcher()); token_fetcher_->StartWithRefreshToken( refresh_token, g_browser_process->system_request_context(), base::Bind(&WildcardLoginChecker::OnPolicyTokenFetched, base::Unretained(this))); } void WildcardLoginChecker::StartWithAccessToken( const std::string& access_token, const StatusCallback& callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); callback_ = callback; StartUserInfoFetcher(access_token); } void WildcardLoginChecker::OnGetUserInfoSuccess( const base::DictionaryValue* response) { if (!start_timestamp_.is_null()) { base::Time now = base::Time::Now(); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayUserInfoFetch, now - token_available_timestamp_); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayTotal, now - start_timestamp_); } OnCheckCompleted(response->HasKey(kHostedDomainKey) ? RESULT_ALLOWED : RESULT_BLOCKED); } void WildcardLoginChecker::OnGetUserInfoFailure( const GoogleServiceAuthError& error) { LOG(ERROR) << "Failed to fetch user info " << error.ToString(); OnCheckCompleted(RESULT_FAILED); } void WildcardLoginChecker::OnPolicyTokenFetched( const std::string& access_token, const GoogleServiceAuthError& error) { if (error.state() != GoogleServiceAuthError::NONE) { LOG(ERROR) << "Failed to fetch policy token " << error.ToString(); OnCheckCompleted(RESULT_FAILED); return; } if (!start_timestamp_.is_null()) { token_available_timestamp_ = base::Time::Now(); UMA_HISTOGRAM_MEDIUM_TIMES(kUMADelayPolicyTokenFetch, token_available_timestamp_ - start_timestamp_); } token_fetcher_.reset(); StartUserInfoFetcher(access_token); } void WildcardLoginChecker::StartUserInfoFetcher( const std::string& access_token) { user_info_fetcher_.reset( new UserInfoFetcher(this, g_browser_process->system_request_context())); user_info_fetcher_->Start(access_token); } void WildcardLoginChecker::OnCheckCompleted(Result result) { if (!callback_.is_null()) callback_.Run(result); } } // namespace policy <|endoftext|>
<commit_before>/** * Copyright (C) 2006 Brad Hards <bradh@frogmouth.net> * * 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 AUTHOR ``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 AUTHOR 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 "filewatchunittest.h" #ifdef QT_STATICPLUGIN #include "import_plugins.h" #endif void FileWatchUnitTest::initTestCase() { m_init = new QCA::Initializer; #include "../fixpaths.include" } void FileWatchUnitTest::cleanupTestCase() { delete m_init; } void FileWatchUnitTest::filewatchTest() { QCA::FileWatch watcher; QCOMPARE( watcher.fileName(), QString() ); QSignalSpy spy( &watcher, SIGNAL(changed()) ); QVERIFY( spy.isValid() ); QCOMPARE( spy.count(), 0 ); QTemporaryFile *tempFile = new QTemporaryFile; tempFile->open(); watcher.setFileName( tempFile->fileName() ); QCOMPARE( watcher.fileName(), tempFile->fileName() ); QTest::qWait(7000); QCOMPARE( spy.count(), 0 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 0 ); tempFile->open(); tempFile->write("foo"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 1 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 1 ); tempFile->open(); tempFile->write("foo"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 2 ); tempFile->write("bar"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 3 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 3 ); delete tempFile; QTest::qWait(7000); QCOMPARE( spy.count(), 4 ); } QTEST_MAIN(FileWatchUnitTest) <commit_msg>filewatchunittest: show 'please wait' message<commit_after>/** * Copyright (C) 2006 Brad Hards <bradh@frogmouth.net> * * 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 AUTHOR ``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 AUTHOR 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 "filewatchunittest.h" #ifdef QT_STATICPLUGIN #include "import_plugins.h" #endif void FileWatchUnitTest::initTestCase() { m_init = new QCA::Initializer; #include "../fixpaths.include" } void FileWatchUnitTest::cleanupTestCase() { delete m_init; } void FileWatchUnitTest::filewatchTest() { QWARN("Unittest will take about 1 minute. Please wait."); QCA::FileWatch watcher; QCOMPARE( watcher.fileName(), QString() ); QSignalSpy spy( &watcher, SIGNAL(changed()) ); QVERIFY( spy.isValid() ); QCOMPARE( spy.count(), 0 ); QTemporaryFile *tempFile = new QTemporaryFile; tempFile->open(); watcher.setFileName( tempFile->fileName() ); QCOMPARE( watcher.fileName(), tempFile->fileName() ); QTest::qWait(7000); QCOMPARE( spy.count(), 0 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 0 ); tempFile->open(); tempFile->write("foo"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 1 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 1 ); tempFile->open(); tempFile->write("foo"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 2 ); tempFile->write("bar"); tempFile->flush(); QTest::qWait(7000); QCOMPARE( spy.count(), 3 ); tempFile->close(); QTest::qWait(7000); QCOMPARE( spy.count(), 3 ); delete tempFile; QTest::qWait(7000); QCOMPARE( spy.count(), 4 ); } QTEST_MAIN(FileWatchUnitTest) <|endoftext|>
<commit_before>#include "pymatching/fill_match/search/search_flooder.h" #include "gtest/gtest.h" TEST(SearchFlooder, RepCodeDetectorSearch) { size_t num_nodes = 40; auto flooder = pm::SearchFlooder(pm::SearchGraph(num_nodes)); auto& g = flooder.graph; g.add_boundary_edge(0, 2, {0}); for (size_t i = 0; i < num_nodes - 1; i++) g.add_edge(i, i + 1, 2, {i + 1}); auto collision_edge = flooder.run_until_collision(&g.nodes[1], &g.nodes[20]); ASSERT_EQ(collision_edge.detector_node, &g.nodes[10]); ASSERT_EQ(collision_edge.neighbor_index, 1); ASSERT_EQ(flooder.target_type, pm::DETECTOR_NODE); std::vector<uint8_t> observables(num_nodes, 0); pm::total_weight_int weight = 0; flooder.iter_edges_tracing_back_from_collision_edge(collision_edge, [&](const pm::SearchGraphEdge& e) { auto& obs = e.detector_node->neighbor_observable_indices[e.neighbor_index]; for (auto i : obs) *(observables.data() + i) ^= 1; weight += e.detector_node->neighbor_weights[e.neighbor_index]; }); std::vector<uint8_t> expected_obs(num_nodes, 0); for (size_t i = 1; i < 20; i++) expected_obs[i + 1] ^= 1; ASSERT_EQ(observables, expected_obs); ASSERT_EQ(weight, 38); flooder.reset_graph(); for (auto& n : g.nodes) { ASSERT_EQ(n.index_of_predecessor, SIZE_MAX); ASSERT_EQ(n.reached_from_source, nullptr); ASSERT_EQ(n.node_event_tracker.desired_time, pm::cyclic_time_int{0}); ASSERT_EQ(n.node_event_tracker.queued_time, pm::cyclic_time_int{0}); ASSERT_EQ(n.node_event_tracker.has_desired_time, false); ASSERT_EQ(n.node_event_tracker.has_queued_time, false); } ASSERT_EQ(flooder.reached_nodes.size(), 0); flooder.reset(); } TEST(SearchFlooder, RepCodeBoundarySearch) { size_t num_nodes = 20; auto flooder = pm::SearchFlooder(pm::SearchGraph(num_nodes)); auto& g = flooder.graph; g.add_boundary_edge(0, 2, {0}); for (size_t i = 0; i < num_nodes - 1; i++) g.add_edge(i, i + 1, 2, {i + 1}); auto collision_edge = flooder.run_until_collision(&g.nodes[6], nullptr); ASSERT_EQ(collision_edge.detector_node, &g.nodes[0]); ASSERT_EQ(collision_edge.neighbor_index, 0); ASSERT_EQ(flooder.target_type, pm::BOUNDARY); std::vector<uint8_t> observables(num_nodes, 0); pm::total_weight_int weight = 0; flooder.iter_edges_tracing_back_from_collision_edge(collision_edge, [&](const pm::SearchGraphEdge& e) { auto& obs = e.detector_node->neighbor_observable_indices[e.neighbor_index]; for (auto i : obs) *(observables.data() + i) ^= 1; weight += e.detector_node->neighbor_weights[e.neighbor_index]; }); std::vector<uint8_t> expected_obs(num_nodes, 0); for (size_t i = 0; i < 7; i++) expected_obs[i] ^= 1; ASSERT_EQ(observables, expected_obs); ASSERT_EQ(weight, 14); flooder.reset(); } <commit_msg>Add test for shortest path from source<commit_after>#include "pymatching/fill_match/search/search_flooder.h" #include "gtest/gtest.h" TEST(SearchFlooder, RepCodeDetectorSearch) { size_t num_nodes = 40; auto flooder = pm::SearchFlooder(pm::SearchGraph(num_nodes)); auto& g = flooder.graph; g.add_boundary_edge(0, 2, {0}); for (size_t i = 0; i < num_nodes - 1; i++) g.add_edge(i, i + 1, 2, {i + 1}); auto collision_edge = flooder.run_until_collision(&g.nodes[1], &g.nodes[20]); ASSERT_EQ(collision_edge.detector_node, &g.nodes[10]); ASSERT_EQ(collision_edge.neighbor_index, 1); ASSERT_EQ(flooder.target_type, pm::DETECTOR_NODE); std::vector<uint8_t> observables(num_nodes, 0); pm::total_weight_int weight = 0; flooder.iter_edges_tracing_back_from_collision_edge(collision_edge, [&](const pm::SearchGraphEdge& e) { auto& obs = e.detector_node->neighbor_observable_indices[e.neighbor_index]; for (auto i : obs) *(observables.data() + i) ^= 1; weight += e.detector_node->neighbor_weights[e.neighbor_index]; }); std::vector<uint8_t> expected_obs(num_nodes, 0); for (size_t i = 1; i < 20; i++) expected_obs[i + 1] ^= 1; ASSERT_EQ(observables, expected_obs); ASSERT_EQ(weight, 38); flooder.reset_graph(); for (auto& n : g.nodes) { ASSERT_EQ(n.index_of_predecessor, SIZE_MAX); ASSERT_EQ(n.reached_from_source, nullptr); ASSERT_EQ(n.node_event_tracker.desired_time, pm::cyclic_time_int{0}); ASSERT_EQ(n.node_event_tracker.queued_time, pm::cyclic_time_int{0}); ASSERT_EQ(n.node_event_tracker.has_desired_time, false); ASSERT_EQ(n.node_event_tracker.has_queued_time, false); } ASSERT_EQ(flooder.reached_nodes.size(), 0); flooder.reset(); } TEST(SearchFlooder, RepCodeBoundarySearch) { size_t num_nodes = 20; auto flooder = pm::SearchFlooder(pm::SearchGraph(num_nodes)); auto& g = flooder.graph; g.add_boundary_edge(0, 2, {0}); for (size_t i = 0; i < num_nodes - 1; i++) g.add_edge(i, i + 1, 2, {i + 1}); auto collision_edge = flooder.run_until_collision(&g.nodes[6], nullptr); ASSERT_EQ(collision_edge.detector_node, &g.nodes[0]); ASSERT_EQ(collision_edge.neighbor_index, 0); ASSERT_EQ(flooder.target_type, pm::BOUNDARY); std::vector<uint8_t> observables(num_nodes, 0); pm::total_weight_int weight = 0; flooder.iter_edges_tracing_back_from_collision_edge(collision_edge, [&](const pm::SearchGraphEdge& e) { auto& obs = e.detector_node->neighbor_observable_indices[e.neighbor_index]; for (auto i : obs) *(observables.data() + i) ^= 1; weight += e.detector_node->neighbor_weights[e.neighbor_index]; }); std::vector<uint8_t> expected_obs(num_nodes, 0); for (size_t i = 0; i < 7; i++) expected_obs[i] ^= 1; ASSERT_EQ(observables, expected_obs); ASSERT_EQ(weight, 14); flooder.reset(); } TEST(SearchFlooder, RepCodeSourceToDestPath) { size_t num_nodes = 20; auto flooder = pm::SearchFlooder(pm::SearchGraph(num_nodes)); auto& g = flooder.graph; g.add_boundary_edge(0, 2, {0}); for (size_t i = 0; i < num_nodes - 1; i++) g.add_edge(i, i + 1, 2, {i + 1}); size_t i_start = 10; for (size_t i_end = 14; i_end < 18; i_end++) { std::vector<pm::SearchGraphEdge> edges; flooder.iter_edges_on_shortest_path_from_source(i_start, i_end, [&](const pm::SearchGraphEdge &edge) { edges.push_back(edge); }); std::vector<size_t> node_indices; for (size_t i = 0; i < edges.size(); i++) { node_indices.push_back(edges[i].detector_node - &flooder.graph.nodes[0]); if (i + 1 < edges.size()) ASSERT_EQ(edges[i].detector_node->neighbors[edges[i].neighbor_index], edges[i+1].detector_node); } std::vector<size_t> expected_node_indices; for (size_t i = i_start; i < i_end; i++) expected_node_indices.push_back(i); ASSERT_EQ(node_indices, expected_node_indices); } std::vector<pm::SearchGraphEdge> edges; flooder.iter_edges_on_shortest_path_from_source(4, SIZE_MAX, [&](const pm::SearchGraphEdge &edge) { edges.push_back(edge); }); std::vector<size_t> node_indices; for (size_t i = 0; i < edges.size(); i++) node_indices.push_back(edges[i].detector_node - &flooder.graph.nodes[0]); std::vector<size_t> expected_node_indices = {4, 3, 2, 1, 0}; ASSERT_EQ(node_indices, expected_node_indices); } <|endoftext|>
<commit_before>#include "band.h" namespace sirius { template <> void Band::orthogonalize<double_complex>(K_point* kp__, int N__, int n__, Wave_functions<false>& phi__, Wave_functions<false>& hphi__, Wave_functions<false>& ophi__, matrix<double_complex>& o__) { return; } template <> void Band::orthogonalize<double>(K_point* kp__, int N__, int n__, Wave_functions<false>& phi__, Wave_functions<false>& hphi__, Wave_functions<false>& ophi__, matrix<double>& o__) { PROFILE_WITH_TIMER("sirius::Band::orthogonalize"); if (N__ > 0) { /* project out the old subspace */ phi__.inner<double>(0, N__, ophi__, N__, n__, o__, 0, 0); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&phi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&phi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&hphi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&hphi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&ophi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&ophi__(0, N__), 2 * kp__->num_gkvec_loc()); } /* orthogonalize new n__ x n__ block */ phi__.inner<double>(N__, n__, ophi__, N__, n__, o__, 0, 0); int info; if ((info = linalg<CPU>::potrf(n__, &o__(0, 0), o__.ld()))) { std::stringstream s; s << "error in factorization, info = " << info; TERMINATE(s); } if (linalg<CPU>::trtri(n__, &o__(0, 0), o__.ld())) TERMINATE("error in inversion"); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&phi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&hphi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&ophi__(0, N__), 2 * kp__->num_gkvec_loc()); //phi__.inner<double>(0, N__ + n__, ophi__, 0, N__ + n__, o__, 0, 0); //for (int i = 0; i < N__ + n__; i++) //{ // for (int j = 0; j < N__ + n__; j++) // { // double a = o__(j, i); // if (i == j) a -= 1; // if (std::abs(a) > 1e-10) // { // printf("wrong overlap"); // TERMINATE("wrong overlap"); // } // } //} } } <commit_msg>comment debug code<commit_after>#include "band.h" namespace sirius { template <> void Band::orthogonalize<double_complex>(K_point* kp__, int N__, int n__, Wave_functions<false>& phi__, Wave_functions<false>& hphi__, Wave_functions<false>& ophi__, matrix<double_complex>& o__) { return; } template <> void Band::orthogonalize<double>(K_point* kp__, int N__, int n__, Wave_functions<false>& phi__, Wave_functions<false>& hphi__, Wave_functions<false>& ophi__, matrix<double>& o__) { PROFILE_WITH_TIMER("sirius::Band::orthogonalize"); if (N__ > 0) { /* project out the old subspace */ phi__.inner<double>(0, N__, ophi__, N__, n__, o__, 0, 0); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&phi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&phi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&hphi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&hphi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::gemm(0, 0, 2 * kp__->num_gkvec_loc(), n__, N__, -1.0, (double*)&ophi__(0, 0), 2 * kp__->num_gkvec_loc(), &o__(0, 0), o__.ld(), 1.0, (double*)&ophi__(0, N__), 2 * kp__->num_gkvec_loc()); } /* orthogonalize new n__ x n__ block */ phi__.inner<double>(N__, n__, ophi__, N__, n__, o__, 0, 0); int info; if ((info = linalg<CPU>::potrf(n__, &o__(0, 0), o__.ld()))) { std::stringstream s; s << "error in factorization, info = " << info; TERMINATE(s); } if (linalg<CPU>::trtri(n__, &o__(0, 0), o__.ld())) TERMINATE("error in inversion"); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&phi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&hphi__(0, N__), 2 * kp__->num_gkvec_loc()); linalg<CPU>::trmm('R', 'U', 'N', 2 * kp__->num_gkvec_loc(), n__, 1.0, &o__(0, 0), o__.ld(), (double*)&ophi__(0, N__), 2 * kp__->num_gkvec_loc()); //== phi__.inner<double>(0, N__ + n__, ophi__, 0, N__ + n__, o__, 0, 0); //== for (int i = 0; i < N__ + n__; i++) //== { //== for (int j = 0; j < N__ + n__; j++) //== { //== double a = o__(j, i); //== if (i == j) a -= 1; //== if (std::abs(a) > 1e-10) //== { //== printf("wrong overlap"); //== TERMINATE("wrong overlap"); //== } //== } //== } } } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// // \file BooleanCellFunctor.hpp // \author Alex Robinson // \brief Functor that takes a boolean array and returns true/false //---------------------------------------------------------------------------// #ifndef BOOLEAN_CELL_FUNCTOR_HPP #define BOOLEAN_CELL_FUNCTOR_HPP // Std Lib Includes #include <string> #include <list> // Trilinos Includes #include <Teuchos_Array.hpp> #include <Teuchos_RCP.hpp> // FACEMC Includes #include "Tuple.hpp" #include "SetOperationFunctor.hpp" namespace FACEMC{ class BooleanCellFunctor { public: //! Constructor BooleanCellFunctor( std::string &cell_definition ); //! Destructor ~BooleanCellFunctor() { /* ... */ } //! Function evaluation operator bool operator()( const std::list<bool> &argument_list ); protected: //! Default Constructor BooleanCellFunctor() { /* ... */ } //! Remove white space from the cell definition string void removeWhiteSpace( std::string &cell_definition ) const; //! Rename the cell definition variables void renameVariables( std::string &cell_definition ) const; //! Determine the number of variables present in the cell definition unsigned getNumberOfVariables( const std::string &cell_definition ); //! Determine the variable range in the string // \brief The string is not passed by reference so that a copy will be made // which will be manipulated. Pair<unsigned,unsigned> getVariableRange( std::string sub_string ) const; //! Construct the child functors void constructChildFunctors( const std::string &cell_definition ); //! Reduce the cell definition so that it contains no parentheses void reduceDefinition( std::string &cell_definition ) const; //! Assign the set operation functors based on the cell definition void assignSetOperationFunctors( const std::string &cell_definition ); //! Get the number of child functors unsigned getNumChildFunctors() const; //! Get the number of SetOperationFunctors unsigned getNumSetOperationFunctors() const; //! Get the variable ranges for the child functors Teuchos::Array<Pair<unsigned,unsigned> > getChildFunctorVariableRanges() const; private: // Child BooleanCellFunctors for evaluation of terms in parentheses Teuchos::Array<BooleanCellFunctor> d_child_functors; // Indices of boolean variables found in parentheses Teuchos::Array<Pair<unsigned,unsigned> > d_child_functor_variables; // SetOperationFunctors for evaluating the cell function Teuchos::Array<Teuchos::RCP<SetOperationFunctor> > d_function_definition; // Number of boolean variables to expect in boolean array unsigned d_number_of_variables; }; } // end FACEMC namespace #endif // end BOOLEAN_CELL_FUNCTOR_HPP //---------------------------------------------------------------------------// // end BooleanCellFunctor.hpp //---------------------------------------------------------------------------// <commit_msg>src/BooleanCellFunctor.cpp<commit_after>//---------------------------------------------------------------------------// // \file BooleanCellFunctor.hpp // \author Alex Robinson // \brief Functor that takes a boolean array and returns true/false //---------------------------------------------------------------------------// #ifndef BOOLEAN_CELL_FUNCTOR_HPP #define BOOLEAN_CELL_FUNCTOR_HPP // Std Lib Includes #include <string> #include <list> // Trilinos Includes #include <Teuchos_Array.hpp> #include <Teuchos_RCP.hpp> // FACEMC Includes #include "Tuple.hpp" #include "SetOperationFunctor.hpp" namespace FACEMC{ class BooleanCellFunctor { public: //! Constructor BooleanCellFunctor( std::string &cell_definition ); //! Destructor ~BooleanCellFunctor() { /* ... */ } //! Function evaluation operator bool operator()( const std::list<bool> &argument_list ); protected: //! Default Constructor BooleanCellFunctor() { /* ... */ } //! Remove white space from the cell definition string void removeWhiteSpace( std::string &cell_definition ) const; //! Rename the cell definition variables void renameVariables( std::string &cell_definition ) const; //! Determine the number of variables present in the cell definition unsigned getNumVariables( const std::string &cell_definition ); //! Determine the variable range in the string // \brief The string is not passed by reference so that a copy will be made // which will be manipulated. Pair<unsigned,unsigned> getVariableRange( std::string sub_string ) const; //! Construct the child functors void constructChildFunctors( const std::string &cell_definition ); //! Reduce the cell definition so that it contains no parentheses void reduceDefinition( std::string &cell_definition ) const; //! Assign the set operation functors based on the cell definition void assignSetOperationFunctors( const std::string &cell_definition ); //! Get the number of child functors unsigned getNumChildFunctors() const; //! Get the number of SetOperationFunctors unsigned getNumSetOperationFunctors() const; //! Get the variable ranges for the child functors Teuchos::Array<Pair<unsigned,unsigned> > getChildFunctorVariableRanges() const; private: // Child BooleanCellFunctors for evaluation of terms in parentheses Teuchos::Array<BooleanCellFunctor> d_child_functors; // Indices of boolean variables found in parentheses Teuchos::Array<Pair<unsigned,unsigned> > d_child_functor_variables; // SetOperationFunctors for evaluating the cell function Teuchos::Array<Teuchos::RCP<SetOperationFunctor> > d_function_definition; // Number of boolean variables to expect in boolean array unsigned d_number_of_variables; }; } // end FACEMC namespace #endif // end BOOLEAN_CELL_FUNCTOR_HPP //---------------------------------------------------------------------------// // end BooleanCellFunctor.hpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include <assert.h> #include <stdlib.h> #include <functional> #include <iostream> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include <isl/cpp.h> /* A binary isl function that appears in the C++ bindings * as a unary method in a class T, taking an extra argument * of type A1 and returning an object of type R. */ template <typename A1, typename R, typename T> using binary_fn = R (T::*)(A1) const; /* A function for selecting an overload of a pointer to a unary C++ method * based on the single argument type. * The object type and the return type are meant to be deduced. */ template <typename A1, typename R, typename T> static binary_fn<A1, R, T> const arg(const binary_fn<A1, R, T> &fn) { return fn; } /* A description of the inputs and the output of a binary operation. */ struct binary { const char *arg1; const char *arg2; const char *res; }; /* A template function for checking whether two objects * of the same (isl) type are (obviously) equal. * The spelling depends on the isl type and * in particular on whether an equality method is available or * whether only obvious equality can be tested. */ template <typename T, typename std::decay<decltype( std::declval<T>().is_equal(std::declval<T>()))>::type = true> static bool is_equal(const T &a, const T &b) { return a.is_equal(b); } template <typename T, typename std::decay<decltype( std::declval<T>().plain_is_equal(std::declval<T>()))>::type = true> static bool is_equal(const T &a, const T &b) { return a.plain_is_equal(b); } /* A helper macro for throwing an isl::exception_invalid with message "msg". */ #define THROW_INVALID(msg) \ isl::exception::throw_error(isl_error_invalid, msg, __FILE__, __LINE__) /* Run a sequence of tests of method "fn" with stringification "name" and * with inputs and output described by "test", * throwing an exception when an unexpected result is produced. */ template <typename R, typename T, typename A1> static void test(isl::ctx ctx, R (T::*fn)(A1) const, const std::string &name, const std::vector<binary> &tests) { for (const auto &test : tests) { T obj(ctx, test.arg1); A1 arg1(ctx, test.arg2); R expected(ctx, test.res); const auto &res = (obj.*fn)(arg1); std::ostringstream ss; if (is_equal(expected, res)) continue; ss << name << "(" << test.arg1 << ", " << test.arg2 << ") =\n" << res << "\n" << "expecting:\n" << test.res; THROW_INVALID(ss.str().c_str()); } } /* A helper macro that calls test with as implicit initial argument "ctx" and * as extra argument a stringification of "FN". */ #define C(FN, ...) test(ctx, FN, #FN, __VA_ARGS__) /* Perform some basic preimage tests. */ static void test_preimage(isl::ctx ctx) { C(arg<isl::multi_aff>(&isl::set::preimage), { { "{ B[i,j] : 0 <= i < 10 and 0 <= j < 100 }", "{ A[j,i] -> B[i,j] }", "{ A[j,i] : 0 <= i < 10 and 0 <= j < 100 }" }, { "{ rat: B[i,j] : 0 <= i, j and 3 i + 5 j <= 100 }", "{ A[a,b] -> B[a/2,b/6] }", "{ rat: A[a,b] : 0 <= a, b and 9 a + 5 b <= 600 }" }, { "{ B[i,j] : 0 <= i, j and 3 i + 5 j <= 100 }", "{ A[a,b] -> B[a/2,b/6] }", "{ A[a,b] : 0 <= a, b and 9 a + 5 b <= 600 and " "exists i,j : a = 2 i and b = 6 j }" }, { "[n] -> { S[i] : 0 <= i <= 100 }", "[n] -> { S[n] }", "[n] -> { : 0 <= n <= 100 }" }, { "{ B[i] : 0 <= i < 100 and exists a : i = 4 a }", "{ A[a] -> B[2a] }", "{ A[a] : 0 <= a < 50 and exists b : a = 2 b }" }, { "{ B[i] : 0 <= i < 100 and exists a : i = 4 a }", "{ A[a] -> B[([a/2])] }", "{ A[a] : 0 <= a < 200 and exists b : [a/2] = 4 b }" }, { "{ B[i,j,k] : 0 <= i,j,k <= 100 }", "{ A[a] -> B[a,a,a/3] }", "{ A[a] : 0 <= a <= 100 and exists b : a = 3 b }" }, { "{ B[i,j] : j = [(i)/2] } ", "{ A[i,j] -> B[i/3,j] }", "{ A[i,j] : j = [(i)/6] and exists a : i = 3 a }" }, }); C(arg<isl::multi_aff>(&isl::union_map::preimage_domain), { { "{ B[i,j] -> C[2i + 3j] : 0 <= i < 10 and 0 <= j < 100 }", "{ A[j,i] -> B[i,j] }", "{ A[j,i] -> C[2i + 3j] : 0 <= i < 10 and 0 <= j < 100 }" }, { "{ B[i] -> C[i]; D[i] -> E[i] }", "{ A[i] -> B[i + 1] }", "{ A[i] -> C[i + 1] }" }, { "{ B[i] -> C[i]; B[i] -> E[i] }", "{ A[i] -> B[i + 1] }", "{ A[i] -> C[i + 1]; A[i] -> E[i + 1] }" }, { "{ B[i] -> C[([i/2])] }", "{ A[i] -> B[2i] }", "{ A[i] -> C[i] }" }, { "{ B[i,j] -> C[([i/2]), ([(i+j)/3])] }", "{ A[i] -> B[([i/5]), ([i/7])] }", "{ A[i] -> C[([([i/5])/2]), ([(([i/5])+([i/7]))/3])] }" }, { "[N] -> { B[i] -> C[([N/2]), i, ([N/3])] }", "[N] -> { A[] -> B[([N/5])] }", "[N] -> { A[] -> C[([N/2]), ([N/5]), ([N/3])] }" }, { "{ B[i] -> C[i] : exists a : i = 5 a }", "{ A[i] -> B[2i] }", "{ A[i] -> C[2i] : exists a : 2i = 5 a }" }, { "{ B[i] -> C[i] : exists a : i = 2 a; " "B[i] -> D[i] : exists a : i = 2 a + 1 }", "{ A[i] -> B[2i] }", "{ A[i] -> C[2i] }" }, { "{ A[i] -> B[i] }", "{ C[i] -> A[(i + floor(i/3))/2] }", "{ C[i] -> B[j] : 2j = i + floor(i/3) }" }, }); C(arg<isl::multi_aff>(&isl::union_map::preimage_range), { { "[M] -> { A[a] -> B[a] }", "[M] -> { C[] -> B[floor(M/2)] }", "[M] -> { A[floor(M/2)] -> C[] }" }, }); } /* Perform some basic intersection tests. */ static void test_intersect(isl::ctx ctx) { C(&isl::union_map::intersect_domain_wrapped_domain, { { "{ [A[x] -> B[y]] -> C[z]; [D[x] -> A[y]] -> E[z] }", "{ A[0] }", "{ [A[0] -> B[y]] -> C[z] }" }, { "{ C[z] -> [A[x] -> B[y]]; E[z] -> [D[x] -> A[y]] }", "{ A[0] }", "{ }" }, }); C(&isl::union_map::intersect_range_wrapped_domain, { { "{ [A[x] -> B[y]] -> C[z]; [D[x] -> A[y]] -> E[z] }", "{ A[0] }", "{ }" }, { "{ C[z] -> [A[x] -> B[y]]; E[z] -> [D[x] -> A[y]] }", "{ A[0] }", "{ C[z] -> [A[0] -> B[y]] }" }, }); } /* Perform some basic gist tests. */ static void test_gist(isl::ctx ctx) { C(&isl::pw_aff::gist_params, { { "[N] -> { D[x] -> [x] : N >= 0; D[x] -> [0] : N < 0 }", "[N] -> { : N >= 0 }", "[N] -> { D[x] -> [x] }" }, }); } /* Perform some basic scaling tests. */ static void test_scale(isl::ctx ctx) { C(arg<isl::multi_val>(&isl::pw_multi_aff::scale), { { "{ A[a] -> B[a, a + 1, a - 1] : a >= 0 }", "{ B[2, 7, 0] }", "{ A[a] -> B[2a, 7a + 7, 0] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale), { { "{ A[a] -> B[a, a - 1] : a >= 0 }", "{ B[1/2, 7] }", "{ A[a] -> B[a/2, 7a - 7] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale_down), { { "{ A[a] -> B[a, a + 1] : a >= 0 }", "{ B[2, 7] }", "{ A[a] -> B[a/2, (a + 1)/7] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale_down), { { "{ A[a] -> B[a, a - 1] : a >= 0 }", "{ B[2, 1/7] }", "{ A[a] -> B[a/2, 7a - 7] : a >= 0 }" }, }); } /* The list of tests to perform. */ static std::vector<std::pair<const char *, void (*)(isl::ctx)>> tests = { { "preimage", &test_preimage }, { "intersect", &test_intersect }, { "gist", &test_gist }, { "scale", &test_scale }, }; /* Perform some basic checks by means of the C++ bindings. */ int main(int argc, char **argv) { int ret = EXIT_SUCCESS; struct isl_ctx *ctx; struct isl_options *options; options = isl_options_new_with_defaults(); assert(options); argc = isl_options_parse(options, argc, argv, ISL_ARG_ALL); ctx = isl_ctx_alloc_with_options(&isl_options_args, options); try { for (const auto &f : tests) { std::cout << f.first << "\n"; f.second(ctx); } } catch (const isl::exception &e) { std::cerr << e.what() << "\n"; ret = EXIT_FAILURE; } isl_ctx_free(ctx); return ret; } <commit_msg>add some basic isl_space tests<commit_after>#include <assert.h> #include <stdlib.h> #include <functional> #include <iostream> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include <isl/cpp.h> /* A binary isl function that appears in the C++ bindings * as a unary method in a class T, taking an extra argument * of type A1 and returning an object of type R. */ template <typename A1, typename R, typename T> using binary_fn = R (T::*)(A1) const; /* A function for selecting an overload of a pointer to a unary C++ method * based on the single argument type. * The object type and the return type are meant to be deduced. */ template <typename A1, typename R, typename T> static binary_fn<A1, R, T> const arg(const binary_fn<A1, R, T> &fn) { return fn; } /* A description of the input and the output of a unary operation. */ struct unary { const char *arg; const char *res; }; /* A description of the inputs and the output of a binary operation. */ struct binary { const char *arg1; const char *arg2; const char *res; }; /* A template function for checking whether two objects * of the same (isl) type are (obviously) equal. * The spelling depends on the isl type and * in particular on whether an equality method is available or * whether only obvious equality can be tested. */ template <typename T, typename std::decay<decltype( std::declval<T>().is_equal(std::declval<T>()))>::type = true> static bool is_equal(const T &a, const T &b) { return a.is_equal(b); } template <typename T, typename std::decay<decltype( std::declval<T>().plain_is_equal(std::declval<T>()))>::type = true> static bool is_equal(const T &a, const T &b) { return a.plain_is_equal(b); } /* A helper macro for throwing an isl::exception_invalid with message "msg". */ #define THROW_INVALID(msg) \ isl::exception::throw_error(isl_error_invalid, msg, __FILE__, __LINE__) /* Run a sequence of tests of method "fn" with stringification "name" and * with input and output described by "test", * throwing an exception when an unexpected result is produced. */ template <typename R, typename T> static void test(isl::ctx ctx, R (T::*fn)() const, const std::string &name, const std::vector<unary> &tests) { for (const auto &test : tests) { T obj(ctx, test.arg); R expected(ctx, test.res); const auto &res = (obj.*fn)(); std::ostringstream ss; if (is_equal(expected, res)) continue; ss << name << "(" << test.arg << ") =\n" << res << "\n" << "expecting:\n" << expected; THROW_INVALID(ss.str().c_str()); } } /* Run a sequence of tests of method "fn" with stringification "name" and * with inputs and output described by "test", * throwing an exception when an unexpected result is produced. */ template <typename R, typename T, typename A1> static void test(isl::ctx ctx, R (T::*fn)(A1) const, const std::string &name, const std::vector<binary> &tests) { for (const auto &test : tests) { T obj(ctx, test.arg1); A1 arg1(ctx, test.arg2); R expected(ctx, test.res); const auto &res = (obj.*fn)(arg1); std::ostringstream ss; if (is_equal(expected, res)) continue; ss << name << "(" << test.arg1 << ", " << test.arg2 << ") =\n" << res << "\n" << "expecting:\n" << test.res; THROW_INVALID(ss.str().c_str()); } } /* A helper macro that calls test with as implicit initial argument "ctx" and * as extra argument a stringification of "FN". */ #define C(FN, ...) test(ctx, FN, #FN, __VA_ARGS__) /* Perform some basic isl::space tests. */ static void test_space(isl::ctx ctx) { C(&isl::space::domain, { { "{ A[] -> B[] }", "{ A[] }" }, { "{ A[C[] -> D[]] -> B[E[] -> F[]] }", "{ A[C[] -> D[]] }" }, }); C(&isl::space::range, { { "{ A[] -> B[] }", "{ B[] }" }, { "{ A[C[] -> D[]] -> B[E[] -> F[]] }", "{ B[E[] -> F[]] }" }, }); C(&isl::space::params, { { "{ A[] -> B[] }", "{ : }" }, { "{ A[C[] -> D[]] -> B[E[] -> F[]] }", "{ : }" }, }); } /* Perform some basic preimage tests. */ static void test_preimage(isl::ctx ctx) { C(arg<isl::multi_aff>(&isl::set::preimage), { { "{ B[i,j] : 0 <= i < 10 and 0 <= j < 100 }", "{ A[j,i] -> B[i,j] }", "{ A[j,i] : 0 <= i < 10 and 0 <= j < 100 }" }, { "{ rat: B[i,j] : 0 <= i, j and 3 i + 5 j <= 100 }", "{ A[a,b] -> B[a/2,b/6] }", "{ rat: A[a,b] : 0 <= a, b and 9 a + 5 b <= 600 }" }, { "{ B[i,j] : 0 <= i, j and 3 i + 5 j <= 100 }", "{ A[a,b] -> B[a/2,b/6] }", "{ A[a,b] : 0 <= a, b and 9 a + 5 b <= 600 and " "exists i,j : a = 2 i and b = 6 j }" }, { "[n] -> { S[i] : 0 <= i <= 100 }", "[n] -> { S[n] }", "[n] -> { : 0 <= n <= 100 }" }, { "{ B[i] : 0 <= i < 100 and exists a : i = 4 a }", "{ A[a] -> B[2a] }", "{ A[a] : 0 <= a < 50 and exists b : a = 2 b }" }, { "{ B[i] : 0 <= i < 100 and exists a : i = 4 a }", "{ A[a] -> B[([a/2])] }", "{ A[a] : 0 <= a < 200 and exists b : [a/2] = 4 b }" }, { "{ B[i,j,k] : 0 <= i,j,k <= 100 }", "{ A[a] -> B[a,a,a/3] }", "{ A[a] : 0 <= a <= 100 and exists b : a = 3 b }" }, { "{ B[i,j] : j = [(i)/2] } ", "{ A[i,j] -> B[i/3,j] }", "{ A[i,j] : j = [(i)/6] and exists a : i = 3 a }" }, }); C(arg<isl::multi_aff>(&isl::union_map::preimage_domain), { { "{ B[i,j] -> C[2i + 3j] : 0 <= i < 10 and 0 <= j < 100 }", "{ A[j,i] -> B[i,j] }", "{ A[j,i] -> C[2i + 3j] : 0 <= i < 10 and 0 <= j < 100 }" }, { "{ B[i] -> C[i]; D[i] -> E[i] }", "{ A[i] -> B[i + 1] }", "{ A[i] -> C[i + 1] }" }, { "{ B[i] -> C[i]; B[i] -> E[i] }", "{ A[i] -> B[i + 1] }", "{ A[i] -> C[i + 1]; A[i] -> E[i + 1] }" }, { "{ B[i] -> C[([i/2])] }", "{ A[i] -> B[2i] }", "{ A[i] -> C[i] }" }, { "{ B[i,j] -> C[([i/2]), ([(i+j)/3])] }", "{ A[i] -> B[([i/5]), ([i/7])] }", "{ A[i] -> C[([([i/5])/2]), ([(([i/5])+([i/7]))/3])] }" }, { "[N] -> { B[i] -> C[([N/2]), i, ([N/3])] }", "[N] -> { A[] -> B[([N/5])] }", "[N] -> { A[] -> C[([N/2]), ([N/5]), ([N/3])] }" }, { "{ B[i] -> C[i] : exists a : i = 5 a }", "{ A[i] -> B[2i] }", "{ A[i] -> C[2i] : exists a : 2i = 5 a }" }, { "{ B[i] -> C[i] : exists a : i = 2 a; " "B[i] -> D[i] : exists a : i = 2 a + 1 }", "{ A[i] -> B[2i] }", "{ A[i] -> C[2i] }" }, { "{ A[i] -> B[i] }", "{ C[i] -> A[(i + floor(i/3))/2] }", "{ C[i] -> B[j] : 2j = i + floor(i/3) }" }, }); C(arg<isl::multi_aff>(&isl::union_map::preimage_range), { { "[M] -> { A[a] -> B[a] }", "[M] -> { C[] -> B[floor(M/2)] }", "[M] -> { A[floor(M/2)] -> C[] }" }, }); } /* Perform some basic intersection tests. */ static void test_intersect(isl::ctx ctx) { C(&isl::union_map::intersect_domain_wrapped_domain, { { "{ [A[x] -> B[y]] -> C[z]; [D[x] -> A[y]] -> E[z] }", "{ A[0] }", "{ [A[0] -> B[y]] -> C[z] }" }, { "{ C[z] -> [A[x] -> B[y]]; E[z] -> [D[x] -> A[y]] }", "{ A[0] }", "{ }" }, }); C(&isl::union_map::intersect_range_wrapped_domain, { { "{ [A[x] -> B[y]] -> C[z]; [D[x] -> A[y]] -> E[z] }", "{ A[0] }", "{ }" }, { "{ C[z] -> [A[x] -> B[y]]; E[z] -> [D[x] -> A[y]] }", "{ A[0] }", "{ C[z] -> [A[0] -> B[y]] }" }, }); } /* Perform some basic gist tests. */ static void test_gist(isl::ctx ctx) { C(&isl::pw_aff::gist_params, { { "[N] -> { D[x] -> [x] : N >= 0; D[x] -> [0] : N < 0 }", "[N] -> { : N >= 0 }", "[N] -> { D[x] -> [x] }" }, }); } /* Perform some basic scaling tests. */ static void test_scale(isl::ctx ctx) { C(arg<isl::multi_val>(&isl::pw_multi_aff::scale), { { "{ A[a] -> B[a, a + 1, a - 1] : a >= 0 }", "{ B[2, 7, 0] }", "{ A[a] -> B[2a, 7a + 7, 0] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale), { { "{ A[a] -> B[a, a - 1] : a >= 0 }", "{ B[1/2, 7] }", "{ A[a] -> B[a/2, 7a - 7] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale_down), { { "{ A[a] -> B[a, a + 1] : a >= 0 }", "{ B[2, 7] }", "{ A[a] -> B[a/2, (a + 1)/7] : a >= 0 }" }, }); C(arg<isl::multi_val>(&isl::pw_multi_aff::scale_down), { { "{ A[a] -> B[a, a - 1] : a >= 0 }", "{ B[2, 1/7] }", "{ A[a] -> B[a/2, 7a - 7] : a >= 0 }" }, }); } /* The list of tests to perform. */ static std::vector<std::pair<const char *, void (*)(isl::ctx)>> tests = { { "space", &test_space }, { "preimage", &test_preimage }, { "intersect", &test_intersect }, { "gist", &test_gist }, { "scale", &test_scale }, }; /* Perform some basic checks by means of the C++ bindings. */ int main(int argc, char **argv) { int ret = EXIT_SUCCESS; struct isl_ctx *ctx; struct isl_options *options; options = isl_options_new_with_defaults(); assert(options); argc = isl_options_parse(options, argc, argv, ISL_ARG_ALL); ctx = isl_ctx_alloc_with_options(&isl_options_args, options); try { for (const auto &f : tests) { std::cout << f.first << "\n"; f.second(ctx); } } catch (const isl::exception &e) { std::cerr << e.what() << "\n"; ret = EXIT_FAILURE; } isl_ctx_free(ctx); return ret; } <|endoftext|>