text
stringlengths
54
60.6k
<commit_before>/* * Copyright 2016 Facebook, Inc. * * 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 <folly/io/async/ScopedEventBaseThread.h> #include <chrono> #include <folly/Baton.h> #include <folly/portability/GTest.h> using namespace std; using namespace std::chrono; using namespace folly; class ScopedEventBaseThreadTest : public testing::Test {}; TEST_F(ScopedEventBaseThreadTest, example) { ScopedEventBaseThread sebt; Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); done.timed_wait(steady_clock::now() + milliseconds(100)); } TEST_F(ScopedEventBaseThreadTest, start_stop) { ScopedEventBaseThread sebt(false); for (size_t i = 0; i < 4; ++i) { EXPECT_EQ(nullptr, sebt.getEventBase()); sebt.start(); EXPECT_NE(nullptr, sebt.getEventBase()); Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); done.timed_wait(steady_clock::now() + milliseconds(100)); EXPECT_NE(nullptr, sebt.getEventBase()); sebt.stop(); EXPECT_EQ(nullptr, sebt.getEventBase()); } } TEST_F(ScopedEventBaseThreadTest, move) { auto sebt0 = ScopedEventBaseThread(); auto sebt1 = std::move(sebt0); auto sebt2 = std::move(sebt1); EXPECT_EQ(nullptr, sebt0.getEventBase()); EXPECT_EQ(nullptr, sebt1.getEventBase()); EXPECT_NE(nullptr, sebt2.getEventBase()); Baton<> done; sebt2.getEventBase()->runInEventBaseThread([&] { done.post(); }); done.timed_wait(steady_clock::now() + milliseconds(100)); } TEST_F(ScopedEventBaseThreadTest, self_move) { ScopedEventBaseThread sebt0; auto sebt = std::move(sebt0); EXPECT_NE(nullptr, sebt.getEventBase()); Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); done.timed_wait(steady_clock::now() + milliseconds(100)); } TEST_F(ScopedEventBaseThreadTest, manager) { EventBaseManager ebm; ScopedEventBaseThread sebt(&ebm); auto sebt_eb = sebt.getEventBase(); auto ebm_eb = (EventBase*)nullptr; sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm.getEventBase(); }); EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb)); } <commit_msg>Check the baton waits in the ScopedEventBaseThread tests<commit_after>/* * Copyright 2016 Facebook, Inc. * * 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 <folly/io/async/ScopedEventBaseThread.h> #include <chrono> #include <folly/Baton.h> #include <folly/portability/GTest.h> using namespace std; using namespace std::chrono; using namespace folly; class ScopedEventBaseThreadTest : public testing::Test {}; TEST_F(ScopedEventBaseThreadTest, example) { ScopedEventBaseThread sebt; Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.timed_wait(seconds(1))); } TEST_F(ScopedEventBaseThreadTest, start_stop) { ScopedEventBaseThread sebt(false); for (size_t i = 0; i < 4; ++i) { EXPECT_EQ(nullptr, sebt.getEventBase()); sebt.start(); EXPECT_NE(nullptr, sebt.getEventBase()); Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.timed_wait(seconds(1))); EXPECT_NE(nullptr, sebt.getEventBase()); sebt.stop(); EXPECT_EQ(nullptr, sebt.getEventBase()); } } TEST_F(ScopedEventBaseThreadTest, move) { auto sebt0 = ScopedEventBaseThread(); auto sebt1 = std::move(sebt0); auto sebt2 = std::move(sebt1); EXPECT_EQ(nullptr, sebt0.getEventBase()); EXPECT_EQ(nullptr, sebt1.getEventBase()); EXPECT_NE(nullptr, sebt2.getEventBase()); Baton<> done; sebt2.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.timed_wait(seconds(1))); } TEST_F(ScopedEventBaseThreadTest, self_move) { ScopedEventBaseThread sebt0; auto sebt = std::move(sebt0); EXPECT_NE(nullptr, sebt.getEventBase()); Baton<> done; sebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.timed_wait(seconds(1))); } TEST_F(ScopedEventBaseThreadTest, manager) { EventBaseManager ebm; ScopedEventBaseThread sebt(&ebm); auto sebt_eb = sebt.getEventBase(); auto ebm_eb = (EventBase*)nullptr; sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm.getEventBase(); }); EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb)); } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <blas.hpp> #include <Array.hpp> #include <arith.hpp> #include <common/half.hpp> #include <common/traits.hpp> #include <complex.hpp> #include <err_opencl.hpp> #include <math.hpp> #include <reduce.hpp> #include <transpose.hpp> #include <complex> #include <vector> // Includes one of the supported OpenCL BLAS back-ends (e.g. clBLAS, CLBlast) #include <magma/magma_blas.h> #if defined(WITH_LINEAR_ALGEBRA) #include <cpu/cpu_blas.hpp> #endif using common::half; namespace opencl { void initBlas() { gpu_blas_init(); } void deInitBlas() { gpu_blas_deinit(); } // Converts an af_mat_prop options to a transpose type for one of the OpenCL // BLAS back-ends OPENCL_BLAS_TRANS_T toBlasTranspose(af_mat_prop opt) { switch (opt) { case AF_MAT_NONE: return OPENCL_BLAS_NO_TRANS; case AF_MAT_TRANS: return OPENCL_BLAS_TRANS; case AF_MAT_CTRANS: return OPENCL_BLAS_CONJ_TRANS; default: AF_ERROR("INVALID af_mat_prop", AF_ERR_ARG); } } template<typename T> void gemm_fallback(Array<T> &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const Array<T> &lhs, const Array<T> &rhs, const T *beta) { cpu::gemm(out, optLhs, optRhs, alpha, lhs, rhs, beta); } template<> void gemm_fallback<half>(Array<half> &out, af_mat_prop optLhs, af_mat_prop optRhs, const half *alpha, const Array<half> &lhs, const Array<half> &rhs, const half *beta) { assert(false && "CPU fallback not implemented for f16"); } template<typename T> void gemm(Array<T> &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const Array<T> &lhs, const Array<T> &rhs, const T *beta) { #if defined(WITH_LINEAR_ALGEBRA) // Do not force offload gemm on OSX Intel devices if (OpenCLCPUOffload(false) && (af_dtype)dtype_traits<T>::af_type != f16) { gemm_fallback(out, optLhs, optRhs, alpha, lhs, rhs, beta); return; } #endif const auto lOpts = toBlasTranspose(optLhs); const auto rOpts = toBlasTranspose(optRhs); const auto aRowDim = (lOpts == OPENCL_BLAS_NO_TRANS) ? 0 : 1; const auto aColDim = (lOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; const auto bColDim = (rOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; const dim4 lDims = lhs.dims(); const dim4 rDims = rhs.dims(); const int M = lDims[aRowDim]; const int N = rDims[bColDim]; const int K = lDims[aColDim]; const dim4 oDims = out.dims(); const dim4 lStrides = lhs.strides(); const dim4 rStrides = rhs.strides(); const dim4 oStrides = out.strides(); int batchSize = oDims[2] * oDims[3]; bool is_l_d2_batched = oDims[2] == lDims[2]; bool is_l_d3_batched = oDims[3] == lDims[3]; bool is_r_d2_batched = oDims[2] == rDims[2]; bool is_r_d3_batched = oDims[3] == rDims[3]; for (int n = 0; n < batchSize; n++) { int w = n / oDims[2]; int z = n - w * oDims[2]; int loff = z * (is_l_d2_batched * lStrides[2]) + w * (is_l_d3_batched * lStrides[3]); int roff = z * (is_r_d2_batched * rStrides[2]) + w * (is_r_d3_batched * rStrides[3]); dim_t lOffset = lhs.getOffset() + loff; dim_t rOffset = rhs.getOffset() + roff; dim_t oOffset = out.getOffset() + z * oStrides[2] + w * oStrides[3]; cl::Event event; if (rDims[bColDim] == 1) { dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1]; gpu_blas_gemv_func<T> gemv; OPENCL_BLAS_CHECK(gemv(lOpts, lDims[0], lDims[1], *alpha, (*lhs.get())(), lOffset, lStrides[1], (*rhs.get())(), rOffset, incr, *beta, (*out.get())(), oOffset, oStrides[0], 1, &getQueue()(), 0, nullptr, &event())); } else { gpu_blas_gemm_func<T> gemm; OPENCL_BLAS_CHECK(gemm(lOpts, rOpts, M, N, K, *alpha, (*lhs.get())(), lOffset, lStrides[1], (*rhs.get())(), rOffset, rStrides[1], *beta, (*out.get())(), oOffset, oStrides[1], 1, &getQueue()(), 0, nullptr, &event())); } } } template<typename T> Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs, af_mat_prop optRhs) { const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs)); const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs)); const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims()); return reduce<af_add_t, T, T>(temp, 0, false, 0); } #define INSTANTIATE_GEMM(TYPE) \ template void gemm<TYPE>(Array<TYPE> &out, af_mat_prop optLhs, af_mat_prop optRhs, \ const TYPE *alpha, \ const Array<TYPE> &lhs, const Array<TYPE> &rhs, \ const TYPE *beta); INSTANTIATE_GEMM(float) INSTANTIATE_GEMM(cfloat) INSTANTIATE_GEMM(double) INSTANTIATE_GEMM(cdouble) INSTANTIATE_GEMM(half) #define INSTANTIATE_DOT(TYPE) \ template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs, \ const Array<TYPE> &rhs, af_mat_prop optLhs, \ af_mat_prop optRhs); INSTANTIATE_DOT(float) INSTANTIATE_DOT(double) INSTANTIATE_DOT(cfloat) INSTANTIATE_DOT(cdouble) INSTANTIATE_DOT(half) } // namespace opencl <commit_msg>Remove guards around cpu blas functions with the OpenCL backend<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <blas.hpp> #include <Array.hpp> #include <arith.hpp> #include <common/half.hpp> #include <common/traits.hpp> #include <complex.hpp> #include <err_opencl.hpp> #include <math.hpp> #include <reduce.hpp> #include <transpose.hpp> #include <complex> #include <vector> // Includes one of the supported OpenCL BLAS back-ends (e.g. clBLAS, CLBlast) #include <magma/magma_blas.h> #include <cpu/cpu_blas.hpp> using common::half; namespace opencl { void initBlas() { gpu_blas_init(); } void deInitBlas() { gpu_blas_deinit(); } // Converts an af_mat_prop options to a transpose type for one of the OpenCL // BLAS back-ends OPENCL_BLAS_TRANS_T toBlasTranspose(af_mat_prop opt) { switch (opt) { case AF_MAT_NONE: return OPENCL_BLAS_NO_TRANS; case AF_MAT_TRANS: return OPENCL_BLAS_TRANS; case AF_MAT_CTRANS: return OPENCL_BLAS_CONJ_TRANS; default: AF_ERROR("INVALID af_mat_prop", AF_ERR_ARG); } } template<typename T> void gemm_fallback(Array<T> &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const Array<T> &lhs, const Array<T> &rhs, const T *beta) { cpu::gemm(out, optLhs, optRhs, alpha, lhs, rhs, beta); } template<> void gemm_fallback<half>(Array<half> &out, af_mat_prop optLhs, af_mat_prop optRhs, const half *alpha, const Array<half> &lhs, const Array<half> &rhs, const half *beta) { assert(false && "CPU fallback not implemented for f16"); } template<typename T> void gemm(Array<T> &out, af_mat_prop optLhs, af_mat_prop optRhs, const T *alpha, const Array<T> &lhs, const Array<T> &rhs, const T *beta) { #if defined(WITH_LINEAR_ALGEBRA) // Do not force offload gemm on OSX Intel devices if (OpenCLCPUOffload(false) && (af_dtype)dtype_traits<T>::af_type != f16) { gemm_fallback(out, optLhs, optRhs, alpha, lhs, rhs, beta); return; } #endif const auto lOpts = toBlasTranspose(optLhs); const auto rOpts = toBlasTranspose(optRhs); const auto aRowDim = (lOpts == OPENCL_BLAS_NO_TRANS) ? 0 : 1; const auto aColDim = (lOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; const auto bColDim = (rOpts == OPENCL_BLAS_NO_TRANS) ? 1 : 0; const dim4 lDims = lhs.dims(); const dim4 rDims = rhs.dims(); const int M = lDims[aRowDim]; const int N = rDims[bColDim]; const int K = lDims[aColDim]; const dim4 oDims = out.dims(); const dim4 lStrides = lhs.strides(); const dim4 rStrides = rhs.strides(); const dim4 oStrides = out.strides(); int batchSize = oDims[2] * oDims[3]; bool is_l_d2_batched = oDims[2] == lDims[2]; bool is_l_d3_batched = oDims[3] == lDims[3]; bool is_r_d2_batched = oDims[2] == rDims[2]; bool is_r_d3_batched = oDims[3] == rDims[3]; for (int n = 0; n < batchSize; n++) { int w = n / oDims[2]; int z = n - w * oDims[2]; int loff = z * (is_l_d2_batched * lStrides[2]) + w * (is_l_d3_batched * lStrides[3]); int roff = z * (is_r_d2_batched * rStrides[2]) + w * (is_r_d3_batched * rStrides[3]); dim_t lOffset = lhs.getOffset() + loff; dim_t rOffset = rhs.getOffset() + roff; dim_t oOffset = out.getOffset() + z * oStrides[2] + w * oStrides[3]; cl::Event event; if (rDims[bColDim] == 1) { dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1]; gpu_blas_gemv_func<T> gemv; OPENCL_BLAS_CHECK(gemv(lOpts, lDims[0], lDims[1], *alpha, (*lhs.get())(), lOffset, lStrides[1], (*rhs.get())(), rOffset, incr, *beta, (*out.get())(), oOffset, oStrides[0], 1, &getQueue()(), 0, nullptr, &event())); } else { gpu_blas_gemm_func<T> gemm; OPENCL_BLAS_CHECK(gemm(lOpts, rOpts, M, N, K, *alpha, (*lhs.get())(), lOffset, lStrides[1], (*rhs.get())(), rOffset, rStrides[1], *beta, (*out.get())(), oOffset, oStrides[1], 1, &getQueue()(), 0, nullptr, &event())); } } } template<typename T> Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs, af_mat_prop optRhs) { const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs)); const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs)); const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims()); return reduce<af_add_t, T, T>(temp, 0, false, 0); } #define INSTANTIATE_GEMM(TYPE) \ template void gemm<TYPE>(Array<TYPE> &out, af_mat_prop optLhs, af_mat_prop optRhs, \ const TYPE *alpha, \ const Array<TYPE> &lhs, const Array<TYPE> &rhs, \ const TYPE *beta); INSTANTIATE_GEMM(float) INSTANTIATE_GEMM(cfloat) INSTANTIATE_GEMM(double) INSTANTIATE_GEMM(cdouble) INSTANTIATE_GEMM(half) #define INSTANTIATE_DOT(TYPE) \ template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs, \ const Array<TYPE> &rhs, af_mat_prop optLhs, \ af_mat_prop optRhs); INSTANTIATE_DOT(float) INSTANTIATE_DOT(double) INSTANTIATE_DOT(cfloat) INSTANTIATE_DOT(cdouble) INSTANTIATE_DOT(half) } // namespace opencl <|endoftext|>
<commit_before>/** * Member selection * ================ * * Member variables declared like a bitset. F**k you SFINAE. * * Note: Compile with -std=c++17. */ #include <iostream> enum class cmd_t : uint32_t { A, B, }; // NOTE: 4 options => 2^4 (=16) specialized templates. enum class opt_t : uint32_t { None, A = 1, B = 1 << 1, }; constexpr uint32_t opt_v(opt_t opt) { return std::underlying_type_t<opt_t>(opt); } constexpr opt_t operator|(opt_t lhs, opt_t rhs) { return static_cast<opt_t>(opt_v(lhs) | opt_v(rhs)); } constexpr opt_t operator&(opt_t lhs, opt_t rhs) { return static_cast<opt_t>(opt_v(rhs) & opt_v(lhs)); } template <cmd_t Cmd> struct cmd_trait { static constexpr auto opts = opt_t::None; }; template <cmd_t Cmd> constexpr bool is_opt(opt_t opt) { return opt == cmd_trait<Cmd>::opts; } template <> struct cmd_trait<cmd_t::A> { static constexpr auto opts = opt_t::A; }; template <> struct cmd_trait<cmd_t::B> { static constexpr auto opts = opt_t::A | opt_t::B; }; template <cmd_t Cmd, typename = void> struct val_t { int A; int B; }; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::A)>> { int A; }; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::B)>> { int B; }; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::A | opt_t::B)>> { int A; int B; }; int main() { val_t<cmd_t::A> val; val.A = 42; // val.B = 69; // member not found std::cout << val.A << std::endl; return 0; } <commit_msg>Updated member_select: default templ<commit_after>/** * Member selection * ================ * * Member variables declared like a bitset. F**k you SFINAE. * * Note: Compile with -std=c++17. */ #include <iostream> enum class cmd_t : uint32_t { A, B, }; // NOTE: 4 options => 2^4 (=16) specialized templates. enum class opt_t : uint32_t { None, A = 1, B = 1 << 1, }; constexpr uint32_t opt_v(opt_t opt) { return std::underlying_type_t<opt_t>(opt); } constexpr opt_t operator|(opt_t lhs, opt_t rhs) { return static_cast<opt_t>(opt_v(lhs) | opt_v(rhs)); } constexpr opt_t operator&(opt_t lhs, opt_t rhs) { return static_cast<opt_t>(opt_v(rhs) & opt_v(lhs)); } template <cmd_t Cmd> struct cmd_trait { static constexpr auto opts = opt_t::None; }; template <cmd_t Cmd> constexpr bool is_opt(opt_t opt) { return opt == cmd_trait<Cmd>::opts; } template <> struct cmd_trait<cmd_t::A> { static constexpr auto opts = opt_t::A; }; template <> struct cmd_trait<cmd_t::B> { static constexpr auto opts = opt_t::A | opt_t::B; }; template <cmd_t Cmd, typename = void> struct val_t {}; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::A)>> { int A; }; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::B)>> { int B; }; template <cmd_t Cmd> struct val_t<Cmd, std::enable_if_t<is_opt<Cmd>(opt_t::A | opt_t::B)>> { int A; int B; }; int main() { val_t<cmd_t::A> val; val.A = 42; // val.B = 69; // member not found std::cout << val.A << std::endl; return 0; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2021 ScyllaDB */ #include <seastar/core/thread.hh> #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include <seastar/testing/test_runner.hh> #include <seastar/core/reactor.hh> #include <seastar/core/smp.hh> #include <seastar/core/when_all.hh> #include <seastar/core/file.hh> #include <seastar/core/io_queue.hh> #include <seastar/core/io_intent.hh> #include <seastar/core/internal/io_request.hh> #include <seastar/core/internal/io_sink.hh> using namespace seastar; template <size_t Len> struct fake_file { int data[Len] = {}; static internal::io_request make_write_req(size_t idx, int val) { int* buf = new int(val); return internal::io_request::make_write(0, idx, buf, 1, false); } void execute_write_req(internal::io_request& rq, io_completion* desc) { data[rq.pos()] = *(reinterpret_cast<int*>(rq.address())); desc->complete_with(rq.size()); } }; struct io_queue_for_tests { io_group_ptr group; internal::io_sink sink; io_queue queue; io_queue_for_tests() : group(std::make_shared<io_group>(io_group::config{})) , sink() , queue(group, sink, io_queue::config{0}) {} }; SEASTAR_THREAD_TEST_CASE(test_basic_flow) { io_queue_for_tests tio; fake_file<1> file; auto f = tio.queue.queue_request(default_priority_class(), 0, file.make_write_req(0, 42), nullptr) .then([&file] (size_t len) { BOOST_REQUIRE(file.data[0] == 42); }); tio.queue.poll_io_queue(); tio.sink.drain([&file] (internal::io_request& rq, io_completion* desc) -> bool { file.execute_write_req(rq, desc); return true; }); f.get(); } SEASTAR_THREAD_TEST_CASE(test_intent_safe_ref) { auto get_cancelled = [] (internal::intent_reference& iref) -> bool { try { iref.retrieve(); return false; } catch(seastar::cancelled_error& err) { return true; } }; io_intent intent, intent_x; internal::intent_reference ref_orig(&intent); BOOST_REQUIRE(ref_orig.retrieve() == &intent); // Test move armed internal::intent_reference ref_armed(std::move(ref_orig)); BOOST_REQUIRE(ref_orig.retrieve() == nullptr); BOOST_REQUIRE(ref_armed.retrieve() == &intent); internal::intent_reference ref_armed_2(&intent_x); ref_armed_2 = std::move(ref_armed); BOOST_REQUIRE(ref_armed.retrieve() == nullptr); BOOST_REQUIRE(ref_armed_2.retrieve() == &intent); intent.cancel(); BOOST_REQUIRE(get_cancelled(ref_armed_2)); // Test move cancelled internal::intent_reference ref_cancelled(std::move(ref_armed_2)); BOOST_REQUIRE(ref_armed_2.retrieve() == nullptr); BOOST_REQUIRE(get_cancelled(ref_cancelled)); internal::intent_reference ref_cancelled_2(&intent_x); ref_cancelled_2 = std::move(ref_cancelled); BOOST_REQUIRE(ref_cancelled.retrieve() == nullptr); BOOST_REQUIRE(get_cancelled(ref_cancelled_2)); // Test move empty internal::intent_reference ref_empty(std::move(ref_orig)); BOOST_REQUIRE(ref_empty.retrieve() == nullptr); internal::intent_reference ref_empty_2(&intent_x); ref_empty_2 = std::move(ref_empty); BOOST_REQUIRE(ref_empty_2.retrieve() == nullptr); } static constexpr int nr_requests = 24; SEASTAR_THREAD_TEST_CASE(test_io_cancellation) { fake_file<nr_requests> file; io_queue_for_tests tio; io_priority_class pc0 = tio.queue.register_one_priority_class("a", 100); io_priority_class pc1 = tio.queue.register_one_priority_class("b", 100); size_t idx = 0; int val = 100; io_intent live, dead; std::vector<future<>> finished; std::vector<future<>> cancelled; auto queue_legacy_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, val), nullptr) .then([&file, idx, val] (size_t len) { BOOST_REQUIRE(file.data[idx] == val); return make_ready_future<>(); }); finished.push_back(std::move(f)); idx++; val++; }; auto queue_live_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, val), &live) .then([&file, idx, val] (size_t len) { BOOST_REQUIRE(file.data[idx] == val); return make_ready_future<>(); }); finished.push_back(std::move(f)); idx++; val++; }; auto queue_dead_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, val), &dead) .then_wrapped([] (auto&& f) { try { f.get(); BOOST_REQUIRE(false); } catch(...) {} return make_ready_future<>(); }) .then([&file, idx] () { BOOST_REQUIRE(file.data[idx] == 0); }); cancelled.push_back(std::move(f)); idx++; val++; }; auto seed = std::random_device{}(); std::default_random_engine reng(seed); std::uniform_int_distribution<> dice(0, 5); for (int i = 0; i < nr_requests; i++) { int pc = dice(reng) % 2; if (dice(reng) < 3) { fmt::print("queue live req to pc {}\n", pc); queue_live_request(tio, pc == 0 ? pc0 : pc1); } else if (dice(reng) < 5) { fmt::print("queue dead req to pc {}\n", pc); queue_dead_request(tio, pc == 0 ? pc0 : pc1); } else { fmt::print("queue legacy req to pc {}\n", pc); queue_legacy_request(tio, pc == 0 ? pc0 : pc1); } } dead.cancel(); // cancelled requests must resolve right at once when_all_succeed(cancelled.begin(), cancelled.end()).get(); tio.queue.poll_io_queue(); tio.sink.drain([&file] (internal::io_request& rq, io_completion* desc) -> bool { file.execute_write_req(rq, desc); return true; }); when_all_succeed(finished.begin(), finished.end()).get(); } <commit_msg>test: Fix leak in io_queue_test<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2021 ScyllaDB */ #include <seastar/core/thread.hh> #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include <seastar/testing/test_runner.hh> #include <seastar/core/reactor.hh> #include <seastar/core/smp.hh> #include <seastar/core/when_all.hh> #include <seastar/core/file.hh> #include <seastar/core/io_queue.hh> #include <seastar/core/io_intent.hh> #include <seastar/core/internal/io_request.hh> #include <seastar/core/internal/io_sink.hh> using namespace seastar; template <size_t Len> struct fake_file { int data[Len] = {}; static internal::io_request make_write_req(size_t idx, int* buf) { return internal::io_request::make_write(0, idx, buf, 1, false); } void execute_write_req(internal::io_request& rq, io_completion* desc) { data[rq.pos()] = *(reinterpret_cast<int*>(rq.address())); desc->complete_with(rq.size()); } }; struct io_queue_for_tests { io_group_ptr group; internal::io_sink sink; io_queue queue; io_queue_for_tests() : group(std::make_shared<io_group>(io_group::config{})) , sink() , queue(group, sink, io_queue::config{0}) {} }; SEASTAR_THREAD_TEST_CASE(test_basic_flow) { io_queue_for_tests tio; fake_file<1> file; auto val = std::make_unique<int>(42); auto f = tio.queue.queue_request(default_priority_class(), 0, file.make_write_req(0, val.get()), nullptr) .then([&file] (size_t len) { BOOST_REQUIRE(file.data[0] == 42); }); tio.queue.poll_io_queue(); tio.sink.drain([&file] (internal::io_request& rq, io_completion* desc) -> bool { file.execute_write_req(rq, desc); return true; }); f.get(); } SEASTAR_THREAD_TEST_CASE(test_intent_safe_ref) { auto get_cancelled = [] (internal::intent_reference& iref) -> bool { try { iref.retrieve(); return false; } catch(seastar::cancelled_error& err) { return true; } }; io_intent intent, intent_x; internal::intent_reference ref_orig(&intent); BOOST_REQUIRE(ref_orig.retrieve() == &intent); // Test move armed internal::intent_reference ref_armed(std::move(ref_orig)); BOOST_REQUIRE(ref_orig.retrieve() == nullptr); BOOST_REQUIRE(ref_armed.retrieve() == &intent); internal::intent_reference ref_armed_2(&intent_x); ref_armed_2 = std::move(ref_armed); BOOST_REQUIRE(ref_armed.retrieve() == nullptr); BOOST_REQUIRE(ref_armed_2.retrieve() == &intent); intent.cancel(); BOOST_REQUIRE(get_cancelled(ref_armed_2)); // Test move cancelled internal::intent_reference ref_cancelled(std::move(ref_armed_2)); BOOST_REQUIRE(ref_armed_2.retrieve() == nullptr); BOOST_REQUIRE(get_cancelled(ref_cancelled)); internal::intent_reference ref_cancelled_2(&intent_x); ref_cancelled_2 = std::move(ref_cancelled); BOOST_REQUIRE(ref_cancelled.retrieve() == nullptr); BOOST_REQUIRE(get_cancelled(ref_cancelled_2)); // Test move empty internal::intent_reference ref_empty(std::move(ref_orig)); BOOST_REQUIRE(ref_empty.retrieve() == nullptr); internal::intent_reference ref_empty_2(&intent_x); ref_empty_2 = std::move(ref_empty); BOOST_REQUIRE(ref_empty_2.retrieve() == nullptr); } static constexpr int nr_requests = 24; SEASTAR_THREAD_TEST_CASE(test_io_cancellation) { fake_file<nr_requests> file; io_queue_for_tests tio; io_priority_class pc0 = tio.queue.register_one_priority_class("a", 100); io_priority_class pc1 = tio.queue.register_one_priority_class("b", 100); size_t idx = 0; int val = 100; io_intent live, dead; std::vector<future<>> finished; std::vector<future<>> cancelled; auto queue_legacy_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto buf = std::make_unique<int>(val); auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, buf.get()), nullptr) .then([&file, idx, val, buf = std::move(buf)] (size_t len) { BOOST_REQUIRE(file.data[idx] == val); return make_ready_future<>(); }); finished.push_back(std::move(f)); idx++; val++; }; auto queue_live_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto buf = std::make_unique<int>(val); auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, buf.get()), &live) .then([&file, idx, val, buf = std::move(buf)] (size_t len) { BOOST_REQUIRE(file.data[idx] == val); return make_ready_future<>(); }); finished.push_back(std::move(f)); idx++; val++; }; auto queue_dead_request = [&] (io_queue_for_tests& q, io_priority_class& pc) { auto buf = std::make_unique<int>(val); auto f = q.queue.queue_request(pc, 0, file.make_write_req(idx, buf.get()), &dead) .then_wrapped([buf = std::move(buf)] (auto&& f) { try { f.get(); BOOST_REQUIRE(false); } catch(...) {} return make_ready_future<>(); }) .then([&file, idx] () { BOOST_REQUIRE(file.data[idx] == 0); }); cancelled.push_back(std::move(f)); idx++; val++; }; auto seed = std::random_device{}(); std::default_random_engine reng(seed); std::uniform_int_distribution<> dice(0, 5); for (int i = 0; i < nr_requests; i++) { int pc = dice(reng) % 2; if (dice(reng) < 3) { fmt::print("queue live req to pc {}\n", pc); queue_live_request(tio, pc == 0 ? pc0 : pc1); } else if (dice(reng) < 5) { fmt::print("queue dead req to pc {}\n", pc); queue_dead_request(tio, pc == 0 ? pc0 : pc1); } else { fmt::print("queue legacy req to pc {}\n", pc); queue_legacy_request(tio, pc == 0 ? pc0 : pc1); } } dead.cancel(); // cancelled requests must resolve right at once when_all_succeed(cancelled.begin(), cancelled.end()).get(); tio.queue.poll_io_queue(); tio.sink.drain([&file] (internal::io_request& rq, io_completion* desc) -> bool { file.execute_write_req(rq, desc); return true; }); when_all_succeed(finished.begin(), finished.end()).get(); } <|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <fj_tool/fapp.h> #include <fjcoll.h> using namespace std; #include "pearson-3d.h" int T_MAX; int T_MONITOR; int mpi_my_rank; const double PI=3.14159265358979323846; float frand() { return rand() / float(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } /* void init() { for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { double x = double(navi.offset_x + ix)/NX; double y = double(navi.offset_y + iy)/NY; double z = double(navi.offset_z + iz)/NZ; U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; if (z > 0.49 && z < 0.51 && x > 0.4 && x < 0.6) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } }*/ typedef pair<int,pair<int,int> > Key; void init() { map<Key ,double> seeds; for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { Key k (ix/16, pair<int,int>(iy/16, iz/16)); U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; double s = seeds[k]; if (s==0) { s = frand(); seeds[k]=s; } if (s < 0.1 ) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } } void write_monitor() { printf("#%d: t = %d\n", mpi_my_rank, navi.time_step); char fn[256]; sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); int global_position[6]; global_position[0] = navi.offset_x + navi.lower_x; global_position[1] = navi.offset_y + navi.lower_y; global_position[2] = navi.offset_z + navi.lower_z; global_position[3] = navi.upper_x - navi.lower_x; global_position[4] = navi.upper_y - navi.lower_y; global_position[5] = navi.upper_z - navi.lower_z; fwrite(global_position, sizeof(int), 6, fp); int x_size = navi.upper_x - navi.lower_x; int y_size = navi.upper_y - navi.lower_y; int z_size = navi.upper_z - navi.lower_z; { const int y=navi.lower_y + y_size/2; for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } { const int x=navi.lower_x + x_size/2; for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } int main (int argc, char **argv) { MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank); srand(time(NULL)+mpi_my_rank*65537); if (argc <= 1) { T_MAX=8192; }else{ sscanf(argv[1], "%d", &T_MAX); } if (argc <= 2) { T_MONITOR=8192; }else{ sscanf(argv[2], "%d", &T_MONITOR); } init(); double t_begin = wctime(), t_end; int last_monitor_t = -T_MONITOR; for(;;){ double t = wctime(); bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR; if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) { printf("%d step @ %lf sec\n", navi.time_step, t-t_begin); } if(monitor_flag) { write_monitor(); } if(monitor_flag) { last_monitor_t += T_MONITOR; } if (navi.time_step >= T_MAX) break; if (navi.time_step == 0) { t_begin = wctime(); start_collection("main"); } Formura_Forward(&navi); // navi.time_step increases MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization if (navi.time_step >= T_MAX) { t_end = wctime(); stop_collection("main"); } } printf("wct = %lf sec\n",t_end - t_begin); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } <commit_msg>Limit the number of output files<commit_after>#include <algorithm> #include <map> #include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <fj_tool/fapp.h> #include <fjcoll.h> using namespace std; #include "pearson-3d.h" bool EXTEND_MISSION=false; int T_MAX; int T_MONITOR; int mpi_my_rank; const double PI=3.14159265358979323846; float frand() { return rand() / float(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } /* void init() { for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { double x = double(navi.offset_x + ix)/NX; double y = double(navi.offset_y + iy)/NY; double z = double(navi.offset_z + iz)/NZ; U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; if (z > 0.49 && z < 0.51 && x > 0.4 && x < 0.6) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } }*/ typedef pair<int,pair<int,int> > Key; void init() { map<Key ,double> seeds; for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { Key k (ix/16, pair<int,int>(iy/16, iz/16)); U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; double s = seeds[k]; if (s==0) { s = frand(); seeds[k]=s; } if (s < 0.1 ) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } } void write_monitor() { printf("#%d: t = %d\n", mpi_my_rank, navi.time_step); int global_position[6]; global_position[0] = navi.offset_x + navi.lower_x; global_position[1] = navi.offset_y + navi.lower_y; global_position[2] = navi.offset_z + navi.lower_z; global_position[3] = navi.upper_x - navi.lower_x; global_position[4] = navi.upper_y - navi.lower_y; global_position[5] = navi.upper_z - navi.lower_z; int x_size = navi.upper_x - navi.lower_x; int y_size = navi.upper_y - navi.lower_y; int z_size = navi.upper_z - navi.lower_z; if (navi.offset_x + navi.lower_x < navi.upper_x) { char fn[256]; sprintf(fn, "out/monitorX-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); fwrite(global_position, sizeof(int), 6, fp); { const int x=navi.lower_x + x_size/2; for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } if (navi.offset_y + navi.lower_y < navi.upper_y) { char fn[256]; sprintf(fn, "out/monitorY-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); fwrite(global_position, sizeof(int), 6, fp); { const int y=navi.lower_y + y_size/2; for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } } int main (int argc, char **argv) { MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank); srand(time(NULL)+mpi_my_rank*65537); if (argc <= 1) { T_MAX=8192; }else{ sscanf(argv[1], "%d", &T_MAX); } if (argc <= 2) { T_MONITOR=8192; }else{ sscanf(argv[2], "%d", &T_MONITOR); } if (argc >= 4) { EXTEND_MISSION = true; } init(); double t_begin = wctime(), t_end; int last_monitor_t = -T_MONITOR; for(;;){ double t = wctime(); bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR; if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) { printf("%d step @ %lf sec\n", navi.time_step, t-t_begin); } if(monitor_flag) { write_monitor(); } if(monitor_flag) { last_monitor_t += T_MONITOR; } if (navi.time_step >= T_MAX) { if (EXTEND_MISSION){ T_MAX*=2; T_MONITOR*=2; }else{ break; } } if (navi.time_step == 0) { t_begin = wctime(); start_collection("main"); } Formura_Forward(&navi); // navi.time_step increases MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization if (navi.time_step >= T_MAX) { t_end = wctime(); stop_collection("main"); } } printf("wct = %lf sec\n",t_end - t_begin); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } <|endoftext|>
<commit_before>#include "neural_network_trainer.hpp" #include "InputData/sentence.hpp" #include "Learning/learning_method.hpp" #include "InputData/image.hpp" #include "Layer/fully_connected_neural_network.hpp" #include "Layer/filters.hpp" using namespace Convolutional; enum class Categories { Cat, NotCat, CategoryCount }; int main(int argc, char* argv[]){ TrainingData<Categories> trainingData; InputData::Image someCat("../../image.png"); trainingData.AddData(std::move(someCat), Categories::Cat); Layer::Layers layers { Layer::Filters{3}, Layer::ReLU{}, Layer::Pooler::MaxPooler{}, Layer::FullyConnectedNeuralNetwork{static_cast<std::size_t>(Categories::CategoryCount)} }; NeuralNetworktrainer<Categories> networktrainer { 50, std::move(trainingData), std::move(layers) }; auto trainedNetwork = networktrainer.Train(); return 0; } <commit_msg>Remove superflous arguments from main()<commit_after>#include "neural_network_trainer.hpp" #include "InputData/sentence.hpp" #include "Learning/learning_method.hpp" #include "InputData/image.hpp" #include "Layer/fully_connected_neural_network.hpp" #include "Layer/filters.hpp" using namespace Convolutional; enum class Categories { Cat, NotCat, CategoryCount }; int main() { TrainingData<Categories> trainingData; InputData::Image someCat("../../image.png"); trainingData.AddData(std::move(someCat), Categories::Cat); Layer::Layers layers { Layer::Filters{3}, Layer::ReLU{}, Layer::Pooler::MaxPooler{}, Layer::FullyConnectedNeuralNetwork{static_cast<std::size_t>(Categories::CategoryCount)} }; NeuralNetworktrainer<Categories> networktrainer { 50, std::move(trainingData), std::move(layers) }; auto trainedNetwork = networktrainer.Train(); return 0; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <stdint.h> #include <vector> #include <utility> #include <mesos/authorizer/authorizer.hpp> #include <mesos/master/detector.hpp> #include <mesos/mesos.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/slave/resource_estimator.hpp> #include <process/owned.hpp> #ifdef __WINDOWS__ #include <process/windows/winsock.hpp> #endif // __WINDOWS__ #include <stout/check.hpp> #include <stout/flags.hpp> #include <stout/hashset.hpp> #include <stout/nothing.hpp> #include <stout/os.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "hook/manager.hpp" #ifdef __linux__ #include "linux/systemd.hpp" #endif // __linux__ #include "logging/logging.hpp" #include "messages/flags.hpp" #include "messages/messages.hpp" #include "module/manager.hpp" #include "slave/gc.hpp" #include "slave/slave.hpp" #include "slave/status_update_manager.hpp" #include "version/version.hpp" using namespace mesos::internal; using namespace mesos::internal::slave; using mesos::master::detector::MasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::master::detector::MasterDetector; using mesos::slave::QoSController; using mesos::slave::ResourceEstimator; using mesos::Authorizer; using mesos::SlaveInfo; using process::Owned; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::string; using std::vector; int main(int argc, char** argv) { // The order of initialization is as follows: // * Windows socket stack. // * Validate flags. // * Log build information. // * Libprocess // * Logging // * Version process // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Systemd support (if it exists). // * Fetcher and Containerizer. // * Master detector. // * Authorizer. // * Garbage collector. // * Status update manager. // * Resource estimator. // * QoS controller. // * `Agent` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. #ifdef __WINDOWS__ // Initialize the Windows socket stack. process::Winsock winsock; #endif GOOGLE_PROTOBUF_VERIFY_VERSION; slave::Flags flags; // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<string> ip; flags.add(&ip, "ip", "IP address to listen on. This cannot be used in conjunction\n" "with `--ip_discovery_command`."); uint16_t port; flags.add(&port, "port", "Port to listen on.", SlaveInfo().port()); Option<string> advertise_ip; flags.add(&advertise_ip, "advertise_ip", "IP address advertised to reach this Mesos agent.\n" "The agent does not bind to this IP address.\n" "However, this IP address may be used to access this agent."); Option<string> advertise_port; flags.add(&advertise_port, "advertise_port", "Port advertised to reach this Mesos agent (along with\n" "`advertise_ip`). The agent does not bind to this port.\n" "However, this port (along with `advertise_ip`) may be used to\n" "access this agent."); Option<string> master; flags.add(&master, "master", "May be one of:\n" " `host:port`\n" " `zk://host1:port1,host2:port2,.../path`\n" " `zk://username:password@host1:port1,host2:port2,.../path`\n" " `file:///path/to/file` (where file contains one of the above)"); // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<string> ip_discovery_command; flags.add(&ip_discovery_command, "ip_discovery_command", "Optional IP discovery binary: if set, it is expected to emit\n" "the IP address which the agent will try to bind to.\n" "Cannot be used in conjunction with `--ip`."); Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); // TODO(marco): this pattern too should be abstracted away // in FlagsBase; I have seen it at least 15 times. if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } if (master.isNone() && flags.master_detector.isNone()) { cerr << flags.usage("Missing required option `--master` or " "`--master_detector`.") << endl; return EXIT_FAILURE; } if (master.isSome() && flags.master_detector.isSome()) { cerr << flags.usage("Only one of --master or --master_detector options " "should be specified."); return EXIT_FAILURE; } // Initialize libprocess. if (ip_discovery_command.isSome() && ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (ip.isSome()) { os::setenv("LIBPROCESS_IP", ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(port)); if (advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", advertise_ip.get()); } if (advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", advertise_port.get()); } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } const string id = process::ID::generate("slave"); // Process ID. // If `process::initialize()` returns `false`, then it was called before this // invocation, meaning the authentication realm for libprocess-level HTTP // endpoints was set incorrectly. This should be the first invocation. if (!process::initialize( id, READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the agent's " << "`main()` was not the function's first invocation"; } logging::initialize(argv[0], flags, true); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } spawn(new VersionProcess(), true); if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free it's memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the slave is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } #ifdef __linux__ // Initialize systemd if it exists. if (systemd::exists() && flags.systemd_enable_support) { LOG(INFO) << "Inializing systemd state"; systemd::Flags systemdFlags; systemdFlags.enabled = flags.systemd_enable_support; systemdFlags.runtime_directory = flags.systemd_runtime_directory; systemdFlags.cgroups_hierarchy = flags.cgroups_hierarchy; Try<Nothing> initialize = systemd::initialize(systemdFlags); if (initialize.isError()) { EXIT(EXIT_FAILURE) << "Failed to initialize systemd: " + initialize.error(); } } #endif // __linux__ Fetcher fetcher; Try<Containerizer*> containerizer = Containerizer::create(flags, false, &fetcher); if (containerizer.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a containerizer: " << containerizer.error(); } Try<MasterDetector*> detector_ = MasterDetector::create( master, flags.master_detector); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } MasterDetector* detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); string authorizerName = flags.authorizer; Result<Authorizer*> authorizer((None())); if (authorizerName != slave::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; // NOTE: The contents of --acls will be ignored. authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the agent // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); GarbageCollector gc; StatusUpdateManager statusUpdateManager(flags); Try<ResourceEstimator*> resourceEstimator = ResourceEstimator::create(flags.resource_estimator); if (resourceEstimator.isError()) { cerr << "Failed to create resource estimator: " << resourceEstimator.error() << endl; return EXIT_FAILURE; } Try<QoSController*> qosController = QoSController::create(flags.qos_controller); if (qosController.isError()) { cerr << "Failed to create QoS Controller: " << qosController.error() << endl; return EXIT_FAILURE; } Slave* slave = new Slave( id, flags, detector, containerizer.get(), &files, &gc, &statusUpdateManager, resourceEstimator.get(), qosController.get(), authorizer_); process::spawn(slave); process::wait(slave->self()); delete slave; delete resourceEstimator.get(); delete qosController.get(); delete detector; delete containerizer.get(); if (authorizer_.isSome()) { delete authorizer_.get(); } return EXIT_SUCCESS; } <commit_msg>Mesos-slave --help should not return as failed.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <stdint.h> #include <vector> #include <utility> #include <mesos/authorizer/authorizer.hpp> #include <mesos/master/detector.hpp> #include <mesos/mesos.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/slave/resource_estimator.hpp> #include <process/owned.hpp> #ifdef __WINDOWS__ #include <process/windows/winsock.hpp> #endif // __WINDOWS__ #include <stout/check.hpp> #include <stout/flags.hpp> #include <stout/hashset.hpp> #include <stout/nothing.hpp> #include <stout/os.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "hook/manager.hpp" #ifdef __linux__ #include "linux/systemd.hpp" #endif // __linux__ #include "logging/logging.hpp" #include "messages/flags.hpp" #include "messages/messages.hpp" #include "module/manager.hpp" #include "slave/gc.hpp" #include "slave/slave.hpp" #include "slave/status_update_manager.hpp" #include "version/version.hpp" using namespace mesos::internal; using namespace mesos::internal::slave; using mesos::master::detector::MasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::master::detector::MasterDetector; using mesos::slave::QoSController; using mesos::slave::ResourceEstimator; using mesos::Authorizer; using mesos::SlaveInfo; using process::Owned; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::string; using std::vector; int main(int argc, char** argv) { // The order of initialization is as follows: // * Windows socket stack. // * Validate flags. // * Log build information. // * Libprocess // * Logging // * Version process // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Systemd support (if it exists). // * Fetcher and Containerizer. // * Master detector. // * Authorizer. // * Garbage collector. // * Status update manager. // * Resource estimator. // * QoS controller. // * `Agent` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. #ifdef __WINDOWS__ // Initialize the Windows socket stack. process::Winsock winsock; #endif GOOGLE_PROTOBUF_VERIFY_VERSION; slave::Flags flags; // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<string> ip; flags.add(&ip, "ip", "IP address to listen on. This cannot be used in conjunction\n" "with `--ip_discovery_command`."); uint16_t port; flags.add(&port, "port", "Port to listen on.", SlaveInfo().port()); Option<string> advertise_ip; flags.add(&advertise_ip, "advertise_ip", "IP address advertised to reach this Mesos agent.\n" "The agent does not bind to this IP address.\n" "However, this IP address may be used to access this agent."); Option<string> advertise_port; flags.add(&advertise_port, "advertise_port", "Port advertised to reach this Mesos agent (along with\n" "`advertise_ip`). The agent does not bind to this port.\n" "However, this port (along with `advertise_ip`) may be used to\n" "access this agent."); Option<string> master; flags.add(&master, "master", "May be one of:\n" " `host:port`\n" " `zk://host1:port1,host2:port2,.../path`\n" " `zk://username:password@host1:port1,host2:port2,.../path`\n" " `file:///path/to/file` (where file contains one of the above)"); // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<string> ip_discovery_command; flags.add(&ip_discovery_command, "ip_discovery_command", "Optional IP discovery binary: if set, it is expected to emit\n" "the IP address which the agent will try to bind to.\n" "Cannot be used in conjunction with `--ip`."); Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } // TODO(marco): this pattern too should be abstracted away // in FlagsBase; I have seen it at least 15 times. if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } if (master.isNone() && flags.master_detector.isNone()) { cerr << flags.usage("Missing required option `--master` or " "`--master_detector`.") << endl; return EXIT_FAILURE; } if (master.isSome() && flags.master_detector.isSome()) { cerr << flags.usage("Only one of --master or --master_detector options " "should be specified."); return EXIT_FAILURE; } // Initialize libprocess. if (ip_discovery_command.isSome() && ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (ip.isSome()) { os::setenv("LIBPROCESS_IP", ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(port)); if (advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", advertise_ip.get()); } if (advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", advertise_port.get()); } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } const string id = process::ID::generate("slave"); // Process ID. // If `process::initialize()` returns `false`, then it was called before this // invocation, meaning the authentication realm for libprocess-level HTTP // endpoints was set incorrectly. This should be the first invocation. if (!process::initialize( id, READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the agent's " << "`main()` was not the function's first invocation"; } logging::initialize(argv[0], flags, true); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } spawn(new VersionProcess(), true); if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free it's memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the slave is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } #ifdef __linux__ // Initialize systemd if it exists. if (systemd::exists() && flags.systemd_enable_support) { LOG(INFO) << "Inializing systemd state"; systemd::Flags systemdFlags; systemdFlags.enabled = flags.systemd_enable_support; systemdFlags.runtime_directory = flags.systemd_runtime_directory; systemdFlags.cgroups_hierarchy = flags.cgroups_hierarchy; Try<Nothing> initialize = systemd::initialize(systemdFlags); if (initialize.isError()) { EXIT(EXIT_FAILURE) << "Failed to initialize systemd: " + initialize.error(); } } #endif // __linux__ Fetcher fetcher; Try<Containerizer*> containerizer = Containerizer::create(flags, false, &fetcher); if (containerizer.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a containerizer: " << containerizer.error(); } Try<MasterDetector*> detector_ = MasterDetector::create( master, flags.master_detector); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } MasterDetector* detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); string authorizerName = flags.authorizer; Result<Authorizer*> authorizer((None())); if (authorizerName != slave::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; // NOTE: The contents of --acls will be ignored. authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the agent // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); GarbageCollector gc; StatusUpdateManager statusUpdateManager(flags); Try<ResourceEstimator*> resourceEstimator = ResourceEstimator::create(flags.resource_estimator); if (resourceEstimator.isError()) { cerr << "Failed to create resource estimator: " << resourceEstimator.error() << endl; return EXIT_FAILURE; } Try<QoSController*> qosController = QoSController::create(flags.qos_controller); if (qosController.isError()) { cerr << "Failed to create QoS Controller: " << qosController.error() << endl; return EXIT_FAILURE; } Slave* slave = new Slave( id, flags, detector, containerizer.get(), &files, &gc, &statusUpdateManager, resourceEstimator.get(), qosController.get(), authorizer_); process::spawn(slave); process::wait(slave->self()); delete slave; delete resourceEstimator.get(); delete qosController.get(); delete detector; delete containerizer.get(); if (authorizer_.isSome()) { delete authorizer_.get(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: popupmenudispatcher.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:05:51 $ * * 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_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ #include <dispatch/popupmenudispatcher.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_ #include <classes/menuconfiguration.hxx> #endif #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_ #include <classes/addonmenu.hxx> #endif #include <services.h> #include <properties.h> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_ #include <com/sun/star/frame/FrameSearchFlag.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_ #include <com/sun/star/awt/XToolkit.hpp> #endif #ifndef _COM_SUN_STAR_AWT_WINDOWATTRIBUTE_HPP_ #include <com/sun/star/awt/WindowAttribute.hpp> #endif #ifndef _COM_SUN_STAR_AWT_WINDOWDESCRIPTOR_HPP_ #include <com/sun/star/awt/WindowDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_ #include <com/sun/star/awt/XWindowPeer.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HPP_ #include <com/sun/star/beans/UnknownPropertyException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <ucbhelper/content.hxx> #include <vos/mutex.hxx> #include <rtl/ustrbuf.hxx> #include <vcl/svapp.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ using namespace ::com::sun::star ; using namespace ::com::sun::star::awt ; using namespace ::com::sun::star::beans ; using namespace ::com::sun::star::container ; using namespace ::com::sun::star::frame ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::util ; using namespace ::cppu ; using namespace ::osl ; using namespace ::rtl ; using namespace ::vos ; //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ const char* PROTOCOL_VALUE = "vnd.sun.star.popup:"; const sal_Int32 PROTOCOL_LENGTH = 19; //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** PopupMenuDispatcher::PopupMenuDispatcher( const Reference< XMultiServiceFactory >& xFactory ) // Init baseclasses first : ThreadHelpBase ( &Application::GetSolarMutex() ) , OWeakObject ( ) // Init member , m_xFactory ( xFactory ) , m_aListenerContainer ( m_aLock.getShareableOslMutex() ) , m_bAlreadyDisposed ( sal_False ) , m_bActivateListener ( sal_False ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** PopupMenuDispatcher::~PopupMenuDispatcher() { // Warn programmer if he forgot to dispose this instance. // We must release all our references ... // and a dtor isn't the best place to do that! } //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_7 ( PopupMenuDispatcher , ::cppu::OWeakObject , DIRECT_INTERFACE( XTypeProvider ), DIRECT_INTERFACE( XServiceInfo ), DIRECT_INTERFACE( XDispatchProvider ), DIRECT_INTERFACE( XDispatch ), DIRECT_INTERFACE( XEventListener ), DIRECT_INTERFACE( XInitialization ), DERIVED_INTERFACE( XFrameActionListener, XEventListener ) ) DEFINE_XTYPEPROVIDER_7 ( PopupMenuDispatcher , XTypeProvider , XServiceInfo , XDispatchProvider , XDispatch , XEventListener , XInitialization , XFrameActionListener ) DEFINE_XSERVICEINFO_MULTISERVICE( PopupMenuDispatcher , ::cppu::OWeakObject , SERVICENAME_PROTOCOLHANDLER , IMPLEMENTATIONNAME_POPUPMENUDISPATCHER ) DEFINE_INIT_SERVICE(PopupMenuDispatcher, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ } ) //***************************************************************************************************************** // XInitialization //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::initialize( const css::uno::Sequence< css::uno::Any >& lArguments ) throw( css::uno::Exception, css::uno::RuntimeException) { css::uno::Reference< css::frame::XFrame > xFrame; /* SAFE { */ WriteGuard aWriteLock(m_aLock); for (int a=0; a<lArguments.getLength(); ++a) { if (a==0) { lArguments[a] >>= xFrame; m_xWeakFrame = xFrame; m_bActivateListener = sal_True; Reference< css::frame::XFrameActionListener > xFrameActionListener( (OWeakObject *)this, css::uno::UNO_QUERY ); xFrame->addFrameActionListener( xFrameActionListener ); } } aWriteLock.unlock(); /* } SAFE */ } //***************************************************************************************************************** // XDispatchProvider //***************************************************************************************************************** css::uno::Reference< css::frame::XDispatch > SAL_CALL PopupMenuDispatcher::queryDispatch( const css::util::URL& rURL , const ::rtl::OUString& sTarget , sal_Int32 nFlags ) throw( css::uno::RuntimeException ) { css::uno::Reference< css::frame::XDispatch > xDispatch; if ( rURL.Complete.compareToAscii( PROTOCOL_VALUE, PROTOCOL_LENGTH ) == 0 ) { // --- SAFE --- ResetableGuard aGuard( m_aLock ); impl_RetrievePopupControllerQuery(); impl_CreateUriRefFactory(); css::uno::Reference< css::container::XNameAccess > xPopupCtrlQuery( m_xPopupCtrlQuery ); css::uno::Reference< css::uri::XUriReferenceFactory > xUriRefFactory( m_xUriRefFactory ); aGuard.unlock(); // --- SAFE --- if ( xPopupCtrlQuery.is() ) { try { // Just use the main part of the URL for popup menu controllers sal_Int32 nQueryPart( 0 ); sal_Int32 nSchemePart( 0 ); rtl::OUString aBaseURL( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.popup:" )); rtl::OUString aURL( rURL.Complete ); nSchemePart = aURL.indexOf( ':' ); if (( nSchemePart > 0 ) && ( aURL.getLength() > ( nSchemePart+1 ))) { nQueryPart = aURL.indexOf( '?', nSchemePart ); if ( nQueryPart > 0 ) aBaseURL += aURL.copy( nSchemePart+1, nQueryPart-(nSchemePart+1) ); else if ( nQueryPart == -1 ) aBaseURL += aURL.copy( nSchemePart+1 ); } css::uno::Reference< css::frame::XDispatchProvider > xDispatchProvider; // Find popup menu controller using the base URL Any a = xPopupCtrlQuery->getByName( aBaseURL ); a >>= xDispatchProvider; aGuard.unlock(); // Ask popup menu dispatch provider for dispatch object if ( xDispatchProvider.is() ) xDispatch = xDispatchProvider->queryDispatch( rURL, sTarget, nFlags ); } catch ( RuntimeException& ) { throw; } catch ( Exception& ) { } } } return xDispatch; } css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL PopupMenuDispatcher::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ) { sal_Int32 nCount = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatcher( nCount ); for( sal_Int32 i=0; i<nCount; ++i ) { lDispatcher[i] = this->queryDispatch( lDescriptor[i].FeatureURL, lDescriptor[i].FrameName, lDescriptor[i].SearchFlags); } return lDispatcher; } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::dispatch( const URL& /*aURL*/ , const Sequence< PropertyValue >& /*seqProperties*/ ) throw( RuntimeException ) { } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::addStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases // Add listener to container. m_aListenerContainer.addInterface( aURL.Complete, xControl ); } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::removeStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases // Add listener to container. m_aListenerContainer.removeInterface( aURL.Complete, xControl ); } //***************************************************************************************************************** // XFrameActionListener //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::frameAction( const FrameActionEvent& aEvent ) throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); if (( aEvent.Action == css::frame::FrameAction_COMPONENT_DETACHING ) || ( aEvent.Action == css::frame::FrameAction_COMPONENT_ATTACHED )) { // Reset query reference to requery it again next time m_xPopupCtrlQuery.clear(); } } //***************************************************************************************************************** // XEventListener //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::disposing( const EventObject& ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases LOG_ASSERT( !(m_bAlreadyDisposed==sal_True), "MenuDispatcher::disposing()\nObject already disposed .. don't call it again!\n" ) if( m_bAlreadyDisposed == sal_False ) { m_bAlreadyDisposed = sal_True; if ( m_bActivateListener ) { Reference< XFrame > xFrame( m_xWeakFrame.get(), UNO_QUERY ); if ( xFrame.is() ) { xFrame->removeFrameActionListener( Reference< XFrameActionListener >( (OWeakObject *)this, UNO_QUERY )); m_bActivateListener = sal_False; } } // Forget our factory. m_xFactory = Reference< XMultiServiceFactory >(); } } void PopupMenuDispatcher::impl_RetrievePopupControllerQuery() { if ( !m_xPopupCtrlQuery.is() ) { css::uno::Reference< css::frame::XLayoutManager > xLayoutManager; css::uno::Reference< css::frame::XFrame > xFrame( m_xWeakFrame ); if ( xFrame.is() ) { css::uno::Reference< css::beans::XPropertySet > xPropSet( xFrame, css::uno::UNO_QUERY ); if ( xPropSet.is() ) { try { Any a = xPropSet->getPropertyValue( FRAME_PROPNAME_LAYOUTMANAGER ); a >>= xLayoutManager; if ( xLayoutManager.is() ) { css::uno::Reference< css::ui::XUIElement > xMenuBar; rtl::OUString aMenuBar( RTL_CONSTASCII_USTRINGPARAM( "private:resource/menubar/menubar" )); xMenuBar = xLayoutManager->getElement( aMenuBar ); m_xPopupCtrlQuery = css::uno::Reference< css::container::XNameAccess >( xMenuBar, css::uno::UNO_QUERY ); } } catch ( css::uno::RuntimeException& ) { throw; } catch ( css::uno::Exception& ) { } } } } } void PopupMenuDispatcher::impl_CreateUriRefFactory() { if ( !m_xUriRefFactory.is() ) { rtl::OUString aUriRefFactoryService( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.uri.UriReferenceFactory" )); m_xUriRefFactory = css::uno::Reference< css::uri::XUriReferenceFactory >( m_xFactory->createInstance( aUriRefFactoryService ), css::uno::UNO_QUERY); } } } // namespace framework <commit_msg>INTEGRATION: CWS bgdlremove (1.2.72); FILE MERGED 2007/05/11 08:57:55 kso 1.2.72.1: #i76911# - ucbhelper lib no longer uses VOS. (vos::ORef => rtl::Reference, vos::OMutex => osl::Mutex, ...)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: popupmenudispatcher.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2007-06-05 14:45:33 $ * * 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_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_DISPATCH_POPUPMENUDISPATCHER_HXX_ #include <dispatch/popupmenudispatcher.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_ #include <classes/menuconfiguration.hxx> #endif #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_ #include <classes/addonmenu.hxx> #endif #include <services.h> #include <properties.h> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_ #include <com/sun/star/frame/FrameSearchFlag.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_ #include <com/sun/star/awt/XToolkit.hpp> #endif #ifndef _COM_SUN_STAR_AWT_WINDOWATTRIBUTE_HPP_ #include <com/sun/star/awt/WindowAttribute.hpp> #endif #ifndef _COM_SUN_STAR_AWT_WINDOWDESCRIPTOR_HPP_ #include <com/sun/star/awt/WindowDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_ #include <com/sun/star/awt/XWindowPeer.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HPP_ #include <com/sun/star/beans/UnknownPropertyException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_ #include <com/sun/star/lang/WrappedTargetException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <ucbhelper/content.hxx> #include <vos/mutex.hxx> #include <rtl/ustrbuf.hxx> #include <vcl/svapp.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ using namespace ::com::sun::star ; using namespace ::com::sun::star::awt ; using namespace ::com::sun::star::beans ; using namespace ::com::sun::star::container ; using namespace ::com::sun::star::frame ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::util ; using namespace ::cppu ; using namespace ::osl ; using namespace ::rtl ; using namespace ::vos ; //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ const char* PROTOCOL_VALUE = "vnd.sun.star.popup:"; const sal_Int32 PROTOCOL_LENGTH = 19; //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** PopupMenuDispatcher::PopupMenuDispatcher( const uno::Reference< XMultiServiceFactory >& xFactory ) // Init baseclasses first : ThreadHelpBase ( &Application::GetSolarMutex() ) , OWeakObject ( ) // Init member , m_xFactory ( xFactory ) , m_aListenerContainer ( m_aLock.getShareableOslMutex() ) , m_bAlreadyDisposed ( sal_False ) , m_bActivateListener ( sal_False ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** PopupMenuDispatcher::~PopupMenuDispatcher() { // Warn programmer if he forgot to dispose this instance. // We must release all our references ... // and a dtor isn't the best place to do that! } //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_7 ( PopupMenuDispatcher , ::cppu::OWeakObject , DIRECT_INTERFACE( XTypeProvider ), DIRECT_INTERFACE( XServiceInfo ), DIRECT_INTERFACE( XDispatchProvider ), DIRECT_INTERFACE( XDispatch ), DIRECT_INTERFACE( XEventListener ), DIRECT_INTERFACE( XInitialization ), DERIVED_INTERFACE( XFrameActionListener, XEventListener ) ) DEFINE_XTYPEPROVIDER_7 ( PopupMenuDispatcher , XTypeProvider , XServiceInfo , XDispatchProvider , XDispatch , XEventListener , XInitialization , XFrameActionListener ) DEFINE_XSERVICEINFO_MULTISERVICE( PopupMenuDispatcher , ::cppu::OWeakObject , SERVICENAME_PROTOCOLHANDLER , IMPLEMENTATIONNAME_POPUPMENUDISPATCHER ) DEFINE_INIT_SERVICE(PopupMenuDispatcher, { /*Attention I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance() to create a new instance of this class by our own supported service factory. see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations! */ } ) //***************************************************************************************************************** // XInitialization //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::initialize( const css::uno::Sequence< css::uno::Any >& lArguments ) throw( css::uno::Exception, css::uno::RuntimeException) { css::uno::Reference< css::frame::XFrame > xFrame; /* SAFE { */ WriteGuard aWriteLock(m_aLock); for (int a=0; a<lArguments.getLength(); ++a) { if (a==0) { lArguments[a] >>= xFrame; m_xWeakFrame = xFrame; m_bActivateListener = sal_True; uno::Reference< css::frame::XFrameActionListener > xFrameActionListener( (OWeakObject *)this, css::uno::UNO_QUERY ); xFrame->addFrameActionListener( xFrameActionListener ); } } aWriteLock.unlock(); /* } SAFE */ } //***************************************************************************************************************** // XDispatchProvider //***************************************************************************************************************** css::uno::Reference< css::frame::XDispatch > SAL_CALL PopupMenuDispatcher::queryDispatch( const css::util::URL& rURL , const ::rtl::OUString& sTarget , sal_Int32 nFlags ) throw( css::uno::RuntimeException ) { css::uno::Reference< css::frame::XDispatch > xDispatch; if ( rURL.Complete.compareToAscii( PROTOCOL_VALUE, PROTOCOL_LENGTH ) == 0 ) { // --- SAFE --- ResetableGuard aGuard( m_aLock ); impl_RetrievePopupControllerQuery(); impl_CreateUriRefFactory(); css::uno::Reference< css::container::XNameAccess > xPopupCtrlQuery( m_xPopupCtrlQuery ); css::uno::Reference< css::uri::XUriReferenceFactory > xUriRefFactory( m_xUriRefFactory ); aGuard.unlock(); // --- SAFE --- if ( xPopupCtrlQuery.is() ) { try { // Just use the main part of the URL for popup menu controllers sal_Int32 nQueryPart( 0 ); sal_Int32 nSchemePart( 0 ); rtl::OUString aBaseURL( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.popup:" )); rtl::OUString aURL( rURL.Complete ); nSchemePart = aURL.indexOf( ':' ); if (( nSchemePart > 0 ) && ( aURL.getLength() > ( nSchemePart+1 ))) { nQueryPart = aURL.indexOf( '?', nSchemePart ); if ( nQueryPart > 0 ) aBaseURL += aURL.copy( nSchemePart+1, nQueryPart-(nSchemePart+1) ); else if ( nQueryPart == -1 ) aBaseURL += aURL.copy( nSchemePart+1 ); } css::uno::Reference< css::frame::XDispatchProvider > xDispatchProvider; // Find popup menu controller using the base URL Any a = xPopupCtrlQuery->getByName( aBaseURL ); a >>= xDispatchProvider; aGuard.unlock(); // Ask popup menu dispatch provider for dispatch object if ( xDispatchProvider.is() ) xDispatch = xDispatchProvider->queryDispatch( rURL, sTarget, nFlags ); } catch ( RuntimeException& ) { throw; } catch ( Exception& ) { } } } return xDispatch; } css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL PopupMenuDispatcher::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw( css::uno::RuntimeException ) { sal_Int32 nCount = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatcher( nCount ); for( sal_Int32 i=0; i<nCount; ++i ) { lDispatcher[i] = this->queryDispatch( lDescriptor[i].FeatureURL, lDescriptor[i].FrameName, lDescriptor[i].SearchFlags); } return lDispatcher; } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::dispatch( const URL& /*aURL*/ , const Sequence< PropertyValue >& /*seqProperties*/ ) throw( RuntimeException ) { } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::addStatusListener( const uno::Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases // Add listener to container. m_aListenerContainer.addInterface( aURL.Complete, xControl ); } //***************************************************************************************************************** // XDispatch //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::removeStatusListener( const uno::Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases // Add listener to container. m_aListenerContainer.removeInterface( aURL.Complete, xControl ); } //***************************************************************************************************************** // XFrameActionListener //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::frameAction( const FrameActionEvent& aEvent ) throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); if (( aEvent.Action == css::frame::FrameAction_COMPONENT_DETACHING ) || ( aEvent.Action == css::frame::FrameAction_COMPONENT_ATTACHED )) { // Reset query reference to requery it again next time m_xPopupCtrlQuery.clear(); } } //***************************************************************************************************************** // XEventListener //***************************************************************************************************************** void SAL_CALL PopupMenuDispatcher::disposing( const EventObject& ) throw( RuntimeException ) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Safe impossible cases LOG_ASSERT( !(m_bAlreadyDisposed==sal_True), "MenuDispatcher::disposing()\nObject already disposed .. don't call it again!\n" ) if( m_bAlreadyDisposed == sal_False ) { m_bAlreadyDisposed = sal_True; if ( m_bActivateListener ) { uno::Reference< XFrame > xFrame( m_xWeakFrame.get(), UNO_QUERY ); if ( xFrame.is() ) { xFrame->removeFrameActionListener( uno::Reference< XFrameActionListener >( (OWeakObject *)this, UNO_QUERY )); m_bActivateListener = sal_False; } } // Forget our factory. m_xFactory = uno::Reference< XMultiServiceFactory >(); } } void PopupMenuDispatcher::impl_RetrievePopupControllerQuery() { if ( !m_xPopupCtrlQuery.is() ) { css::uno::Reference< css::frame::XLayoutManager > xLayoutManager; css::uno::Reference< css::frame::XFrame > xFrame( m_xWeakFrame ); if ( xFrame.is() ) { css::uno::Reference< css::beans::XPropertySet > xPropSet( xFrame, css::uno::UNO_QUERY ); if ( xPropSet.is() ) { try { Any a = xPropSet->getPropertyValue( FRAME_PROPNAME_LAYOUTMANAGER ); a >>= xLayoutManager; if ( xLayoutManager.is() ) { css::uno::Reference< css::ui::XUIElement > xMenuBar; rtl::OUString aMenuBar( RTL_CONSTASCII_USTRINGPARAM( "private:resource/menubar/menubar" )); xMenuBar = xLayoutManager->getElement( aMenuBar ); m_xPopupCtrlQuery = css::uno::Reference< css::container::XNameAccess >( xMenuBar, css::uno::UNO_QUERY ); } } catch ( css::uno::RuntimeException& ) { throw; } catch ( css::uno::Exception& ) { } } } } } void PopupMenuDispatcher::impl_CreateUriRefFactory() { if ( !m_xUriRefFactory.is() ) { rtl::OUString aUriRefFactoryService( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.uri.UriReferenceFactory" )); m_xUriRefFactory = css::uno::Reference< css::uri::XUriReferenceFactory >( m_xFactory->createInstance( aUriRefFactoryService ), css::uno::UNO_QUERY); } } } // namespace framework <|endoftext|>
<commit_before>/* * DIPlib 3.0 * This file contains basic binary morphology functions: dilation, erosion, opening, closing. * * (c)2017, Erik Schuitema. * Based on original DIPlib code: (c)1995-2014, Delft University of Technology. * * 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 "diplib.h" #include "diplib/binary.h" #include "diplib/neighborlist.h" #include "diplib/iterators.h" #include "binary_support.h" namespace dip { namespace { /// The BinaryPropagationFunc type is used to define what to do with pixels added /// to the processing queue during dilation and erosion. using BinaryPropagationFunc = std::function< void( uint8& pixel, uint8 dataMask ) >; /// Worker function for both dilation and erosion, since they are very alike void BinaryDilationErosion( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition, bool findObjectPixels, BinaryPropagationFunc const& propagationOperation ) { // Verify that the image is forged, scalar and binary DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); DIP_THROW_IF( !in.DataType().IsBinary(), E::IMAGE_NOT_BINARY ); DIP_THROW_IF( !in.IsScalar(), E::IMAGE_NOT_SCALAR ); dip::uint nDims = in.Dimensionality(); DIP_THROW_IF( connectivity > static_cast< dip::sint >( nDims ), E::PARAMETER_OUT_OF_RANGE ); // Edge condition: true means object, false means background bool outsideImageIsObject = BooleanFromString( s_edgeCondition, S::OBJECT, S::BACKGROUND ); // Copy input plane to output plane. Operation takes place directly in the output plane. Image c_in = in; // temporary copy of image header, so we can strip out out.ReForge( in.Sizes(), 1, DT_BIN ); // reforging first in case `out` is the right size but a different data type out.Copy( c_in ); // Negative connectivity means: alternate between two different connectivities // Create arrays with offsets to neighbours for even iterations dip::uint iterConnectivity0 = GetAbsBinaryConnectivity( nDims, connectivity, 0 ); NeighborList neighborList0( { Metric::TypeCode::CONNECTED, iterConnectivity0 }, nDims ); IntegerArray neighborOffsetsOut0 = neighborList0.ComputeOffsets( out.Strides() ); // Create arrays with offsets to neighbours for odd iterations dip::uint iterConnectivity1 = GetAbsBinaryConnectivity( nDims, connectivity, 1 ); NeighborList neighborList1( { Metric::TypeCode::CONNECTED, iterConnectivity1 }, nDims ); IntegerArray neighborOffsetsOut1 = neighborList1.ComputeOffsets( out.Strides() ); // Data mask: the pixel data is in the first 'plane' uint8 dataMask = 1; // Use border mask to mark pixels of the image border uint8 borderMask = uint8( 1 << 2 ); ApplyBinaryBorderMask( out, borderMask ); // The edge pixel queue dip::queue< dip::bin* > edgePixels; // Initialize the queue by finding all edge pixels of the type according to findObjectPixels FindBinaryEdgePixels( out, findObjectPixels, neighborList0, neighborOffsetsOut0, dataMask, borderMask, outsideImageIsObject, &edgePixels ); // First iteration: simply process the queue if( iterations > 0 ) { for( dip::queue< dip::bin* >::const_iterator itEP = edgePixels.begin(); itEP != edgePixels.end(); ++itEP ) { propagationOperation( static_cast< uint8& >( **itEP ), dataMask ); } } // Create a coordinates computer for bounds checking of border pixels const CoordinatesComputer coordsComputer = out.OffsetToCoordinatesComputer(); // Second and further iterations for( dip::uint iDilIter = 1; iDilIter < iterations; ++iDilIter ) { // Obtain neighbor list and offsets for this iteration NeighborList const& neighborList = iDilIter & 1 ? neighborList1 : neighborList0; IntegerArray const& neighborOffsetsOut = iDilIter & 1 ? neighborOffsetsOut1 : neighborOffsetsOut0; // Process all elements currently in the queue dip::sint count = static_cast< dip::sint >( edgePixels.size() ); while( --count >= 0 ) { // Get front pixel from the queue dip::bin* pPixel = edgePixels.front(); uint8& pixelByte = static_cast< uint8& >( *pPixel ); bool isBorderPixel = pixelByte & borderMask; // Propagate to all neighbours which are not yet processed dip::IntegerArray::const_iterator itNeighborOffset = neighborOffsetsOut.begin(); for( NeighborList::Iterator itNeighbor = neighborList.begin(); itNeighbor != neighborList.end(); ++itNeighbor, ++itNeighborOffset ) { if( !isBorderPixel || itNeighbor.IsInImage( coordsComputer( pPixel - static_cast< dip::bin* >( out.Origin() )), out.Sizes() )) { // IsInImage() is not evaluated for non-border pixels dip::bin* pNeighbor = pPixel + *itNeighborOffset; uint8& neighborByte = static_cast< uint8& >( *pNeighbor ); bool neighborIsObject = neighborByte & dataMask; if( neighborIsObject == findObjectPixels ) { // Propagate to the neighbor pixel propagationOperation( neighborByte, dataMask ); // Add neighbor to the queue edgePixels.push_back( pNeighbor ); } } } // Remove the front pixel from the queue edgePixels.pop_front(); } } // Clear the edge mask of the image border ClearBinaryBorderMask( out, borderMask ); } } // namespace void BinaryDilation( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition ) { bool findObjectPixels = false; // Dilation propagates to background pixels auto propagationFunc = []( uint8& pixel, uint8 dataMask ) { pixel |= dataMask; }; // Propagate by adding the data mask BinaryDilationErosion( in, out, connectivity, iterations, s_edgeCondition, findObjectPixels, propagationFunc ); } void BinaryErosion( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition ) { bool findObjectPixels = true; // Erosion propagates to object pixels auto propagationFunc = []( uint8& pixel, uint8 dataMask ) { pixel &= static_cast< uint8 >( ~dataMask ); }; // Propagate by removing the data mask BinaryDilationErosion( in, out, connectivity, iterations, s_edgeCondition, findObjectPixels, propagationFunc ); } void BinaryOpening( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& edgeCondition ) { if( edgeCondition == S::BACKGROUND || edgeCondition == S::OBJECT ) { BinaryErosion( in, out, connectivity, iterations, edgeCondition ); BinaryDilation( out, out, connectivity, iterations, edgeCondition ); } else { // "Special handling" DIP_THROW_IF( edgeCondition != S::SPECIAL, E::INVALID_FLAG ); BinaryErosion( in, out, connectivity, iterations, S::OBJECT ); BinaryDilation( out, out, connectivity, iterations, S::BACKGROUND ); } } void BinaryClosing( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& edgeCondition ) { if( edgeCondition == S::BACKGROUND || edgeCondition == S::OBJECT ) { BinaryDilation( in, out, connectivity, iterations, edgeCondition ); BinaryErosion( out, out, connectivity, iterations, edgeCondition ); } else { // "Special handling" DIP_THROW_IF( edgeCondition != S::SPECIAL, E::INVALID_FLAG ); BinaryDilation( in, out, connectivity, iterations, S::BACKGROUND ); BinaryErosion( out, out, connectivity, iterations, S::OBJECT ); } } } // namespace dip #ifdef DIP__ENABLE_DOCTEST #include "doctest.h" #include "diplib/statistics.h" DOCTEST_TEST_CASE("[DIPlib] testing the binary morphological filters") { dip::Image in( { 64, 41 }, 1, dip::DT_BIN ); in = 0; in.At( 32, 20 ) = 1; dip::Image out; // connectivity = 2 dip::BinaryDilation( in, out, 2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 15 * 15 ); dip::BinaryErosion( out, out, 2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = 1 dip::BinaryDilation( in, out, 1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 7*8*2 + 1 ); dip::BinaryErosion( out, out, 1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = -1 dip::BinaryDilation( in, out, -1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 185 ); dip::BinaryErosion( out, out, -1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = -2 dip::BinaryDilation( in, out, -2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 201 ); dip::BinaryErosion( out, out, -2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); } #endif // DIP__ENABLE_DOCTEST <commit_msg>Small speed increase using template with lambda over `std::function`.<commit_after>/* * DIPlib 3.0 * This file contains basic binary morphology functions: dilation, erosion, opening, closing. * * (c)2017, Erik Schuitema. * Based on original DIPlib code: (c)1995-2014, Delft University of Technology. * * 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 "diplib.h" #include "diplib/binary.h" #include "diplib/neighborlist.h" #include "diplib/iterators.h" #include "binary_support.h" namespace dip { namespace { // Worker function for both dilation and erosion, since they are very alike template< typename F > void BinaryDilationErosion( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition, bool findObjectPixels, F const& propagationOperation ) { // Verify that the image is forged, scalar and binary DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); DIP_THROW_IF( !in.DataType().IsBinary(), E::IMAGE_NOT_BINARY ); DIP_THROW_IF( !in.IsScalar(), E::IMAGE_NOT_SCALAR ); dip::uint nDims = in.Dimensionality(); DIP_THROW_IF( connectivity > static_cast< dip::sint >( nDims ), E::PARAMETER_OUT_OF_RANGE ); // Edge condition: true means object, false means background bool outsideImageIsObject = BooleanFromString( s_edgeCondition, S::OBJECT, S::BACKGROUND ); // Copy input plane to output plane. Operation takes place directly in the output plane. Image c_in = in; // temporary copy of image header, so we can strip out out.ReForge( in.Sizes(), 1, DT_BIN ); // reforging first in case `out` is the right size but a different data type out.Copy( c_in ); // Negative connectivity means: alternate between two different connectivities // Create arrays with offsets to neighbours for even iterations dip::uint iterConnectivity0 = GetAbsBinaryConnectivity( nDims, connectivity, 0 ); NeighborList neighborList0( { Metric::TypeCode::CONNECTED, iterConnectivity0 }, nDims ); IntegerArray neighborOffsetsOut0 = neighborList0.ComputeOffsets( out.Strides() ); // Create arrays with offsets to neighbours for odd iterations dip::uint iterConnectivity1 = GetAbsBinaryConnectivity( nDims, connectivity, 1 ); NeighborList neighborList1( { Metric::TypeCode::CONNECTED, iterConnectivity1 }, nDims ); IntegerArray neighborOffsetsOut1 = neighborList1.ComputeOffsets( out.Strides() ); // Data mask: the pixel data is in the first 'plane' uint8 dataMask = 1; // Use border mask to mark pixels of the image border uint8 borderMask = uint8( 1 << 2 ); ApplyBinaryBorderMask( out, borderMask ); // The edge pixel queue dip::queue< dip::bin* > edgePixels; // Initialize the queue by finding all edge pixels of the type according to findObjectPixels FindBinaryEdgePixels( out, findObjectPixels, neighborList0, neighborOffsetsOut0, dataMask, borderMask, outsideImageIsObject, &edgePixels ); // First iteration: simply process the queue if( iterations > 0 ) { for( dip::queue< dip::bin* >::const_iterator itEP = edgePixels.begin(); itEP != edgePixels.end(); ++itEP ) { propagationOperation( static_cast< uint8& >( **itEP ), dataMask ); } } // Create a coordinates computer for bounds checking of border pixels const CoordinatesComputer coordsComputer = out.OffsetToCoordinatesComputer(); // Second and further iterations for( dip::uint iDilIter = 1; iDilIter < iterations; ++iDilIter ) { // Obtain neighbor list and offsets for this iteration NeighborList const& neighborList = iDilIter & 1 ? neighborList1 : neighborList0; IntegerArray const& neighborOffsetsOut = iDilIter & 1 ? neighborOffsetsOut1 : neighborOffsetsOut0; // Process all elements currently in the queue dip::sint count = static_cast< dip::sint >( edgePixels.size() ); while( --count >= 0 ) { // Get front pixel from the queue dip::bin* pPixel = edgePixels.front(); uint8& pixelByte = static_cast< uint8& >( *pPixel ); bool isBorderPixel = pixelByte & borderMask; // Propagate to all neighbours which are not yet processed dip::IntegerArray::const_iterator itNeighborOffset = neighborOffsetsOut.begin(); for( NeighborList::Iterator itNeighbor = neighborList.begin(); itNeighbor != neighborList.end(); ++itNeighbor, ++itNeighborOffset ) { if( !isBorderPixel || itNeighbor.IsInImage( coordsComputer( pPixel - static_cast< dip::bin* >( out.Origin() )), out.Sizes() )) { // IsInImage() is not evaluated for non-border pixels dip::bin* pNeighbor = pPixel + *itNeighborOffset; uint8& neighborByte = static_cast< uint8& >( *pNeighbor ); bool neighborIsObject = neighborByte & dataMask; if( neighborIsObject == findObjectPixels ) { // Propagate to the neighbor pixel propagationOperation( neighborByte, dataMask ); // Add neighbor to the queue edgePixels.push_back( pNeighbor ); } } } // Remove the front pixel from the queue edgePixels.pop_front(); } } // Clear the edge mask of the image border ClearBinaryBorderMask( out, borderMask ); } } // namespace void BinaryDilation( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition ) { bool findObjectPixels = false; // Dilation propagates to background pixels auto propagationFunc = []( uint8& pixel, uint8 dataMask ) { pixel |= dataMask; }; // Propagate by adding the data mask BinaryDilationErosion( in, out, connectivity, iterations, s_edgeCondition, findObjectPixels, propagationFunc ); } void BinaryErosion( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& s_edgeCondition ) { bool findObjectPixels = true; // Erosion propagates to object pixels auto propagationFunc = []( uint8& pixel, uint8 dataMask ) { pixel &= static_cast< uint8 >( ~dataMask ); }; // Propagate by removing the data mask BinaryDilationErosion( in, out, connectivity, iterations, s_edgeCondition, findObjectPixels, propagationFunc ); } void BinaryOpening( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& edgeCondition ) { if( edgeCondition == S::BACKGROUND || edgeCondition == S::OBJECT ) { BinaryErosion( in, out, connectivity, iterations, edgeCondition ); BinaryDilation( out, out, connectivity, iterations, edgeCondition ); } else { // "Special handling" DIP_THROW_IF( edgeCondition != S::SPECIAL, E::INVALID_FLAG ); BinaryErosion( in, out, connectivity, iterations, S::OBJECT ); BinaryDilation( out, out, connectivity, iterations, S::BACKGROUND ); } } void BinaryClosing( Image const& in, Image& out, dip::sint connectivity, dip::uint iterations, String const& edgeCondition ) { if( edgeCondition == S::BACKGROUND || edgeCondition == S::OBJECT ) { BinaryDilation( in, out, connectivity, iterations, edgeCondition ); BinaryErosion( out, out, connectivity, iterations, edgeCondition ); } else { // "Special handling" DIP_THROW_IF( edgeCondition != S::SPECIAL, E::INVALID_FLAG ); BinaryDilation( in, out, connectivity, iterations, S::BACKGROUND ); BinaryErosion( out, out, connectivity, iterations, S::OBJECT ); } } } // namespace dip #ifdef DIP__ENABLE_DOCTEST #include "doctest.h" #include "diplib/statistics.h" DOCTEST_TEST_CASE("[DIPlib] testing the binary morphological filters") { dip::Image in( { 64, 41 }, 1, dip::DT_BIN ); in = 0; in.At( 32, 20 ) = 1; dip::Image out; // connectivity = 2 dip::BinaryDilation( in, out, 2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 15 * 15 ); dip::BinaryErosion( out, out, 2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = 1 dip::BinaryDilation( in, out, 1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 7*8*2 + 1 ); dip::BinaryErosion( out, out, 1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = -1 dip::BinaryDilation( in, out, -1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 185 ); dip::BinaryErosion( out, out, -1, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); // connectivity = -2 dip::BinaryDilation( in, out, -2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 201 ); dip::BinaryErosion( out, out, -2, 7 ); DOCTEST_CHECK( dip::Count( out ) == 1 ); DOCTEST_CHECK( out.At( 32, 20 ) == 1 ); } #endif // DIP__ENABLE_DOCTEST <|endoftext|>
<commit_before>/* Proxy for the crypto project. Simply creates a new thread for each incoming connection and forwards its data Derived from code at http://www.cs.rpi.edu/~goldsd/docs/spring2015-csci4210/server.c.txt */ #include <sys/socket.h> #include <iostream> #include <thread> #include <cstdlib> #include <cstdio> #include <unistd.h> #include <netinet/in.h> #include <signal.h> #include "constants.h" using namespace std; //Evil global variables because it's simplest to do it this way int send_port; int listener_socket; //Load tested via for i in $(seq 1 10000); do (nc localhost 8080 &) ; done void handle_control_c(int s){ close(listener_socket); exit(0); } void handleConnection(int sd){ cout << "Connection handled on sd " << sd << endl; close(sd); } int main(int argc, char* argv[]){ if(argc != 3){ cout << "Proxy takes arguments <listen port> <send port>" << endl; return EXIT_FAILURE; } //Get ports int listen_port = (unsigned short) atoi(argv[1]); send_port = (unsigned short) atoi(argv[2]); if( listen_port > 65535 || send_port > 65535 ){ cout << "Port larger than supported value" << endl; return EXIT_FAILURE; } //Create listener socket listener_socket = socket( PF_INET, SOCK_STREAM, 0 ); if ( listener_socket < 0 ){ cerr << "Socket creation failed" << endl; return EXIT_FAILURE; } signal(SIGINT, &handle_control_c); //Bind socket struct sockaddr_in server; server.sin_family = PF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(listen_port); int len = sizeof(server); if ( bind( listener_socket, (struct sockaddr *)&server, len ) < 0 ){ cerr << "Bind failed" << endl; return EXIT_FAILURE; } //Start listening listen(listener_socket, MAX_CLIENTS); struct sockaddr_in client; int fromlen = sizeof(client); while(true){ int client_sock = accept(listener_socket, (struct sockaddr *) &client, (socklen_t*) &fromlen); if(client_sock < 0){ cerr << "Failed to accept connection" << endl; continue; } thread client_thread(handleConnection, client_sock); client_thread.detach(); } }<commit_msg>Finished proxy except for the fact that it doesn't work<commit_after>/* Proxy for the crypto project. Simply creates a new thread for each incoming connection and forwards its data Derived from code at http://www.cs.rpi.edu/~goldsd/docs/spring2015-csci4210/server.c.txt */ #include <sys/socket.h> #include <iostream> #include <thread> #include <cstdlib> #include <cstdio> #include <unistd.h> #include <netinet/in.h> #include <signal.h> #include <sys/epoll.h> #include "constants.h" #define MAX_EVENTS 2 #define NUM_BYTES_FORWARD 1024 using namespace std; //Evil global variables because it's simplest to do it this way unsigned short send_port; int listener_socket; //Close socket on ^C void handle_control_c(int s){ close(listener_socket); exit(EXIT_SUCCESS); } //Forwards data from one socket to the other int forwardData(int in_sd, int out_sd){ ssize_t num_bytes_read, num_bytes_sent; char buffer[NUM_BYTES_FORWARD]; num_bytes_read = recv(in_sd, buffer, (size_t)NUM_BYTES_FORWARD, 0); if(num_bytes_read == 0){ return 0; } else if(num_bytes_read < 0){ return -1; } num_bytes_sent = send(out_sd, buffer, (size_t) num_bytes_read, 0); if(num_bytes_sent != num_bytes_read){ return -1; } return num_bytes_sent; } //Handle an incoming connection from an ATM //Load tested via "for i in $(seq 1 10000); do (nc localhost 8080 &) ; done" void handleConnection(int client_sd){ cout << "Start" << endl; //Create a socket for the connection to the bank int server_sd = socket(AF_INET, SOCK_STREAM, 0); if(server_sd < 0){ cerr << "Failed to create socket for connection to bank" << endl; close(client_sd); return; } cout << "Server socket created" << endl; struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_LOOPBACK; server.sin_port = htons(send_port); //Connect to the bank if( connect(server_sd, (struct sockaddr*) &server, sizeof(server)) < 0 ){ cerr << "Failed to connect to bank" << endl; close(client_sd); close(server_sd); return; } cout << "Connected to bank" << endl; //Create epoll int epoll_fd = epoll_create1(0); if(epoll_fd < 0){ cerr << "epoll creation failed" << endl; close(client_sd); close(server_sd); return; } cout << "Epoll created" << endl; //Setup epoll struct epoll_event ev, events[MAX_EVENTS]; ev.events = EPOLLIN; ev.data.fd = client_sd; if( epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_sd, &ev) < 0 ){ cerr << "Failed to setup epoll for atm" << endl; close(client_sd); close(server_sd); close(epoll_fd); return; } ev.data.fd = server_sd; if( epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_sd, &ev) < 0 ){ cerr << "Failed to setup epoll for bank" << endl; close(client_sd); close(server_sd); close(epoll_fd); return; } //Listen for any data and forward it int num_fds, rc; while(true){ num_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); for(int i = 0; i < num_fds; i++){ if(events[i].data.fd == client_sd){ cout << "Received data from client" << endl; rc = forwardData(client_sd, server_sd); } else{ cout << "Received data from server" << endl; rc = forwardData(server_sd, client_sd); } if(rc == -1){ cerr << "Error forwarding data" << endl; close(client_sd); close(server_sd); close(epoll_fd); return; } else if(rc == 0){ cerr << "Connection closed" << endl; close(client_sd); close(server_sd); close(epoll_fd); return; } } } close(client_sd); close(server_sd); close(epoll_fd); } //Listens for connections on the specified port and creates a thread to handle each one int main(int argc, char* argv[]){ if(argc != 3){ cout << "Proxy takes arguments <listen port> <send port>" << endl; return EXIT_FAILURE; } //Get ports unsigned short listen_port = (unsigned short) atoi(argv[1]); send_port = (unsigned short) atoi(argv[2]); if( listen_port > 65535 || send_port > 65535 ){ cout << "Port larger than supported value" << endl; return EXIT_FAILURE; } //Create listener socket listener_socket = socket( AF_INET, SOCK_STREAM, 0 ); if ( listener_socket < 0 ){ cerr << "Socket creation failed" << endl; return EXIT_FAILURE; } signal(SIGINT, &handle_control_c); //Bind socket struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(listen_port); int len = sizeof(server); if ( bind( listener_socket, (struct sockaddr *) &server, len ) < 0 ){ cerr << "Bind failed" << endl; return EXIT_FAILURE; } //Start listening listen(listener_socket, MAX_CLIENTS); struct sockaddr_in client; int fromlen = sizeof(client); while(true){ int client_sd = accept(listener_socket, (struct sockaddr *) &client, (socklen_t*) &fromlen); if(client_sd < 0){ cerr << "Failed to accept connection" << endl; continue; } thread client_thread(handleConnection, client_sd); client_thread.detach(); } }<|endoftext|>
<commit_before>/* Copyright 2016 Fixstars Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include <libsgm.h> #include "internal.h" namespace sgm { static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; } static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; } struct CudaStereoSGMResources { void* d_src_left; void* d_src_right; void* d_left; void* d_right; void* d_scost; void* d_matching_cost; void* d_left_disp; void* d_right_disp; void* d_tmp_left_disp; void* d_tmp_right_disp; cudaStream_t cuda_streams[8]; void* d_output_16bit_buffer; uint16_t* h_output_16bit_buffer; CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) { if (is_cuda_input(inout_type_)) { this->d_src_left = NULL; this->d_src_right = NULL; } else { CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_)); } CudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamCreate(&this->cuda_streams[i])); } // create temporary buffer when dst type is 8bit host pointer if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { this->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_); } else { this->h_output_16bit_buffer = NULL; } } ~CudaStereoSGMResources() { CudaSafeCall(cudaFree(this->d_src_left)); CudaSafeCall(cudaFree(this->d_src_right)); CudaSafeCall(cudaFree(this->d_left)); CudaSafeCall(cudaFree(this->d_right)); CudaSafeCall(cudaFree(this->d_matching_cost)); CudaSafeCall(cudaFree(this->d_scost)); CudaSafeCall(cudaFree(this->d_left_disp)); CudaSafeCall(cudaFree(this->d_right_disp)); CudaSafeCall(cudaFree(this->d_tmp_left_disp)); CudaSafeCall(cudaFree(this->d_tmp_right_disp)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamDestroy(this->cuda_streams[i])); } free(h_output_16bit_buffer); } }; StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) : width_(width), height_(height), disparity_size_(disparity_size), input_depth_bits_(input_depth_bits), output_depth_bits_(output_depth_bits), inout_type_(inout_type), cu_res_(NULL) { // check values if (width_ % 2 != 0 || height_ % 2 != 0) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("width and height must be even"); } if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("depth bits must be 8 or 16"); } if (disparity_size_ != 64 && disparity_size_ != 128) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("disparity size must be 64 or 128"); } cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_); } StereoSGM::~StereoSGM() { if (cu_res_) { delete cu_res_; } } void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) { const void *d_input_left, *d_input_right; if (is_cuda_input(inout_type_)) { d_input_left = left_pixels; d_input_right = right_pixels; } else { CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); d_input_left = cu_res_->d_src_left; d_input_right = cu_res_->d_src_right; } sgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]); sgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]); CudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4])); sgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_); sgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams); cudaStreamSynchronize(cu_res_->cuda_streams[2]); cudaStreamSynchronize(cu_res_->cuda_streams[3]); sgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_); sgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_); sgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_); sgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_); // output disparity image void* disparity_image = cu_res_->d_tmp_left_disp; if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) { CudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) { *dst = disparity_image; // optimize! no-copy! } else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { CudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); for (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; } } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) { sgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_); } else { std::cerr << "not impl" << std::endl; } } } <commit_msg>zero clear tmp_disp<commit_after>/* Copyright 2016 Fixstars Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include <libsgm.h> #include "internal.h" namespace sgm { static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; } static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; } struct CudaStereoSGMResources { void* d_src_left; void* d_src_right; void* d_left; void* d_right; void* d_scost; void* d_matching_cost; void* d_left_disp; void* d_right_disp; void* d_tmp_left_disp; void* d_tmp_right_disp; cudaStream_t cuda_streams[8]; void* d_output_16bit_buffer; uint16_t* h_output_16bit_buffer; CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) { if (is_cuda_input(inout_type_)) { this->d_src_left = NULL; this->d_src_right = NULL; } else { CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_)); } CudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamCreate(&this->cuda_streams[i])); } // create temporary buffer when dst type is 8bit host pointer if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { this->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_); } else { this->h_output_16bit_buffer = NULL; } } ~CudaStereoSGMResources() { CudaSafeCall(cudaFree(this->d_src_left)); CudaSafeCall(cudaFree(this->d_src_right)); CudaSafeCall(cudaFree(this->d_left)); CudaSafeCall(cudaFree(this->d_right)); CudaSafeCall(cudaFree(this->d_matching_cost)); CudaSafeCall(cudaFree(this->d_scost)); CudaSafeCall(cudaFree(this->d_left_disp)); CudaSafeCall(cudaFree(this->d_right_disp)); CudaSafeCall(cudaFree(this->d_tmp_left_disp)); CudaSafeCall(cudaFree(this->d_tmp_right_disp)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamDestroy(this->cuda_streams[i])); } free(h_output_16bit_buffer); } }; StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) : width_(width), height_(height), disparity_size_(disparity_size), input_depth_bits_(input_depth_bits), output_depth_bits_(output_depth_bits), inout_type_(inout_type), cu_res_(NULL) { // check values if (width_ % 2 != 0 || height_ % 2 != 0) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("width and height must be even"); } if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("depth bits must be 8 or 16"); } if (disparity_size_ != 64 && disparity_size_ != 128) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("disparity size must be 64 or 128"); } cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_); } StereoSGM::~StereoSGM() { if (cu_res_) { delete cu_res_; } } void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) { const void *d_input_left, *d_input_right; if (is_cuda_input(inout_type_)) { d_input_left = left_pixels; d_input_right = right_pixels; } else { CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); d_input_left = cu_res_->d_src_left; d_input_right = cu_res_->d_src_right; } sgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]); sgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]); CudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4])); sgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_); sgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams); cudaStreamSynchronize(cu_res_->cuda_streams[2]); cudaStreamSynchronize(cu_res_->cuda_streams[3]); sgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_); sgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_); sgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_); sgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_); // output disparity image void* disparity_image = cu_res_->d_tmp_left_disp; if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) { CudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) { *dst = disparity_image; // optimize! no-copy! } else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { CudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); for (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; } } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) { sgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_); } else { std::cerr << "not impl" << std::endl; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Daniele E. Domenichelli <[email protected]> * Copyright (C) 1999 Preston Brown <[email protected]> * * 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 */ #include "telepathy-handler-application.h" #include <QTimer> #include <KCmdLineArgs> #include <KDebug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Debug> extern bool kde_kdebug_enable_dbus_interface; namespace KTelepathy { namespace { int s_tpqt4DebugArea; static void tpDebugCallback(const QString &libraryName, const QString &libraryVersion, QtMsgType type, const QString &msg) { Q_UNUSED(libraryName) Q_UNUSED(libraryVersion) kDebugStream(type, s_tpqt4DebugArea, __FILE__, __LINE__, "Telepathy-Qt4") << qPrintable(msg); } } class TelepathyHandlerApplication::Private { public: Private(TelepathyHandlerApplication *q); ~Private(); void _k_onInitialTimeout(); void _k_onTimeout(); static KComponentData initHack(); void init(int initialTimeout, int timeout); TelepathyHandlerApplication *q; static bool s_persist; static bool s_debug; int initialTimeout; int timeout; QTimer *timer; bool firstJobStarted; QAtomicInt jobCount; }; TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q) : q(q), firstJobStarted(false), jobCount(0) { } TelepathyHandlerApplication::Private::~Private() { } void TelepathyHandlerApplication::Private::_k_onInitialTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "No job received. Exiting"; QCoreApplication::quit(); } } void TelepathyHandlerApplication::Private::_k_onTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "Timeout. Exiting"; QCoreApplication::quit(); } } // this gets called before even entering QApplication::QApplication() KComponentData TelepathyHandlerApplication::Private::initHack() { KComponentData cData(KCmdLineArgs::aboutData()); KCmdLineOptions handler_options; handler_options.add("persist", ki18n("Persistent mode (do not exit on timeout)")); handler_options.add("debug", ki18n("Show Telepathy debugging information")); KCmdLineArgs::addCmdLineOptions(handler_options, ki18n("KDE Telepathy"), "kde-telepathy", "kde"); KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde-telepathy"); Private::s_persist = args->isSet("persist"); Private::s_debug = args->isSet("debug"); s_tpqt4DebugArea = KDebug::registerArea("Telepathy-Qt4"); return cData; } void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout) { this->initialTimeout = initialTimeout; this->timeout = timeout; // If timeout < 0 we let the application exit when the last window is closed, // Otherwise we handle it with the timeout if (timeout >= 0) { q->setQuitOnLastWindowClosed(false); } // Register TpQt4 types Tp::registerTypes(); // Redirect Tp debug and warnings to KDebug output Tp::setDebugCallback(&tpDebugCallback); // Enable telepathy-Qt4 debug Tp::enableDebug(s_debug); Tp::enableWarnings(true); // Enable KDebug DBus interface // FIXME This must be enabled here because there is a bug in plasma // it should be removed when this is fixed kde_kdebug_enable_dbus_interface = s_debug; if (!Private::s_persist) { timer = new QTimer(q); if (initialTimeout >= 0) { q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout())); timer->start(initialTimeout); } } } bool TelepathyHandlerApplication::Private::s_persist = false; bool TelepathyHandlerApplication::Private::s_debug = false; TelepathyHandlerApplication::TelepathyHandlerApplication(bool GUIenabled, int initialTimeout, int timeout) : KApplication(GUIenabled, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::TelepathyHandlerApplication(Display *display, Qt::HANDLE visual, Qt::HANDLE colormap, int initialTimeout, int timeout) : KApplication(display, visual, colormap, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::~TelepathyHandlerApplication() { delete d; } int TelepathyHandlerApplication::newJob() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; int ret = d->jobCount.fetchAndAddOrdered(1); if (!Private::s_persist) { if (d->timer->isActive()) { d->timer->stop(); } if (!d->firstJobStarted) { if (d->initialTimeout) { disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout())); } if (d->timeout >= 0) { connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout())); } d->firstJobStarted = true; } } return ret; } void TelepathyHandlerApplication::jobFinished() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; if (d->jobCount.fetchAndAddOrdered(-1) <= 1) { if (!Private::s_persist && d->timeout >= 0) { kDebug() << "No other jobs at the moment. Starting timer."; d->timer->start(d->timeout); } } } } // namespace KTelepathy #include "telepathy-handler-application.moc" <commit_msg>Fix crash in debug callback<commit_after>/* * Copyright (C) 2011 Daniele E. Domenichelli <[email protected]> * Copyright (C) 1999 Preston Brown <[email protected]> * * 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 */ #include "telepathy-handler-application.h" #include <QTimer> #include <KCmdLineArgs> #include <KDebug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Debug> extern bool kde_kdebug_enable_dbus_interface; namespace KTelepathy { namespace { int s_tpqt4DebugArea; static void tpDebugCallback(const QString &libraryName, const QString &libraryVersion, QtMsgType type, const QString &msg) { Q_UNUSED(libraryName) Q_UNUSED(libraryVersion) kDebugStream(type, s_tpqt4DebugArea, __FILE__, __LINE__, 0) << qPrintable(msg); } } class TelepathyHandlerApplication::Private { public: Private(TelepathyHandlerApplication *q); ~Private(); void _k_onInitialTimeout(); void _k_onTimeout(); static KComponentData initHack(); void init(int initialTimeout, int timeout); TelepathyHandlerApplication *q; static bool s_persist; static bool s_debug; int initialTimeout; int timeout; QTimer *timer; bool firstJobStarted; QAtomicInt jobCount; }; TelepathyHandlerApplication::Private::Private(TelepathyHandlerApplication *q) : q(q), firstJobStarted(false), jobCount(0) { } TelepathyHandlerApplication::Private::~Private() { } void TelepathyHandlerApplication::Private::_k_onInitialTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "No job received. Exiting"; QCoreApplication::quit(); } } void TelepathyHandlerApplication::Private::_k_onTimeout() { if (jobCount == 0 && jobCount.fetchAndAddOrdered(-1) == 0) { // m_jobCount is now -1 kDebug() << "Timeout. Exiting"; QCoreApplication::quit(); } } // this gets called before even entering QApplication::QApplication() KComponentData TelepathyHandlerApplication::Private::initHack() { KComponentData cData(KCmdLineArgs::aboutData()); KCmdLineOptions handler_options; handler_options.add("persist", ki18n("Persistent mode (do not exit on timeout)")); handler_options.add("debug", ki18n("Show Telepathy debugging information")); KCmdLineArgs::addCmdLineOptions(handler_options, ki18n("KDE Telepathy"), "kde-telepathy", "kde"); KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde-telepathy"); Private::s_persist = args->isSet("persist"); Private::s_debug = args->isSet("debug"); s_tpqt4DebugArea = KDebug::registerArea("Telepathy-Qt4"); return cData; } void TelepathyHandlerApplication::Private::init(int initialTimeout, int timeout) { this->initialTimeout = initialTimeout; this->timeout = timeout; // If timeout < 0 we let the application exit when the last window is closed, // Otherwise we handle it with the timeout if (timeout >= 0) { q->setQuitOnLastWindowClosed(false); } // Register TpQt4 types Tp::registerTypes(); // Redirect Tp debug and warnings to KDebug output Tp::setDebugCallback(&tpDebugCallback); // Enable telepathy-Qt4 debug Tp::enableDebug(s_debug); Tp::enableWarnings(true); // Enable KDebug DBus interface // FIXME This must be enabled here because there is a bug in plasma // it should be removed when this is fixed kde_kdebug_enable_dbus_interface = s_debug; if (!Private::s_persist) { timer = new QTimer(q); if (initialTimeout >= 0) { q->connect(timer, SIGNAL(timeout()), q, SLOT(_k_onInitialTimeout())); timer->start(initialTimeout); } } } bool TelepathyHandlerApplication::Private::s_persist = false; bool TelepathyHandlerApplication::Private::s_debug = false; TelepathyHandlerApplication::TelepathyHandlerApplication(bool GUIenabled, int initialTimeout, int timeout) : KApplication(GUIenabled, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::TelepathyHandlerApplication(Display *display, Qt::HANDLE visual, Qt::HANDLE colormap, int initialTimeout, int timeout) : KApplication(display, visual, colormap, Private::initHack()), d(new Private(this)) { d->init(initialTimeout, timeout); } TelepathyHandlerApplication::~TelepathyHandlerApplication() { delete d; } int TelepathyHandlerApplication::newJob() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; int ret = d->jobCount.fetchAndAddOrdered(1); if (!Private::s_persist) { if (d->timer->isActive()) { d->timer->stop(); } if (!d->firstJobStarted) { if (d->initialTimeout) { disconnect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onInitialTimeout())); } if (d->timeout >= 0) { connect(d->timer, SIGNAL(timeout()), app, SLOT(_k_onTimeout())); } d->firstJobStarted = true; } } return ret; } void TelepathyHandlerApplication::jobFinished() { TelepathyHandlerApplication *app = qobject_cast<TelepathyHandlerApplication*>(KApplication::kApplication()); TelepathyHandlerApplication::Private *d = app->d; if (d->jobCount.fetchAndAddOrdered(-1) <= 1) { if (!Private::s_persist && d->timeout >= 0) { kDebug() << "No other jobs at the moment. Starting timer."; d->timer->start(d->timeout); } } } } // namespace KTelepathy #include "telepathy-handler-application.moc" <|endoftext|>
<commit_before> #pragma once #include <proxc.hpp> #include <stdlib.h> // posix_memalign #include <new> #include <type_traits> PROXC_NAMESPACE_BEGIN void* aligned_alloc(std::size_t size, std::size_t align) { #ifdef _WIN32 void *ptr = _aligned_malloc(size, align); if (!ptr) { throw std::bad_alloc(); } return ptr; #else void *ptr; if (posix_memalign(&ptr, align, size)) { throw std::bad_alloc(); } return ptr; #endif } void aligned_free(void* addr) noexcept { #ifdef _WIN32 _aligned_free(addr); #else free(addr); #endif } template<typename T, std::size_t Align = std::alignment_of<T>::value> class AlignedArray { public: AlignedArray() : m_length(0), m_ptr(nullptr) {} AlignedArray(std::nullptr_t) : m_length(0), m_ptr(nullptr) {} explicit AlignedArray(std::size_t length) : m_length(length) { m_ptr = static_cast<T*>(aligned_alloc(length * sizeof(T), Align)); std::size_t i; try { for (i = 0; i < m_length; ++i) { new(m_ptr + i) T; } } catch(...) { for (std::size_t j = 0; j < i; ++j) { m_ptr[i].~T(); throw; } } } AlignedArray(AlignedArray&& other) noexcept : m_length(other.m_length), m_ptr(other.m_ptr) { } AlignedArray& operator=(std::nullptr_t) { return *this = AlignedArray(); } ~AlignedArray() { for (std::size_t i = 0; i < m_length; ++i) { m_ptr[i].~T(); } aligned_free(m_ptr); } T& operator[](std::size_t i) const { return m_ptr[i]; } std::size_t size() const { return m_length; } T* get() const { return m_ptr; } explicit operator bool() const { return m_ptr != nullptr; } private: std::size_t m_length; T* m_ptr; }; PROXC_NAMESPACE_END <commit_msg>Forgot impl of move constructor for AlignedArray<commit_after> #pragma once #include <proxc.hpp> #include <stdlib.h> // posix_memalign #include <new> #include <type_traits> PROXC_NAMESPACE_BEGIN void* aligned_alloc(std::size_t size, std::size_t align) { #ifdef _WIN32 void *ptr = _aligned_malloc(size, align); if (!ptr) { throw std::bad_alloc(); } return ptr; #else void *ptr; if (posix_memalign(&ptr, align, size)) { throw std::bad_alloc(); } return ptr; #endif } void aligned_free(void* addr) noexcept { #ifdef _WIN32 _aligned_free(addr); #else free(addr); #endif } template<typename T, std::size_t Align = std::alignment_of<T>::value> class AlignedArray { public: AlignedArray() : m_length(0), m_ptr(nullptr) {} AlignedArray(std::nullptr_t) : m_length(0), m_ptr(nullptr) {} explicit AlignedArray(std::size_t length) : m_length(length) { m_ptr = static_cast<T*>(aligned_alloc(length * sizeof(T), Align)); std::size_t i; try { for (i = 0; i < m_length; ++i) { new(m_ptr + i) T; } } catch(...) { for (std::size_t j = 0; j < i; ++j) { m_ptr[i].~T(); throw; } } } AlignedArray(AlignedArray&& other) noexcept : m_length(other.m_length), m_ptr(other.m_ptr) { other.m_ptr = nullptr; other.m_length = 0; } AlignedArray& operator=(std::nullptr_t) { return *this = AlignedArray(); } ~AlignedArray() { for (std::size_t i = 0; i < m_length; ++i) { m_ptr[i].~T(); } aligned_free(m_ptr); } T& operator[](std::size_t i) const { return m_ptr[i]; } std::size_t size() const { return m_length; } T* get() const { return m_ptr; } explicit operator bool() const { return m_ptr != nullptr; } private: std::size_t m_length; T* m_ptr; }; PROXC_NAMESPACE_END <|endoftext|>
<commit_before>#include "prune.hpp" namespace vg { constexpr size_t PRUNE_THREAD_BUFFER_SIZE = 128 * 1024; pair_hash_set<edge_t> find_edges_to_prune(const HandleGraph& graph, size_t k, size_t edge_max) { // Each thread collects edges to be deleted into a separate buffer. When the buffer grows // large enough, flush it into a shared hash set. pair_hash_set<edge_t> result; auto flush_buffer = [&result](pair_hash_set<edge_t>& buffer) { #pragma omp critical (prune_flush) { for (const edge_t& edge : buffer) { result.insert(edge); } } buffer.clear(); }; // for each position on the forward and reverse of the graph std::vector<pair_hash_set<edge_t>> buffers(get_thread_count()); graph.for_each_handle([&](const handle_t& h) { // for the forward and reverse of this handle // walk k bases from the end, so that any kmer starting on the node will be represented in the tree we build for (auto handle_is_rev : { false, true }) { //cerr << "###########################################" << endl; handle_t handle = handle_is_rev ? graph.flip(h) : h; list<walk_t> walks; // for each position in the node, set up a kmer with that start position and the node end or kmer length as the end position // determine next positions id_t handle_id = graph.get_id(handle); size_t handle_length = graph.get_length(handle); string handle_seq = graph.get_sequence(handle); for (size_t i = 0; i < handle_length; ++i) { pos_t begin = make_pos_t(handle_id, handle_is_rev, handle_length); pos_t end = make_pos_t(handle_id, handle_is_rev, min(handle_length, i+k)); walk_t walk = walk_t(offset(end)-offset(begin), begin, end, handle, 0); if (walk.length < k) { // are we branching over more than one edge? size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); } else { walks.push_back(walk); } } // now expand the kmers until they reach k while (!walks.empty()) { // first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list auto walks_end = walks.end(); for (list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) { auto& walk = *q; // did we reach our target length? if (walk.length >= k) { q = walks.erase(q); } else { id_t curr_id = graph.get_id(walk.curr); size_t curr_length = graph.get_length(walk.curr); bool curr_is_rev = graph.get_is_reverse(walk.curr); size_t take = min(curr_length, k-walk.length); walk.end = make_pos_t(curr_id, curr_is_rev, take); walk.length += take; if (walk.length < k) { // if not, we need to expand through the node then follow on size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); q = walks.erase(q); } else { // nothing, we'll remove it next time around } } } } } }, true); // Flush the buffers and return the result. for (pair_hash_set<edge_t>& buffer : buffers) { flush_buffer(buffer); } return result; } } <commit_msg>Use DFS in prune<commit_after>#include "prune.hpp" #include <stack> namespace vg { constexpr size_t PRUNE_THREAD_BUFFER_SIZE = 128 * 1024; pair_hash_set<edge_t> find_edges_to_prune(const HandleGraph& graph, size_t k, size_t edge_max) { // Each thread collects edges to be deleted into a separate buffer. When the buffer grows // large enough, flush it into a shared hash set. pair_hash_set<edge_t> result; auto flush_buffer = [&result](pair_hash_set<edge_t>& buffer) { #pragma omp critical (prune_flush) { for (const edge_t& edge : buffer) { result.insert(edge); } } buffer.clear(); }; // for each position on the forward and reverse of the graph std::vector<pair_hash_set<edge_t>> buffers(get_thread_count()); graph.for_each_handle([&](const handle_t& h) { // for the forward and reverse of this handle // walk k bases from the end, so that any kmer starting on the node will be represented in the tree we build for (auto handle_is_rev : { false, true }) { handle_t handle = handle_is_rev ? graph.flip(h) : h; std::stack<walk_t> walks; // for each position in the node, set up a kmer with that start position and the node end or kmer length as the end position // determine next positions id_t handle_id = graph.get_id(handle); size_t handle_length = graph.get_length(handle); for (size_t i = 0; i < handle_length; i++) { pos_t begin = make_pos_t(handle_id, handle_is_rev, handle_length); pos_t end = make_pos_t(handle_id, handle_is_rev, std::min(handle_length, i + k)); // We are only interested in walks that did not reach length k in the initial node. if (offset(end) - offset(begin) < k) { size_t outdegree = graph.get_degree(handle, false); graph.follow_edges(handle, false, [&](const handle_t& next) { if (outdegree > 1 && edge_max == 0) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(handle, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walk_t walk(offset(end) - offset(begin), begin, end, next, 0); if (outdegree > 1) { walk.forks++; } walks.push(walk); } }); } } // Now expand the kmers until they reach k. while (!walks.empty()) { walk_t walk = walks.top(); walks.pop(); // Did we reach our target length? if (walk.length >= k) { continue; } id_t curr_id = graph.get_id(walk.curr); size_t curr_length = graph.get_length(walk.curr); bool curr_is_rev = graph.get_is_reverse(walk.curr); size_t take = min(curr_length, k - walk.length); walk.end = make_pos_t(curr_id, curr_is_rev, take); walk.length += take; // Do we need to continue to the successor nodes? if (walk.length < k) { size_t outdegree = graph.get_degree(walk.curr, false); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (outdegree > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walk_t next_walk = walk; next_walk.curr = next; if (outdegree > 1) { next_walk.forks++; } walks.push(next_walk); } }); } } } }, true); // Flush the buffers and return the result. for (pair_hash_set<edge_t>& buffer : buffers) { flush_buffer(buffer); } return result; } } <|endoftext|>
<commit_before><commit_msg>coverity#1194898 Logically dead code<commit_after><|endoftext|>
<commit_before>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include <vector> #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/IR/TypeBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5) #include "llvm/IR/InstIterator.h" #else #include "llvm/Support/InstIterator.h" #endif #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; class RemoveInfiniteLoops : public FunctionPass { public: static char ID; RemoveInfiniteLoops() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F); }; static RegisterPass<RemoveInfiniteLoops> RIL("remove-infinite-loops", "delete patterns like LABEL: goto LABEL" "and replace them with exit(0)"); char RemoveInfiniteLoops::ID; bool RemoveInfiniteLoops::runOnFunction(Function &F) { Module *M = F.getParent(); std::vector<BasicBlock *> to_process; for (BasicBlock& block : F) { // if this is a block that jumps on itself (it has the only instruction // which is the jump) if (block.size() == 1 && block.getSingleSuccessor() == &block) to_process.push_back(&block); } if (to_process.empty()) return false; CallInst* ext; LLVMContext& Ctx = M->getContext(); Type *argTy = Type::getInt32Ty(Ctx); Function *extF = cast<Function>(M->getOrInsertFunction("exit", Type::getVoidTy(Ctx), argTy, nullptr)); std::vector<Value *> args = { ConstantInt::get(argTy, 0) }; for (BasicBlock *block : to_process) { Instruction *T = block->getTerminator(); ext = CallInst::Create(extF, args); ext->insertBefore(T); // replace the jump with unreachable, since exit will terminate // the computation new UnreachableInst(Ctx, T); T->eraseFromParent(); } llvm::errs() << "Removed infinite loop in " << F.getName().data() << "\n"; return true; } <commit_msg>RemoveInfiniteLoops: clone metadata too<commit_after>// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include <vector> #include "llvm/IR/DataLayout.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/Type.h" #include "llvm/IR/TypeBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5) #include "llvm/IR/InstIterator.h" #else #include "llvm/Support/InstIterator.h" #endif #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; class RemoveInfiniteLoops : public FunctionPass { public: static char ID; RemoveInfiniteLoops() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F); }; static RegisterPass<RemoveInfiniteLoops> RIL("remove-infinite-loops", "delete patterns like LABEL: goto LABEL" "and replace them with exit(0)"); char RemoveInfiniteLoops::ID; void CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2); bool RemoveInfiniteLoops::runOnFunction(Function &F) { Module *M = F.getParent(); std::vector<BasicBlock *> to_process; for (BasicBlock& block : F) { // if this is a block that jumps on itself (it has the only instruction // which is the jump) if (block.size() == 1 && block.getSingleSuccessor() == &block) to_process.push_back(&block); } if (to_process.empty()) return false; CallInst* ext; LLVMContext& Ctx = M->getContext(); Type *argTy = Type::getInt32Ty(Ctx); Function *extF = cast<Function>(M->getOrInsertFunction("exit", Type::getVoidTy(Ctx), argTy, nullptr)); std::vector<Value *> args = { ConstantInt::get(argTy, 0) }; for (BasicBlock *block : to_process) { Instruction *T = block->getTerminator(); ext = CallInst::Create(extF, args); CloneMetadata(&*(block->begin()), ext); ext->insertBefore(T); // replace the jump with unreachable, since exit will terminate // the computation new UnreachableInst(Ctx, T); T->eraseFromParent(); } llvm::errs() << "Removed infinite loop in " << F.getName().data() << "\n"; return true; } <|endoftext|>
<commit_before>//============================================================================ // Name : jaco_arm.cpp // Author : WPI, Clearpath Robotics // Version : 0.5 // Copyright : BSD // Description : A ROS driver for controlling the Kinova Jaco robotic manipulator arm //============================================================================ #include "jaco_driver/jaco_arm.h" namespace jaco { JacoArm::JacoArm(JacoComm &arm_comm, ros::NodeHandle &nh) : arm(arm_comm) { std::string joint_velocity_topic, joint_angles_topic, cartesian_velocity_topic, tool_position_topic, set_finger_position_topic, finger_position_topic, joint_state_topic, set_joint_angle_topic; nh.param<std::string>("joint_velocity_topic", joint_velocity_topic, "joint_velocity"); nh.param<std::string>("joint_angles_topic", joint_angles_topic, "joint_angles"); nh.param<std::string>("cartesian_velocity_topic", cartesian_velocity_topic, "cartesian_velocity"); nh.param<std::string>("tool_position_topic", tool_position_topic, "tool_position"); nh.param<std::string>("set_finger_position_topic", set_finger_position_topic, "set_finger_position"); nh.param<std::string>("finger_position_topic", finger_position_topic, "finger_position"); nh.param<std::string>("joint_state_topic", joint_state_topic, "joint_state"); nh.param<std::string>("set_joint_angle_topic", set_joint_angle_topic, "set_joint_angle"); //Print out received topics ROS_DEBUG("Got Joint Velocity Topic Name: <%s>", joint_velocity_topic.c_str()); ROS_DEBUG("Got Joint Angles Topic Name: <%s>", joint_angles_topic.c_str()); ROS_DEBUG("Got Cartesian Velocity Topic Name: <%s>", cartesian_velocity_topic.c_str()); ROS_DEBUG("Got Tool Position Topic Name: <%s>", tool_position_topic.c_str()); ROS_DEBUG("Got Set Finger Position Topic Name: <%s>", set_finger_position_topic.c_str()); ROS_DEBUG("Got Finger Position Topic Name: <%s>", finger_position_topic.c_str()); ROS_DEBUG("Got Joint State Topic Name: <%s>", joint_state_topic.c_str()); ROS_DEBUG("Got Set Joint Angle Topic Name: <%s>", set_joint_angle_topic.c_str()); ROS_INFO("Starting Up Jaco Arm Controller..."); previous_state = 0; /* Set up Services */ stop_service = nh.advertiseService("stop", &JacoArm::StopSRV, this); start_service = nh.advertiseService("start", &JacoArm::StartSRV, this); homing_service = nh.advertiseService("home_arm", &JacoArm::HomeArmSRV, this); /* Set Default Configuration */ // API->RestoreFactoryDefault(); // uncomment comment ONLY if you want to lose your settings on each launch. ClientConfigurations configuration; arm.GetConfig(configuration); arm.PrintConfig(configuration); last_update_time = ros::Time::now(); update_time = ros::Duration(5.0); /* Storing arm in home position */ /* Set up Publishers */ JointAngles_pub = nh.advertise<jaco_driver::JointAngles>(joint_angles_topic, 2); JointState_pub = nh.advertise<sensor_msgs::JointState>(joint_state_topic, 2); ToolPosition_pub = nh.advertise<geometry_msgs::PoseStamped>(tool_position_topic, 2); FingerPosition_pub = nh.advertise<jaco_driver::FingerPosition>(finger_position_topic, 2); /* Set up Subscribers*/ JointVelocity_sub = nh.subscribe(joint_velocity_topic, 1, &JacoArm::VelocityMSG, this); CartesianVelocity_sub = nh.subscribe(cartesian_velocity_topic, 1, &JacoArm::CartesianVelocityMSG, this); SetFingerPosition_sub = nh.subscribe(set_finger_position_topic, 1, &JacoArm::SetFingerPositionMSG, this); SetJoint_sub = nh.subscribe(set_joint_angle_topic, 1, &JacoArm::SetJointAnglesMSG, this); status_timer = nh.createTimer(ros::Duration(0.05), &JacoArm::StatusTimer, this); joint_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::JointVelTimer, this); joint_vel_timer.stop(); joint_vel_timer_flag = false; cartesian_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::CartesianVelTimer, this); cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; ROS_INFO("The Arm is ready to use."); TrajectoryPoint Jaco_Velocity; memset(&Jaco_Velocity, 0, sizeof(Jaco_Velocity)); //zero structure arm.SetCartesianVelocities(Jaco_Velocity.Position.CartesianPosition); } JacoArm::~JacoArm() { } bool JacoArm::HomeArmSRV(jaco_driver::HomeArm::Request &req, jaco_driver::HomeArm::Response &res) { arm.HomeArm(); res.homearm_result = "JACO ARM HAS BEEN RETURNED HOME"; return true; } /*! * \brief Receives ROS command messages and relays them to SetFingers. */ void JacoArm::SetFingerPositionMSG(const jaco_driver::FingerPositionConstPtr& finger_pos) { if (!arm.Stopped()) { FingersPosition Finger_Position; memset(&Finger_Position, 0, sizeof(Finger_Position)); //zero structure Finger_Position.Finger1 = finger_pos->Finger_1; Finger_Position.Finger2 = finger_pos->Finger_2; Finger_Position.Finger3 = finger_pos->Finger_3; arm.SetFingers(Finger_Position); } } /*! * \brief Receives ROS command messages and relays them to SetAngles. */ void JacoArm::SetJointAnglesMSG(const jaco_driver::JointAnglesConstPtr& msg) { if (!arm.Stopped()) { jaco_driver::JointAngles angles(*msg); JacoAngles position(angles); arm.SetAngles(position); } } void JacoArm::VelocityMSG(const jaco_driver::JointVelocityConstPtr& joint_vel) { if (!arm.Stopped()) { joint_velocities.Actuator1 = joint_vel->Velocity_J1; joint_velocities.Actuator2 = joint_vel->Velocity_J2; joint_velocities.Actuator3 = joint_vel->Velocity_J3; joint_velocities.Actuator4 = joint_vel->Velocity_J4; joint_velocities.Actuator5 = joint_vel->Velocity_J5; joint_velocities.Actuator6 = joint_vel->Velocity_J6; last_joint_update = ros::Time().now(); if (joint_vel_timer_flag == false) { joint_vel_timer.start(); joint_vel_timer_flag = true; } } } /*! * \brief Handler for "stop" service. * * Instantly stops the arm and prevents further movement until start service is * invoked. */ bool JacoArm::StopSRV(jaco_driver::Stop::Request &req, jaco_driver::Stop::Response &res) { arm.Stop(); res.stop_result = "JACO ARM HAS BEEN STOPPED"; ROS_DEBUG("JACO ARM STOP REQUEST"); return true; } /*! * \brief Handler for "start" service. * * Re-enables control of the arm after a stop. */ bool JacoArm::StartSRV(jaco_driver::Start::Request &req, jaco_driver::Start::Response &res) { arm.Start(); res.start_result = "JACO ARM CONTROL HAS BEEN ENABLED"; ROS_DEBUG("JACO ARM START REQUEST"); return true; } void JacoArm::CartesianVelocityMSG(const geometry_msgs::TwistStampedConstPtr& cartesian_vel) { if (!arm.Stopped()) { cartesian_velocities.X = cartesian_vel->twist.linear.x; cartesian_velocities.Y = cartesian_vel->twist.linear.y; cartesian_velocities.Z = cartesian_vel->twist.linear.z; cartesian_velocities.ThetaX = cartesian_vel->twist.angular.x; cartesian_velocities.ThetaY = cartesian_vel->twist.angular.y; cartesian_velocities.ThetaZ = cartesian_vel->twist.angular.z; last_cartesian_update = ros::Time().now(); if (cartesian_vel_timer_flag == false) { cartesian_vel_timer.start(); cartesian_vel_timer_flag = true; } } } void JacoArm::CartesianVelTimer(const ros::TimerEvent&) { arm.SetCartesianVelocities(cartesian_velocities); if ((ros::Time().now().toSec() - last_cartesian_update.toSec()) > 1) { cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; } } void JacoArm::JointVelTimer(const ros::TimerEvent&) { arm.SetVelocities(joint_velocities); if ((ros::Time().now().toSec() - last_joint_update.toSec()) > 1) { joint_vel_timer.stop(); joint_vel_timer_flag = false; } } /*! * \brief Contains coordinates for an alternate "Home" position * * GoHome() function must be enabled in the initialization routine for this to * work. */ void JacoArm::GoHome(void) { /* AngularInfo joint_home; joint_home.Actuator1 = 176.0; joint_home.Actuator2 = 111.0; joint_home.Actuator3 = 107.0; joint_home.Actuator4 = 459.0; joint_home.Actuator5 = 102.0; joint_home.Actuator6 = 106.0; SetAngles(joint_home, 10); //send joints to home position API->SetCartesianControl(); */ } /*! * \brief Publishes the current joint angles. * * Joint angles are published in both their raw state as obtained from the arm * (JointAngles), and transformed & converted to radians (joint_state) as per * the Jaco Kinematics PDF. * * JointState will eventually also publish the velocity and effort for each * joint, when this data is made available by the C++ API. Currenty velocity * and effort are reported as being zero (0.0) for all joints. */ void JacoArm::BroadCastAngles(void) { // Populate an array of joint names. arm_0_joint is the base, arm_5_joint is the wrist. const char* nameArgs[] = {"arm_0_joint", "arm_1_joint", "arm_2_joint", "arm_3_joint", "arm_4_joint", "arm_5_joint"}; std::vector<std::string> JointName(nameArgs, nameArgs+6); jaco_driver::JointAngles current_angles; sensor_msgs::JointState joint_state; joint_state.name = JointName; // Define array sizes for the joint_state topic joint_state.position.resize(6); joint_state.velocity.resize(6); joint_state.effort.resize(6); //Query arm for current joint angles JacoAngles arm_angles; arm.GetAngles(arm_angles); jaco_driver::JointAngles angles = arm_angles.Angles(); // Transform from Kinova DH algorithm to physical angles in radians, then place into vector array joint_state.position[0] = angles.Angle_J1; joint_state.position[1] = angles.Angle_J2; joint_state.position[2] = angles.Angle_J3; joint_state.position[3] = angles.Angle_J4; joint_state.position[4] = angles.Angle_J5; joint_state.position[5] = angles.Angle_J6; //Publish the joint state messages JointAngles_pub.publish(angles); // Publishes the raw joint angles in a custom message. JointState_pub.publish(joint_state); // Publishes the transformed angles in a standard sensor_msgs format. } /*! * \brief Publishes the current cartesian coordinates */ void JacoArm::BroadCastPosition(void) { JacoPose pose; geometry_msgs::PoseStamped current_position; arm.GetPosition(pose); current_position.pose = pose.Pose(); ToolPosition_pub.publish(current_position); } void JacoArm::BroadCastFingerPosition(void) { /* Publishes the current finger positions. */ CartesianPosition Jaco_Position; jaco_driver::FingerPosition finger_position; memset(&Jaco_Position, 0, sizeof(Jaco_Position)); //zero structure arm.GetFingers(Jaco_Position.Fingers); finger_position.Finger_1 = Jaco_Position.Fingers.Finger1; finger_position.Finger_2 = Jaco_Position.Fingers.Finger2; finger_position.Finger_3 = Jaco_Position.Fingers.Finger3; FingerPosition_pub.publish(finger_position); } void JacoArm::StatusTimer(const ros::TimerEvent&) { BroadCastAngles(); BroadCastPosition(); BroadCastFingerPosition(); } } <commit_msg>Send angles in degrees for tf_publisher.<commit_after>//============================================================================ // Name : jaco_arm.cpp // Author : WPI, Clearpath Robotics // Version : 0.5 // Copyright : BSD // Description : A ROS driver for controlling the Kinova Jaco robotic manipulator arm //============================================================================ #include "jaco_driver/jaco_arm.h" namespace jaco { JacoArm::JacoArm(JacoComm &arm_comm, ros::NodeHandle &nh) : arm(arm_comm) { std::string joint_velocity_topic, joint_angles_topic, cartesian_velocity_topic, tool_position_topic, set_finger_position_topic, finger_position_topic, joint_state_topic, set_joint_angle_topic; nh.param<std::string>("joint_velocity_topic", joint_velocity_topic, "joint_velocity"); nh.param<std::string>("joint_angles_topic", joint_angles_topic, "joint_angles"); nh.param<std::string>("cartesian_velocity_topic", cartesian_velocity_topic, "cartesian_velocity"); nh.param<std::string>("tool_position_topic", tool_position_topic, "tool_position"); nh.param<std::string>("set_finger_position_topic", set_finger_position_topic, "set_finger_position"); nh.param<std::string>("finger_position_topic", finger_position_topic, "finger_position"); nh.param<std::string>("joint_state_topic", joint_state_topic, "joint_state"); nh.param<std::string>("set_joint_angle_topic", set_joint_angle_topic, "set_joint_angle"); //Print out received topics ROS_DEBUG("Got Joint Velocity Topic Name: <%s>", joint_velocity_topic.c_str()); ROS_DEBUG("Got Joint Angles Topic Name: <%s>", joint_angles_topic.c_str()); ROS_DEBUG("Got Cartesian Velocity Topic Name: <%s>", cartesian_velocity_topic.c_str()); ROS_DEBUG("Got Tool Position Topic Name: <%s>", tool_position_topic.c_str()); ROS_DEBUG("Got Set Finger Position Topic Name: <%s>", set_finger_position_topic.c_str()); ROS_DEBUG("Got Finger Position Topic Name: <%s>", finger_position_topic.c_str()); ROS_DEBUG("Got Joint State Topic Name: <%s>", joint_state_topic.c_str()); ROS_DEBUG("Got Set Joint Angle Topic Name: <%s>", set_joint_angle_topic.c_str()); ROS_INFO("Starting Up Jaco Arm Controller..."); previous_state = 0; /* Set up Services */ stop_service = nh.advertiseService("stop", &JacoArm::StopSRV, this); start_service = nh.advertiseService("start", &JacoArm::StartSRV, this); homing_service = nh.advertiseService("home_arm", &JacoArm::HomeArmSRV, this); /* Set Default Configuration */ // API->RestoreFactoryDefault(); // uncomment comment ONLY if you want to lose your settings on each launch. ClientConfigurations configuration; arm.GetConfig(configuration); arm.PrintConfig(configuration); last_update_time = ros::Time::now(); update_time = ros::Duration(5.0); /* Storing arm in home position */ /* Set up Publishers */ JointAngles_pub = nh.advertise<jaco_driver::JointAngles>(joint_angles_topic, 2); JointState_pub = nh.advertise<sensor_msgs::JointState>(joint_state_topic, 2); ToolPosition_pub = nh.advertise<geometry_msgs::PoseStamped>(tool_position_topic, 2); FingerPosition_pub = nh.advertise<jaco_driver::FingerPosition>(finger_position_topic, 2); /* Set up Subscribers*/ JointVelocity_sub = nh.subscribe(joint_velocity_topic, 1, &JacoArm::VelocityMSG, this); CartesianVelocity_sub = nh.subscribe(cartesian_velocity_topic, 1, &JacoArm::CartesianVelocityMSG, this); SetFingerPosition_sub = nh.subscribe(set_finger_position_topic, 1, &JacoArm::SetFingerPositionMSG, this); SetJoint_sub = nh.subscribe(set_joint_angle_topic, 1, &JacoArm::SetJointAnglesMSG, this); status_timer = nh.createTimer(ros::Duration(0.05), &JacoArm::StatusTimer, this); joint_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::JointVelTimer, this); joint_vel_timer.stop(); joint_vel_timer_flag = false; cartesian_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::CartesianVelTimer, this); cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; ROS_INFO("The Arm is ready to use."); TrajectoryPoint Jaco_Velocity; memset(&Jaco_Velocity, 0, sizeof(Jaco_Velocity)); //zero structure arm.SetCartesianVelocities(Jaco_Velocity.Position.CartesianPosition); } JacoArm::~JacoArm() { } bool JacoArm::HomeArmSRV(jaco_driver::HomeArm::Request &req, jaco_driver::HomeArm::Response &res) { arm.HomeArm(); res.homearm_result = "JACO ARM HAS BEEN RETURNED HOME"; return true; } /*! * \brief Receives ROS command messages and relays them to SetFingers. */ void JacoArm::SetFingerPositionMSG(const jaco_driver::FingerPositionConstPtr& finger_pos) { if (!arm.Stopped()) { FingersPosition Finger_Position; memset(&Finger_Position, 0, sizeof(Finger_Position)); //zero structure Finger_Position.Finger1 = finger_pos->Finger_1; Finger_Position.Finger2 = finger_pos->Finger_2; Finger_Position.Finger3 = finger_pos->Finger_3; arm.SetFingers(Finger_Position); } } /*! * \brief Receives ROS command messages and relays them to SetAngles. */ void JacoArm::SetJointAnglesMSG(const jaco_driver::JointAnglesConstPtr& msg) { if (!arm.Stopped()) { jaco_driver::JointAngles angles(*msg); JacoAngles position(angles); arm.SetAngles(position); } } void JacoArm::VelocityMSG(const jaco_driver::JointVelocityConstPtr& joint_vel) { if (!arm.Stopped()) { joint_velocities.Actuator1 = joint_vel->Velocity_J1; joint_velocities.Actuator2 = joint_vel->Velocity_J2; joint_velocities.Actuator3 = joint_vel->Velocity_J3; joint_velocities.Actuator4 = joint_vel->Velocity_J4; joint_velocities.Actuator5 = joint_vel->Velocity_J5; joint_velocities.Actuator6 = joint_vel->Velocity_J6; last_joint_update = ros::Time().now(); if (joint_vel_timer_flag == false) { joint_vel_timer.start(); joint_vel_timer_flag = true; } } } /*! * \brief Handler for "stop" service. * * Instantly stops the arm and prevents further movement until start service is * invoked. */ bool JacoArm::StopSRV(jaco_driver::Stop::Request &req, jaco_driver::Stop::Response &res) { arm.Stop(); res.stop_result = "JACO ARM HAS BEEN STOPPED"; ROS_DEBUG("JACO ARM STOP REQUEST"); return true; } /*! * \brief Handler for "start" service. * * Re-enables control of the arm after a stop. */ bool JacoArm::StartSRV(jaco_driver::Start::Request &req, jaco_driver::Start::Response &res) { arm.Start(); res.start_result = "JACO ARM CONTROL HAS BEEN ENABLED"; ROS_DEBUG("JACO ARM START REQUEST"); return true; } void JacoArm::CartesianVelocityMSG(const geometry_msgs::TwistStampedConstPtr& cartesian_vel) { if (!arm.Stopped()) { cartesian_velocities.X = cartesian_vel->twist.linear.x; cartesian_velocities.Y = cartesian_vel->twist.linear.y; cartesian_velocities.Z = cartesian_vel->twist.linear.z; cartesian_velocities.ThetaX = cartesian_vel->twist.angular.x; cartesian_velocities.ThetaY = cartesian_vel->twist.angular.y; cartesian_velocities.ThetaZ = cartesian_vel->twist.angular.z; last_cartesian_update = ros::Time().now(); if (cartesian_vel_timer_flag == false) { cartesian_vel_timer.start(); cartesian_vel_timer_flag = true; } } } void JacoArm::CartesianVelTimer(const ros::TimerEvent&) { arm.SetCartesianVelocities(cartesian_velocities); if ((ros::Time().now().toSec() - last_cartesian_update.toSec()) > 1) { cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; } } void JacoArm::JointVelTimer(const ros::TimerEvent&) { arm.SetVelocities(joint_velocities); if ((ros::Time().now().toSec() - last_joint_update.toSec()) > 1) { joint_vel_timer.stop(); joint_vel_timer_flag = false; } } /*! * \brief Contains coordinates for an alternate "Home" position * * GoHome() function must be enabled in the initialization routine for this to * work. */ void JacoArm::GoHome(void) { /* AngularInfo joint_home; joint_home.Actuator1 = 176.0; joint_home.Actuator2 = 111.0; joint_home.Actuator3 = 107.0; joint_home.Actuator4 = 459.0; joint_home.Actuator5 = 102.0; joint_home.Actuator6 = 106.0; SetAngles(joint_home, 10); //send joints to home position API->SetCartesianControl(); */ } /*! * \brief Publishes the current joint angles. * * Joint angles are published in both their raw state as obtained from the arm * (JointAngles), and transformed & converted to radians (joint_state) as per * the Jaco Kinematics PDF. * * JointState will eventually also publish the velocity and effort for each * joint, when this data is made available by the C++ API. Currenty velocity * and effort are reported as being zero (0.0) for all joints. */ void JacoArm::BroadCastAngles(void) { // Populate an array of joint names. arm_0_joint is the base, arm_5_joint is the wrist. const char* nameArgs[] = {"arm_0_joint", "arm_1_joint", "arm_2_joint", "arm_3_joint", "arm_4_joint", "arm_5_joint"}; std::vector<std::string> JointName(nameArgs, nameArgs+6); jaco_driver::JointAngles current_angles; sensor_msgs::JointState joint_state; joint_state.name = JointName; // Define array sizes for the joint_state topic joint_state.position.resize(6); joint_state.velocity.resize(6); joint_state.effort.resize(6); //Query arm for current joint angles JacoAngles arm_angles; arm.GetAngles(arm_angles); jaco_driver::JointAngles ros_angles = arm_angles.Angles(); // Transform from Kinova DH algorithm to physical angles in radians, then place into vector array joint_state.position[0] = ros_angles.Angle_J1; joint_state.position[1] = ros_angles.Angle_J2; joint_state.position[2] = ros_angles.Angle_J3; joint_state.position[3] = ros_angles.Angle_J4; joint_state.position[4] = ros_angles.Angle_J5; joint_state.position[5] = ros_angles.Angle_J6; //Publish the joint state messages ros_angles.Angle_J1 = arm_angles.Actuator1; ros_angles.Angle_J2 = arm_angles.Actuator2; ros_angles.Angle_J3 = arm_angles.Actuator3; ros_angles.Angle_J4 = arm_angles.Actuator4; ros_angles.Angle_J5 = arm_angles.Actuator5; ros_angles.Angle_J6 = arm_angles.Actuator6; JointAngles_pub.publish(ros_angles); // Publishes the raw joint angles in a custom message. JointState_pub.publish(joint_state); // Publishes the transformed angles in a standard sensor_msgs format. } /*! * \brief Publishes the current cartesian coordinates */ void JacoArm::BroadCastPosition(void) { JacoPose pose; geometry_msgs::PoseStamped current_position; arm.GetPosition(pose); current_position.pose = pose.Pose(); ToolPosition_pub.publish(current_position); } void JacoArm::BroadCastFingerPosition(void) { /* Publishes the current finger positions. */ CartesianPosition Jaco_Position; jaco_driver::FingerPosition finger_position; memset(&Jaco_Position, 0, sizeof(Jaco_Position)); //zero structure arm.GetFingers(Jaco_Position.Fingers); finger_position.Finger_1 = Jaco_Position.Fingers.Finger1; finger_position.Finger_2 = Jaco_Position.Fingers.Finger2; finger_position.Finger_3 = Jaco_Position.Fingers.Finger3; FingerPosition_pub.publish(finger_position); } void JacoArm::StatusTimer(const ros::TimerEvent&) { BroadCastAngles(); BroadCastPosition(); BroadCastFingerPosition(); } } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "arm_controller/arm_controller.h" #include "controllers/armMove.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include "arm_controller/arduino-serial-lib.h" Arm_Controller::Arm_Controller() {} void Arm_Controller::run() {} void Arm_Controller::init() {} char *formatMessage(int base, int shoulder, int shoulder1, int elbow, int elbow1, int wrist, int wrot, int grip); bool Arm_Controller::armMove(controllers::armMove::Request &req, controllers::armMove::Response &res) { int fd; int base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip; base = req.base; shoulder = req.shoulder; shoulder1= req.shoulder1; elbow = req.elbow; elbow1 = req.elbow1; wrist = req.wrist; wrot = req.wrot; grip = req.grip; char *portname = (char*)malloc(sizeof(char) * 40); strcpy(portname, "/dev/tty.usbserial-A602ZALM"); printf("copy success\n"); fd = serialport_init(portname, 9600); printf("open success!\n"); char returnval[256]; char* teststr = formatMessage(base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip); //strcpy(teststr, "Start:35,55,55,42,42,66,12,100:End"); printf("copy success\n"); serialport_write(fd, teststr); printf("write success!\n"); serialport_read_until(fd, returnval, ':', 256, 10000); printf("read success!\n"); printf("%s\n", returnval); free(portname); res.success = true; return true; } char *formatMessage(int base, int shoulder, int shoulder1, int elbow, int elbow1, int wrist, int wrot, int grip) { char *teststr = (char *)malloc(sizeof(char) * 256); sprintf(teststr, "Start:%d,%d,%d,%d,%d,%d,%d,%d:End", base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip); return teststr; } int main(int argc, char **argv) { ros::init(argc, argv, "arm_controller"); Arm_Controller armC; ros::ServiceServer tester = armC.n.advertiseService("plan2ArmMove", &Arm_Controller::armMove, &armC); ros::spin(); return 0; } <commit_msg>fire in the hole<commit_after>#include "ros/ros.h" #include "arm_controller/arm_controller.h" #include "controllers/armMove.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include "arm_controller/arduino-serial-lib.h" Arm_Controller::Arm_Controller() {} void Arm_Controller::run() {} void Arm_Controller::init() {} char *formatMessage(int base, int shoulder, int shoulder1, int elbow, int elbow1, int wrist, int wrot, int grip); bool Arm_Controller::armMove(controllers::armMove::Request &req, controllers::armMove::Response &res) { //TODO Change generalize to array of angles for each join int fd; int base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip; base = req.base; shoulder = req.shoulder; shoulder1= req.shoulder1; elbow = req.elbow; elbow1 = req.elbow1; wrist = req.wrist; wrot = req.wrot; grip = req.grip; char *portname = (char*)malloc(sizeof(char) * 40); strcpy(portname, "/dev/tty.usbserial-A602ZALM"); printf("copy success\n"); fd = serialport_init(portname, 9600); printf("open success!\n"); char returnval[256]; char* teststr = formatMessage(base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip); //strcpy(teststr, "Start:35,55,55,42,42,66,12,100:End"); printf("copy success\n"); serialport_write(fd, teststr); printf("write success!\n"); serialport_read_until(fd, returnval, ':', 256, 10000); printf("read success!\n"); printf("%s\n", returnval); free(portname); res.success = true; return true; } char *formatMessage(int base, int shoulder, int shoulder1, int elbow, int elbow1, int wrist, int wrot, int grip) { char *teststr = (char *)malloc(sizeof(char) * 256); sprintf(teststr, "Start:%d,%d,%d,%d,%d,%d,%d,%d:End", base, shoulder, shoulder1, elbow, elbow1, wrist, wrot, grip); return teststr; } int main(int argc, char **argv) { ros::init(argc, argv, "arm_controller"); Arm_Controller armC; ros::ServiceServer tester = armC.n.advertiseService("plan2ArmMove", &Arm_Controller::armMove, &armC); ros::spin(); return 0; } <|endoftext|>
<commit_before>// (C) Copyright John Maddock 2000. // Use, modification and distribution are subject to 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) // See http://www.boost.org/libs/static_assert for documentation. /* Revision history: 02 August 2000 Initial version. */ #ifndef BOOST_STATIC_ASSERT_HPP #define BOOST_STATIC_ASSERT_HPP #include "boost/config.hpp" #include "boost/detail/workaround.hpp" #ifdef __BORLANDC__ // // workaround for buggy integral-constant expression support: #define BOOST_BUGGY_INTEGRAL_CONSTANT_EXPRESSIONS #endif #if defined(__GNUC__) && (__GNUC__ == 3) && ((__GNUC_MINOR__ == 3) || (__GNUC_MINOR__ == 4)) // gcc 3.3 and 3.4 don't produce good error messages with the default version: # define BOOST_SA_GCC_WORKAROUND #endif // // If the compiler issues warnings about old C style casts, // then enable this: // #if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))) # define BOOST_STATIC_ASSERT_BOOL_CAST( x ) ((x) == 0 ? false : true) #else # define BOOST_STATIC_ASSERT_BOOL_CAST(x) (bool)(x) #endif #ifdef BOOST_HAS_STATIC_ASSERT # define BOOST_STATIC_ASSERT( B ) static_assert(B, #B) #else namespace boost{ // HP aCC cannot deal with missing names for template value parameters template <bool x> struct STATIC_ASSERTION_FAILURE; template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; }; // HP aCC cannot deal with missing names for template value parameters template<int x> struct static_assert_test{}; } // // Implicit instantiation requires that all member declarations be // instantiated, but that the definitions are *not* instantiated. // // It's not particularly clear how this applies to enum's or typedefs; // both are described as declarations [7.1.3] and [7.2] in the standard, // however some compilers use "delayed evaluation" of one or more of // these when implicitly instantiating templates. We use typedef declarations // by default, but try defining BOOST_USE_ENUM_STATIC_ASSERT if the enum // version gets better results from your compiler... // // Implementation: // Both of these versions rely on sizeof(incomplete_type) generating an error // message containing the name of the incomplete type. We use // "STATIC_ASSERTION_FAILURE" as the type name here to generate // an eye catching error message. The result of the sizeof expression is either // used as an enum initialiser, or as a template argument depending which version // is in use... // Note that the argument to the assert is explicitly cast to bool using old- // style casts: too many compilers currently have problems with static_cast // when used inside integral constant expressions. // #if !defined(BOOST_BUGGY_INTEGRAL_CONSTANT_EXPRESSIONS) #if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) // __LINE__ macro broken when -ZI is used see Q199057 // fortunately MSVC ignores duplicate typedef's. #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< (bool)( B ) >)\ > boost_static_assert_typedef_ #elif defined(BOOST_MSVC) #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST ( B ) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __COUNTER__) #elif defined(BOOST_INTEL_CXX_VERSION) || defined(BOOST_SA_GCC_WORKAROUND) // agurt 15/sep/02: a special care is needed to force Intel C++ issue an error // instead of warning in case of failure # define BOOST_STATIC_ASSERT( B ) \ typedef char BOOST_JOIN(boost_static_assert_typedef_, __LINE__) \ [ ::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >::value ] #elif defined(__sgi) // special version for SGI MIPSpro compiler #define BOOST_STATIC_ASSERT( B ) \ BOOST_STATIC_CONSTANT(bool, \ BOOST_JOIN(boost_static_assert_test_, __LINE__) = ( B )); \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< \ BOOST_JOIN(boost_static_assert_test_, __LINE__) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __LINE__) #elif BOOST_WORKAROUND(__MWERKS__, <= 0x3003) // special version for CodeWarrior <= 8.x #define BOOST_STATIC_ASSERT( B ) \ BOOST_STATIC_CONSTANT(int, \ BOOST_JOIN(boost_static_assert_test_, __LINE__) = \ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >) ) #else // generic version #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __LINE__) #endif #else // alternative enum based implementation: #define BOOST_STATIC_ASSERT( B ) \ enum { BOOST_JOIN(boost_static_assert_enum_, __LINE__) \ = sizeof(::boost::STATIC_ASSERTION_FAILURE< (bool)( B ) >) } #endif #endif // ndef BOOST_HAS_STATIC_ASSERT #endif // BOOST_STATIC_ASSERT_HPP <commit_msg>Supress boost STATIC_ASSERT warnings when using gcc > 4.8<commit_after>// (C) Copyright John Maddock 2000. // Use, modification and distribution are subject to 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) // See http://www.boost.org/libs/static_assert for documentation. /* Revision history: 02 August 2000 Initial version. */ #ifndef BOOST_STATIC_ASSERT_HPP #define BOOST_STATIC_ASSERT_HPP #include "boost/config.hpp" #include "boost/detail/workaround.hpp" #ifdef __BORLANDC__ // // workaround for buggy integral-constant expression support: #define BOOST_BUGGY_INTEGRAL_CONSTANT_EXPRESSIONS #endif #if defined(__GNUC__) && (__GNUC__ == 3) && ((__GNUC_MINOR__ == 3) || (__GNUC_MINOR__ == 4)) // gcc 3.3 and 3.4 don't produce good error messages with the default version: # define BOOST_SA_GCC_WORKAROUND #endif // // If the compiler issues warnings about old C style casts, // then enable this: // #if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))) # define BOOST_STATIC_ASSERT_BOOL_CAST( x ) ((x) == 0 ? false : true) #else # define BOOST_STATIC_ASSERT_BOOL_CAST(x) (bool)(x) #endif #ifdef BOOST_HAS_STATIC_ASSERT # define BOOST_STATIC_ASSERT( B ) static_assert(B, #B) #else namespace boost{ // HP aCC cannot deal with missing names for template value parameters template <bool x> struct STATIC_ASSERTION_FAILURE; template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; }; // HP aCC cannot deal with missing names for template value parameters template<int x> struct static_assert_test{}; } // // Implicit instantiation requires that all member declarations be // instantiated, but that the definitions are *not* instantiated. // // It's not particularly clear how this applies to enum's or typedefs; // both are described as declarations [7.1.3] and [7.2] in the standard, // however some compilers use "delayed evaluation" of one or more of // these when implicitly instantiating templates. We use typedef declarations // by default, but try defining BOOST_USE_ENUM_STATIC_ASSERT if the enum // version gets better results from your compiler... // // Implementation: // Both of these versions rely on sizeof(incomplete_type) generating an error // message containing the name of the incomplete type. We use // "STATIC_ASSERTION_FAILURE" as the type name here to generate // an eye catching error message. The result of the sizeof expression is either // used as an enum initialiser, or as a template argument depending which version // is in use... // Note that the argument to the assert is explicitly cast to bool using old- // style casts: too many compilers currently have problems with static_cast // when used inside integral constant expressions. // #if !defined(BOOST_BUGGY_INTEGRAL_CONSTANT_EXPRESSIONS) #if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) // __LINE__ macro broken when -ZI is used see Q199057 // fortunately MSVC ignores duplicate typedef's. #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< (bool)( B ) >)\ > boost_static_assert_typedef_ #elif defined(BOOST_MSVC) #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST ( B ) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __COUNTER__) #elif defined(BOOST_INTEL_CXX_VERSION) || defined(BOOST_SA_GCC_WORKAROUND) // agurt 15/sep/02: a special care is needed to force Intel C++ issue an error // instead of warning in case of failure # define BOOST_STATIC_ASSERT( B ) \ typedef char BOOST_JOIN(boost_static_assert_typedef_, __LINE__) \ [ ::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >::value ] #elif defined(__sgi) // special version for SGI MIPSpro compiler #define BOOST_STATIC_ASSERT( B ) \ BOOST_STATIC_CONSTANT(bool, \ BOOST_JOIN(boost_static_assert_test_, __LINE__) = ( B )); \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< \ BOOST_JOIN(boost_static_assert_test_, __LINE__) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __LINE__) #elif BOOST_WORKAROUND(__MWERKS__, <= 0x3003) // special version for CodeWarrior <= 8.x #define BOOST_STATIC_ASSERT( B ) \ BOOST_STATIC_CONSTANT(int, \ BOOST_JOIN(boost_static_assert_test_, __LINE__) = \ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >) ) #else // generic version #define BOOST_STATIC_ASSERT( B ) \ typedef ::boost::static_assert_test<\ sizeof(::boost::STATIC_ASSERTION_FAILURE< BOOST_STATIC_ASSERT_BOOL_CAST( B ) >)>\ BOOST_JOIN(boost_static_assert_typedef_, __LINE__) __attribute__((unused)) #endif #else // alternative enum based implementation: #define BOOST_STATIC_ASSERT( B ) \ enum { BOOST_JOIN(boost_static_assert_enum_, __LINE__) \ = sizeof(::boost::STATIC_ASSERTION_FAILURE< (bool)( B ) >) } #endif #endif // ndef BOOST_HAS_STATIC_ASSERT #endif // BOOST_STATIC_ASSERT_HPP <|endoftext|>
<commit_before>#include <catch.hpp> #include <rapidcheck-catch.h> #include "rapidcheck/detail/RandomEngine.h" using namespace rc; using namespace rc::detail; #define ENOUGH 10000 TEST_CASE("RandomEngine") { SECTION("nextAtom") { prop("same seeds yields same sequences of numbers", [] (RandomEngine::Seed seed) { RandomEngine r1(seed); RandomEngine r2(seed); for (int i = 0; i < ENOUGH; i++) RC_ASSERT(r1.nextAtom() == r2.nextAtom()); }); prop("a copy of a randomEngine yields the same sequences of numbers as" " the original", [] (RandomEngine::Seed seed) { RandomEngine r1(seed); RandomEngine r2(r1); for (int i = 0; i < ENOUGH; i++) RC_ASSERT(r1.nextAtom() == r2.nextAtom()); }); prop("different seeds yields different sequences of numbers", [] { auto s1 = *gen::arbitrary<RandomEngine::Seed>(); auto s2 = *gen::distinctFrom(s1); RandomEngine r1(s1); RandomEngine r2(s2); std::vector<RandomEngine::Atom> atoms1; std::vector<RandomEngine::Atom> atoms2; for (int i = 0; i < ENOUGH; i++) { atoms1.push_back(r1.nextAtom()); atoms2.push_back(r2.nextAtom()); } RC_ASSERT(atoms1 != atoms2); }); } } <commit_msg>Move RandomEngineTests to new framework<commit_after>#include <catch.hpp> #include <rapidcheck-catch.h> #include "rapidcheck/detail/RandomEngine.h" using namespace rc; using namespace rc::detail; #define ENOUGH 10000 TEST_CASE("RandomEngine") { SECTION("nextAtom") { newprop( "same seeds yields same sequences of numbers", [] (RandomEngine::Seed seed) { RandomEngine r1(seed); RandomEngine r2(seed); for (int i = 0; i < ENOUGH; i++) RC_ASSERT(r1.nextAtom() == r2.nextAtom()); }); newprop( "a copy of a randomEngine yields the same sequences of numbers as" " the original", [] (RandomEngine::Seed seed) { RandomEngine r1(seed); RandomEngine r2(r1); for (int i = 0; i < ENOUGH; i++) RC_ASSERT(r1.nextAtom() == r2.nextAtom()); }); newprop( "different seeds yields different sequences of numbers", [] { auto s1 = *newgen::arbitrary<RandomEngine::Seed>(); auto s2 = *newgen::distinctFrom(s1); RandomEngine r1(s1); RandomEngine r2(s2); std::vector<RandomEngine::Atom> atoms1; std::vector<RandomEngine::Atom> atoms2; for (int i = 0; i < ENOUGH; i++) { atoms1.push_back(r1.nextAtom()); atoms2.push_back(r2.nextAtom()); } RC_ASSERT(atoms1 != atoms2); }); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc * * 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 "config.h" #include <atomic> #if defined(HAVE_MEMALIGN) #include <malloc.h> #endif #include "daemon/alloc_hooks.h" std::atomic_size_t alloc_size; // Test pointer in global scope to prevent compiler optimizing malloc/free away // via DCE. char* p; extern "C" { static void NewHook(const void* ptr, size_t) { if (ptr != NULL) { void* p = const_cast<void*>(ptr); alloc_size += AllocHooks::get_allocation_size(p); } } static void DeleteHook(const void* ptr) { if (ptr != NULL) { void* p = const_cast<void*>(ptr); alloc_size -= AllocHooks::get_allocation_size(p); } } static void TestThread(void* arg) { alloc_size = 0; // Test new & delete ////////////////////////////////////////////////// p = new char(); cb_assert(alloc_size > 0); delete p; cb_assert(alloc_size == 0); // Test new[] & delete[] ////////////////////////////////////////////// p = new char[100]; cb_assert(alloc_size >= 100); delete []p; cb_assert(alloc_size == 0); // Test malloc() / free() ///////////////////////////////////////////// p = static_cast<char*>(malloc(sizeof(char) * 10)); cb_assert(alloc_size >= 10); free(p); cb_assert(alloc_size == 0); // Test realloc() ///////////////////////////////////////////////////// p = static_cast<char*>(malloc(1)); cb_assert(alloc_size >= 1); // Allocator may round up allocation sizes; so it's hard to // accurately predict how much alloc_size will increase. Hence // we just increase by a "large" amount and check at least half that // increment. size_t prev_size = alloc_size; p = static_cast<char*>(realloc(p, sizeof(char) * 100)); cb_assert(alloc_size >= (prev_size + 50)); prev_size = alloc_size; p = static_cast<char*>(realloc(p, 1)); cb_assert(alloc_size < prev_size); prev_size = alloc_size; char* q = static_cast<char*>(realloc(NULL, 10)); cb_assert(alloc_size >= prev_size + 10); free(p); free(q); cb_assert(alloc_size == 0); // Test calloc() ////////////////////////////////////////////////////// p = static_cast<char*>(calloc(sizeof(char), 20)); cb_assert(alloc_size >= 20); free(p); cb_assert(alloc_size == 0); // Test indirect use of malloc() via strdup() ///////////////////////// p = strdup("random string"); cb_assert(alloc_size >= sizeof("random string")); free(p); cb_assert(alloc_size == 0); #if defined(HAVE_MEMALIGN) // Test memalign ////////////////////////////////////////////////////// p = static_cast<char*>(memalign(16, 64)); cb_assert(alloc_size >= 64); free(p); cb_assert(alloc_size == 0); // Test posix_memalign //////////////////////////////////////////////// void* ptr; cb_assert(posix_memalign(&ptr, 16, 64) == 0); cb_assert(alloc_size >= 64); free(ptr); cb_assert(alloc_size == 0); #endif } } int main(void) { AllocHooks::initialize(); AllocHooks::add_new_hook(NewHook); AllocHooks::add_delete_hook(DeleteHook); cb_thread_t tid; cb_assert(cb_create_thread(&tid, TestThread, 0, 0) == 0); cb_assert(cb_join_thread(tid) == 0); AllocHooks::remove_new_hook(NewHook); AllocHooks::remove_delete_hook(DeleteHook); return 0; } <commit_msg>MB-20586: Fix build break on OS X due to missing strdup header<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc * * 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 "config.h" #include <atomic> #include <cstring> #if defined(HAVE_MEMALIGN) #include <malloc.h> #endif #include "daemon/alloc_hooks.h" std::atomic_size_t alloc_size; // Test pointer in global scope to prevent compiler optimizing malloc/free away // via DCE. char* p; extern "C" { static void NewHook(const void* ptr, size_t) { if (ptr != NULL) { void* p = const_cast<void*>(ptr); alloc_size += AllocHooks::get_allocation_size(p); } } static void DeleteHook(const void* ptr) { if (ptr != NULL) { void* p = const_cast<void*>(ptr); alloc_size -= AllocHooks::get_allocation_size(p); } } static void TestThread(void* arg) { alloc_size = 0; // Test new & delete ////////////////////////////////////////////////// p = new char(); cb_assert(alloc_size > 0); delete p; cb_assert(alloc_size == 0); // Test new[] & delete[] ////////////////////////////////////////////// p = new char[100]; cb_assert(alloc_size >= 100); delete []p; cb_assert(alloc_size == 0); // Test malloc() / free() ///////////////////////////////////////////// p = static_cast<char*>(malloc(sizeof(char) * 10)); cb_assert(alloc_size >= 10); free(p); cb_assert(alloc_size == 0); // Test realloc() ///////////////////////////////////////////////////// p = static_cast<char*>(malloc(1)); cb_assert(alloc_size >= 1); // Allocator may round up allocation sizes; so it's hard to // accurately predict how much alloc_size will increase. Hence // we just increase by a "large" amount and check at least half that // increment. size_t prev_size = alloc_size; p = static_cast<char*>(realloc(p, sizeof(char) * 100)); cb_assert(alloc_size >= (prev_size + 50)); prev_size = alloc_size; p = static_cast<char*>(realloc(p, 1)); cb_assert(alloc_size < prev_size); prev_size = alloc_size; char* q = static_cast<char*>(realloc(NULL, 10)); cb_assert(alloc_size >= prev_size + 10); free(p); free(q); cb_assert(alloc_size == 0); // Test calloc() ////////////////////////////////////////////////////// p = static_cast<char*>(calloc(sizeof(char), 20)); cb_assert(alloc_size >= 20); free(p); cb_assert(alloc_size == 0); // Test indirect use of malloc() via strdup() ///////////////////////// p = strdup("random string"); cb_assert(alloc_size >= sizeof("random string")); free(p); cb_assert(alloc_size == 0); #if defined(HAVE_MEMALIGN) // Test memalign ////////////////////////////////////////////////////// p = static_cast<char*>(memalign(16, 64)); cb_assert(alloc_size >= 64); free(p); cb_assert(alloc_size == 0); // Test posix_memalign //////////////////////////////////////////////// void* ptr; cb_assert(posix_memalign(&ptr, 16, 64) == 0); cb_assert(alloc_size >= 64); free(ptr); cb_assert(alloc_size == 0); #endif } } int main(void) { AllocHooks::initialize(); AllocHooks::add_new_hook(NewHook); AllocHooks::add_delete_hook(DeleteHook); cb_thread_t tid; cb_assert(cb_create_thread(&tid, TestThread, 0, 0) == 0); cb_assert(cb_join_thread(tid) == 0); AllocHooks::remove_new_hook(NewHook); AllocHooks::remove_delete_hook(DeleteHook); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: confsvccomponent.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:17:45 $ * * 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 CONFIGMGR_API_SVCCOMPONENT_HXX_ #define CONFIGMGR_API_SVCCOMPONENT_HXX_ #ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_ #include "serviceinfohelper.hxx" #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_COMPBASE1_HXX_ #include <cppuhelper/compbase1.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/Mutex.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif namespace configmgr { //---------------------------------------------------------------------------- namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; using ::rtl::OUString; //---------------------------------------------------------------------------- typedef ::cppu::WeakComponentImplHelper1< lang::XServiceInfo > ServiceImplBase; //---------------------------------------------------------------------------- class ServiceComponentImpl : public ServiceImplBase { protected: ServiceImplementationInfo const*const m_info; public: ServiceComponentImpl(ServiceImplementationInfo const* aInfo); // XTypeProvider virtual uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw(uno::RuntimeException); //virtual uno::Sequence<uno::Type> SAL_CALL getTypes( ) throw(uno::RuntimeException) = 0; // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw(uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw(uno::RuntimeException); // Component Helper - force override virtual void SAL_CALL disposing() = 0; // Component Helper - check object state virtual void checkAlive() throw (uno::RuntimeException); void checkAlive(char const* message) throw (uno::RuntimeException) { checkAlive( OUString::createFromAscii(message) ); } void checkAlive(OUString const& message) throw (uno::RuntimeException); // Extra helpers static uno::Sequence<sal_Int8> getStaticImplementationId(ServiceImplementationInfo const* pServiceInfo) throw(uno::RuntimeException); private: // no implementation ServiceComponentImpl(ServiceComponentImpl&); void operator=(ServiceComponentImpl&); }; //---------------------------------------------------------------------------- } // namespace configmgr #endif // CONFIGMGR_API_SVCCOMPONENT_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.5.16); FILE MERGED 2008/04/01 15:06:43 thb 1.5.16.3: #i85898# Stripping all external header guards 2008/04/01 12:27:23 thb 1.5.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:43 rt 1.5.16.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: confsvccomponent.hxx,v $ * $Revision: 1.6 $ * * 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 CONFIGMGR_API_SVCCOMPONENT_HXX_ #define CONFIGMGR_API_SVCCOMPONENT_HXX_ #include "serviceinfohelper.hxx" #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/compbase1.hxx> #include <cppuhelper/typeprovider.hxx> #ifndef _OSL_MUTEX_HXX_ #include <osl/Mutex.hxx> #endif #include <rtl/ustring.hxx> namespace configmgr { //---------------------------------------------------------------------------- namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; using ::rtl::OUString; //---------------------------------------------------------------------------- typedef ::cppu::WeakComponentImplHelper1< lang::XServiceInfo > ServiceImplBase; //---------------------------------------------------------------------------- class ServiceComponentImpl : public ServiceImplBase { protected: ServiceImplementationInfo const*const m_info; public: ServiceComponentImpl(ServiceImplementationInfo const* aInfo); // XTypeProvider virtual uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw(uno::RuntimeException); //virtual uno::Sequence<uno::Type> SAL_CALL getTypes( ) throw(uno::RuntimeException) = 0; // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw(uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw(uno::RuntimeException); // Component Helper - force override virtual void SAL_CALL disposing() = 0; // Component Helper - check object state virtual void checkAlive() throw (uno::RuntimeException); void checkAlive(char const* message) throw (uno::RuntimeException) { checkAlive( OUString::createFromAscii(message) ); } void checkAlive(OUString const& message) throw (uno::RuntimeException); // Extra helpers static uno::Sequence<sal_Int8> getStaticImplementationId(ServiceImplementationInfo const* pServiceInfo) throw(uno::RuntimeException); private: // no implementation ServiceComponentImpl(ServiceComponentImpl&); void operator=(ServiceComponentImpl&); }; //---------------------------------------------------------------------------- } // namespace configmgr #endif // CONFIGMGR_API_SVCCOMPONENT_HXX_ <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2012/08/22 // Author: Mike Ovsiannikov // // Copyright 2012,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // // \file KfsAttr.cc // \brief Kfs i-node attributes class. // //---------------------------------------------------------------------------- #include "KfsAttr.h" #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> namespace KFS { namespace client { void FileAttr::ToStat( struct stat& outStat) const { memset(&outStat, 0, sizeof(outStat)); outStat.st_ino = fileId; // Directories are drwxrwxrwx, files are drw-rw-rw- if (isDirectory) { outStat.st_mode = S_IFDIR | (mode_t)((mode == kKfsModeUndef ? (kfsMode_t)0777 : mode) & 0777); outStat.st_size = 0; } else { outStat.st_mode = S_IFREG | (mode_t)((mode == kKfsModeUndef ? (kfsMode_t)0666 : mode) & 0777); outStat.st_size = fileSize; } #ifdef S_ISVTX if (IsSticky()) { outStat.st_mode |= S_ISVTX; } #endif outStat.st_blksize = CHUNKSIZE; outStat.st_blocks = chunkCount(); outStat.st_uid = (uid_t)user; outStat.st_gid = (gid_t)group; #ifdef KFS_OS_NAME_DARWIN outStat.st_atimespec.tv_sec = crtime.tv_sec; outStat.st_atimespec.tv_nsec = crtime.tv_usec * 1000; outStat.st_mtimespec.tv_sec = mtime.tv_sec; outStat.st_mtimespec.tv_nsec = mtime.tv_usec * 1000; outStat.st_ctimespec.tv_sec = ctime.tv_sec; outStat.st_ctimespec.tv_nsec = ctime.tv_usec * 1000; #else outStat.st_atime = crtime.tv_sec; outStat.st_mtime = mtime.tv_sec; outStat.st_ctime = ctime.tv_sec; #endif } }} <commit_msg>Client library: take into the account replication in QFS attribute to stat conversions when reporting number of blocks.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2012/08/22 // Author: Mike Ovsiannikov // // Copyright 2012,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // // \file KfsAttr.cc // \brief Kfs i-node attributes class. // //---------------------------------------------------------------------------- #include "KfsAttr.h" #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> namespace KFS { namespace client { void FileAttr::ToStat( struct stat& outStat) const { memset(&outStat, 0, sizeof(outStat)); outStat.st_ino = fileId; // Directories are drwxrwxrwx, files are drw-rw-rw- if (isDirectory) { outStat.st_mode = S_IFDIR | (mode_t)((mode == kKfsModeUndef ? (kfsMode_t)0777 : mode) & 0777); outStat.st_size = 0; } else { outStat.st_mode = S_IFREG | (mode_t)((mode == kKfsModeUndef ? (kfsMode_t)0666 : mode) & 0777); outStat.st_size = fileSize; } #ifdef S_ISVTX if (IsSticky()) { outStat.st_mode |= S_ISVTX; } #endif outStat.st_blksize = CHUNKSIZE; outStat.st_blocks = chunkCount(); if (0 < numReplicas) { outStat.st_blocks *= numReplicas; } outStat.st_uid = (uid_t)user; outStat.st_gid = (gid_t)group; #ifdef KFS_OS_NAME_DARWIN outStat.st_atimespec.tv_sec = crtime.tv_sec; outStat.st_atimespec.tv_nsec = crtime.tv_usec * 1000; outStat.st_mtimespec.tv_sec = mtime.tv_sec; outStat.st_mtimespec.tv_nsec = mtime.tv_usec * 1000; outStat.st_ctimespec.tv_sec = ctime.tv_sec; outStat.st_ctimespec.tv_nsec = ctime.tv_usec * 1000; #else outStat.st_atime = crtime.tv_sec; outStat.st_mtime = mtime.tv_sec; outStat.st_ctime = ctime.tv_sec; #endif } }} <|endoftext|>
<commit_before>#include "auto-wrap.h" #include "text-buffer.h" #include <emscripten/bind.h> using std::string; using std::u16string; static TextBuffer *construct(const std::string &text) { return new TextBuffer(u16string(text.begin(), text.end())); } static emscripten::val search_sync(TextBuffer &buffer, std::string js_pattern) { u16string pattern(js_pattern.begin(), js_pattern.end()); u16string error_message; Regex regex(pattern, &error_message); if (!error_message.empty()) { return emscripten::val(string(error_message.begin(), error_message.end())); } auto result = buffer.search(regex); if (result) { return emscripten::val(*result); } return emscripten::val::null(); } static emscripten::val line_ending_for_row(TextBuffer &buffer, uint32_t row) { auto line_ending = buffer.line_ending_for_row(row); if (line_ending) { string result; for (const uint16_t *character = line_ending; *character != 0; character++) { result += (char)*character; } return emscripten::val(result); } return emscripten::val::undefined(); } static uint32_t character_index_for_position(TextBuffer &buffer, Point position) { return buffer.clip_position(position).offset; } static Point position_for_character_index(TextBuffer &buffer, long index) { return index < 0 ? Point{0, 0} : buffer.position_for_offset(static_cast<uint32_t>(index)); } EMSCRIPTEN_BINDINGS(TextBuffer) { emscripten::class_<TextBuffer>("TextBuffer") .constructor<>() .constructor(construct, emscripten::allow_raw_pointers()) .function("getText", WRAP(&TextBuffer::text)) .function("setText", WRAP_OVERLOAD(&TextBuffer::set_text, void (TextBuffer::*)(Text::String &&))) .function("getTextInRange", WRAP(&TextBuffer::text_in_range)) .function("setTextInRange", WRAP_OVERLOAD(&TextBuffer::set_text_in_range, void (TextBuffer::*)(Range, Text::String &&))) .function("getLength", &TextBuffer::size) .function("getExtent", &TextBuffer::extent) .function("reset", WRAP(&TextBuffer::reset)) .function("lineLengthForRow", WRAP(&TextBuffer::line_length_for_row)) .function("lineEndingForRow", line_ending_for_row) .function("lineForRow", WRAP(&TextBuffer::line_for_row)) .function("characterIndexForPosition", character_index_for_position) .function("positionForCharacterIndex", position_for_character_index) .function("isModified", &TextBuffer::is_modified) .function("searchSync", search_sync); } <commit_msg>Specify overload in emscripten binding for isModified<commit_after>#include "auto-wrap.h" #include "text-buffer.h" #include <emscripten/bind.h> using std::string; using std::u16string; static TextBuffer *construct(const std::string &text) { return new TextBuffer(u16string(text.begin(), text.end())); } static emscripten::val search_sync(TextBuffer &buffer, std::string js_pattern) { u16string pattern(js_pattern.begin(), js_pattern.end()); u16string error_message; Regex regex(pattern, &error_message); if (!error_message.empty()) { return emscripten::val(string(error_message.begin(), error_message.end())); } auto result = buffer.search(regex); if (result) { return emscripten::val(*result); } return emscripten::val::null(); } static emscripten::val line_ending_for_row(TextBuffer &buffer, uint32_t row) { auto line_ending = buffer.line_ending_for_row(row); if (line_ending) { string result; for (const uint16_t *character = line_ending; *character != 0; character++) { result += (char)*character; } return emscripten::val(result); } return emscripten::val::undefined(); } static uint32_t character_index_for_position(TextBuffer &buffer, Point position) { return buffer.clip_position(position).offset; } static Point position_for_character_index(TextBuffer &buffer, long index) { return index < 0 ? Point{0, 0} : buffer.position_for_offset(static_cast<uint32_t>(index)); } EMSCRIPTEN_BINDINGS(TextBuffer) { emscripten::class_<TextBuffer>("TextBuffer") .constructor<>() .constructor(construct, emscripten::allow_raw_pointers()) .function("getText", WRAP(&TextBuffer::text)) .function("setText", WRAP_OVERLOAD(&TextBuffer::set_text, void (TextBuffer::*)(Text::String &&))) .function("getTextInRange", WRAP(&TextBuffer::text_in_range)) .function("setTextInRange", WRAP_OVERLOAD(&TextBuffer::set_text_in_range, void (TextBuffer::*)(Range, Text::String &&))) .function("getLength", &TextBuffer::size) .function("getExtent", &TextBuffer::extent) .function("reset", WRAP(&TextBuffer::reset)) .function("lineLengthForRow", WRAP(&TextBuffer::line_length_for_row)) .function("lineEndingForRow", line_ending_for_row) .function("lineForRow", WRAP(&TextBuffer::line_for_row)) .function("characterIndexForPosition", character_index_for_position) .function("positionForCharacterIndex", position_for_character_index) .function("isModified", WRAP_OVERLOAD(&TextBuffer::is_modified, bool (TextBuffer::*)() const)) .function("searchSync", search_sync); } <|endoftext|>
<commit_before>#pragma once #include <mutex> #include <boost/thread.hpp> #include "blackhole/forwards.hpp" #include "blackhole/logger.hpp" namespace blackhole { template<class Logger, class Mutex> class synchronized { public: typedef Logger logger_type; typedef Mutex mutex_type; private: logger_type log; mutable mutex_type mutex; friend class scoped_attributes_t; public: synchronized() {} explicit synchronized(logger_type&& logger) : log(std::move(logger)) {} synchronized(synchronized&& other) { *this = std::move(other); } synchronized& operator=(synchronized&& other) { //! @compat GCC4.4 //! GCC4.4 doesn't implement `std::lock` as like as `std::adopt_lock`. boost::lock(mutex, other.mutex); boost::lock_guard<mutex_type> lock(mutex, boost::adopt_lock); boost::lock_guard<mutex_type> other_lock(other.mutex, boost::adopt_lock); log = std::move(other.log); return *this; } bool enabled() const { std::lock_guard<mutex_type> lock(mutex); return log.enabled(); } void enable() { std::lock_guard<mutex_type> lock(mutex); log.enable(); } void disable() { std::lock_guard<mutex_type> lock(mutex); log.disable(); } void set_filter(filter_t&& filter) { std::lock_guard<mutex_type> lock(mutex); log.set_filter(std::move(filter)); } void add_attribute(const log::attribute_pair_t& attr) { std::lock_guard<mutex_type> lock(mutex); log.add_attribute(attr); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { std::lock_guard<mutex_type> lock(mutex); log.add_frontend(std::move(frontend)); } void set_exception_handler(log::exception_handler_t&& handler) { std::lock_guard<mutex_type> lock(mutex); log.set_exception_handler(std::move(handler)); } template<typename... Args> log::record_t open_record(Args&&... args) const { std::lock_guard<mutex_type> lock(mutex); return log.open_record(std::forward<Args>(args)...); } void push(log::record_t&& record) const { std::lock_guard<mutex_type> lock(mutex); log.push(std::move(record)); } template<typename Level> typename std::enable_if< std::is_same< logger_type, verbose_logger_t<Level> >::value, Level >::type verbosity() const { std::lock_guard<mutex_type> lock(mutex); return log.verbosity(); } template<typename Level> typename std::enable_if< std::is_same< logger_type, verbose_logger_t<Level> >::value >::type verbosity(Level level) { std::lock_guard<mutex_type> lock(mutex); return log.verbosity(level); } }; } // namespace blackhole <commit_msg>[API] Synchronized wrapper now provides reference to its underlying logger.<commit_after>#pragma once #include <mutex> #include <boost/thread.hpp> #include "blackhole/forwards.hpp" #include "blackhole/logger.hpp" namespace blackhole { template<class Logger, class Mutex> class synchronized { public: typedef Logger logger_type; typedef Mutex mutex_type; private: logger_type log_; mutable mutex_type mutex; friend class scoped_attributes_t; public: synchronized() {} explicit synchronized(logger_type&& logger) : log_(std::move(logger)) {} synchronized(synchronized&& other) { *this = std::move(other); } synchronized& operator=(synchronized&& other) { //! @compat GCC4.4 //! GCC4.4 doesn't implement `std::lock` as like as `std::adopt_lock`. boost::lock(mutex, other.mutex); boost::lock_guard<mutex_type> lock(mutex, boost::adopt_lock); boost::lock_guard<mutex_type> other_lock(other.mutex, boost::adopt_lock); log_ = std::move(other.log_); return *this; } logger_type& log() { return log_; } bool enabled() const { std::lock_guard<mutex_type> lock(mutex); return log_.enabled(); } void enable() { std::lock_guard<mutex_type> lock(mutex); log_.enable(); } void disable() { std::lock_guard<mutex_type> lock(mutex); log_.disable(); } void set_filter(filter_t&& filter) { std::lock_guard<mutex_type> lock(mutex); log_.set_filter(std::move(filter)); } void add_attribute(const log::attribute_pair_t& attr) { std::lock_guard<mutex_type> lock(mutex); log_.add_attribute(attr); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { std::lock_guard<mutex_type> lock(mutex); log_.add_frontend(std::move(frontend)); } void set_exception_handler(log::exception_handler_t&& handler) { std::lock_guard<mutex_type> lock(mutex); log_.set_exception_handler(std::move(handler)); } template<typename... Args> log::record_t open_record(Args&&... args) const { std::lock_guard<mutex_type> lock(mutex); return log_.open_record(std::forward<Args>(args)...); } void push(log::record_t&& record) const { std::lock_guard<mutex_type> lock(mutex); log_.push(std::move(record)); } template<typename Level> typename std::enable_if< std::is_same< logger_type, verbose_logger_t<Level> >::value, Level >::type verbosity() const { std::lock_guard<mutex_type> lock(mutex); return log_.verbosity(); } template<typename Level> typename std::enable_if< std::is_same< logger_type, verbose_logger_t<Level> >::value >::type verbosity(Level level) { std::lock_guard<mutex_type> lock(mutex); return log_.verbosity(level); } }; } // namespace blackhole <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AView.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2007-03-26 13:58:49 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_VIEW_HXX_ #include "ado/AView.hxx" #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_ #include "ado/adoimp.hxx" #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif // ------------------------------------------------------------------------- using namespace comphelper; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // IMPLEMENT_SERVICE_INFO(OAdoView,"com.sun.star.sdbcx.AView","com.sun.star.sdbcx.View"); // ------------------------------------------------------------------------- OAdoView::OAdoView(sal_Bool _bCase,ADOView* _pView) : OView_ADO(_bCase,NULL) ,m_aView(_pView) { } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoView::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoView::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OView_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoView::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const { if(m_aView.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: rValue <<= m_aView.get_Name(); break; case PROPERTY_ID_CATALOGNAME: break; case PROPERTY_ID_SCHEMANAME: // rValue <<= m_aView.get_Type(); break; case PROPERTY_ID_COMMAND: { OLEVariant aVar; m_aView.get_Command(aVar); if(!aVar.isNull() && !aVar.isEmpty()) { ADOCommand* pCom = (ADOCommand*)aVar.getIDispatch(); OLEString aBSTR; pCom->get_CommandText(&aBSTR); rValue <<= (::rtl::OUString) aBSTR; } } break; } } else OView_ADO::getFastPropertyValue(rValue,nHandle); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoView::acquire() throw() { OView_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoView::release() throw() { OView_ADO::release(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.16.144); FILE MERGED 2008/04/01 15:08:37 thb 1.16.144.3: #i85898# Stripping all external header guards 2008/04/01 10:52:50 thb 1.16.144.2: #i85898# Stripping all external header guards 2008/03/28 15:23:27 rt 1.16.144.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: AView.cxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "ado/AView.hxx" #include <com/sun/star/lang/DisposedException.hpp> #include "ado/adoimp.hxx" #include <cppuhelper/typeprovider.hxx> #include "ado/Awrapado.hxx" #include <comphelper/sequence.hxx> #include <comphelper/types.hxx> #include "TConnection.hxx" // ------------------------------------------------------------------------- using namespace comphelper; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // IMPLEMENT_SERVICE_INFO(OAdoView,"com.sun.star.sdbcx.AView","com.sun.star.sdbcx.View"); // ------------------------------------------------------------------------- OAdoView::OAdoView(sal_Bool _bCase,ADOView* _pView) : OView_ADO(_bCase,NULL) ,m_aView(_pView) { } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoView::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoView::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OView_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoView::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const { if(m_aView.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: rValue <<= m_aView.get_Name(); break; case PROPERTY_ID_CATALOGNAME: break; case PROPERTY_ID_SCHEMANAME: // rValue <<= m_aView.get_Type(); break; case PROPERTY_ID_COMMAND: { OLEVariant aVar; m_aView.get_Command(aVar); if(!aVar.isNull() && !aVar.isEmpty()) { ADOCommand* pCom = (ADOCommand*)aVar.getIDispatch(); OLEString aBSTR; pCom->get_CommandText(&aBSTR); rValue <<= (::rtl::OUString) aBSTR; } } break; } } else OView_ADO::getFastPropertyValue(rValue,nHandle); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoView::acquire() throw() { OView_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoView::release() throw() { OView_ADO::release(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "meshoptimizer.h" #include <cassert> #include <vector> namespace meshopt { static unsigned int findStripFirst(const unsigned int buffer[][3], unsigned int buffer_size, const unsigned int* valence) { unsigned int index = 0; unsigned int iv = ~0u; for (unsigned int i = 0; i < buffer_size; ++i) { unsigned int va = valence[buffer[i][0]], vb = valence[buffer[i][1]], vc = valence[buffer[i][2]]; unsigned int v = (va < vb && va < vc) ? va : (vb < vc) ? vb : vc; if (v < iv) { index = i; iv = v; } } return index; } static int findStripNext(const unsigned int buffer[][3], unsigned int buffer_size, unsigned int e0, unsigned int e1) { for (unsigned int i = 0; i < buffer_size; ++i) { unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; if (e0 == a && e1 == b) return (i << 2) | 2; else if (e0 == b && e1 == c) return (i << 2) | 0; else if (e0 == c && e1 == a) return (i << 2) | 1; } return -1; } } // namespace meshopt size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count) { assert(destination != indices); assert(index_count % 3 == 0); using namespace meshopt; const size_t buffer_capacity = 8; unsigned int buffer[buffer_capacity][3] = {}; unsigned int buffer_size = 0; size_t index_offset = 0; unsigned int strip[2] = {}; unsigned int parity = 0; size_t strip_size = 0; // compute vertex valence; this is used to prioritize starting triangle for strips std::vector<unsigned int> valence(vertex_count, 0); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); valence[index]++; } int next = -1; while (buffer_size > 0 || index_offset < index_count) { assert(next < 0 || (size_t(next >> 2) < buffer_size && (next & 3) < 3)); // fill triangle buffer while (buffer_size < buffer_capacity && index_offset < index_count) { buffer[buffer_size][0] = indices[index_offset + 0]; buffer[buffer_size][1] = indices[index_offset + 1]; buffer[buffer_size][2] = indices[index_offset + 2]; buffer_size++; index_offset += 3; } assert(buffer_size > 0); if (next >= 0) { unsigned int i = next >> 2; unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; unsigned int v = buffer[i][next & 3]; // unordered removal from the buffer buffer[i][0] = buffer[buffer_size - 1][0]; buffer[i][1] = buffer[buffer_size - 1][1]; buffer[i][2] = buffer[buffer_size - 1][2]; buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // find next triangle (note that edge order flips on every iteration) // in some cases we need to perform a swap to pick a different outgoing triangle edge // for [a b c], the default strip edge is [b c], but we might want to use [a c] int cont = findStripNext(buffer, buffer_size, parity ? strip[1] : v, parity ? v : strip[1]); int swap = cont < 0 ? findStripNext(buffer, buffer_size, parity ? v : strip[0], parity ? strip[0] : v) : -1; if (cont < 0 && swap >= 0) { // [a b c] => [a b a c] destination[strip_size++] = strip[0]; destination[strip_size++] = v; // next strip has same winding // ? a b => b a v strip[1] = v; next = swap; } else { // emit the next vertex in the strip destination[strip_size++] = v; // next strip has flipped winding strip[0] = strip[1]; strip[1] = v; parity ^= 1; next = cont; } } else { // if we didn't find anything, we need to find the next new triangle // we use a heuristic to maximize the strip length unsigned int i = findStripFirst(buffer, buffer_size, &valence[0]); unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; // unordered removal from the buffer buffer[i][0] = buffer[buffer_size - 1][0]; buffer[i][1] = buffer[buffer_size - 1][1]; buffer[i][2] = buffer[buffer_size - 1][2]; buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // we need to pre-rotate the triangle so that we will find a match in the existing buffer on the next iteration int ea = findStripNext(buffer, buffer_size, c, b); int eb = ea < 0 ? findStripNext(buffer, buffer_size, a, c) : -1; int ec = eb < 0 ? findStripNext(buffer, buffer_size, b, a) : -1; if (ea >= 0) { // keep abc next = ea; } else if (eb >= 0) { // abc -> bca unsigned int t = a; a = b, b = c, c = t; next = eb; } else if (ec >= 0) { // abc -> cab unsigned int t = c; c = b, b = a, a = t; next = ec; } // emit the new strip; we use restart indices if (strip_size) destination[strip_size++] = ~0u; destination[strip_size++] = a; destination[strip_size++] = b; destination[strip_size++] = c; // new strip always starts with the same edge winding strip[0] = b; strip[1] = c; parity = 1; } } return strip_size; } size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count) { assert(destination != indices); size_t offset = 0; size_t start = 0; for (size_t i = 0; i < index_count; ++i) { if (indices[i] == ~0u) { start = i + 1; } else if (i - start >= 2) { unsigned int a = indices[i - 2], b = indices[i - 1], c = indices[i]; if ((i - start) & 1) { unsigned int t = a; a = b, b = t; } if (a != b && a != c && b != c) { destination[offset + 0] = a; destination[offset + 1] = b; destination[offset + 2] = c; offset += 3; } } } return offset; } <commit_msg>stripify: Convert to meshopt_Buffer<T><commit_after>#include "meshoptimizer.h" #include <assert.h> #include <string.h> namespace meshopt { static unsigned int findStripFirst(const unsigned int buffer[][3], unsigned int buffer_size, const unsigned int* valence) { unsigned int index = 0; unsigned int iv = ~0u; for (unsigned int i = 0; i < buffer_size; ++i) { unsigned int va = valence[buffer[i][0]], vb = valence[buffer[i][1]], vc = valence[buffer[i][2]]; unsigned int v = (va < vb && va < vc) ? va : (vb < vc) ? vb : vc; if (v < iv) { index = i; iv = v; } } return index; } static int findStripNext(const unsigned int buffer[][3], unsigned int buffer_size, unsigned int e0, unsigned int e1) { for (unsigned int i = 0; i < buffer_size; ++i) { unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; if (e0 == a && e1 == b) return (i << 2) | 2; else if (e0 == b && e1 == c) return (i << 2) | 0; else if (e0 == c && e1 == a) return (i << 2) | 1; } return -1; } } // namespace meshopt size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count) { assert(destination != indices); assert(index_count % 3 == 0); using namespace meshopt; const size_t buffer_capacity = 8; unsigned int buffer[buffer_capacity][3] = {}; unsigned int buffer_size = 0; size_t index_offset = 0; unsigned int strip[2] = {}; unsigned int parity = 0; size_t strip_size = 0; // compute vertex valence; this is used to prioritize starting triangle for strips meshopt_Buffer<unsigned int> valence(vertex_count); memset(valence.data, 0, vertex_count * sizeof(unsigned int)); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); valence[index]++; } int next = -1; while (buffer_size > 0 || index_offset < index_count) { assert(next < 0 || (size_t(next >> 2) < buffer_size && (next & 3) < 3)); // fill triangle buffer while (buffer_size < buffer_capacity && index_offset < index_count) { buffer[buffer_size][0] = indices[index_offset + 0]; buffer[buffer_size][1] = indices[index_offset + 1]; buffer[buffer_size][2] = indices[index_offset + 2]; buffer_size++; index_offset += 3; } assert(buffer_size > 0); if (next >= 0) { unsigned int i = next >> 2; unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; unsigned int v = buffer[i][next & 3]; // unordered removal from the buffer buffer[i][0] = buffer[buffer_size - 1][0]; buffer[i][1] = buffer[buffer_size - 1][1]; buffer[i][2] = buffer[buffer_size - 1][2]; buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // find next triangle (note that edge order flips on every iteration) // in some cases we need to perform a swap to pick a different outgoing triangle edge // for [a b c], the default strip edge is [b c], but we might want to use [a c] int cont = findStripNext(buffer, buffer_size, parity ? strip[1] : v, parity ? v : strip[1]); int swap = cont < 0 ? findStripNext(buffer, buffer_size, parity ? v : strip[0], parity ? strip[0] : v) : -1; if (cont < 0 && swap >= 0) { // [a b c] => [a b a c] destination[strip_size++] = strip[0]; destination[strip_size++] = v; // next strip has same winding // ? a b => b a v strip[1] = v; next = swap; } else { // emit the next vertex in the strip destination[strip_size++] = v; // next strip has flipped winding strip[0] = strip[1]; strip[1] = v; parity ^= 1; next = cont; } } else { // if we didn't find anything, we need to find the next new triangle // we use a heuristic to maximize the strip length unsigned int i = findStripFirst(buffer, buffer_size, &valence[0]); unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; // unordered removal from the buffer buffer[i][0] = buffer[buffer_size - 1][0]; buffer[i][1] = buffer[buffer_size - 1][1]; buffer[i][2] = buffer[buffer_size - 1][2]; buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // we need to pre-rotate the triangle so that we will find a match in the existing buffer on the next iteration int ea = findStripNext(buffer, buffer_size, c, b); int eb = ea < 0 ? findStripNext(buffer, buffer_size, a, c) : -1; int ec = eb < 0 ? findStripNext(buffer, buffer_size, b, a) : -1; if (ea >= 0) { // keep abc next = ea; } else if (eb >= 0) { // abc -> bca unsigned int t = a; a = b, b = c, c = t; next = eb; } else if (ec >= 0) { // abc -> cab unsigned int t = c; c = b, b = a, a = t; next = ec; } // emit the new strip; we use restart indices if (strip_size) destination[strip_size++] = ~0u; destination[strip_size++] = a; destination[strip_size++] = b; destination[strip_size++] = c; // new strip always starts with the same edge winding strip[0] = b; strip[1] = c; parity = 1; } } return strip_size; } size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count) { assert(destination != indices); size_t offset = 0; size_t start = 0; for (size_t i = 0; i < index_count; ++i) { if (indices[i] == ~0u) { start = i + 1; } else if (i - start >= 2) { unsigned int a = indices[i - 2], b = indices[i - 1], c = indices[i]; if ((i - start) & 1) { unsigned int t = a; a = b, b = t; } if (a != b && a != c && b != c) { destination[offset + 0] = a; destination[offset + 1] = b; destination[offset + 2] = c; offset += 3; } } } return offset; } <|endoftext|>
<commit_before>#include "ruby.h" #include <Rpc.h> #pragma comment(lib, "Rpcrt4.lib") VALUE method_generate(VALUE self) { UUID uuid = {0}; char * uuid_string; ::UuidCreate(&uuid); RPC_CSTR szUuid = NULL; if (::UuidToStringA(&uuid, &szUuid) == RPC_S_OK) { uuid_string = (char*) szUuid; ::RpcStringFreeA(&szUuid); } return rb_str_new2(uuid_string); } <commit_msg>Remove pragma from win implementation.<commit_after>#include "ruby.h" #include <Rpc.h> VALUE method_generate(VALUE self) { UUID uuid = {0}; char * uuid_string; ::UuidCreate(&uuid); RPC_CSTR szUuid = NULL; if (::UuidToStringA(&uuid, &szUuid) == RPC_S_OK) { uuid_string = (char*) szUuid; ::RpcStringFreeA(&szUuid); } return rb_str_new2(uuid_string); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief Fixed FIFO (first in first out) テンプレート @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <cstdint> namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 固定サイズ FIFO クラス @param[in] UNIT 基本形 @param[in] SIZE バッファサイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class UNIT, uint32_t SIZE> class fixed_fifo { volatile uint32_t get_; volatile uint32_t put_; UNIT buff_[SIZE]; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// fixed_fifo() noexcept : get_(0), put_(0) { } //-----------------------------------------------------------------// /*! @brief バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// inline uint32_t size() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 長さを返す @return 長さ */ //-----------------------------------------------------------------// uint32_t length() const noexcept { if(put_ >= get_) return (put_ - get_); else return (SIZE + put_ - get_); } //-----------------------------------------------------------------// /*! @brief クリア */ //-----------------------------------------------------------------// inline void clear() noexcept { get_ = put_ = 0; } //-----------------------------------------------------------------// /*! @brief 値の格納参照を得る @param[in] ofs オフセット(格納領域を超えたオフセットは未定義) @return 値の格納参照 */ //-----------------------------------------------------------------// inline UNIT& put_at(uint32_t ofs = 0) noexcept { return buff_[(put_ + ofs) % SIZE]; } //-----------------------------------------------------------------// /*! @brief 値の格納ポイントの移動 */ //-----------------------------------------------------------------// inline void put_go() noexcept { volatile uint16_t put = put_; ++put; if(put >= SIZE) { put = 0; } put_ = put; } //-----------------------------------------------------------------// /*! @brief 値の格納 @param[in] v 値 */ //-----------------------------------------------------------------// void put(const UNIT& v) noexcept { buff_[put_] = v; put_go(); } //-----------------------------------------------------------------// /*! @brief 値の取得参照を得る @param[in] ofs オフセット(格納領域を超えたオフセットは未定義) @return 値の取得参照 */ //-----------------------------------------------------------------// inline const UNIT& get_at(uint32_t ofs = 0) const noexcept { return buff_[(get_ + ofs) % SIZE]; } //-----------------------------------------------------------------// /*! @brief 値の取得 */ //-----------------------------------------------------------------// inline void get_go() noexcept { volatile uint16_t get = get_; ++get; if(get >= SIZE) { get = 0; } get_ = get; } //-----------------------------------------------------------------// /*! @brief 値の取得 @return 値 */ //-----------------------------------------------------------------// UNIT get() noexcept { UNIT v = buff_[get_]; get_go(); return v; } //-----------------------------------------------------------------// /*! @brief get 位置を返す @return 位置 */ //-----------------------------------------------------------------// inline uint16_t pos_get() const noexcept { return get_; } //-----------------------------------------------------------------// /*! @brief put 位置を返す @return 位置 */ //-----------------------------------------------------------------// inline uint16_t pos_put() const noexcept { return put_; } }; } <commit_msg>Update: cleanup<commit_after>#pragma once //=====================================================================// /*! @file @brief Fixed FIFO (first in first out) テンプレート @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <cstdint> namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 固定サイズ FIFO クラス @param[in] UNIT 基本形 @param[in] SIZE バッファサイズ(最低2) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class UNIT, uint32_t SIZE> class fixed_fifo { volatile uint32_t get_; volatile uint32_t put_; UNIT buff_[SIZE]; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// fixed_fifo() noexcept : get_(0), put_(0) { } //-----------------------------------------------------------------// /*! @brief バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// inline uint32_t size() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 長さを返す @return 長さ */ //-----------------------------------------------------------------// uint32_t length() const noexcept { if(put_ >= get_) return (put_ - get_); else return (SIZE + put_ - get_); } //-----------------------------------------------------------------// /*! @brief クリア */ //-----------------------------------------------------------------// inline void clear() noexcept { get_ = put_ = 0; } //-----------------------------------------------------------------// /*! @brief 値の格納参照を得る @param[in] ofs オフセット(格納領域を超えたオフセットは未定義) @return 値の格納参照 */ //-----------------------------------------------------------------// inline UNIT& put_at(uint32_t ofs = 0) noexcept { return buff_[(put_ + ofs) % SIZE]; } //-----------------------------------------------------------------// /*! @brief 値の格納ポイントの移動 */ //-----------------------------------------------------------------// inline void put_go() noexcept { volatile auto put = put_; ++put; if(put >= SIZE) { put = 0; } put_ = put; } //-----------------------------------------------------------------// /*! @brief 値の格納 @param[in] v 値 */ //-----------------------------------------------------------------// void put(const UNIT& v) noexcept { buff_[put_] = v; put_go(); } //-----------------------------------------------------------------// /*! @brief 値の取得参照を得る @param[in] ofs オフセット(格納領域を超えたオフセットは未定義) @return 値の取得参照 */ //-----------------------------------------------------------------// inline const UNIT& get_at(uint32_t ofs = 0) const noexcept { return buff_[(get_ + ofs) % SIZE]; } //-----------------------------------------------------------------// /*! @brief 値の取得 */ //-----------------------------------------------------------------// inline void get_go() noexcept { volatile auto get = get_; ++get; if(get >= SIZE) { get = 0; } get_ = get; } //-----------------------------------------------------------------// /*! @brief 値の取得 @return 値 */ //-----------------------------------------------------------------// UNIT get() noexcept { UNIT v = buff_[get_]; get_go(); return v; } //-----------------------------------------------------------------// /*! @brief get 位置を返す @return 位置 */ //-----------------------------------------------------------------// inline uint16_t pos_get() const noexcept { return get_; } //-----------------------------------------------------------------// /*! @brief put 位置を返す @return 位置 */ //-----------------------------------------------------------------// inline uint16_t pos_put() const noexcept { return put_; } }; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014—2016 David Wicks, sansumbrella.com * 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. * * 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 <vector> #include "Phrase.hpp" #include "UnitBezier.h" #include "TimeType.h" namespace choreograph { class Curve { public: enum Type { Bezier, Hold, Linear }; float solve(float t) const; void setType(Type type) { _type = type; } void hold() { _type = Hold; } BezierInterpolant& bezier() { _type = Bezier; return _bezier; } private: Type _type = Linear; BezierInterpolant _bezier; }; float Curve::solve(float t) const { switch (_type) { case Bezier: return _bezier.solve(t); break; case Hold: return 0.0f; break; case Linear: return t; break; default: return t; break; } } /// /// Simple channel concept with bezier interpolation between keys. /// Goals: /// - Easy serialization /// - Easy to create graphical manipulation tools. /// - Support direct manipulation of animation data. /// - Avoid deeply nested information. Flat hierarchy. /// - Flexible enough to create an AfterEffects-style timeline. /// /// Good for animating single values, like floats or quaternions. /// For vector types, use a channel per component (and maybe add a group type to associate them). /// Grouping type could be a manipulator/animator type class that reads/writes multiple channels. /// template <typename T> class Channel { public: struct Key { Key(T value, Time time): value(value), time(time) {} T value; Time time; }; Channel() = default; /// Return the value of the channel at a given time. T value(Time at_time) const; /// Return the interpolated value between two keys. /// If you keep track of keys yourself, this is faster. T interpolatedValue(size_t curve_index, Time at_time) const; /// Returns the index of the starting key for the current time. /// The curve lies between two keys. size_t index(Time at_time) const; size_t lastIndex() const { return _keys.empty() ? 0 : _keys.size() - 1; } /// Append a key to the list of keys, positioned at \offset time after the previous key. Channel& appendKeyAfter(T value, Time offset) { if (! _keys.empty()) { _curves.emplace_back(); } _keys.emplace_back(value, duration() + offset); return *this; } /// Insert a key at the given time. Channel& insertKey(T value, Time at_time); Time duration() const { return _keys.empty() ? 0 : _keys.back().time; } const std::vector<Key>& keys() const { return _keys; } const std::vector<Curve>& curves() const { return _curves; } std::vector<Key>& mutableKeys() { return _keys; } std::vector<Curve>& mutableCurves() { return _curves; } private: std::vector<Key> _keys; // may make polymorphic in future (like phrases are). Basically just an ease fn. // Compare std::function<float (float)> for max flexibility against custom class. std::vector<Curve> _curves; }; #pragma mark - Channel Template Implementation template <typename T> size_t Channel<T>::index(Time at_time) const { if( at_time <= 0 ) { return 0; } else if ( at_time >= this->duration() ) { return lastIndex(); } for (auto i = 0; i < _keys.size() - 1; i += 1) { auto &a = _keys[i], &b = _keys[i + 1]; if (a.time <= at_time && b.time >= at_time) { return i; } } return lastIndex(); } template <typename T> T Channel<T>::value(Time at_time) const { if (at_time >= duration()) { return _keys.back().value; } else if (at_time <= 0.0) { return _keys.front().value; } return interpolatedValue(index(at_time), at_time); } template <typename T> T Channel<T>::interpolatedValue(size_t curve_index, Time at_time) const { auto &a = _keys[curve_index]; auto &b = _keys[curve_index + 1]; auto &c = _curves[curve_index]; auto x = (at_time - a.time) / (b.time - a.time); auto t = c.solve(x); return lerpT(a.value, b.value, t); } template <typename T> Channel<T>& Channel<T>::insertKey(T value, Time at_time) { if (_keys.empty()) { _keys.emplace_back(value, at_time); return *this; } auto i = index(at_time); if (_curves.empty()) { _curves.emplace_back(); } else { _curves.insert(_curves.begin() + i, {}); } _keys.insert(_keys.begin() + i + 1, {value, at_time}); return *this; } } // namepsace choreograph <commit_msg>Properly construct curve for insertion.<commit_after>/* * Copyright (c) 2014—2016 David Wicks, sansumbrella.com * 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. * * 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 <vector> #include "Phrase.hpp" #include "UnitBezier.h" #include "TimeType.h" namespace choreograph { class Curve { public: enum Type { Bezier, Hold, Linear }; Curve() = default; explicit Curve(Type t): _type(t) {} explicit Curve(const BezierInterpolant &bezier): _type(Bezier), _bezier(bezier) {} float solve(float t) const; void setType(Type type) { _type = type; } void hold() { _type = Hold; } BezierInterpolant& bezier() { _type = Bezier; return _bezier; } private: Type _type = Linear; BezierInterpolant _bezier; }; float Curve::solve(float t) const { switch (_type) { case Bezier: return _bezier.solve(t); break; case Hold: return 0.0f; break; case Linear: return t; break; default: return t; break; } } /// /// Simple channel concept with bezier interpolation between keys. /// Goals: /// - Easy serialization /// - Easy to create graphical manipulation tools. /// - Support direct manipulation of animation data. /// - Avoid deeply nested information. Flat hierarchy. /// - Flexible enough to create an AfterEffects-style timeline. /// - Separate motion path with bezier interpolation for full effect. /// - Get time along section with channel, calculate value using path. /// - Channel for timing, with key values corresponding to control points on spatial curve. /// /// Good for animating single values, like floats or quaternions. /// For vector types, use a channel per component (and maybe add a group type to associate them). /// Grouping type could be a manipulator/animator type class that reads/writes multiple channels. /// template <typename T> class Channel { public: struct Key { Key(T value, Time time): value(value), time(time) {} T value; Time time; }; Channel() = default; /// Return the value of the channel at a given time. T value(Time at_time) const; /// Return the interpolated value between two keys. /// If you keep track of keys yourself, this is faster. T interpolatedValue(size_t curve_index, Time at_time) const; /// Returns the index of the starting key for the current time. /// The curve lies between two keys. size_t index(Time at_time) const; size_t lastIndex() const { return _keys.empty() ? 0 : _keys.size() - 1; } /// Append a key to the list of keys, positioned at \offset time after the previous key. Channel& appendKeyAfter(T value, Time offset) { if (! _keys.empty()) { _curves.emplace_back(); } _keys.emplace_back(value, duration() + offset); return *this; } /// Insert a key at the given time. Channel& insertKey(T value, Time at_time); Time duration() const { return _keys.empty() ? 0 : _keys.back().time; } const std::vector<Key>& keys() const { return _keys; } const std::vector<Curve>& curves() const { return _curves; } std::vector<Key>& mutableKeys() { return _keys; } std::vector<Curve>& mutableCurves() { return _curves; } private: std::vector<Key> _keys; // may make polymorphic in future (like phrases are). Basically just an ease fn. // Compare std::function<float (float)> for max flexibility against custom class. std::vector<Curve> _curves; }; #pragma mark - Channel Template Implementation template <typename T> size_t Channel<T>::index(Time at_time) const { if( at_time <= 0 ) { return 0; } else if ( at_time >= this->duration() ) { return lastIndex(); } for (auto i = 0; i < _keys.size() - 1; i += 1) { auto &a = _keys[i], &b = _keys[i + 1]; if (a.time <= at_time && b.time >= at_time) { return i; } } return lastIndex(); } template <typename T> T Channel<T>::value(Time at_time) const { if (at_time >= duration()) { return _keys.back().value; } else if (at_time <= 0.0) { return _keys.front().value; } return interpolatedValue(index(at_time), at_time); } template <typename T> T Channel<T>::interpolatedValue(size_t curve_index, Time at_time) const { auto &a = _keys[curve_index]; auto &b = _keys[curve_index + 1]; auto &c = _curves[curve_index]; auto x = (at_time - a.time) / (b.time - a.time); auto t = c.solve(x); return lerpT(a.value, b.value, t); } template <typename T> Channel<T>& Channel<T>::insertKey(T value, Time at_time) { if (_keys.empty()) { _keys.emplace_back(value, at_time); return *this; } auto i = index(at_time); if (_curves.empty()) { _curves.emplace_back(Curve::Linear); } else { _curves.insert(_curves.begin() + i, Curve(Curve::Linear)); } _keys.insert(_keys.begin() + i + 1, {value, at_time}); return *this; } } // namepsace choreograph <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qcontactmanager.h" #include "qcontact_p.h" #include "qcontactgroup_p.h" #include "qcontactdetaildefinition.h" #include "qcontactmanager_p.h" #include "qcontactmanagerengine.h" #include "qcontactmemorybackend_p.h" #include <QUuid> #include <QSharedData> /*! * \class QContactMemoryEngine * \brief This class provides an in-memory implementation of a contacts backend. * * It may be used as a reference implementation, or when persistent storage is not required. * * During construction, it will load the in-memory data associated with the memory store * identified by the "id" parameter from the given parameters if it exists, or a new, * anonymous store if it does not. * * Data stored in this engine is only available in the current process. * * This engine supports sharing, so an internal reference count is increased * whenever a manager uses this backend, and is decreased when the manager * no longer requires this engine. */ /* static data for manager class */ QMap<QString, QContactMemoryEngine*> QContactMemoryEngine::engines; /*! * Factory function for creating a new in-memory backend, based * on the given \a parameters. * * The same engine will be returned for multiple calls with the * same value for the "id" parameter, while one of them is in scope. */ QContactMemoryEngine* QContactMemoryEngine::createMemoryEngine(const QMap<QString, QString>& parameters) { QString idValue = parameters.value(QLatin1String("id")); if (idValue.isNull() || idValue.isEmpty()) { // no store given? new, anonymous store. idValue = QUuid::createUuid().toString(); } if (engines.contains(idValue)) { QContactMemoryEngine *engine = engines.value(idValue); engine->d->m_refCount.ref(); return engine; } else { QContactMemoryEngine *engine = new QContactMemoryEngine(parameters); engine->d->m_id = idValue; engines.insert(idValue, engine); return engine; } } /*! * Constructs a new in-memory backend. * * Loads the in-memory data associated with the memory store identified by the "id" parameter * from the given \a parameters if it exists, or a new, anonymous store if it does not. */ QContactMemoryEngine::QContactMemoryEngine(const QMap<QString, QString>& parameters) : d(new QContactMemoryEngineData) { Q_UNUSED(parameters); } /*! \reimp */ void QContactMemoryEngine::deref() { if (!d->m_refCount.deref()) { engines.remove(d->m_id); delete d; delete this; } } /*! \reimp */ QList<QUniqueId> QContactMemoryEngine::contacts(const QContactSortOrder& sortOrder, QContactManager::Error& error) const { error = QContactManager::NoError; if (!sortOrder.isValid()) return d->m_contactIds; // TODO: this needs to be done properly... QList<QUniqueId> sortedIds; QList<QContact> sortedContacts; for (int i = 0; i < d->m_contacts.size(); i++) QContactManagerEngine::addSorted(&sortedContacts, d->m_contacts.at(i), sortOrder); for (int i = 0; i < sortedContacts.size(); i++) sortedIds.append(sortedContacts.at(i).id()); return sortedIds; } /*! \reimp */ QContact QContactMemoryEngine::contact(const QUniqueId& contactId, QContactManager::Error& error) const { int index = d->m_contactIds.indexOf(contactId); if (index != -1) { error = QContactManager::NoError; QContact retn = d->m_contacts.at(index); QContactDisplayLabel dl = retn.detail(QLatin1String(QContactDisplayLabel::DefinitionName)); if (dl.label().isEmpty()) { QContactManager::Error synthError; dl.setLabel(synthesiseDisplayLabel(retn, synthError)); dl.setSynthesised(true); retn.saveDetail(&dl); } return retn; } error = QContactManager::DoesNotExistError; return QContact(); } /*! \reimp */ bool QContactMemoryEngine::saveContact(QContact* contact, bool batch, QContactManager::Error& error) { // ensure that the contact's details conform to their definitions if (!validateContact(*contact, error)) { error = QContactManager::InvalidDetailError; return false; } // check to see if this contact already exists int index = d->m_contactIds.indexOf(contact->id()); if (index != -1) { /* We also need to check that there are no modified create only details */ QContact oldContact = d->m_contacts.at(index); QSetIterator<QString> it(d->m_createOnlyIds); while (it.hasNext()) { const QString& id = it.next(); QList<QContactDetail> details = oldContact.details(id); QList<QContactDetail> newDetails = contact->details(id); /* Any entries in old should still be in new */ if (newDetails.count() < details.count()) { error = QContactManager::DetailAccessError; return false; } /* Now do a more detailed check */ for (int i=0; i < details.count(); i++) { if (!newDetails.contains(details.at(i))) { error = QContactManager::DetailAccessError; return false; } } } // Looks ok, so continue d->m_contacts.replace(index, *contact); error = QContactManager::NoError; if (!batch) { QList<QUniqueId> emitList; emitList.append(contact->id()); emit contactsChanged(emitList); } return true; } /* We ignore read only details here - we may have provided some */ // update the contact item - set its ID contact->setId(++d->m_nextContactId); // finally, add the contact to our internal lists and return d->m_contacts.append(*contact); // add contact to list d->m_contactIds.append(contact->id()); // track the contact id. error = QContactManager::NoError; // successful. // if we need to emit signals (ie, this isn't part of a batch operation) // then emit the correct one. if (!batch) { QList<QUniqueId> emitList; emitList.append(contact->id()); emit contactsAdded(emitList); } return true; } /*! \reimp */ bool QContactMemoryEngine::removeContact(const QUniqueId& contactId, bool batch, QContactManager::Error& error) { int index = d->m_contactIds.indexOf(contactId); if (index == -1) { error = QContactManager::DoesNotExistError; return false; } // remove the contact from the lists. d->m_contacts.removeAt(index); d->m_contactIds.removeAt(index); error = QContactManager::NoError; // also remove it from any groups that we have QMutableMapIterator<QUniqueId, QContactGroup> it(d->m_groups); while (it.hasNext()) { it.next(); it.value().removeMember(contactId); } // if we need to emit signals (ie, this isn't part of a batch operation) // then emit the correct one. if (!batch) { QList<QUniqueId> emitList; emitList.append(contactId); emit contactsRemoved(emitList); } return true; } /*! \reimp */ QList<QUniqueId> QContactMemoryEngine::groups(QContactManager::Error& error) const { error = QContactManager::NoError; return d->m_groups.keys(); } /*! \reimp */ QContactGroup QContactMemoryEngine::group(const QUniqueId& groupId, QContactManager::Error& error) const { error = QContactManager::NoError; if (!d->m_groups.contains(groupId)) error = QContactManager::DoesNotExistError; return d->m_groups.value(groupId); } /*! \reimp */ bool QContactMemoryEngine::saveGroup(QContactGroup* group, QContactManager::Error& error) { if (!group) { error = QContactManager::BadArgumentError; return false; } if (group->name().isEmpty()) { error = QContactManager::BadArgumentError; return false; } // if the group does not exist, generate a new group id for it. if (!d->m_groups.contains(group->id())) { group->setId(++d->m_nextGroupId); } // save it in the database d->m_groups.insert(group->id(), *group); error = QContactManager::NoError; return true; } /*! \reimp */ bool QContactMemoryEngine::removeGroup(const QUniqueId& groupId, QContactManager::Error& error) { if (!d->m_groups.contains(groupId)) { error = QContactManager::DoesNotExistError; return false; } d->m_groups.remove(groupId); error = QContactManager::NoError; return true; } /*! \reimp */ QMap<QString, QContactDetailDefinition> QContactMemoryEngine::detailDefinitions(QContactManager::Error& error) const { // lazy initialisation of schema definitions. if (d->m_definitions.isEmpty()) { d->m_definitions = QContactManagerEngine::schemaDefinitions(); // Extract create only definitions QMapIterator<QString, QContactDetailDefinition> it(d->m_definitions); while (it.hasNext()) { it.next(); if (it.value().accessConstraint() == QContactDetailDefinition::CreateOnly) d->m_createOnlyIds.insert(it.key()); } } error = QContactManager::NoError; return d->m_definitions; } /*! \reimp */ bool QContactMemoryEngine::saveDetailDefinition(const QContactDetailDefinition& def, QContactManager::Error& error) { if (!validateDefinition(def, error)) { return false; } detailDefinitions(error); // just to populate the definitions if we haven't already. d->m_definitions.insert(def.id(), def); if (def.accessConstraint() == QContactDetailDefinition::CreateOnly) d->m_createOnlyIds.insert(def.id()); error = QContactManager::NoError; return true; } /*! \reimp */ bool QContactMemoryEngine::removeDetailDefinition(const QString& definitionId, QContactManager::Error& error) { if (definitionId.isEmpty()) { error = QContactManager::BadArgumentError; return false; } detailDefinitions(error); // just to populate the definitions if we haven't already. bool success = d->m_definitions.remove(definitionId); d->m_createOnlyIds.remove(definitionId); if (success) error = QContactManager::NoError; else error = QContactManager::DoesNotExistError; return success; } /*! * \reimp */ bool QContactMemoryEngine::hasFeature(QContactManagerInfo::ManagerFeature feature) const { switch (feature) { case QContactManagerInfo::Groups: case QContactManagerInfo::Batch: case QContactManagerInfo::ActionPreferences: case QContactManagerInfo::ReadOnlyDetails: case QContactManagerInfo::CreateOnlyDetails: case QContactManagerInfo::MutableDefinitions: case QContactManagerInfo::Synchronous: return true; default: return false; } } /*! * \reimp */ QList<QVariant::Type> QContactMemoryEngine::supportedDataTypes() const { QList<QVariant::Type> st; st.append(QVariant::String); st.append(QVariant::Date); st.append(QVariant::DateTime); st.append(QVariant::Time); st.append(QVariant::Int); st.append(QVariant::UInt); st.append(QVariant::LongLong); st.append(QVariant::ULongLong); return st; } /*! * \reimp */ bool QContactMemoryEngine::filterSupported(const QContactFilter& filter) const { Q_UNUSED(filter); // Until we add hashes for common stuff, fall back to slow code return false; } <commit_msg>Add double support to memory engine.<commit_after>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qcontactmanager.h" #include "qcontact_p.h" #include "qcontactgroup_p.h" #include "qcontactdetaildefinition.h" #include "qcontactmanager_p.h" #include "qcontactmanagerengine.h" #include "qcontactmemorybackend_p.h" #include <QUuid> #include <QSharedData> /*! * \class QContactMemoryEngine * \brief This class provides an in-memory implementation of a contacts backend. * * It may be used as a reference implementation, or when persistent storage is not required. * * During construction, it will load the in-memory data associated with the memory store * identified by the "id" parameter from the given parameters if it exists, or a new, * anonymous store if it does not. * * Data stored in this engine is only available in the current process. * * This engine supports sharing, so an internal reference count is increased * whenever a manager uses this backend, and is decreased when the manager * no longer requires this engine. */ /* static data for manager class */ QMap<QString, QContactMemoryEngine*> QContactMemoryEngine::engines; /*! * Factory function for creating a new in-memory backend, based * on the given \a parameters. * * The same engine will be returned for multiple calls with the * same value for the "id" parameter, while one of them is in scope. */ QContactMemoryEngine* QContactMemoryEngine::createMemoryEngine(const QMap<QString, QString>& parameters) { QString idValue = parameters.value(QLatin1String("id")); if (idValue.isNull() || idValue.isEmpty()) { // no store given? new, anonymous store. idValue = QUuid::createUuid().toString(); } if (engines.contains(idValue)) { QContactMemoryEngine *engine = engines.value(idValue); engine->d->m_refCount.ref(); return engine; } else { QContactMemoryEngine *engine = new QContactMemoryEngine(parameters); engine->d->m_id = idValue; engines.insert(idValue, engine); return engine; } } /*! * Constructs a new in-memory backend. * * Loads the in-memory data associated with the memory store identified by the "id" parameter * from the given \a parameters if it exists, or a new, anonymous store if it does not. */ QContactMemoryEngine::QContactMemoryEngine(const QMap<QString, QString>& parameters) : d(new QContactMemoryEngineData) { Q_UNUSED(parameters); } /*! \reimp */ void QContactMemoryEngine::deref() { if (!d->m_refCount.deref()) { engines.remove(d->m_id); delete d; delete this; } } /*! \reimp */ QList<QUniqueId> QContactMemoryEngine::contacts(const QContactSortOrder& sortOrder, QContactManager::Error& error) const { error = QContactManager::NoError; if (!sortOrder.isValid()) return d->m_contactIds; // TODO: this needs to be done properly... QList<QUniqueId> sortedIds; QList<QContact> sortedContacts; for (int i = 0; i < d->m_contacts.size(); i++) QContactManagerEngine::addSorted(&sortedContacts, d->m_contacts.at(i), sortOrder); for (int i = 0; i < sortedContacts.size(); i++) sortedIds.append(sortedContacts.at(i).id()); return sortedIds; } /*! \reimp */ QContact QContactMemoryEngine::contact(const QUniqueId& contactId, QContactManager::Error& error) const { int index = d->m_contactIds.indexOf(contactId); if (index != -1) { error = QContactManager::NoError; QContact retn = d->m_contacts.at(index); QContactDisplayLabel dl = retn.detail(QLatin1String(QContactDisplayLabel::DefinitionName)); if (dl.label().isEmpty()) { QContactManager::Error synthError; dl.setLabel(synthesiseDisplayLabel(retn, synthError)); dl.setSynthesised(true); retn.saveDetail(&dl); } return retn; } error = QContactManager::DoesNotExistError; return QContact(); } /*! \reimp */ bool QContactMemoryEngine::saveContact(QContact* contact, bool batch, QContactManager::Error& error) { // ensure that the contact's details conform to their definitions if (!validateContact(*contact, error)) { error = QContactManager::InvalidDetailError; return false; } // check to see if this contact already exists int index = d->m_contactIds.indexOf(contact->id()); if (index != -1) { /* We also need to check that there are no modified create only details */ QContact oldContact = d->m_contacts.at(index); QSetIterator<QString> it(d->m_createOnlyIds); while (it.hasNext()) { const QString& id = it.next(); QList<QContactDetail> details = oldContact.details(id); QList<QContactDetail> newDetails = contact->details(id); /* Any entries in old should still be in new */ if (newDetails.count() < details.count()) { error = QContactManager::DetailAccessError; return false; } /* Now do a more detailed check */ for (int i=0; i < details.count(); i++) { if (!newDetails.contains(details.at(i))) { error = QContactManager::DetailAccessError; return false; } } } // Looks ok, so continue d->m_contacts.replace(index, *contact); error = QContactManager::NoError; if (!batch) { QList<QUniqueId> emitList; emitList.append(contact->id()); emit contactsChanged(emitList); } return true; } /* We ignore read only details here - we may have provided some */ // update the contact item - set its ID contact->setId(++d->m_nextContactId); // finally, add the contact to our internal lists and return d->m_contacts.append(*contact); // add contact to list d->m_contactIds.append(contact->id()); // track the contact id. error = QContactManager::NoError; // successful. // if we need to emit signals (ie, this isn't part of a batch operation) // then emit the correct one. if (!batch) { QList<QUniqueId> emitList; emitList.append(contact->id()); emit contactsAdded(emitList); } return true; } /*! \reimp */ bool QContactMemoryEngine::removeContact(const QUniqueId& contactId, bool batch, QContactManager::Error& error) { int index = d->m_contactIds.indexOf(contactId); if (index == -1) { error = QContactManager::DoesNotExistError; return false; } // remove the contact from the lists. d->m_contacts.removeAt(index); d->m_contactIds.removeAt(index); error = QContactManager::NoError; // also remove it from any groups that we have QMutableMapIterator<QUniqueId, QContactGroup> it(d->m_groups); while (it.hasNext()) { it.next(); it.value().removeMember(contactId); } // if we need to emit signals (ie, this isn't part of a batch operation) // then emit the correct one. if (!batch) { QList<QUniqueId> emitList; emitList.append(contactId); emit contactsRemoved(emitList); } return true; } /*! \reimp */ QList<QUniqueId> QContactMemoryEngine::groups(QContactManager::Error& error) const { error = QContactManager::NoError; return d->m_groups.keys(); } /*! \reimp */ QContactGroup QContactMemoryEngine::group(const QUniqueId& groupId, QContactManager::Error& error) const { error = QContactManager::NoError; if (!d->m_groups.contains(groupId)) error = QContactManager::DoesNotExistError; return d->m_groups.value(groupId); } /*! \reimp */ bool QContactMemoryEngine::saveGroup(QContactGroup* group, QContactManager::Error& error) { if (!group) { error = QContactManager::BadArgumentError; return false; } if (group->name().isEmpty()) { error = QContactManager::BadArgumentError; return false; } // if the group does not exist, generate a new group id for it. if (!d->m_groups.contains(group->id())) { group->setId(++d->m_nextGroupId); } // save it in the database d->m_groups.insert(group->id(), *group); error = QContactManager::NoError; return true; } /*! \reimp */ bool QContactMemoryEngine::removeGroup(const QUniqueId& groupId, QContactManager::Error& error) { if (!d->m_groups.contains(groupId)) { error = QContactManager::DoesNotExistError; return false; } d->m_groups.remove(groupId); error = QContactManager::NoError; return true; } /*! \reimp */ QMap<QString, QContactDetailDefinition> QContactMemoryEngine::detailDefinitions(QContactManager::Error& error) const { // lazy initialisation of schema definitions. if (d->m_definitions.isEmpty()) { d->m_definitions = QContactManagerEngine::schemaDefinitions(); // Extract create only definitions QMapIterator<QString, QContactDetailDefinition> it(d->m_definitions); while (it.hasNext()) { it.next(); if (it.value().accessConstraint() == QContactDetailDefinition::CreateOnly) d->m_createOnlyIds.insert(it.key()); } } error = QContactManager::NoError; return d->m_definitions; } /*! \reimp */ bool QContactMemoryEngine::saveDetailDefinition(const QContactDetailDefinition& def, QContactManager::Error& error) { if (!validateDefinition(def, error)) { return false; } detailDefinitions(error); // just to populate the definitions if we haven't already. d->m_definitions.insert(def.id(), def); if (def.accessConstraint() == QContactDetailDefinition::CreateOnly) d->m_createOnlyIds.insert(def.id()); error = QContactManager::NoError; return true; } /*! \reimp */ bool QContactMemoryEngine::removeDetailDefinition(const QString& definitionId, QContactManager::Error& error) { if (definitionId.isEmpty()) { error = QContactManager::BadArgumentError; return false; } detailDefinitions(error); // just to populate the definitions if we haven't already. bool success = d->m_definitions.remove(definitionId); d->m_createOnlyIds.remove(definitionId); if (success) error = QContactManager::NoError; else error = QContactManager::DoesNotExistError; return success; } /*! * \reimp */ bool QContactMemoryEngine::hasFeature(QContactManagerInfo::ManagerFeature feature) const { switch (feature) { case QContactManagerInfo::Groups: case QContactManagerInfo::Batch: case QContactManagerInfo::ActionPreferences: case QContactManagerInfo::ReadOnlyDetails: case QContactManagerInfo::CreateOnlyDetails: case QContactManagerInfo::MutableDefinitions: case QContactManagerInfo::Synchronous: return true; default: return false; } } /*! * \reimp */ QList<QVariant::Type> QContactMemoryEngine::supportedDataTypes() const { QList<QVariant::Type> st; st.append(QVariant::String); st.append(QVariant::Date); st.append(QVariant::DateTime); st.append(QVariant::Time); st.append(QVariant::Int); st.append(QVariant::UInt); st.append(QVariant::LongLong); st.append(QVariant::ULongLong); st.append(QVariant::Double); return st; } /*! * \reimp */ bool QContactMemoryEngine::filterSupported(const QContactFilter& filter) const { Q_UNUSED(filter); // Until we add hashes for common stuff, fall back to slow code return false; } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 NVIDIA Corporation * * 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 <thrust/random/uniform_real_distribution.h> #include <math.h> // XXX WAR missing definitions on MSVC __host__ __device__ double nextafter(double, double); __host__ __device__ float nextafterf(float, float); namespace thrust { namespace random { template<typename RealType> uniform_real_distribution<RealType> ::uniform_real_distribution(RealType a, RealType b) :m_param(a,b) { } // end uniform_real_distribution::uniform_real_distribution() template<typename RealType> uniform_real_distribution<RealType> ::uniform_real_distribution(const param_type &parm) :m_param(parm) { } // end uniform_real_distribution::uniform_real_distribution() template<typename RealType> void uniform_real_distribution<RealType> ::reset(void) { } // end uniform_real_distribution::reset() template<typename RealType> template<typename UniformRandomNumberGenerator> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng) { return operator()(urng, m_param); } // end uniform_real::operator()() namespace detail { __host__ __device__ __inline__ double nextafter(double x, double y) { return ::nextafter(x,y); } __host__ __device__ __inline__ float nextafter(float x, float y) { return ::nextafterf(x,y); } } template<typename RealType> template<typename UniformRandomNumberGenerator> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng, const param_type &parm) { // call the urng & map its result to [0,1] result_type result = static_cast<result_type>(urng() - UniformRandomNumberGenerator::min); result /= static_cast<result_type>(UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min); // do not include parm.second in the result // get the next value after parm.second in the direction of parm.first // we need to do this because the range is half-open at parm.second return (result * (detail::nextafter(parm.second,parm.first) - parm.first)) + parm.first; } // end uniform_real::operator()() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::a(void) const { return m_param.first; } // end uniform_real::a() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::b(void) const { return m_param.second; } // end uniform_real_distribution::b() template<typename RealType> typename uniform_real_distribution<RealType>::param_type uniform_real_distribution<RealType> ::param(void) const { return m_param;; } // end uniform_real_distribution::param() template<typename RealType> void uniform_real_distribution<RealType> ::param(const param_type &parm) { m_param = parm; } // end uniform_real_distribution::param() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::min(void) const { return a(); } // end uniform_real_distribution::min() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::max(void) const { return b(); } // end uniform_real_distribution::max() template<typename RealType> bool uniform_real_distribution<RealType> ::equal(const uniform_real_distribution &rhs) const { return m_param == rhs.param(); } template<typename RealType> template<typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& uniform_real_distribution<RealType> ::stream_out(std::basic_ostream<CharT,Traits> &os) const { typedef std::basic_ostream<CharT,Traits> ostream_type; typedef typename ostream_type::ios_base ios_base; // save old flags and fill character const typename ios_base::fmtflags flags = os.flags(); const CharT fill = os.fill(); const CharT space = os.widen(' '); os.flags(ios_base::dec | ios_base::fixed | ios_base::left); os.fill(space); os << a() << space << b(); // restore old flags and fill character os.flags(flags); os.fill(fill); return os; } template<typename RealType> template<typename CharT, typename Traits> std::basic_istream<CharT,Traits>& uniform_real_distribution<RealType> ::stream_in(std::basic_istream<CharT,Traits> &is) { typedef std::basic_istream<CharT,Traits> istream_type; typedef typename istream_type::ios_base ios_base; // save old flags const typename ios_base::fmtflags flags = is.flags(); is.flags(ios_base::skipws); is >> m_param.first >> m_param.second; // restore old flags is.flags(flags); return is; } template<typename RealType> bool operator==(const uniform_real_distribution<RealType> &lhs, const uniform_real_distribution<RealType> &rhs) { return thrust::random::detail::random_core_access::equal(lhs,rhs); } template<typename RealType> bool operator!=(const uniform_real_distribution<RealType> &lhs, const uniform_real_distribution<RealType> &rhs) { return !(lhs == rhs); } template<typename RealType, typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits> &os, const uniform_real_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_out(os,d); } template<typename RealType, typename CharT, typename Traits> std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits> &is, uniform_real_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_in(is,d); } } // end random } // end thrust <commit_msg>Guard forward declarations of nextafter & nextafterf from compilers that aren't MSVC.<commit_after>/* * Copyright 2008-2010 NVIDIA Corporation * * 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 <thrust/random/uniform_real_distribution.h> #include <math.h> #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // XXX WAR missing definitions on MSVC __host__ __device__ double nextafter(double, double); __host__ __device__ float nextafterf(float, float); #endif // THRUST_HOST_COMPILER_MSVC namespace thrust { namespace random { template<typename RealType> uniform_real_distribution<RealType> ::uniform_real_distribution(RealType a, RealType b) :m_param(a,b) { } // end uniform_real_distribution::uniform_real_distribution() template<typename RealType> uniform_real_distribution<RealType> ::uniform_real_distribution(const param_type &parm) :m_param(parm) { } // end uniform_real_distribution::uniform_real_distribution() template<typename RealType> void uniform_real_distribution<RealType> ::reset(void) { } // end uniform_real_distribution::reset() template<typename RealType> template<typename UniformRandomNumberGenerator> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng) { return operator()(urng, m_param); } // end uniform_real::operator()() namespace detail { __host__ __device__ __inline__ double nextafter(double x, double y) { return ::nextafter(x,y); } __host__ __device__ __inline__ float nextafter(float x, float y) { return ::nextafterf(x,y); } } template<typename RealType> template<typename UniformRandomNumberGenerator> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng, const param_type &parm) { // call the urng & map its result to [0,1] result_type result = static_cast<result_type>(urng() - UniformRandomNumberGenerator::min); result /= static_cast<result_type>(UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min); // do not include parm.second in the result // get the next value after parm.second in the direction of parm.first // we need to do this because the range is half-open at parm.second return (result * (detail::nextafter(parm.second,parm.first) - parm.first)) + parm.first; } // end uniform_real::operator()() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::a(void) const { return m_param.first; } // end uniform_real::a() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::b(void) const { return m_param.second; } // end uniform_real_distribution::b() template<typename RealType> typename uniform_real_distribution<RealType>::param_type uniform_real_distribution<RealType> ::param(void) const { return m_param;; } // end uniform_real_distribution::param() template<typename RealType> void uniform_real_distribution<RealType> ::param(const param_type &parm) { m_param = parm; } // end uniform_real_distribution::param() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::min(void) const { return a(); } // end uniform_real_distribution::min() template<typename RealType> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType> ::max(void) const { return b(); } // end uniform_real_distribution::max() template<typename RealType> bool uniform_real_distribution<RealType> ::equal(const uniform_real_distribution &rhs) const { return m_param == rhs.param(); } template<typename RealType> template<typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& uniform_real_distribution<RealType> ::stream_out(std::basic_ostream<CharT,Traits> &os) const { typedef std::basic_ostream<CharT,Traits> ostream_type; typedef typename ostream_type::ios_base ios_base; // save old flags and fill character const typename ios_base::fmtflags flags = os.flags(); const CharT fill = os.fill(); const CharT space = os.widen(' '); os.flags(ios_base::dec | ios_base::fixed | ios_base::left); os.fill(space); os << a() << space << b(); // restore old flags and fill character os.flags(flags); os.fill(fill); return os; } template<typename RealType> template<typename CharT, typename Traits> std::basic_istream<CharT,Traits>& uniform_real_distribution<RealType> ::stream_in(std::basic_istream<CharT,Traits> &is) { typedef std::basic_istream<CharT,Traits> istream_type; typedef typename istream_type::ios_base ios_base; // save old flags const typename ios_base::fmtflags flags = is.flags(); is.flags(ios_base::skipws); is >> m_param.first >> m_param.second; // restore old flags is.flags(flags); return is; } template<typename RealType> bool operator==(const uniform_real_distribution<RealType> &lhs, const uniform_real_distribution<RealType> &rhs) { return thrust::random::detail::random_core_access::equal(lhs,rhs); } template<typename RealType> bool operator!=(const uniform_real_distribution<RealType> &lhs, const uniform_real_distribution<RealType> &rhs) { return !(lhs == rhs); } template<typename RealType, typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits> &os, const uniform_real_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_out(os,d); } template<typename RealType, typename CharT, typename Traits> std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits> &is, uniform_real_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_in(is,d); } } // end random } // end thrust <|endoftext|>
<commit_before>/* StartingGateMission.cpp -- Implementation of StartingGateMission class Copyright (C) 2014 Tushar Pankaj This file is part of San Diego Robotics 101 Robosub. San Diego Robotics 101 Robosub 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. San Diego Robotics 101 Robosub 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 San Diego Robotics 101 Robosub. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <vector> #include <opencv2/opencv.hpp> #include "Robot.hpp" #include "Logger.hpp" #include "Contour.hpp" #include "Circle.hpp" #include "Rectangle.hpp" #include "ContourDetector.hpp" #include "Mission.hpp" #include "StartingGateMission.hpp" StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr) { mission_name = "Starting Gate Mission"; } void StartingGateMission::run() { robot->get_logger()->write("Running mission " + mission_name, Logger::MESSAGE); //cv::Mat image = cv::imread("/tmp/starting_gate.png"); cv::Mat image; while (true) { image = robot->get_forward_camera()->get_image(); ContourDetector::Params detector_params; detector_params.filter_by_hue = true; detector_params.min_hue = 100; detector_params.max_hue = 150; detector_params.max_canny = 50; detector_params.filter_with_blur = false; ContourDetector detector(detector_params); std::vector < Contour > contours = detector.detect(image); if (contours.empty()) { robot->get_logger()->write("No contours found", Logger::WARNING); continue; } std::vector < Rectangle > filtered_rectangles = filter_rectangles(contours); if (filtered_rectangles.empty()) { robot->get_logger()-> write("No filtered rectangles found", Logger::WARNING); continue; } std::vector < cv::Point2f > centroids = find_centroids(filtered_rectangles); /*for (uint i = 0; i < centroids.size(); i++) cv::circle(image, centroids.at(i), 5, cv::Scalar(0, 0, 0)); */ double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0)); robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement); robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE); } } std::vector < Circle > StartingGateMission::contours_to_circles(std::vector < Contour > contours) { std::vector < Circle > circles; for (uint i = 0; i < contours.size(); i++) circles.push_back(Circle(contours.at(i).get_points())); return circles; } std::vector < Rectangle > StartingGateMission::contours_to_rectangles(std::vector < Contour > contours) { std::vector < Rectangle > rectangles; for (uint i = 0; i < contours.size(); i++) rectangles.push_back(Rectangle(contours.at(i).get_points())); return rectangles; } std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector < Contour > detected_contours) { std::vector < Circle > detected_enclosing_circles = contours_to_circles(detected_contours); std::vector < Rectangle > detected_bounding_rectangles = contours_to_rectangles(detected_contours); std::vector < Rectangle > filtered_rectangles; for (uint i = 0; i < detected_contours.size(); i++) // Filter out circular contours and filter on aspect ratio { if (detected_bounding_rectangles.at(i).get_area_ratio() < detected_enclosing_circles.at(i).get_area_ratio() && detected_bounding_rectangles.at(i).get_aspect_ratio() < 0.2) filtered_rectangles.push_back (detected_bounding_rectangles.at(i)); } return filtered_rectangles; } std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector < Rectangle > rectangles) { cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F); for (uint i = 0; i < rectangles.size(); i++) { data.at < float >(i, 0) = rectangles.at(i).get_center().x; data.at < float >(i, 1) = rectangles.at(i).get_center().y; } int K = 2; cv::Mat best_labels; cv::TermCriteria criteria = cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0); int attempts = 3; int flags = cv::KMEANS_PP_CENTERS; cv::Mat centroids; cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids); std::vector < cv::Point2f > centroids_vector; for (int i = 0; i < centroids.rows; i++) centroids_vector.push_back(cv::Point2f (centroids.at < float >(i, 0), centroids.at < float >(i, 1))); return centroids_vector; } double StartingGateMission::find_angular_displacement(std::vector < cv::Point2f > centroids, cv::Point2f image_center) { cv::Point2f centroids_average = cv::Point2f(0.0, 0.0); for (uint i = 0; i < centroids.size(); i++) centroids_average += centroids.at(i); centroids_average.x /= centroids.size(); centroids_average.y /= centroids.size(); return robot->get_forward_camera()->pixels_to_angle((centroids_average = image_center).x); } <commit_msg>Fixed typo in angle calculation in StartingGateMission<commit_after>/* StartingGateMission.cpp -- Implementation of StartingGateMission class Copyright (C) 2014 Tushar Pankaj This file is part of San Diego Robotics 101 Robosub. San Diego Robotics 101 Robosub 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. San Diego Robotics 101 Robosub 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 San Diego Robotics 101 Robosub. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <vector> #include <opencv2/opencv.hpp> #include "Robot.hpp" #include "Logger.hpp" #include "Contour.hpp" #include "Circle.hpp" #include "Rectangle.hpp" #include "ContourDetector.hpp" #include "Mission.hpp" #include "StartingGateMission.hpp" StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr) { mission_name = "Starting Gate Mission"; } void StartingGateMission::run() { robot->get_logger()->write("Running mission " + mission_name, Logger::MESSAGE); //cv::Mat image = cv::imread("/tmp/starting_gate.png"); cv::Mat image; while (true) { image = robot->get_forward_camera()->get_image(); ContourDetector::Params detector_params; detector_params.filter_by_hue = true; detector_params.min_hue = 100; detector_params.max_hue = 150; detector_params.max_canny = 50; detector_params.filter_with_blur = false; ContourDetector detector(detector_params); std::vector < Contour > contours = detector.detect(image); if (contours.empty()) { robot->get_logger()->write("No contours found", Logger::WARNING); continue; } std::vector < Rectangle > filtered_rectangles = filter_rectangles(contours); if (filtered_rectangles.empty()) { robot->get_logger()-> write("No filtered rectangles found", Logger::WARNING); continue; } std::vector < cv::Point2f > centroids = find_centroids(filtered_rectangles); /*for (uint i = 0; i < centroids.size(); i++) cv::circle(image, centroids.at(i), 5, cv::Scalar(0, 0, 0)); */ double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0)); robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement); robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE); } } std::vector < Circle > StartingGateMission::contours_to_circles(std::vector < Contour > contours) { std::vector < Circle > circles; for (uint i = 0; i < contours.size(); i++) circles.push_back(Circle(contours.at(i).get_points())); return circles; } std::vector < Rectangle > StartingGateMission::contours_to_rectangles(std::vector < Contour > contours) { std::vector < Rectangle > rectangles; for (uint i = 0; i < contours.size(); i++) rectangles.push_back(Rectangle(contours.at(i).get_points())); return rectangles; } std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector < Contour > detected_contours) { std::vector < Circle > detected_enclosing_circles = contours_to_circles(detected_contours); std::vector < Rectangle > detected_bounding_rectangles = contours_to_rectangles(detected_contours); std::vector < Rectangle > filtered_rectangles; for (uint i = 0; i < detected_contours.size(); i++) // Filter out circular contours and filter on aspect ratio { if (detected_bounding_rectangles.at(i).get_area_ratio() < detected_enclosing_circles.at(i).get_area_ratio() && detected_bounding_rectangles.at(i).get_aspect_ratio() < 0.2) filtered_rectangles.push_back (detected_bounding_rectangles.at(i)); } return filtered_rectangles; } std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector < Rectangle > rectangles) { cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F); for (uint i = 0; i < rectangles.size(); i++) { data.at < float >(i, 0) = rectangles.at(i).get_center().x; data.at < float >(i, 1) = rectangles.at(i).get_center().y; } int K = 2; cv::Mat best_labels; cv::TermCriteria criteria = cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0); int attempts = 3; int flags = cv::KMEANS_PP_CENTERS; cv::Mat centroids; cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids); std::vector < cv::Point2f > centroids_vector; for (int i = 0; i < centroids.rows; i++) centroids_vector.push_back(cv::Point2f (centroids.at < float >(i, 0), centroids.at < float >(i, 1))); return centroids_vector; } double StartingGateMission::find_angular_displacement(std::vector < cv::Point2f > centroids, cv::Point2f image_center) { cv::Point2f centroids_average = cv::Point2f(0.0, 0.0); for (uint i = 0; i < centroids.size(); i++) centroids_average += centroids.at(i); centroids_average.x /= centroids.size(); centroids_average.y /= centroids.size(); return robot->get_forward_camera()->pixels_to_angle((centroids_average - image_center).x); } <|endoftext|>
<commit_before>/* Used to calculate the m-dimension submatrices used in the Four Russians algorithm. Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows: - (i-1, j-1) to (i, j) with 0 cost added if the characters at (i, j) match, replaceCost otherwise - (i-1, j) to (i, j) with deleteCost added - (i, j-1) to (i, j) with insertCost added Notes: The strings start with a space because the (0, x) and (x, 0) fields refer to one string being empty. The costs are not directly stored, they're converted to step vectors as per the Four Russians algorithm. */ #include <cstdio> #include <iostream> #include <vector> #include <map> #include <cmath> #include <string> #include <cstdlib> #include <ctime> #include <numeric> using namespace std; class SubmatrixCalculator { public: SubmatrixCalculator(int _dimension, string _alphabet, char _blankCharacter = '-', int _replaceCost = 2, int _deleteCost = 1, int _insertCost = 1) { this->dimension = _dimension; this->alphabet = _alphabet; this->blankCharacter = _blankCharacter; this->replaceCost = _replaceCost; this->deleteCost = _deleteCost; this->insertCost = _insertCost; this->initialSteps.reserve(pow(3, _dimension)); this->initialStrings.reserve(pow(_alphabet.size(), _dimension)); int startTime = clock(); this->resultIndex = new pair<string, string>[this->submatrixCountLimit]; cout << "Allocation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl; } void calculate() { printf("Clearing the submatrix data...\n"); results.clear(); generateInitialSteps(0, "1"); generateInitialStrings(0, " "); //printDebug(); // setting up temporary matrix storage lastSubH.reserve(this->dimension + 1); lastSubV.reserve(this->dimension + 1); vector<int> rowVec(this->dimension + 1, 0); for (int i = 0; i <= this->dimension; i++) { lastSubH.push_back(rowVec); lastSubV.push_back(rowVec); } // all possible initial steps and strings combinations int startTime = clock(); for (int strA = 0; strA < initialStrings.size(); strA++) { for (int strB = 0; strB < initialStrings.size(); strB++) { for (int stepC = 0; stepC < initialSteps.size(); stepC++) { for (int stepD = 0; stepD < initialSteps.size(); stepD++) { string key = initialStrings[strA]; key += initialStrings[strB]; key += initialSteps[stepC]; key += initialSteps[stepD]; // storing the resulting final rows for future reference resultIndex[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB], initialSteps[stepC], initialSteps[stepD]); //result[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB], // initialSteps[stepC], initialSteps[stepD]); } } } //cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << results.size() << " )" << endl; cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << (strA + 1) * initialStrings.size() * initialSteps.size() * initialSteps.size() << " )" << endl; } cout << "Submatrix calculation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl; } pair<vector<int>, pair<pair<int, int>, pair<int, int> > > getSubmatrixPath(string strLeft, string strTop, string stepLeft, string stepTop, int finalRow, int finalCol) { calculateSubmatrix(strLeft, strTop, stepLeft, stepTop); int i = finalRow; int j = finalCol; vector<int> operations; while (i > 0 && j > 0){ // TODO } pair<int, int> nextMatrix; pair<int, int> nextCell; if (i == 0 && j == 0){ nextMatrix = make_pair(-1, -1); nextCell = make_pair(this->dimension, this->dimension); } else if (i == 0){ nextMatrix = make_pair(-1, 0); nextCell = make_pair(this->dimension, j); } else { nextMatrix = make_pair(0, -1); nextCell = make_pair(i, this->dimension); } return make_pair(operations, make_pair(nextMatrix, nextCell)); } /* Calculates the step-matrix determined by the two strings and two initial vectors provided. The step matrix has two parts, vertical and horizontal steps, stored in lastSubV and lastSubH. */ inline void calculateSubmatrix(string strLeft, string strTop, string stepLeft, string stepTop) { /* TODO: CHECK: MIGHT BE WRONG AFTER TRANSPOSING have to transpose to keep cache functionality, huge speedup; old/new way commented */ for (int i = 1; i <= this->dimension; i++) { //lastSubV[i][0] = stepLeft[i] - '1'; // old lastSubV[0][i] = stepLeft[i] - '1'; // new lastSubH[0][i] = stepTop[i] - '1'; } for (int i = 1; i <= this->dimension; i++) { for (int j = 1; j <= this->dimension; j++) { int R = (strLeft[i] == strTop[j]) * this->replaceCost; //int lastV = lastSubV[i][j - 1]; // old int lastV = lastSubV[i - 1][j]; // new int lastH = lastSubH[i - 1][j]; /*lastSubV[i][j] = min(min(R - lastH, this->deleteCost), this->insertCost + lastV - lastH); lastSubH[i][j] = min(min(R - lastV, this->insertCost), this->deleteCost + lastH - lastV);*/ lastSubV[i][j] = mmin(R - lastH, this->deleteCost, this->insertCost + lastV - lastH); lastSubH[i][j] = mmin(R - lastV, this->insertCost, this->deleteCost + lastH - lastV); } } /* // DEBUG cout << "left " << strLeft << " top " << strTop << " stepleft " << stepsToPrettyString(stepLeft) << " steptop " << stepsToPrettyString(stepTop) << endl; cout << "vertical:" << endl; for (int i = 0; i <= this->dimension; i++){ for (int j = 0; j <= this->dimension; j++) cout << stepMatrixV[i][j] << " "; cout << endl; } cout << "horizontal:" << endl; for (int i = 0; i <= this->dimension; i++){ for (int j = 0; j <= this->dimension; j++) cout << stepMatrixH[i][j] << " "; cout << endl; } system("pause"); */ } /* Calculates the final step vectors for a given initial submatrix description. */ pair<string, string> calculateFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { calculateSubmatrix(strLeft, strTop, stepLeft, stepTop); /* // WARNING: check calculateSubmatrix() comments // old vector<int> stepRight(this->dimension + 1, 0); for (int i = 1; i <= this->dimension; i++){ //stepRight[i] = lastSubV[i][this->dimension]; } */ vector<int> stepRight = lastSubV[this->dimension]; vector<int> stepBot = lastSubH[this->dimension]; return make_pair(stepsToString(stepRight), stepsToString(stepBot)); } /* Returns the precalculated final step vectors for a given initial submatrix description. */ inline pair<string, string> getFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { //return results[hash(strLeft + strTop + stepLeft + stepTop)]; return resultIndex[hash(strLeft + strTop + stepLeft + stepTop)]; } /* Returns the sum of the step values for a given step string. */ inline int sumSteps(string steps) { vector<int> stepValues = stepsToVector(steps); return accumulate(stepValues.begin(), stepValues.end(), 0); } /* Transforms the step vector to a string. The string characters have no special meaning, strings are used for easier mapping. */ static string stepsToString(vector<int> steps) { string ret = ""; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) { ret += steps[i] + '1'; } return ret; } /* Transforms the string of steps (possibly a result of stepsToString()) to a vector of steps, where each step value is expected to be in {-1, 0, 1}. I.e., the steps string characters are expected to be in {'0', '1', '2'}. */ static vector<int> stepsToVector(string steps) { vector<int> ret; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) { ret.push_back(steps[i] - '1'); } return ret; } /* Adds spaces and signs to the step string and transforms the values to real step values. */ static string stepsToPrettyString(string steps) { string ret = ""; for (int i = 0; i < steps.size(); i++) { if (steps[i] == '0') { ret += "-1 "; } else if (steps[i] == '2') { ret += "+1 "; } else { ret += "0 "; } } return ret; } void generateInitialSteps(int pos, string currStep) { if (pos == this->dimension) { initialSteps.push_back(currStep); return; } for (int i = -1; i <= 1; i++) { string tmp = currStep; tmp.push_back('1' + i); generateInitialSteps(pos + 1, tmp); } } void generateInitialStrings(int pos, string currString) { if (pos == this->dimension) { initialStrings.push_back(currString); return; } for (int i = 0; i < this->alphabet.size(); i++) { string tmp = currString; tmp.push_back(this->alphabet[i]); generateInitialStrings(pos + 1, tmp); } } // DEBUG void printDebug() { for (int i = 0; i < initialSteps.size(); i++) cout << stepsToPrettyString(initialSteps[i]) << endl; for (int i = 0; i < initialStrings.size(); i++) cout << initialStrings[i] << endl; } const long long HASH_BASE = 137; inline long long hash(string x) { long long ret = 0; for (int i = 0; i < x.size(); i++) { ret = (ret * HASH_BASE + x[i]); } ret &= this->submatrixCountLimit - 1; // fancy bit-work return ret; } inline int mmin(int x, int y, int z) { return x>y?(y<z?y:z):x<z?x:z; } private: int dimension; int replaceCost; int deleteCost; int insertCost; // the actual maximum number of submatrices should be much lower // in order to decrease the possibility of hash collisions // when storing results const long long submatrixCountLimit = 16777216; // 2^24, coprime with hash base string alphabet; char blankCharacter; vector<string> initialSteps; vector<string> initialStrings; vector<vector<int> > lastSubH, lastSubV; map<long long, pair<string, string> > results; pair<string, string>* resultIndex; }; int main() { SubmatrixCalculator calc(3, "ATGC"); calc.calculate(); return 0; } <commit_msg>Internal parameter modifications<commit_after>/* Used to calculate the m-dimension submatrices used in the Four Russians algorithm. Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows: - (i-1, j-1) to (i, j) with 0 cost added if the characters at (i, j) match, replaceCost otherwise - (i-1, j) to (i, j) with deleteCost added - (i, j-1) to (i, j) with insertCost added Notes: The strings start with a space because the (0, x) and (x, 0) fields refer to one string being empty. The costs are not directly stored, they're converted to step vectors as per the Four Russians algorithm. */ #include <cstdio> #include <iostream> #include <vector> #include <map> #include <cmath> #include <string> #include <cstdlib> #include <ctime> #include <numeric> using namespace std; class SubmatrixCalculator { public: SubmatrixCalculator(int _dimension, string _alphabet, char _blankCharacter = '-', int _replaceCost = 2, int _deleteCost = 1, int _insertCost = 1) { this->dimension = _dimension; this->alphabet = _alphabet; this->blankCharacter = _blankCharacter; this->replaceCost = _replaceCost; this->deleteCost = _deleteCost; this->insertCost = _insertCost; this->initialSteps.reserve(pow(3, _dimension)); this->initialStrings.reserve(pow(_alphabet.size(), _dimension)); int startTime = clock(); this->resultIndex = new pair<string, string>[this->submatrixCountLimit]; cout << "Allocation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl; } void calculate() { printf("Clearing the submatrix data...\n"); results.clear(); generateInitialSteps(0, ""); generateInitialStrings(0, "", false); //printDebug(); // setting up temporary matrix storage lastSubH.reserve(this->dimension + 1); lastSubV.reserve(this->dimension + 1); vector<int> rowVec(this->dimension + 1, 0); for (int i = 0; i <= this->dimension; i++) { lastSubH.push_back(rowVec); lastSubV.push_back(rowVec); } // all possible initial steps and strings combinations int startTime = clock(); for (int strA = 0; strA < initialStrings.size(); strA++) { for (int strB = 0; strB < initialStrings.size(); strB++) { for (int stepC = 0; stepC < initialSteps.size(); stepC++) { for (int stepD = 0; stepD < initialSteps.size(); stepD++) { string key = initialStrings[strA]; key += initialStrings[strB]; key += initialSteps[stepC]; key += initialSteps[stepD]; // storing the resulting final rows for future reference resultIndex[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB], initialSteps[stepC], initialSteps[stepD]); //result[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB], // initialSteps[stepC], initialSteps[stepD]); } } } //cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << results.size() << " )" << endl; cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << (strA + 1) * initialStrings.size() * initialSteps.size() * initialSteps.size() << " )" << endl; } cout << "Submatrix calculation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl; } pair<vector<int>, pair<pair<int, int>, pair<int, int> > > getSubmatrixPath(string strLeft, string strTop, string stepLeft, string stepTop, int finalRow, int finalCol) { calculateSubmatrix(strLeft, strTop, stepLeft, stepTop); int i = finalRow; int j = finalCol; vector<int> operations; while (i > 0 && j > 0) { // TODO } pair<int, int> nextMatrix; pair<int, int> nextCell; if (i == 0 && j == 0) { nextMatrix = make_pair(-1, -1); nextCell = make_pair(this->dimension, this->dimension); } else if (i == 0) { nextMatrix = make_pair(-1, 0); nextCell = make_pair(this->dimension, j); } else { nextMatrix = make_pair(0, -1); nextCell = make_pair(i, this->dimension); } return make_pair(operations, make_pair(nextMatrix, nextCell)); } /* Calculates the step-matrix determined by the two strings and two initial vectors provided. The step matrix has two parts, vertical and horizontal steps, stored in lastSubV and lastSubH. */ inline void calculateSubmatrix(string strLeft, string strTop, string stepLeft, string stepTop) { /* TODO: CHECK: MIGHT BE WRONG AFTER TRANSPOSING have to transpose to keep cache functionality, huge speedup; old/new way commented */ for (int i = 1; i <= this->dimension; i++) { //lastSubV[i][0] = stepLeft[i] - '1'; // old lastSubV[0][i] = stepLeft[i - 1] - '1'; // new lastSubH[0][i] = stepTop[i - 1] - '1'; } for (int i = 1; i <= this->dimension; i++) { for (int j = 1; j <= this->dimension; j++) { int R = (strLeft[i - 1] == strTop[j - 1]) * this->replaceCost; if (strLeft[i - 1] == blankCharacter or strTop[j - 1] == blankCharacter) R = 0; //int lastV = lastSubV[i][j - 1]; // old int lastV = lastSubV[i - 1][j]; // new int lastH = lastSubH[i - 1][j]; /*lastSubV[i][j] = min(min(R - lastH, this->deleteCost), this->insertCost + lastV - lastH); lastSubH[i][j] = min(min(R - lastV, this->insertCost), this->deleteCost + lastH - lastV);*/ lastSubV[i][j] = mmin(R - lastH, this->deleteCost, this->insertCost + lastV - lastH); lastSubH[i][j] = mmin(R - lastV, this->insertCost, this->deleteCost + lastH - lastV); } } /* // DEBUG cout << "left " << strLeft << " top " << strTop << " stepleft " << stepsToPrettyString(stepLeft) << " steptop " << stepsToPrettyString(stepTop) << endl; cout << "vertical:" << endl; for (int i = 0; i <= this->dimension; i++){ for (int j = 0; j <= this->dimension; j++) cout << stepMatrixV[i][j] << " "; cout << endl; } cout << "horizontal:" << endl; for (int i = 0; i <= this->dimension; i++){ for (int j = 0; j <= this->dimension; j++) cout << stepMatrixH[i][j] << " "; cout << endl; } system("pause"); */ } /* Calculates the final step vectors for a given initial submatrix description. */ pair<string, string> calculateFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { calculateSubmatrix(strLeft, strTop, stepLeft, stepTop); /* // WARNING: check calculateSubmatrix() comments // old vector<int> stepRight(this->dimension + 1, 0); for (int i = 1; i <= this->dimension; i++){ //stepRight[i] = lastSubV[i][this->dimension]; } */ vector<int> stepRight = lastSubV[this->dimension]; vector<int> stepBot = lastSubH[this->dimension]; return make_pair(stepsToString(stepRight), stepsToString(stepBot)); } /* Returns the precalculated final step vectors for a given initial submatrix description. */ inline pair<string, string> getFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { //return results[hash(strLeft + strTop + stepLeft + stepTop)]; return resultIndex[hash(strLeft + strTop + stepLeft + stepTop)]; } /* Returns the sum of the step values for a given step string. */ inline int sumSteps(string steps) { vector<int> stepValues = stepsToVector(steps); return accumulate(stepValues.begin(), stepValues.end(), 0); } /* Transforms the step vector to a string. The string characters have no special meaning, strings are used for easier mapping. Check SubmatrixCalculator::stepsToVector comments. */ static string stepsToString(vector<int> steps) { string ret = ""; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) { ret += steps[i] + '1'; } return ret; } /* Transforms the string of steps (possibly a result of stepsToString()) to a vector of steps, where each step value is expected to be in {-1, 0, 1}. I.e., the steps string characters are expected to be in {'0', '1', '2'}. */ static vector<int> stepsToVector(string steps) { vector<int> ret; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) { ret.push_back(steps[i] - '1'); } return ret; } /* Adds spaces and signs to the step string and transforms the values to real step values. */ static string stepsToPrettyString(string steps) { string ret = ""; for (int i = 0; i < steps.size(); i++) { if (steps[i] == '0') { ret += "-1 "; } else if (steps[i] == '2') { ret += "+1 "; } else { ret += "0 "; } } return ret; } void generateInitialSteps(int pos, string currStep) { if (pos == this->dimension) { initialSteps.push_back(currStep); return; } for (int i = -1; i <= 1; i++) { string tmp = currStep; tmp.push_back('1' + i); generateInitialSteps(pos + 1, tmp); } } void generateInitialStrings(int pos, string currString, bool blanks) { if (pos == this->dimension) { initialStrings.push_back(currString); return; } if (!blanks) { for (int i = 0; i < this->alphabet.size(); i++) { string tmp = currString; tmp.push_back(this->alphabet[i]); generateInitialStrings(pos + 1, tmp, false); } } string tmp = currString; tmp.push_back(blankCharacter); generateInitialStrings(pos + 1, tmp, true); } // DEBUG void printDebug() { for (int i = 0; i < initialSteps.size(); i++) cout << stepsToPrettyString(initialSteps[i]) << endl; for (int i = 0; i < initialStrings.size(); i++) cout << initialStrings[i] << endl; } const long long HASH_BASE = 137; inline long long hash(string x) { long long ret = 0; for (int i = 0; i < x.size(); i++) { ret = (ret * HASH_BASE + x[i]); } ret &= this->submatrixCountLimit - 1; // fancy bit-work return ret; } inline int mmin(int x, int y, int z) { return x>y?(y<z?y:z):x<z?x:z; } private: int dimension; int replaceCost; int deleteCost; int insertCost; // the actual maximum number of submatrices should be much lower // in order to decrease the possibility of hash collisions // when storing results const long long submatrixCountLimit = 16777216; // 2^24, coprime with hash base string alphabet; char blankCharacter; vector<string> initialSteps; vector<string> initialStrings; vector<vector<int> > lastSubH, lastSubV; map<long long, pair<string, string> > results; pair<string, string>* resultIndex; }; int main() { SubmatrixCalculator calc(3, "ATGC"); calc.calculate(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlgpage.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: thb $ $Date: 2001-06-06 15:13:55 $ * * 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): _______________________________________ * * ************************************************************************/ #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_GRADIENT_LIST SID_GRADIENT_LIST #define ITEMID_HATCH_LIST SID_HATCH_LIST #define ITEMID_BITMAP_LIST SID_BITMAP_LIST #ifndef _SVX_PAGE_HXX #include <svx/page.hxx> #endif #ifndef _SVX_DIALOGS_HRC #include <svx/dialogs.hrc> #endif #ifndef _SVX_TAB_AREA_HXX #include <svx/tabarea.hxx> #endif #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "dlgpage.hxx" #include "docshell.hxx" /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) : SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ), rOutAttrs ( *pAttr ), pDocShell ( pDocSh ) { SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*) ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) ); SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*) ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) ); SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*) ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) ); SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*) ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) ); pColorTab = aColorTableItem.GetColorTable(); pGradientList = aGradientListItem.GetGradientList(); pHatchingList = aHatchListItem.GetHatchList(); pBitmapList = aBitmapListItem.GetBitmapList(); FreeResource(); AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0); AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 ); nDlgType = 1; // Vorlagen-Dialog nPageType = 0; nPos = 0; nColorTableState = CT_NONE; nBitmapListState = CT_NONE; nGradientListState = CT_NONE; nHatchingListState = CT_NONE; if(!bAreaPage) // I have to add the page before I remove it ! RemoveTabPage( RID_SVXPAGE_AREA ); } /************************************************************************* |* |* Seite wird erzeugt |* \************************************************************************/ void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage) { switch(nId) { case RID_SVXPAGE_PAGE: ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION); ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E ); break; case RID_SVXPAGE_AREA: ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList ); ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList ); ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList ); ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxAreaTabPage&) rPage ).SetPos( &nPos ); ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState ); ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState ); ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState ); ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState ); ( (SvxAreaTabPage&) rPage ).Construct(); break; } } <commit_msg>INTEGRATION: CWS impress1 (1.2.248); FILE MERGED 2003/09/17 09:20:30 af 1.2.248.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/************************************************************************* * * $RCSfile: dlgpage.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-01-20 10:43:36 $ * * 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): _______________________________________ * * ************************************************************************/ #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_GRADIENT_LIST SID_GRADIENT_LIST #define ITEMID_HATCH_LIST SID_HATCH_LIST #define ITEMID_BITMAP_LIST SID_BITMAP_LIST #ifndef _SVX_PAGE_HXX #include <svx/page.hxx> #endif #ifndef _SVX_DIALOGS_HRC #include <svx/dialogs.hrc> #endif #ifndef _SVX_TAB_AREA_HXX #include <svx/tabarea.hxx> #endif #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "dlgpage.hxx" #include "DrawDocShell.hxx" /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) : SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ), rOutAttrs ( *pAttr ), pDocShell ( pDocSh ) { SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*) ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) ); SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*) ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) ); SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*) ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) ); SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*) ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) ); pColorTab = aColorTableItem.GetColorTable(); pGradientList = aGradientListItem.GetGradientList(); pHatchingList = aHatchListItem.GetHatchList(); pBitmapList = aBitmapListItem.GetBitmapList(); FreeResource(); AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0); AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 ); nDlgType = 1; // Vorlagen-Dialog nPageType = 0; nPos = 0; nColorTableState = CT_NONE; nBitmapListState = CT_NONE; nGradientListState = CT_NONE; nHatchingListState = CT_NONE; if(!bAreaPage) // I have to add the page before I remove it ! RemoveTabPage( RID_SVXPAGE_AREA ); } /************************************************************************* |* |* Seite wird erzeugt |* \************************************************************************/ void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage) { switch(nId) { case RID_SVXPAGE_PAGE: ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION); ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E ); break; case RID_SVXPAGE_AREA: ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList ); ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList ); ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList ); ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxAreaTabPage&) rPage ).SetPos( &nPos ); ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState ); ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState ); ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState ); ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState ); ( (SvxAreaTabPage&) rPage ).Construct(); break; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: futhes.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dl $ $Date: 2000-10-25 10:27:48 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <tools/pstm.hxx> #include <svx/outliner.hxx> #include <offmgr/osplcfg.hxx> #ifndef _OFF_APP_HXX //autogen #include <offmgr/app.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _SVDOTEXT_HXX //autogen #include <svx/svdotext.hxx> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_ #include <com/sun/star/linguistic2/XLinguServiceManager.hpp> #endif #define ITEMID_LANGUAGE SID_ATTR_CHAR_LANGUAGE #include <svx/dialogs.hrc> #include <svx/svxerr.hxx> #include <svx/dialmgr.hxx> #ifndef _UNO_LINGU_HXX #include <svx/unolingu.hxx> #endif #include <unotools/processfactory.hxx> #include "app.hrc" #include "strings.hrc" #include "drawdoc.hxx" #include "app.hxx" #include "futhes.hxx" #include "sdview.hxx" #include "sdoutl.hxx" #include "drviewsh.hxx" #include "outlnvsh.hxx" #include "sdwindow.hxx" #include "sdresid.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::linguistic2; class SfxRequest; TYPEINIT1( FuThesaurus, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuThesaurus::FuThesaurus( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(), pWin, RID_SVXERRCTX, DIALOG_MGR() ); if ( pViewShell->ISA(SdDrawViewShell) ) { SdrTextObj* pTextObj = NULL; if ( pView->HasMarkedObj() ) { const SdrMarkList& rMarkList = pView->GetMarkList(); if ( rMarkList.GetMarkCount() == 1 ) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); if ( pObj->ISA(SdrTextObj) ) { pTextObj = (SdrTextObj*) pObj; } } } Outliner* pOutliner = pView->GetTextEditOutliner(); const OutlinerView* pOutlView = pView->GetTextEditOutlinerView(); if ( pTextObj && pOutliner && pOutlView ) { if ( !pOutliner->GetSpeller().is() ) { Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() ); Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))), uno::UNO_QUERY ); if ( xLinguServiceManager.is() ) { Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY ); if ( xSpellChecker.is() ) pOutliner->SetSpeller( xSpellChecker ); Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY ); if( xHyphenator.is() ) pOutliner->SetHyphenator( xHyphenator ); } pOutliner->SetDefaultLanguage( pDoc->GetLanguage() ); } EESpellState eState = ( (OutlinerView*) pOutlView) ->StartThesaurus( pDoc->GetLanguage() ); DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker"); if (eState == EE_SPELL_NOLANGUAGE) { ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute(); } } } else if ( pViewShell->ISA(SdOutlineViewShell) ) { Outliner* pOutliner = pDoc->GetOutliner(); OutlinerView* pOutlView = pOutliner->GetView(0); if ( !pOutliner->GetSpeller().is() ) { Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() ); Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))), uno::UNO_QUERY ); if ( xLinguServiceManager.is() ) { Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY ); if ( xSpellChecker.is() ) pOutliner->SetSpeller( xSpellChecker ); Reference< XHyphenator1 > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY ); if( xHyphenator.is() ) pOutliner->SetHyphenator( xHyphenator ); } pOutliner->SetDefaultLanguage( pDoc->GetLanguage() ); } EESpellState eState = pOutlView->StartThesaurus( pDoc->GetLanguage() ); DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker"); if (eState == EE_SPELL_NOLANGUAGE) { ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute(); } } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuThesaurus::~FuThesaurus() { } <commit_msg>Change: xHyphenator1 to xHyphenator<commit_after>/************************************************************************* * * $RCSfile: futhes.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2000-10-31 15:42:38 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <tools/pstm.hxx> #include <svx/outliner.hxx> #include <offmgr/osplcfg.hxx> #ifndef _OFF_APP_HXX //autogen #include <offmgr/app.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _SVDOTEXT_HXX //autogen #include <svx/svdotext.hxx> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_ #include <com/sun/star/linguistic2/XLinguServiceManager.hpp> #endif #define ITEMID_LANGUAGE SID_ATTR_CHAR_LANGUAGE #include <svx/dialogs.hrc> #include <svx/svxerr.hxx> #include <svx/dialmgr.hxx> #ifndef _UNO_LINGU_HXX #include <svx/unolingu.hxx> #endif #include <unotools/processfactory.hxx> #include "app.hrc" #include "strings.hrc" #include "drawdoc.hxx" #include "app.hxx" #include "futhes.hxx" #include "sdview.hxx" #include "sdoutl.hxx" #include "drviewsh.hxx" #include "outlnvsh.hxx" #include "sdwindow.hxx" #include "sdresid.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::linguistic2; class SfxRequest; TYPEINIT1( FuThesaurus, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuThesaurus::FuThesaurus( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(), pWin, RID_SVXERRCTX, DIALOG_MGR() ); if ( pViewShell->ISA(SdDrawViewShell) ) { SdrTextObj* pTextObj = NULL; if ( pView->HasMarkedObj() ) { const SdrMarkList& rMarkList = pView->GetMarkList(); if ( rMarkList.GetMarkCount() == 1 ) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); if ( pObj->ISA(SdrTextObj) ) { pTextObj = (SdrTextObj*) pObj; } } } Outliner* pOutliner = pView->GetTextEditOutliner(); const OutlinerView* pOutlView = pView->GetTextEditOutlinerView(); if ( pTextObj && pOutliner && pOutlView ) { if ( !pOutliner->GetSpeller().is() ) { Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() ); Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))), uno::UNO_QUERY ); if ( xLinguServiceManager.is() ) { Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY ); if ( xSpellChecker.is() ) pOutliner->SetSpeller( xSpellChecker ); Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY ); if( xHyphenator.is() ) pOutliner->SetHyphenator( xHyphenator ); } pOutliner->SetDefaultLanguage( pDoc->GetLanguage() ); } EESpellState eState = ( (OutlinerView*) pOutlView) ->StartThesaurus( pDoc->GetLanguage() ); DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker"); if (eState == EE_SPELL_NOLANGUAGE) { ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute(); } } } else if ( pViewShell->ISA(SdOutlineViewShell) ) { Outliner* pOutliner = pDoc->GetOutliner(); OutlinerView* pOutlView = pOutliner->GetView(0); if ( !pOutliner->GetSpeller().is() ) { Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() ); Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))), uno::UNO_QUERY ); if ( xLinguServiceManager.is() ) { Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY ); if ( xSpellChecker.is() ) pOutliner->SetSpeller( xSpellChecker ); Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY ); if( xHyphenator.is() ) pOutliner->SetHyphenator( xHyphenator ); } pOutliner->SetDefaultLanguage( pDoc->GetLanguage() ); } EESpellState eState = pOutlView->StartThesaurus( pDoc->GetLanguage() ); DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker"); if (eState == EE_SPELL_NOLANGUAGE) { ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute(); } } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuThesaurus::~FuThesaurus() { } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <limits> #include <stdexcept> #include <math.h> #include "supercubic.h" using namespace std; Supercubic::Supercubic():dimen(0),n(nullptr),L(0) {} Supercubic::Supercubic(int Dc, const int* Nc) { dimen=Dc; n=new int[dimen]; std::copy(Nc,Nc+dimen,n); L=1; for(int i=0; i<dimen; i++) L*=n[i]; } Supercubic::Supercubic(string filename) { n=nullptr; //We first initial n, since read_param function assume n is either nullptr or allocated. read_param(filename); //read dimen and *n, allocate n L=1; for(int i=0; i<dimen; i++) L*=n[i]; } Supercubic::Supercubic(const Supercubic& x) { dimen=x.dimen;L=x.L; n=new int[dimen]; std::copy(x.n,x.n+dimen,n); } Supercubic::Supercubic(Supercubic&& x) { dimen=x.dimen;L=x.L; n=x.n; x.n=nullptr; } Supercubic::~Supercubic() {if(n) delete[] n;} Supercubic& Supercubic::operator = (const Supercubic& x) { dimen=x.dimen;L=x.L; if(n) delete[] n; n=new int[dimen]; std::copy(x.n,x.n+dimen,n); return *this; } Supercubic& Supercubic::operator = (Supercubic&& x) { dimen=x.dimen;L=x.L; int* ntmp=n; n=x.n; x.n=ntmp; //swap return *this; } vector<int> Supercubic::coor(int lattice_index) const { vector<int> coordinate(dimen); int den=L; for(int i=dimen-1; i>=0; i--) { den/=n[i]; coordinate[i]=lattice_index/den; lattice_index%=den; } return coordinate; } int Supercubic::index(const vector<int>& lattice_coor) const { int size=lattice_coor.size(); if(size!=dimen) { std::cout<<"Input for index in Supercubic error! Size of lattice_coor !=dimen \n"; exit(1); } int lattice_index=0; int den=1; for(int i=0; i<dimen; i++) { lattice_index+=(lattice_coor[i]*den); den*=n[i]; } return lattice_index; } int Supercubic::bound(const int i, const int i_max) const { int i_bound = (i>=0) ? i%i_max : i%i_max+i_max; if(i_bound==i_max) i_bound=0; return i_bound; } //return coor_j-coor_i vector<int> Supercubic::coor_relat(const vector<int>& coor_i, const vector<int>& coor_j) const { int size_i=coor_i.size(); int size_j=coor_j.size(); if(size_i!=dimen||size_j!=dimen) { std::cout<<"Input for coor_relat in Supercubic error! Size of coor_i or coor_j !=dimen \n"; exit(1); } vector<int> dist(dimen); for(int i=0; i<dimen; i++) dist[i]=this->bound(coor_j[i]-coor_i[i], n[i]); return dist; } //return the inverse point of lattice_index with zero point int Supercubic::inverse(int lattice_index) const { vector<int> coordinate=this->coor(lattice_index); for(int i=0; i<dimen; i++) coordinate[i]=this->bound(-coordinate[i],n[i]); return this->index(coordinate); } //Read the parameters from "filename" //Read dimen and *n, allocate n void Supercubic::read_param(string filename) { int rank=0; #ifdef MPI_HAO MPI_Comm_rank(MPI_COMM_WORLD, &rank); #endif if(rank==0) { ifstream latt_file; latt_file.open(filename, ios::in); if ( ! latt_file.is_open() ) {cout << "Error opening file!!!"; exit(1);} latt_file>>dimen; latt_file.ignore(numeric_limits<streamsize>::max(),'\n'); if(n) delete[] n; n=new int[dimen]; for(int i=0; i<dimen; i++) {latt_file>>n[i];} latt_file.ignore(numeric_limits<streamsize>::max(),'\n'); latt_file.close(); } #ifdef MPI_HAO MPI_Bcast(&dimen, 1, MPI_INT, 0, MPI_COMM_WORLD); if(rank!=0) { if(n) delete[] n; n=new int[dimen]; } MPI_Bcast(n, dimen, MPI_INT, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); #endif } <commit_msg>Remove latt_file.ignore(numeric_limits<streamsize>::max(),'\n').<commit_after>#include <iostream> #include <fstream> #include <limits> #include <stdexcept> #include <math.h> #include "supercubic.h" using namespace std; Supercubic::Supercubic():dimen(0),n(nullptr),L(0) {} Supercubic::Supercubic(int Dc, const int* Nc) { dimen=Dc; n=new int[dimen]; std::copy(Nc,Nc+dimen,n); L=1; for(int i=0; i<dimen; i++) L*=n[i]; } Supercubic::Supercubic(string filename) { n=nullptr; //We first initial n, since read_param function assume n is either nullptr or allocated. read_param(filename); //read dimen and *n, allocate n L=1; for(int i=0; i<dimen; i++) L*=n[i]; } Supercubic::Supercubic(const Supercubic& x) { dimen=x.dimen;L=x.L; n=new int[dimen]; std::copy(x.n,x.n+dimen,n); } Supercubic::Supercubic(Supercubic&& x) { dimen=x.dimen;L=x.L; n=x.n; x.n=nullptr; } Supercubic::~Supercubic() {if(n) delete[] n;} Supercubic& Supercubic::operator = (const Supercubic& x) { dimen=x.dimen;L=x.L; if(n) delete[] n; n=new int[dimen]; std::copy(x.n,x.n+dimen,n); return *this; } Supercubic& Supercubic::operator = (Supercubic&& x) { dimen=x.dimen;L=x.L; int* ntmp=n; n=x.n; x.n=ntmp; //swap return *this; } vector<int> Supercubic::coor(int lattice_index) const { vector<int> coordinate(dimen); int den=L; for(int i=dimen-1; i>=0; i--) { den/=n[i]; coordinate[i]=lattice_index/den; lattice_index%=den; } return coordinate; } int Supercubic::index(const vector<int>& lattice_coor) const { int size=lattice_coor.size(); if(size!=dimen) { std::cout<<"Input for index in Supercubic error! Size of lattice_coor !=dimen \n"; exit(1); } int lattice_index=0; int den=1; for(int i=0; i<dimen; i++) { lattice_index+=(lattice_coor[i]*den); den*=n[i]; } return lattice_index; } int Supercubic::bound(const int i, const int i_max) const { int i_bound = (i>=0) ? i%i_max : i%i_max+i_max; if(i_bound==i_max) i_bound=0; return i_bound; } //return coor_j-coor_i vector<int> Supercubic::coor_relat(const vector<int>& coor_i, const vector<int>& coor_j) const { int size_i=coor_i.size(); int size_j=coor_j.size(); if(size_i!=dimen||size_j!=dimen) { std::cout<<"Input for coor_relat in Supercubic error! Size of coor_i or coor_j !=dimen \n"; exit(1); } vector<int> dist(dimen); for(int i=0; i<dimen; i++) dist[i]=this->bound(coor_j[i]-coor_i[i], n[i]); return dist; } //return the inverse point of lattice_index with zero point int Supercubic::inverse(int lattice_index) const { vector<int> coordinate=this->coor(lattice_index); for(int i=0; i<dimen; i++) coordinate[i]=this->bound(-coordinate[i],n[i]); return this->index(coordinate); } //Read the parameters from "filename" //Read dimen and *n, allocate n void Supercubic::read_param(string filename) { int rank=0; #ifdef MPI_HAO MPI_Comm_rank(MPI_COMM_WORLD, &rank); #endif if(rank==0) { ifstream latt_file; latt_file.open(filename, ios::in); if ( ! latt_file.is_open() ) {cout << "Error opening file!!!"; exit(1);} latt_file>>dimen; //latt_file.ignore(numeric_limits<streamsize>::max(),'\n'); if(n) delete[] n; n=new int[dimen]; for(int i=0; i<dimen; i++) latt_file>>n[i];; latt_file.close(); } #ifdef MPI_HAO MPI_Bcast(&dimen, 1, MPI_INT, 0, MPI_COMM_WORLD); if(rank!=0) { if(n) delete[] n; n=new int[dimen]; } MPI_Bcast(n, dimen, MPI_INT, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); #endif } <|endoftext|>
<commit_before>#include "WProgram.h" #define encoderPinA 4 #define encoderPinB 6 #define encoderOutputI 5 int counter=0; int stateA; int stateB; int lastStateA=LOW; int lastStateB=LOW; void loopTest(); int main() { init(); pinMode(encoderPinA,INPUT); pinMode(encoderPinB,INPUT); loopTest(); return 0; } void loopTest() { while(true) { stateA=digitalRead(encoderPinA); stateB=digitalRead(encoderPinB); if(stateA=!lastStateA && encoderPinB!=lastStateB) { counter++; lastStateA=stateA; lastStateB=stateB; } printf("%d\n",counter); } } <commit_msg>Added freaking tabs<commit_after>#include "WProgram.h" #define encoderPinA 4 #define encoderPinB 6 #define encoderOutputI 5 int counter=0; int stateA; int stateB; int lastStateA=LOW; int lastStateB=LOW; void loopTest(); int main() { init(); pinMode(encoderPinA,INPUT); pinMode(encoderPinB,INPUT); loopTest(); return 0; } void loopTest() { while(true) { stateA=digitalRead(encoderPinA); stateB=digitalRead(encoderPinB); if(stateA=!lastStateA && encoderPinB!=lastStateB) { counter++; lastStateA=stateA; lastStateB=stateB; } printf("%d\n",counter); } } <|endoftext|>
<commit_before>/* File: lcds.cpp * Synchronous lcd hd44780 interface. */ /* Copyright (c) 2012-2013 Domen Ipavec ([email protected]) * * 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 "lcds.h" #include "bitop.h" #include <util/delay.h> #include <avr/pgmspace.h> avr_cpp_lib::LCDS::LCDS(OutputPin rs, OutputPin e, OutputPin d4, OutputPin d5, OutputPin d6, OutputPin d7) : rs(rs), e(e), d4(d4), d5(d5), d6(d6), d7(d7) { d7.clear(); d6.clear(); d5.set(); d4.set(); rs.clear(); // one (8 bit mode) enableToggle(); // two (8 bit mode) enableToggle(); // three (4 bit mode) d4.clear(); enableToggle(); // dual line, 4 bit mode command(0b00101000); // turn display on, cursor off command(DISPLAY_ON); } void avr_cpp_lib::LCDS::enableToggle() { e.set(); _delay_ms(1); e.clear(); _delay_ms(1); } void avr_cpp_lib::LCDS::command(uint8_t c) { rs.clear(); send(c); _delay_ms(2); } void avr_cpp_lib::LCDS::character(uint8_t c) { rs.set(); send(c); } void avr_cpp_lib::LCDS::send(uint8_t c) { if (BITSET(c, 7)) { d7.set(); } else { d7.clear(); } if (BITSET(c, 6)) { d6.set(); } else { d6.clear(); } if (BITSET(c, 5)) { d5.set(); } else { d5.clear(); } if (BITSET(c, 4)) { d4.set(); } else { d4.clear(); } enableToggle(); if (BITSET(c, 3)) { d7.set(); } else { d7.clear(); } if (BITSET(c, 2)) { d6.set(); } else { d6.clear(); } if (BITSET(c, 1)) { d5.set(); } else { d5.clear(); } if (BITSET(c, 0)) { d4.set(); } else { d4.clear(); } enableToggle(); } void avr_cpp_lib::LCDS::gotoXY(uint8_t x, uint8_t y) { uint8_t tmp; switch (y) { case 0: tmp = x; break; case 1: tmp = 0x40 + x; break; case 2: tmp = 0x14 + x; break; default: tmp = 0x54 + x; } command(1<<7 | tmp); } void avr_cpp_lib::LCDS::write(uint32_t i, uint8_t l, uint8_t m) { char buf[l + 1]; buf[l] = '\0'; for (; l > 0; l--) { uint8_t c = i % m; if (c < 10) { buf[l-1] = 0x30 + c; } else { buf[l-1] = 0x41 + c - 10; } i = i / m; } write(buf); } void avr_cpp_lib::LCDS::write(const char * s) { while (*s != '\0') { character(*s); s++; } } void avr_cpp_lib::LCDS::writeFlash(const char * s) { uint8_t c = pgm_read_byte(s); while (c != '\0') { character(c); s++; c = pgm_read_byte(s); } } <commit_msg>Some more pause and additional clear<commit_after>/* File: lcds.cpp * Synchronous lcd hd44780 interface. */ /* Copyright (c) 2012-2013 Domen Ipavec ([email protected]) * * 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 "lcds.h" #include "bitop.h" #include <util/delay.h> #include <avr/pgmspace.h> avr_cpp_lib::LCDS::LCDS(OutputPin rs, OutputPin e, OutputPin d4, OutputPin d5, OutputPin d6, OutputPin d7) : rs(rs), e(e), d4(d4), d5(d5), d6(d6), d7(d7) { d7.clear(); d6.clear(); d5.set(); d4.set(); rs.clear(); // one (8 bit mode) enableToggle(); // two (8 bit mode) enableToggle(); // three (4 bit mode) d4.clear(); enableToggle(); // dual line, 4 bit mode command(0b00101000); // turn display on, cursor off command(DISPLAY_ON); // clear display command(CLEAR); } void avr_cpp_lib::LCDS::enableToggle() { e.set(); _delay_ms(1); e.clear(); _delay_ms(1); } void avr_cpp_lib::LCDS::command(uint8_t c) { rs.clear(); send(c); _delay_ms(5); } void avr_cpp_lib::LCDS::character(uint8_t c) { rs.set(); send(c); } void avr_cpp_lib::LCDS::send(uint8_t c) { if (BITSET(c, 7)) { d7.set(); } else { d7.clear(); } if (BITSET(c, 6)) { d6.set(); } else { d6.clear(); } if (BITSET(c, 5)) { d5.set(); } else { d5.clear(); } if (BITSET(c, 4)) { d4.set(); } else { d4.clear(); } enableToggle(); if (BITSET(c, 3)) { d7.set(); } else { d7.clear(); } if (BITSET(c, 2)) { d6.set(); } else { d6.clear(); } if (BITSET(c, 1)) { d5.set(); } else { d5.clear(); } if (BITSET(c, 0)) { d4.set(); } else { d4.clear(); } enableToggle(); } void avr_cpp_lib::LCDS::gotoXY(uint8_t x, uint8_t y) { uint8_t tmp; switch (y) { case 0: tmp = x; break; case 1: tmp = 0x40 + x; break; case 2: tmp = 0x14 + x; break; default: tmp = 0x54 + x; } command(1<<7 | tmp); } void avr_cpp_lib::LCDS::write(uint32_t i, uint8_t l, uint8_t m) { char buf[l + 1]; buf[l] = '\0'; for (; l > 0; l--) { uint8_t c = i % m; if (c < 10) { buf[l-1] = 0x30 + c; } else { buf[l-1] = 0x41 + c - 10; } i = i / m; } write(buf); } void avr_cpp_lib::LCDS::write(const char * s) { while (*s != '\0') { character(*s); s++; } } void avr_cpp_lib::LCDS::writeFlash(const char * s) { uint8_t c = pgm_read_byte(s); while (c != '\0') { character(c); s++; c = pgm_read_byte(s); } } <|endoftext|>
<commit_before>#include <fstream> #include <sstream> #include <queue> #include "pugixml/pugixml.hpp" #include "pixelboost/data/resources/svgResource.h" #include "pixelboost/file/fileSystem.h" using namespace pb; PB_DEFINE_RESOURCE(pb::SvgResource) class PathTokenizer { public: PathTokenizer(const std::string& path); ~PathTokenizer(); enum TokenType { kTokenTypeUnknown, kTokenTypeMoveAbsolute, kTokenTypeMoveRelative, kTokenTypeCurveAbsolute, kTokenTypeCurveRelative, kTokenTypeSmoothAbsolute, kTokenTypeSmoothRelative, kTokenTypeNumber, }; struct Token { Token(TokenType type = kTokenTypeUnknown, const std::string& data = ""); TokenType type; std::string data; }; const std::queue<Token>& GetTokens(); bool Tokenize(); private: enum State { kStateMain, kStateNumber, }; std::string _Path; State _State; int _Index; std::queue<Token> _Tokens; }; class PathParser { public: PathParser(const std::string& path, float scale); ~PathParser(); bool Parse(SvgPath& path); struct Point { Point(float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2); float x1; float y1; float cx1; float cy1; float cx2; float cy2; float x2; float y2; }; std::vector<Point> Points; private: std::queue<PathTokenizer::Token> _Tokens; float _Scale; float _X; float _Y; PathTokenizer _Tokenizer; }; SvgResource::SvgResource(ResourcePool* pool, const std::string& filename) : Resource(pool, filename) { } SvgResource::~SvgResource() { } ResourceError SvgResource::ProcessResource(ResourcePool* pool, ResourceProcess process, const std::string& filename, std::string& errorDetails) { switch (process) { case kResourceProcessLoad: { return Load(filename); } case kResourceProcessProcess: { pugi::xpath_node svg = _Xml.select_single_node("svg"); _Size = glm::vec2(atof(svg.node().attribute("width").value()), atof(svg.node().attribute("height").value()))/32.f; ParseAll(); _Xml.reset(); for (auto& group : _Groups) { for (auto& path : group.second.Paths) { path.Curve.Parameterize(); } } return kResourceErrorNone; } case kResourceProcessUnload: { _Groups.clear(); _Size = glm::vec2(0,0); return kResourceErrorNone; } case kResourceProcessPostProcess: { return kResourceErrorNone; } } } const std::map<std::string, SvgGroup>& SvgResource::GetGroups() { return _Groups; } ResourceError SvgResource::Load(const std::string& filename) { std::string data; pb::File* file = pb::FileSystem::Instance()->OpenFile(filename, pb::kFileModeRead); if (!file) { return kResourceErrorNoSuchResource; } file->ReadAll(data); delete file; if (!_Xml.load_buffer(data.c_str(), data.length())) { return kResourceErrorSystemError; } return kResourceErrorNone; } bool SvgResource::ParseAll() { pugi::xpath_node_set groups = _Xml.select_nodes("/svg/g"); for (const auto& group : groups) { ParseGroup(group.node().attribute("id").value()); } return true; } bool SvgResource::ParseGroup(const std::string& name) { SvgGroup group; char query[256]; snprintf(query, 256, "/svg/g[@id='%s']/path", name.c_str()); pugi::xpath_node_set paths = _Xml.select_nodes(query); for (pugi::xpath_node_set::const_iterator pathIt = paths.begin(); pathIt != paths.end(); ++pathIt) { SvgPath path; path.Name = pathIt->node().attribute("id").value(); PathParser parser(pathIt->node().attribute("d").value(), 32.f); parser.Parse(path); if (parser.Points.size() > 1) { auto pointA = parser.Points[0]; auto pointB = parser.Points[1]; glm::vec2 pos = glm::vec2(pointA.x1, pointA.y1); path.Curve.AddPoint(HermiteCurve2D::Point(pos, glm::vec2(0,0), (glm::vec2(pointB.cx1, pointB.cy1)-pos)*3.f)); } for (int i=0; i<parser.Points.size()-1; i++) { auto pointA = parser.Points[i]; auto pointB = parser.Points[i+1]; glm::vec2 pos = glm::vec2(pointB.x1, pointB.y1); path.Curve.AddPoint(HermiteCurve2D::Point(pos, (glm::vec2(pointA.cx2, pointA.cy2)-pos)*3.f, (glm::vec2(pointB.cx1, pointB.cy1)-pos)*3.f)); } group.Paths.push_back(path); } _Groups[name] = group; return true; } PathTokenizer::Token::Token(TokenType type, const std::string& data) : data(data) , type(type) { } PathTokenizer::PathTokenizer(const std::string& path) { _Path = path; } PathTokenizer::~PathTokenizer() { } const std::queue<PathTokenizer::Token>& PathTokenizer::GetTokens() { return _Tokens; } bool PathTokenizer::Tokenize() { std::string tokenData; bool finished = false; _Index = 0; _State = kStateMain; while (!finished) { char character = _Index >= _Path.length() ? 0 : _Path[_Index]; switch (_State) { case kStateMain: { int absolute = false; if (character >= 'A' && character <= 'Z') { absolute = true; character -= 'A'-'a'; } if (character == 'm') { _Tokens.push(Token(absolute?kTokenTypeMoveAbsolute:kTokenTypeMoveRelative)); } else if (character == 'c') { _Tokens.push(Token(absolute?kTokenTypeCurveAbsolute:kTokenTypeCurveRelative)); } else if (character == 's') { _Tokens.push(Token(absolute?kTokenTypeSmoothAbsolute:kTokenTypeSmoothRelative)); } else if ((character >= '0' && character <= '9') || character == '-') { _State = kStateNumber; continue; } else if (character == 0) { finished = true; } _Index++; break; } case kStateNumber: { if ((character >= '0' && character <= '9') || character == '-' || character == '.') { if (character == '-') { if (tokenData.length()) { _Tokens.push(Token(kTokenTypeNumber, tokenData)); tokenData = ""; } } } else { if (tokenData.length()) { _Tokens.push(Token(kTokenTypeNumber, tokenData)); tokenData = ""; } _State = kStateMain; continue; } tokenData += character; _Index++; break; } } } return true; } PathParser::Point::Point(float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2) : x1(x1) , y1(y1) , cx1(cx1) , cy1(cy1) , cx2(cx2) , cy2(cy2) , x2(x2) , y2(y2) { } PathParser::PathParser(const std::string& path, float scale) : _Tokenizer(path) , _Scale(scale) { } PathParser::~PathParser() { } bool PathParser::Parse(SvgPath& path) { _X = 0; _Y = 0; _Tokenizer.Tokenize(); _Tokens = _Tokenizer.GetTokens(); std::vector<float> numbers; PathTokenizer::Token stateToken; while (_Tokens.size()) { PathTokenizer::Token token = _Tokens.front(); _Tokens.pop(); if (token.type != PathTokenizer::kTokenTypeNumber) { if (numbers.size() != 0) return false; stateToken = token; } else { numbers.push_back(atof(token.data.c_str())); } switch (stateToken.type) { case PathTokenizer::kTokenTypeMoveAbsolute: { if (numbers.size() == 2) { _X = numbers[0]; _Y = numbers[1]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeMoveRelative: { if (numbers.size() == 2) { _X += numbers[0]; _Y += numbers[1]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeCurveAbsolute: { if (numbers.size() == 6) { Points.push_back(Point(_X, _Y, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5])); _X = numbers[4]; _Y = numbers[5]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeCurveRelative: { if (numbers.size() == 6) { Points.push_back(Point(_X, _Y, _X + numbers[0], _Y + numbers[1], _X + numbers[2], _Y + numbers[3], _X + numbers[4], _Y + numbers[5])); _X += numbers[4]; _Y += numbers[5]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeSmoothAbsolute: { if (numbers.size() == 4) { float cx; float cy; if (Points.size()) { cx = 2*_X - Points.back().cx2; cy = 2*_Y - Points.back().cy2; } else { cx = _X; cy = _Y; } Points.push_back(Point(_X, _Y, cx, cy, numbers[0], numbers[1], numbers[2], numbers[3])); _X = numbers[2]; _Y = numbers[3]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeSmoothRelative: { if (numbers.size() == 4) { float cx; float cy; if (Points.size()) { cx = 2*_X - Points.back().cx2; cy = 2*_Y - Points.back().cy2; } else { cx = _X; cy = _Y; } Points.push_back(Point(_X, _Y, cx, cy, _X + numbers[0], _Y + numbers[1], _X + numbers[2], _Y + numbers[3])); _X += numbers[2]; _Y += numbers[3]; numbers.clear(); } break; } default: break; } } for (auto& point : Points) { point.x1 /= _Scale; point.cx1 /= _Scale; point.cx2 /= _Scale; point.x2 /= _Scale; point.y1 = -point.y1/_Scale; point.cy1 = -point.cy1/_Scale; point.cy2 = -point.cy2/_Scale; point.y2 = -point.y2/_Scale; } return true; } <commit_msg>Add missing GetSize implementation in SvgResource<commit_after>#include <fstream> #include <sstream> #include <queue> #include "pugixml/pugixml.hpp" #include "pixelboost/data/resources/svgResource.h" #include "pixelboost/file/fileSystem.h" using namespace pb; PB_DEFINE_RESOURCE(pb::SvgResource) class PathTokenizer { public: PathTokenizer(const std::string& path); ~PathTokenizer(); enum TokenType { kTokenTypeUnknown, kTokenTypeMoveAbsolute, kTokenTypeMoveRelative, kTokenTypeCurveAbsolute, kTokenTypeCurveRelative, kTokenTypeSmoothAbsolute, kTokenTypeSmoothRelative, kTokenTypeNumber, }; struct Token { Token(TokenType type = kTokenTypeUnknown, const std::string& data = ""); TokenType type; std::string data; }; const std::queue<Token>& GetTokens(); bool Tokenize(); private: enum State { kStateMain, kStateNumber, }; std::string _Path; State _State; int _Index; std::queue<Token> _Tokens; }; class PathParser { public: PathParser(const std::string& path, float scale); ~PathParser(); bool Parse(SvgPath& path); struct Point { Point(float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2); float x1; float y1; float cx1; float cy1; float cx2; float cy2; float x2; float y2; }; std::vector<Point> Points; private: std::queue<PathTokenizer::Token> _Tokens; float _Scale; float _X; float _Y; PathTokenizer _Tokenizer; }; SvgResource::SvgResource(ResourcePool* pool, const std::string& filename) : Resource(pool, filename) { } SvgResource::~SvgResource() { } ResourceError SvgResource::ProcessResource(ResourcePool* pool, ResourceProcess process, const std::string& filename, std::string& errorDetails) { switch (process) { case kResourceProcessLoad: { return Load(filename); } case kResourceProcessProcess: { pugi::xpath_node svg = _Xml.select_single_node("svg"); _Size = glm::vec2(atof(svg.node().attribute("width").value()), atof(svg.node().attribute("height").value()))/32.f; ParseAll(); _Xml.reset(); for (auto& group : _Groups) { for (auto& path : group.second.Paths) { path.Curve.Parameterize(); } } return kResourceErrorNone; } case kResourceProcessUnload: { _Groups.clear(); _Size = glm::vec2(0,0); return kResourceErrorNone; } case kResourceProcessPostProcess: { return kResourceErrorNone; } } } const std::map<std::string, SvgGroup>& SvgResource::GetGroups() { return _Groups; } glm::vec2 SvgResource::GetSize() { return _Size; } ResourceError SvgResource::Load(const std::string& filename) { std::string data; pb::File* file = pb::FileSystem::Instance()->OpenFile(filename, pb::kFileModeRead); if (!file) { return kResourceErrorNoSuchResource; } file->ReadAll(data); delete file; if (!_Xml.load_buffer(data.c_str(), data.length())) { return kResourceErrorSystemError; } return kResourceErrorNone; } bool SvgResource::ParseAll() { pugi::xpath_node_set groups = _Xml.select_nodes("/svg/g"); for (const auto& group : groups) { ParseGroup(group.node().attribute("id").value()); } return true; } bool SvgResource::ParseGroup(const std::string& name) { SvgGroup group; char query[256]; snprintf(query, 256, "/svg/g[@id='%s']/path", name.c_str()); pugi::xpath_node_set paths = _Xml.select_nodes(query); for (pugi::xpath_node_set::const_iterator pathIt = paths.begin(); pathIt != paths.end(); ++pathIt) { SvgPath path; path.Name = pathIt->node().attribute("id").value(); PathParser parser(pathIt->node().attribute("d").value(), 32.f); parser.Parse(path); if (parser.Points.size() > 1) { auto pointA = parser.Points[0]; auto pointB = parser.Points[1]; glm::vec2 pos = glm::vec2(pointA.x1, pointA.y1); path.Curve.AddPoint(HermiteCurve2D::Point(pos, glm::vec2(0,0), (glm::vec2(pointB.cx1, pointB.cy1)-pos)*3.f)); } for (int i=0; i<parser.Points.size()-1; i++) { auto pointA = parser.Points[i]; auto pointB = parser.Points[i+1]; glm::vec2 pos = glm::vec2(pointB.x1, pointB.y1); path.Curve.AddPoint(HermiteCurve2D::Point(pos, (glm::vec2(pointA.cx2, pointA.cy2)-pos)*3.f, (glm::vec2(pointB.cx1, pointB.cy1)-pos)*3.f)); } group.Paths.push_back(path); } _Groups[name] = group; return true; } PathTokenizer::Token::Token(TokenType type, const std::string& data) : data(data) , type(type) { } PathTokenizer::PathTokenizer(const std::string& path) { _Path = path; } PathTokenizer::~PathTokenizer() { } const std::queue<PathTokenizer::Token>& PathTokenizer::GetTokens() { return _Tokens; } bool PathTokenizer::Tokenize() { std::string tokenData; bool finished = false; _Index = 0; _State = kStateMain; while (!finished) { char character = _Index >= _Path.length() ? 0 : _Path[_Index]; switch (_State) { case kStateMain: { int absolute = false; if (character >= 'A' && character <= 'Z') { absolute = true; character -= 'A'-'a'; } if (character == 'm') { _Tokens.push(Token(absolute?kTokenTypeMoveAbsolute:kTokenTypeMoveRelative)); } else if (character == 'c') { _Tokens.push(Token(absolute?kTokenTypeCurveAbsolute:kTokenTypeCurveRelative)); } else if (character == 's') { _Tokens.push(Token(absolute?kTokenTypeSmoothAbsolute:kTokenTypeSmoothRelative)); } else if ((character >= '0' && character <= '9') || character == '-') { _State = kStateNumber; continue; } else if (character == 0) { finished = true; } _Index++; break; } case kStateNumber: { if ((character >= '0' && character <= '9') || character == '-' || character == '.') { if (character == '-') { if (tokenData.length()) { _Tokens.push(Token(kTokenTypeNumber, tokenData)); tokenData = ""; } } } else { if (tokenData.length()) { _Tokens.push(Token(kTokenTypeNumber, tokenData)); tokenData = ""; } _State = kStateMain; continue; } tokenData += character; _Index++; break; } } } return true; } PathParser::Point::Point(float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2) : x1(x1) , y1(y1) , cx1(cx1) , cy1(cy1) , cx2(cx2) , cy2(cy2) , x2(x2) , y2(y2) { } PathParser::PathParser(const std::string& path, float scale) : _Tokenizer(path) , _Scale(scale) { } PathParser::~PathParser() { } bool PathParser::Parse(SvgPath& path) { _X = 0; _Y = 0; _Tokenizer.Tokenize(); _Tokens = _Tokenizer.GetTokens(); std::vector<float> numbers; PathTokenizer::Token stateToken; while (_Tokens.size()) { PathTokenizer::Token token = _Tokens.front(); _Tokens.pop(); if (token.type != PathTokenizer::kTokenTypeNumber) { if (numbers.size() != 0) return false; stateToken = token; } else { numbers.push_back(atof(token.data.c_str())); } switch (stateToken.type) { case PathTokenizer::kTokenTypeMoveAbsolute: { if (numbers.size() == 2) { _X = numbers[0]; _Y = numbers[1]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeMoveRelative: { if (numbers.size() == 2) { _X += numbers[0]; _Y += numbers[1]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeCurveAbsolute: { if (numbers.size() == 6) { Points.push_back(Point(_X, _Y, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5])); _X = numbers[4]; _Y = numbers[5]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeCurveRelative: { if (numbers.size() == 6) { Points.push_back(Point(_X, _Y, _X + numbers[0], _Y + numbers[1], _X + numbers[2], _Y + numbers[3], _X + numbers[4], _Y + numbers[5])); _X += numbers[4]; _Y += numbers[5]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeSmoothAbsolute: { if (numbers.size() == 4) { float cx; float cy; if (Points.size()) { cx = 2*_X - Points.back().cx2; cy = 2*_Y - Points.back().cy2; } else { cx = _X; cy = _Y; } Points.push_back(Point(_X, _Y, cx, cy, numbers[0], numbers[1], numbers[2], numbers[3])); _X = numbers[2]; _Y = numbers[3]; numbers.clear(); } break; } case PathTokenizer::kTokenTypeSmoothRelative: { if (numbers.size() == 4) { float cx; float cy; if (Points.size()) { cx = 2*_X - Points.back().cx2; cy = 2*_Y - Points.back().cy2; } else { cx = _X; cy = _Y; } Points.push_back(Point(_X, _Y, cx, cy, _X + numbers[0], _Y + numbers[1], _X + numbers[2], _Y + numbers[3])); _X += numbers[2]; _Y += numbers[3]; numbers.clear(); } break; } default: break; } } for (auto& point : Points) { point.x1 /= _Scale; point.cx1 /= _Scale; point.cx2 /= _Scale; point.x2 /= _Scale; point.y1 = -point.y1/_Scale; point.cy1 = -point.cy1/_Scale; point.cy2 = -point.cy2/_Scale; point.y2 = -point.y2/_Scale; } return true; } <|endoftext|>
<commit_before>// Copyright(c) 2016 Jounayd Id Salah // Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT). #include "app/pch.h" #include "app/coApp.h" coResult coApp::ProcessEvents() { MSG msg; if (::GetMessageW(&msg, NULL, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessageW(&msg); } else { exitRequested = true; return msg.wParam == 0; } return true; } <commit_msg>Fixed main app loop on Windows.<commit_after>// Copyright(c) 2016 Jounayd Id Salah // Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT). #include "app/pch.h" #include "app/coApp.h" coResult coApp::ProcessEvents() { MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // Translate the message and dispatch it to WindowProc() ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (msg.message == WM_QUIT) { exitRequested = true; return msg.wParam == 0; } return true; } <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <exception> #include <algorithm> #include <vector> using std::vector ; #include <fstream> using std::ofstream ; #include <string> using std::string ; #include <sofa/helper/system/FileMonitor.h> using sofa::helper::system::FileEventListener ; using sofa::helper::system::FileMonitor ; static std::string getPath(std::string s) { return std::string(FRAMEWORK_TEST_RESOURCES_DIR) + std::string("/") + s; } void createAFilledFile(const string filename, unsigned int rep){ ofstream file1 ; file1.open(filename.c_str(), ofstream::out) ; //throw_when(!file1.is_open()) ; string sample = "#include<TODOD> int main(int argc...){ ... }\n}" ; for(unsigned int i=0;i<rep;i++){ file1.write(sample.c_str(), sample.size()) ; } file1.close(); } class MyFileListener : public FileEventListener { public: vector<string> m_files ; virtual void fileHasChanged(const std::string& filename){ //std::cout << "FileHasChanged: " << filename << std::endl ; m_files.push_back(filename) ; } }; TEST(FileMonitor, addFileNotExist_test) { MyFileListener listener ; // Should refuse to add a file that does not exists EXPECT_EQ( FileMonitor::addFile(getPath("nonexisting.txt"), &listener), -1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileNotExist2_test) { MyFileListener listener ; // Should refuse to add a file that does not exists EXPECT_EQ( FileMonitor::addFile(getPath(""),"nonexisting.txt", &listener), -1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileExist_test) { MyFileListener listener ; // Add an existing file.It should work. EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileTwice_test) { MyFileListener listener ; // Add an existing file.It should work. FileMonitor::addFile(getPath("existing.txt"), &listener); // Retry to add an existing file. It should fail. EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ; // change the file content.. createAFilledFile(getPath("existing.txt"), 10) ; FileMonitor::updates(0) ; // The listener should be notified 1 times with the same event. EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, noUpdate_test) { MyFileListener listener ; // Add an existing file.It should work. FileMonitor::addFile(getPath("existing.txt"), &listener) ; EXPECT_EQ( listener.m_files.size(), 0u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, updateNoChange_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 0u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileChange_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; // change the file content.. createAFilledFile(getPath("existing.txt"), 10) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileChangeTwice_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 100) ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileListenerRemoved_test) { MyFileListener listener1 ; MyFileListener listener2 ; FileMonitor::addFile(getPath("existing.txt"), &listener1) ; FileMonitor::addFile(getPath("existing.txt"), &listener2) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener1.m_files.clear() ; listener2.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::removeFileListener(getPath("existing.txt"), &listener1) ; FileMonitor::updates(0) ; EXPECT_EQ( listener1.m_files.size(), 0u) ; EXPECT_EQ( listener2.m_files.size(), 1u) ; FileMonitor::removeListener(&listener1) ; FileMonitor::removeListener(&listener2) ; } TEST(FileMonitor, listenerRemoved_test) { MyFileListener listener1 ; MyFileListener listener2 ; FileMonitor::addFile(getPath("existing.txt"), &listener1) ; FileMonitor::addFile(getPath("existing.txt"), &listener2) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener1.m_files.clear() ; listener2.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::removeListener(&listener1) ; FileMonitor::updates(0) ; EXPECT_EQ( listener1.m_files.size(), 0u) ; EXPECT_EQ( listener2.m_files.size(), 1u) ; FileMonitor::removeListener(&listener1) ; FileMonitor::removeListener(&listener2) ; } <commit_msg>Filemonitor_test: added the test of the second addFile fonction as fileChange2_test (reverted from commit d818ce134d8ce2c4ce408b9bd07e88ac72a0edee)<commit_after> #include <gtest/gtest.h> #include <exception> #include <algorithm> #include <vector> using std::vector ; #include <fstream> using std::ofstream ; #include <string> using std::string ; #include <sofa/helper/system/FileMonitor.h> using sofa::helper::system::FileEventListener ; using sofa::helper::system::FileMonitor ; static std::string getPath(std::string s) { return std::string(FRAMEWORK_TEST_RESOURCES_DIR) + std::string("/") + s; } void createAFilledFile(const string filename, unsigned int rep){ ofstream file1 ; file1.open(filename.c_str(), ofstream::out) ; //throw_when(!file1.is_open()) ; string sample = "#include<TODOD> int main(int argc...){ ... }\n}" ; for(unsigned int i=0;i<rep;i++){ file1.write(sample.c_str(), sample.size()) ; } file1.close(); } class MyFileListener : public FileEventListener { public: vector<string> m_files ; virtual void fileHasChanged(const std::string& filename){ //std::cout << "FileHasChanged: " << filename << std::endl ; m_files.push_back(filename) ; } }; TEST(FileMonitor, addFileNotExist_test) { MyFileListener listener ; // Should refuse to add a file that does not exists EXPECT_EQ( FileMonitor::addFile(getPath("nonexisting.txt"), &listener), -1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileNotExist2_test) { MyFileListener listener ; // Should refuse to add a file that does not exists EXPECT_EQ( FileMonitor::addFile(getPath(""),"nonexisting.txt", &listener), -1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileExist_test) { MyFileListener listener ; // Add an existing file.It should work. EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, addFileTwice_test) { MyFileListener listener ; // Add an existing file.It should work. FileMonitor::addFile(getPath("existing.txt"), &listener); // Retry to add an existing file. It should fail. EXPECT_EQ( FileMonitor::addFile(getPath("existing.txt"), &listener), 1 ) ; // change the file content.. createAFilledFile(getPath("existing.txt"), 10) ; FileMonitor::updates(0) ; // The listener should be notified 1 times with the same event. EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, noUpdate_test) { MyFileListener listener ; // Add an existing file.It should work. FileMonitor::addFile(getPath("existing.txt"), &listener) ; EXPECT_EQ( listener.m_files.size(), 0u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, updateNoChange_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 0u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileChange_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; // change the file content.. createAFilledFile(getPath("existing.txt"), 10) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileChange2_test) { MyFileListener listener ; FileMonitor::addFile(getPath(""),"existing.txt", &listener) ; FileMonitor::updates(0) ; // change the file content.. createAFilledFile(getPath("existing.txt"), 10) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileChangeTwice_test) { MyFileListener listener ; FileMonitor::addFile(getPath("existing.txt"), &listener) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 100) ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::updates(0) ; EXPECT_EQ( listener.m_files.size(), 1u) ; FileMonitor::removeListener(&listener) ; } TEST(FileMonitor, fileListenerRemoved_test) { MyFileListener listener1 ; MyFileListener listener2 ; FileMonitor::addFile(getPath("existing.txt"), &listener1) ; FileMonitor::addFile(getPath("existing.txt"), &listener2) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener1.m_files.clear() ; listener2.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::removeFileListener(getPath("existing.txt"), &listener1) ; FileMonitor::updates(0) ; EXPECT_EQ( listener1.m_files.size(), 0u) ; EXPECT_EQ( listener2.m_files.size(), 1u) ; FileMonitor::removeListener(&listener1) ; FileMonitor::removeListener(&listener2) ; } TEST(FileMonitor, listenerRemoved_test) { MyFileListener listener1 ; MyFileListener listener2 ; FileMonitor::addFile(getPath("existing.txt"), &listener1) ; FileMonitor::addFile(getPath("existing.txt"), &listener2) ; FileMonitor::updates(0) ; // change the file content 2x to test if the events are coalesced. listener1.m_files.clear() ; listener2.m_files.clear() ; createAFilledFile(getPath("existing.txt"), 200) ; FileMonitor::removeListener(&listener1) ; FileMonitor::updates(0) ; EXPECT_EQ( listener1.m_files.size(), 0u) ; EXPECT_EQ( listener2.m_files.size(), 1u) ; FileMonitor::removeListener(&listener1) ; FileMonitor::removeListener(&listener2) ; } <|endoftext|>
<commit_before>#include <gtest\gtest.h> #include "vm.h" using namespace elsa::vm; class StructTest : public testing::Test { protected: virtual void SetUp() { int ep = 0; vm_.add_constant_entry(new FunctionInfo("main", 0, 2, ep, FunctionType::Static)); vm_.set_entry_point(ep); auto si = new StructInfo("my_struct"); si->add_field(new FieldInfo("field0", OType::Int)); si->add_field(new FieldInfo("field1", OType::Float)); si->add_field(new FieldInfo("field2", OType::Int)); si->add_field(new FieldInfo("field3", OType::Float)); si->add_field(new FieldInfo("field4", OType::Int)); vm_.add_constant_entry(si); vm_.add_constant_entry(new FloatEntry(12.0f)); vm_.add_constant_entry(new FloatEntry(99.0f)); auto si2 = new StructInfo("my_struct2"); si2->add_field(new FieldInfo("field0", OType::GCOPtr)); si2->add_field(new FieldInfo("field1", OType::GCOPtr)); vm_.add_constant_entry(si2); } virtual void TearDown() {} VM vm_; }; TEST_F(StructTest, NEW) { std::vector<int> p = { new_struct, 1 }; vm_.set_program(p); vm_.execute(); auto obj = vm_.eval_stack_top(); ASSERT_EQ(OType::GCOPtr, obj.get_type()); auto si = obj.gco()->si; ASSERT_EQ("my_struct", si->get_name()); ASSERT_EQ(20, si->get_size()); } TEST_F(StructTest, FIELD_STORE_LOAD) { std::vector<int> p = { new_struct, 1, s_local, 0, // Store 77 in field 0 (int) l_local, 0, iconst, 77, s_field, 0, // Store 12.0 in field 1 (float) l_local, 0, fconst, 2, s_field, 1, // Store 100 in field 2 (int) l_local, 0, iconst, 100, s_field, 2, // Store 99.0 in field 3 (float) l_local, 0, fconst, 3, s_field, 3, // Store -1829 in field 4 (int) l_local, 0, iconst, -1829, s_field, 4, // Load field 0 l_local, 0, l_field, 0, halt, // Load field 1 l_local, 0, l_field, 1, halt, // Load field 2 l_local, 0, l_field, 2, halt, // Load field 3 l_local, 0, l_field, 3, halt, // Load field 4 l_local, 0, l_field, 4, halt, }; vm_.set_program(p); vm_.execute(); ASSERT_EQ(77, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(12.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(100, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(99.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(-1829, vm_.eval_stack_top().i()); } TEST_F(StructTest, STRUCT_FIELD_STORE_LOAD) { std::vector<int> p = { new_struct, 1, s_local, 0, // Store 77 in field 0 (int) l_local, 0, halt, iconst, 77, s_field, 0, new_struct, 4, s_local, 1, // Store a pointer to the fist struct in field 0 of the second struct l_local, 1, halt, l_local, 0, halt, s_field, 0, l_local, 1, halt, l_field, 0, halt, l_field, 0, }; vm_.set_program(p); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ(77, vm_.eval_stack_top().i()); } <commit_msg>wrote some more struct pointer tests<commit_after>#include <gtest\gtest.h> #include "vm.h" using namespace elsa::vm; class StructTest : public testing::Test { protected: virtual void SetUp() { int ep = 0; vm_.add_constant_entry(new FunctionInfo("main", 0, 3, ep, FunctionType::Static)); vm_.set_entry_point(ep); auto si = new StructInfo("my_struct"); si->add_field(new FieldInfo("field0", OType::Int)); si->add_field(new FieldInfo("field1", OType::Float)); si->add_field(new FieldInfo("field2", OType::Int)); si->add_field(new FieldInfo("field3", OType::Float)); si->add_field(new FieldInfo("field4", OType::Int)); vm_.add_constant_entry(si); vm_.add_constant_entry(new FloatEntry(12.0f)); vm_.add_constant_entry(new FloatEntry(99.0f)); auto si2 = new StructInfo("my_struct2"); si2->add_field(new FieldInfo("field0", OType::GCOPtr)); si2->add_field(new FieldInfo("field1", OType::Int)); si2->add_field(new FieldInfo("field2", OType::GCOPtr)); vm_.add_constant_entry(si2); } virtual void TearDown() {} VM vm_; }; TEST_F(StructTest, NEW) { std::vector<int> p = { new_struct, 1 }; vm_.set_program(p); vm_.execute(); auto obj = vm_.eval_stack_top(); ASSERT_EQ(OType::GCOPtr, obj.get_type()); auto si = obj.gco()->si; ASSERT_EQ("my_struct", si->get_name()); ASSERT_EQ(20, si->get_size()); } TEST_F(StructTest, FIELD_STORE_LOAD) { std::vector<int> p = { new_struct, 1, s_local, 0, // Store 77 in field 0 (int) l_local, 0, iconst, 77, s_field, 0, // Store 12.0 in field 1 (float) l_local, 0, fconst, 2, s_field, 1, // Store 100 in field 2 (int) l_local, 0, iconst, 100, s_field, 2, // Store 99.0 in field 3 (float) l_local, 0, fconst, 3, s_field, 3, // Store -1829 in field 4 (int) l_local, 0, iconst, -1829, s_field, 4, // Load field 0 l_local, 0, l_field, 0, halt, // Load field 1 l_local, 0, l_field, 1, halt, // Load field 2 l_local, 0, l_field, 2, halt, // Load field 3 l_local, 0, l_field, 3, halt, // Load field 4 l_local, 0, l_field, 4, halt, }; vm_.set_program(p); vm_.execute(); ASSERT_EQ(77, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(12.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(100, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(99.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(-1829, vm_.eval_stack_top().i()); } TEST_F(StructTest, STRUCT_FIELD_STORE_LOAD) { std::vector<int> p = { new_struct, 1, s_local, 0, // Store 77 in field 0 (int) l_local, 0, halt, iconst, 77, s_field, 0, new_struct, 4, s_local, 1, // Store a pointer to the fist struct in field 0 of the second struct l_local, 1, halt, l_local, 0, halt, s_field, 0, l_local, 1, halt, l_field, 0, halt, l_field, 0, }; vm_.set_program(p); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ(77, vm_.eval_stack_top().i()); } TEST_F(StructTest, STRUCT_ON_STRUCT_FIELD_STORE_LOAD) { std::vector<int> p = { new_struct, 1, s_local, 0, l_local, 0, iconst, 77, s_field, 0, l_local, 0, fconst, 2, s_field, 1, l_local, 0, iconst, 100, s_field, 2, l_local, 0, fconst, 3, s_field, 3, l_local, 0, iconst, -1829, s_field, 4, new_struct, 4, s_local, 1, l_local, 1, l_local, 0, halt, s_field, 0, l_local, 1, iconst, 12378, s_field, 1, new_struct, 4, halt, s_local, 2, l_local, 2, l_local, 0, s_field, 0, l_local, 1, l_local, 2, s_field, 2, l_local, 1, l_field, 1, halt, l_local, 1, l_field, 2, halt, // Load 77(field 0) from a pointer to struct 0 l_local, 1, l_field, 2, l_field, 0, l_field, 0, halt, // Load 12.0f(field 1) from a pointer to struct 0 l_local, 1, l_field, 2, l_field, 0, l_field, 1, halt, // Load 100(field 2) from a pointer to struct 0 l_local, 1, l_field, 2, l_field, 0, l_field, 2, halt, // Load 99.0f(field 3) from a pointer to struct 0 l_local, 1, l_field, 2, l_field, 0, l_field, 3, halt, // Load -1829(field 4) from a pointer to struct 0 l_local, 1, l_field, 2, l_field, 0, l_field, 4, halt, }; vm_.set_program(p); vm_.execute(); ASSERT_EQ("my_struct", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ(12378, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_EQ("my_struct2", vm_.eval_stack_top().gco()->si->get_name()); vm_.execute(); ASSERT_EQ(77, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(12.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(100, vm_.eval_stack_top().i()); vm_.execute(); ASSERT_FLOAT_EQ(99.0f, vm_.eval_stack_top().f()); vm_.execute(); ASSERT_EQ(-1829, vm_.eval_stack_top().i()); } <|endoftext|>
<commit_before>/*===- Integrator.cpp - libSimulation -========================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #include "Integrator.h" #include "CacheOperator.h" #include <cmath> #include <limits> Integrator::Integrator(Cloud * const C, const ForceArray &FA, const double timeStep, double startTime) : currentTime(startTime), cloud(C), forces(FA), init_dt(timeStep), operations({{new CacheOperator(C)}}) SEMAPHORES_MALLOC(1) { SEMAPHORES_INIT(1); } Integrator::~Integrator() { for (Operator * const opt : operations) delete opt; SEMAPHORES_FREE(1); } // If particle spacing is less than the specified distance reduce timestep by a // factor of 10 and recheck with disance reduced by a factor of 10. Once all // particle spacings are outside the specified distance use the current // timestep. This allows fine grain control of reduced timesteps. const double Integrator::modifyTimeStep(float currentDist, double currentTimeStep) const { // set constants: const cloud_index numPar = cloud->n; const float redFactor = 10.0f; #ifdef DISPATCH_QUEUES // You cannot block capture method arguments. Store these values in to non // const block captured variables. The correct names supsequently used by // BLOCK_VALUE_DIST and BLOCK_VALUE_TIME __block float currDist = currentDist; __block double currTimeStep = currentTimeStep; #endif // Loop through entire cloud, or until reduction occures. Reset innerIndex // after each loop iteration. #ifdef DISPATCH_QUEUES const cloud_index outerLoop = numPar; #else const cloud_index outerLoop = numPar - 1; #endif BEGIN_PARALLEL_FOR(outerIndex, e, outerLoop, FLOAT_STRIDE, dynamic) // caculate separation distance b/t adjacent elements: const floatV outPosX = loadFloatVector(cloud->x + outerIndex); const floatV outPosY = loadFloatVector(cloud->y + outerIndex); // seperation (a1 - a2, a3 - a4, a1 - a3, a2 - a4) floatV sepx = _mm_hsub_ps(outPosX, _mm_shuffle_ps(outPosX, outPosX, _MM_SHUFFLE(1, 2, 0, 3))); floatV sepy = _mm_hsub_ps(outPosY, _mm_shuffle_ps(outPosY, outPosY, _MM_SHUFFLE(1, 2, 0, 3))); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // seperation (a1 - a2, a3 - a4, a1 - a4, a2 - a3) The lower half // operation is a repeat of the lower half of the above. sepx = _mm_hsub_ps(outPosX, _mm_shuffle_ps(outPosX, outPosX, _MM_SHUFFLE(1, 3, 0, 2))); sepy = _mm_hsub_ps(outPosY, _mm_shuffle_ps(outPosY, outPosY, _MM_SHUFFLE(1, 3, 0, 2))); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // Calculate separation distance b/t nonadjacent elements: for (cloud_index innerIndex = outerIndex + FLOAT_STRIDE; innerIndex < numPar; innerIndex += FLOAT_STRIDE) { const floatV inPosX = loadFloatVector(cloud->x + innerIndex); const floatV inPosY = loadFloatVector(cloud->y + innerIndex); sepx = outPosX - inPosX; sepy = outPosY - inPosY; // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(0, 1, 2, 3)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(0, 1, 2, 3)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(1, 0, 3, 2)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(1, 0, 3, 2)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(2, 3, 0, 1)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(2, 3, 0, 1)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } } END_PARALLEL_FOR return BLOCK_VALUE_TIME; } inline floatV Integrator::loadFloatVector(double * const x) { #ifdef __AVX__ return _mm256_set_ps((float)x[0], (float)x[1], (float)x[2], (float)x[3], (float)x[4], (float)x[5], (float)x[6], (float)x[7]); #else return _mm_set_ps((float)x[0], (float)x[1], (float)x[2], (float)x[3]); #endif } inline bool Integrator::isWithInDistance(const floatV a, const floatV b, const float dist) { return (bool)movemask_ps(cmple_ps(sqrt_ps(add_ps(mul_ps(a, a), mul_ps(b, b))), set1_ps(dist))); } <commit_msg>Add comments to explain which comparison is which.<commit_after>/*===- Integrator.cpp - libSimulation -========================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #include "Integrator.h" #include "CacheOperator.h" #include <cmath> #include <limits> Integrator::Integrator(Cloud * const C, const ForceArray &FA, const double timeStep, double startTime) : currentTime(startTime), cloud(C), forces(FA), init_dt(timeStep), operations({{new CacheOperator(C)}}) SEMAPHORES_MALLOC(1) { SEMAPHORES_INIT(1); } Integrator::~Integrator() { for (Operator * const opt : operations) delete opt; SEMAPHORES_FREE(1); } // If particle spacing is less than the specified distance reduce timestep by a // factor of 10 and recheck with disance reduced by a factor of 10. Once all // particle spacings are outside the specified distance use the current // timestep. This allows fine grain control of reduced timesteps. const double Integrator::modifyTimeStep(float currentDist, double currentTimeStep) const { // set constants: const cloud_index numPar = cloud->n; const float redFactor = 10.0f; #ifdef DISPATCH_QUEUES // You cannot block capture method arguments. Store these values in to non // const block captured variables. The correct names supsequently used by // BLOCK_VALUE_DIST and BLOCK_VALUE_TIME __block float currDist = currentDist; __block double currTimeStep = currentTimeStep; #endif // Loop through entire cloud, or until reduction occures. Reset innerIndex // after each loop iteration. #ifdef DISPATCH_QUEUES const cloud_index outerLoop = numPar; #else const cloud_index outerLoop = numPar - 1; #endif BEGIN_PARALLEL_FOR(outerIndex, e, outerLoop, FLOAT_STRIDE, dynamic) // caculate separation distance b/t adjacent elements: const floatV outPosX = loadFloatVector(cloud->x + outerIndex); const floatV outPosY = loadFloatVector(cloud->y + outerIndex); // seperation (a1 - a2, a3 - a4, a1 - a3, a2 - a4) floatV sepx = _mm_hsub_ps(outPosX, _mm_shuffle_ps(outPosX, outPosX, _MM_SHUFFLE(1, 2, 0, 3))); floatV sepy = _mm_hsub_ps(outPosY, _mm_shuffle_ps(outPosY, outPosY, _MM_SHUFFLE(1, 2, 0, 3))); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // seperation (a1 - a2, a3 - a4, a1 - a4, a2 - a3) The lower half // operation is a repeat of the lower half of the above. sepx = _mm_hsub_ps(outPosX, _mm_shuffle_ps(outPosX, outPosX, _MM_SHUFFLE(1, 3, 0, 2))); sepy = _mm_hsub_ps(outPosY, _mm_shuffle_ps(outPosY, outPosY, _MM_SHUFFLE(1, 3, 0, 2))); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // Calculate separation distance b/t nonadjacent elements: for (cloud_index innerIndex = outerIndex + FLOAT_STRIDE; innerIndex < numPar; innerIndex += FLOAT_STRIDE) { const floatV inPosX = loadFloatVector(cloud->x + innerIndex); const floatV inPosY = loadFloatVector(cloud->y + innerIndex); // seperation (a1 - b1, a2 - b2, a3 - b3, a4 - b4) sepx = outPosX - inPosX; sepy = outPosY - inPosY; // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // seperation (a1 - b2, a2 - b3, a3 - b4, a4 - b5) sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(3, 2, 1, 0)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(3, 2, 1, 0)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // seperation (a1 - b3, a2 - b4, a3 - b1, a4 - b2) sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(0, 3, 2, 1)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(0, 3, 2, 1)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } // seperation (a1 - b4, a2 - b1, a3 - b2, a4 - b3) sepx = outPosX - _mm_shuffle_ps(inPosX, inPosX, _MM_SHUFFLE(1, 0, 3, 2)); sepy = outPosY - _mm_shuffle_ps(inPosY, inPosY, _MM_SHUFFLE(1, 0, 3, 2)); // If particles are too close, reduce time step: while (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { // Only one thread should modify the distance and timesStep at a time. SEMAPHORE_WAIT(0) if (isWithInDistance(sepx, sepy, BLOCK_VALUE_DIST)) { BLOCK_VALUE_DIST /= redFactor; BLOCK_VALUE_TIME /= redFactor; } SEMAPHORE_SIGNAL(0) } } END_PARALLEL_FOR return BLOCK_VALUE_TIME; } inline floatV Integrator::loadFloatVector(double * const x) { #ifdef __AVX__ return _mm256_set_ps((float)x[0], (float)x[1], (float)x[2], (float)x[3], (float)x[4], (float)x[5], (float)x[6], (float)x[7]); #else return _mm_set_ps((float)x[0], (float)x[1], (float)x[2], (float)x[3]); #endif } inline bool Integrator::isWithInDistance(const floatV a, const floatV b, const float dist) { return (bool)movemask_ps(cmple_ps(sqrt_ps(add_ps(mul_ps(a, a), mul_ps(b, b))), set1_ps(dist))); } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Timothy Reaves [email protected] 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, see <http://www.gnu.org/licenses/>. */ #include "priv/classhandlermanager.h" #include "classhandler.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QJsonArray> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QJsonValue> #include <QtCore/QMetaObject> #include <QtCore/QMetaMethod> #include <QtCore/QMetaType> #include <QtCore/QtPlugin> #include <QtCore/QPluginLoader> #include <QtCore/QSet> #include <QtCore/QString> #include <QtCore/QUrl> #include <QtCore/QVariant> #include "httpserverrequest.h" #include "headers.h" namespace Tufao { // Initialize static members. /* \warning the variable is never fully initialized. * `QCoreApplication::applicationDirPath()` (aka the install location), which * can only be retrieved at runtime, after the QCoreApplication was constructed, * is never present in this list. */ QStringList ClassHandlerManager::pluginLocations = []() { QStringList ret; // Add standard locations to pluginLocations // First, the typical app config dir's #ifdef Q_OS_WIN // Code can be added here, but, for the time being, I'm leaving it empty. #elif defined(Q_OS_MAC) ret.append(QDir::homePath() + "/Library/Application Support/Tufao"); ret.append("/Library/Application Support/Tufao"); #else ret.append(QDir::homePath() + "/.tufao"); #endif // The standard library locations for (const QString &libraryPath: QCoreApplication::libraryPaths()) { QDir testDir(libraryPath + QDir::separator() + "Tufao"); if(testDir.exists()){ ret.append(testDir.absolutePath()); } } return ret; }(); /* ************************************************************************** */ /* Object lifecycle */ /* ************************************************************************** */ ClassHandlerManager::ClassHandlerManager(const QString &pluginID, const QString &urlNamespace, QObject * parent) : QObject(parent), priv{new Priv{pluginID, urlNamespace}} { // Now load the plugin of interest // First list all static plugins. foreach (QObject * pluginInterface, QPluginLoader::staticInstances()){ ClassHandler * plugin = qobject_cast<ClassHandler *>(pluginInterface); if (plugin){ registerHandler(plugin); } } /// // Then list dynamic libraries from the plugins/ directory QStringList contents; // retrieve a list of all dynamic libraries from the search paths { auto retrieveDynlib = [&contents](const QString &path) { QFileInfo thisPath(QDir(path).filePath("plugins")); if (thisPath.isDir()) { QDir thisDir(thisPath.absoluteFilePath()); qDebug() << "Search " << thisPath.absolutePath() << " for plugins."; for (const QString &entry: thisDir.entryList()) { if (QLibrary::isLibrary(entry)) contents.append(thisDir.filePath(entry)); } } }; for (const QString &path: pluginLocations) retrieveDynlib(path); QFileInfo installDir(QCoreApplication::applicationDirPath()); if (installDir.isDir()) retrieveDynlib(installDir.absolutePath()); } // Check each dynamic library to see if it is a plugin foreach (QString pluginPath, contents) { QPluginLoader loader(pluginPath); // If we were constructed with a pluginID, we need to chech each plugin. if(pluginID.isEmpty() || pluginID == loader.metaData().value("IID").toString()) { if (!loader.load()) { qWarning() << "Couldn't load the dynamic library: " << QDir::toNativeSeparators(pluginPath) << ": " << loader.errorString(); continue; } QObject* obj = loader.instance(); if (!obj) { qWarning() << "Couldn't open the dynamic library: " << QDir::toNativeSeparators(pluginPath) << ": " << loader.errorString(); continue; } ClassHandler * plugin = qobject_cast<ClassHandler *>(obj); if (plugin) { if (plugin){ registerHandler(plugin); } } } } } ClassHandlerManager::~ClassHandlerManager() { foreach (ClassHandlerManager::PluginDescriptor *descriptor, priv->handlers) { delete descriptor; } delete priv; } /* ************************************************************************** */ /* Accessors & mutators */ /* ************************************************************************** */ QString ClassHandlerManager::urlNamespace() const { return priv->urlNamespace; } /* ************************************************************************** */ /* Static Methods */ /* ************************************************************************** */ void ClassHandlerManager::addPluginLocation(const QString location) { if(!pluginLocations.contains(location)){ pluginLocations.append(location); } } /* ************************************************************************** */ /* Private Methods */ /* ************************************************************************** */ void ClassHandlerManager::dispatchVoidMethod(QMetaMethod method, ClassHandler * handler, const QGenericArgument * args) const { method.invoke(handler, Qt::DirectConnection, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9] ); } void ClassHandlerManager::dispatchJSONMethod(HttpServerResponse & response, QMetaMethod method, ClassHandler *handler, const QGenericArgument *args) const { QJsonObject result; bool wasInvoked = method.invoke(handler, Qt::DirectConnection, Q_RETURN_ARG(QJsonObject, result), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9] ); if(wasInvoked) { HttpResponseStatus status = HttpResponseStatus::OK; QJsonDocument jsonDocument; if(result.contains(ClassHandler::HttpResponseStatusKey)) { status = HttpResponseStatus(result[ClassHandler::HttpResponseStatusKey].toInt()); //The response will either be an JsonObject, or a JsonArray if(result[ClassHandler::JsonResponseKey].isArray()) { jsonDocument.setArray(result[ClassHandler::JsonResponseKey].toArray()); } else { jsonDocument = QJsonDocument(result[ClassHandler::JsonResponseKey].toObject()); } } response.writeHead(status); response.headers().replace("Content-Type", "application/json"); response.end(jsonDocument.toJson()); } } bool ClassHandlerManager::processRequest(HttpServerRequest & request, HttpServerResponse & response, const QString className, const QString methodName, const QHash<QString, QString> arguments) { bool handled = false; bool canHandle = true; int methodIndex = selectMethod(className, methodName, arguments); if(methodIndex > -1) { ClassHandlerManager::PluginDescriptor *handler = priv->handlers[className]; QMetaMethod method = handler->handler->metaObject()->method(methodIndex); // Create the arguments QGenericArgument argumentTable[10]; argumentTable[0] = Q_ARG(Tufao::HttpServerRequest, request); argumentTable[1] = Q_ARG(Tufao::HttpServerResponse, response); // We need this to keep objects in scope until the actual invoke() call. QVariant variants[10]; int argumentIndex = 2; while(argumentIndex < method.parameterCount()){ QString parameterName = method.parameterNames()[argumentIndex]; // qDebug() << "Processing " << parameterName; variants[argumentIndex] = QVariant::fromValue(arguments.value(parameterName)); int methodType = method.parameterType(argumentIndex); if(variants[argumentIndex].canConvert(methodType)) { variants[argumentIndex].convert(methodType); argumentTable[argumentIndex] = QGenericArgument(variants[argumentIndex].typeName(), variants[argumentIndex].data()); // qDebug() << "Converted " // << arguments.value(parameterName) // << " to type " // << QVariant::typeToName(methodType) // << " index " // << argumentIndex; } else { qWarning() << "Can not convert " << arguments.value(parameterName) << " to type " << QVariant::typeToName(methodType); } argumentIndex+=1; } if(canHandle) { if(method.returnType() == QMetaType::QJsonObject) { this->dispatchJSONMethod(response, method, handler->handler, argumentTable); } else { this->dispatchVoidMethod(method, handler->handler, argumentTable); } handled = true; } } else { qWarning() << "Cound not find a method named with a matching signature."; } return handled; } void ClassHandlerManager::registerHandler(ClassHandler * handler) { // Only process plugins that have not already been registered. if (!priv->handlers.contains(handler->objectName())){ qDebug() << "Registering " << handler->objectName() << " as a handler."; bool canDispathTo = false; const QMetaObject* metaObject = handler->metaObject(); for(int methodIndex = metaObject->methodOffset(); methodIndex < metaObject->methodCount(); ++methodIndex) { QMetaMethod method = metaObject->method(methodIndex); // We only want public slots whos first two arguements are request & response if(method.methodType() == QMetaMethod::Slot && method.access() == QMetaMethod::Public) { QList<QByteArray> parameterNames = method.parameterNames(); if(parameterNames[0] == QByteArray("request") && parameterNames[1] == QByteArray("response")) { canDispathTo = true; ClassHandlerManager::PluginDescriptor *pluginDescriptor = priv->handlers[handler->objectName()]; if(pluginDescriptor == NULL) { pluginDescriptor = new ClassHandlerManager::PluginDescriptor(); priv->handlers[handler->objectName()] = pluginDescriptor; } pluginDescriptor->className = handler->objectName(); pluginDescriptor->handler = handler; uint parameterHash = qHash(QString::fromLatin1(method.name())); foreach (QByteArray nameBytes, parameterNames) { parameterHash += qHash(QString::fromLatin1(nameBytes)); } pluginDescriptor->methods.insert(parameterHash, methodIndex); pluginDescriptor->methodNames.append(QString::fromLatin1(method.name())); QString signature = QString::fromLatin1(method.methodSignature()); qDebug() << signature << " is a dispatchable endpoint."; } } } if(canDispathTo) { handler->init(); } } } int ClassHandlerManager::selectMethod(const QString className, const QString methodName, const QHash<QString, QString> arguments) const { int methodIndex = -1; uint parameterHash = qHash(methodName); parameterHash += qHash(QString("request")); parameterHash += qHash(QString("response")); foreach (QString key, arguments.keys()) { parameterHash += qHash(key); } PluginDescriptor *pluginDescriptor = priv->handlers[className]; if (pluginDescriptor->methods.contains(parameterHash)) { methodIndex = pluginDescriptor->methods.value(parameterHash); } return methodIndex; } /* ************************************************************************** */ /* Override Tufao::AbstractHttpServerRequestHandler Methods */ /* ************************************************************************** */ bool ClassHandlerManager::handleRequest(Tufao::HttpServerRequest & request, Tufao::HttpServerResponse & response) { /* Apply urlNamespace and resume request dispatching or abort if request has a different urlNamespace */ const QUrl originalUrl = request.url(); const QString originalPath = originalUrl.path(); if (!priv->urlNamespace.isEmpty()) { if (!(originalPath.size() > priv->urlNamespace.size() && originalPath.startsWith(priv->urlNamespace) && originalPath[priv->urlNamespace.size()] == '/')) { return false; } } const QString namespacedPath = [&originalPath,this]() { return originalPath.mid(priv->urlNamespace.size()); }(); /* The user MUST NOT view the original url. This design ease the implementation of nested handlers. request.setUrl(namespacedUrl) MUST be called before pass the request to the user and the previous url (originalUrl) MUST be restored if the dispatch failed and we'll return the request to HttpServerRequestRouter. */ const QUrl namespacedUrl = [&originalUrl,&namespacedPath]() { QUrl ret = originalUrl; ret.setPath(namespacedPath); return ret; }(); QStringList pathComponents = namespacedPath.split("/", QString::SkipEmptyParts); // There must be at least two path components (class & method) const int minimumPathComponents = 2; if (pathComponents.length() < minimumPathComponents) { qWarning() << "Request was dispatched to handler, but too few path" " components found. The path components are" << pathComponents; return false; } if (pathComponents.length() > minimumPathComponents + 16) { // We also can not have too many arguments; 16 is max, as that is 8 // argumetns plus request & response qWarning() << "Request was dispatched to handler, but too many path" " components found. The path components are" << pathComponents; return false; } int pathIndex = 0; QString className = pathComponents[pathIndex++]; QString methodName = pathComponents[pathIndex++]; // We need to have an even number of path components left if ((pathComponents.length() - pathIndex) % 2 != 0) { qWarning() << "Can not dispath as an odd number of parameter components" " were supplied."; return false; } // See if we have a class handler with a matching method if (!(priv->handlers.contains(className) && priv->handlers[className]->methodNames.contains(methodName))) { if (priv->handlers.contains(className)) { qWarning() << "The class" << className << "has no method named" << methodName; } } // Convert the remaining path components into an argument hash QHash<QString, QString> arguments; while(pathIndex < pathComponents.length()){ arguments[pathComponents[pathIndex]] = pathComponents[pathIndex + 1]; pathIndex += 2; } request.setUrl(namespacedUrl); if (!processRequest(request, response, className, methodName, arguments)) { request.setUrl(originalUrl); return false; } return true; } } // namespace Tufao <commit_msg>Protecting access to pluginLocations global variable through mutex.<commit_after>/* Copyright (c) 2013 Timothy Reaves [email protected] 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, see <http://www.gnu.org/licenses/>. */ #include "priv/classhandlermanager.h" #include "classhandler.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QJsonArray> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QJsonValue> #include <QtCore/QMetaObject> #include <QtCore/QMetaMethod> #include <QtCore/QMetaType> #include <QtCore/QtPlugin> #include <QtCore/QPluginLoader> #include <QtCore/QSet> #include <QtCore/QString> #include <QtCore/QUrl> #include <QtCore/QVariant> #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include "httpserverrequest.h" #include "headers.h" namespace Tufao { // Initialize static members. /* \warning the variable is never fully initialized. * `QCoreApplication::applicationDirPath()` (aka the install location), which * can only be retrieved at runtime, after the QCoreApplication was constructed, * is never present in this list. */ QStringList ClassHandlerManager::pluginLocations = []() { QStringList ret; // Add standard locations to pluginLocations // First, the typical app config dir's #ifdef Q_OS_WIN // Code can be added here, but, for the time being, I'm leaving it empty. #elif defined(Q_OS_MAC) ret.append(QDir::homePath() + "/Library/Application Support/Tufao"); ret.append("/Library/Application Support/Tufao"); #else ret.append(QDir::homePath() + "/.tufao"); #endif // The standard library locations for (const QString &libraryPath: QCoreApplication::libraryPaths()) { QDir testDir(libraryPath + QDir::separator() + "Tufao"); if(testDir.exists()){ ret.append(testDir.absolutePath()); } } return ret; }(); QMutex pluginLocationsMutex; /* ************************************************************************** */ /* Object lifecycle */ /* ************************************************************************** */ ClassHandlerManager::ClassHandlerManager(const QString &pluginID, const QString &urlNamespace, QObject * parent) : QObject(parent), priv{new Priv{pluginID, urlNamespace}} { // Now load the plugin of interest // First list all static plugins. foreach (QObject * pluginInterface, QPluginLoader::staticInstances()){ ClassHandler * plugin = qobject_cast<ClassHandler *>(pluginInterface); if (plugin){ registerHandler(plugin); } } /// // Then list dynamic libraries from the plugins/ directory QStringList contents; // retrieve a list of all dynamic libraries from the search paths { QMutexLocker guard(&pluginLocationsMutex); auto retrieveDynlib = [&contents](const QString &path) { QFileInfo thisPath(QDir(path).filePath("plugins")); if (thisPath.isDir()) { QDir thisDir(thisPath.absoluteFilePath()); qDebug() << "Search " << thisPath.absolutePath() << " for plugins."; for (const QString &entry: thisDir.entryList()) { if (QLibrary::isLibrary(entry)) contents.append(thisDir.filePath(entry)); } } }; for (const QString &path: pluginLocations) retrieveDynlib(path); QFileInfo installDir(QCoreApplication::applicationDirPath()); if (installDir.isDir()) retrieveDynlib(installDir.absolutePath()); } // Check each dynamic library to see if it is a plugin foreach (QString pluginPath, contents) { QPluginLoader loader(pluginPath); // If we were constructed with a pluginID, we need to chech each plugin. if(pluginID.isEmpty() || pluginID == loader.metaData().value("IID").toString()) { if (!loader.load()) { qWarning() << "Couldn't load the dynamic library: " << QDir::toNativeSeparators(pluginPath) << ": " << loader.errorString(); continue; } QObject* obj = loader.instance(); if (!obj) { qWarning() << "Couldn't open the dynamic library: " << QDir::toNativeSeparators(pluginPath) << ": " << loader.errorString(); continue; } ClassHandler * plugin = qobject_cast<ClassHandler *>(obj); if (plugin) { if (plugin){ registerHandler(plugin); } } } } } ClassHandlerManager::~ClassHandlerManager() { foreach (ClassHandlerManager::PluginDescriptor *descriptor, priv->handlers) { delete descriptor; } delete priv; } /* ************************************************************************** */ /* Accessors & mutators */ /* ************************************************************************** */ QString ClassHandlerManager::urlNamespace() const { return priv->urlNamespace; } /* ************************************************************************** */ /* Static Methods */ /* ************************************************************************** */ void ClassHandlerManager::addPluginLocation(const QString location) { QMutexLocker guard(&pluginLocationsMutex); if(!pluginLocations.contains(location)){ pluginLocations.append(location); } } /* ************************************************************************** */ /* Private Methods */ /* ************************************************************************** */ void ClassHandlerManager::dispatchVoidMethod(QMetaMethod method, ClassHandler * handler, const QGenericArgument * args) const { method.invoke(handler, Qt::DirectConnection, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9] ); } void ClassHandlerManager::dispatchJSONMethod(HttpServerResponse & response, QMetaMethod method, ClassHandler *handler, const QGenericArgument *args) const { QJsonObject result; bool wasInvoked = method.invoke(handler, Qt::DirectConnection, Q_RETURN_ARG(QJsonObject, result), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9] ); if(wasInvoked) { HttpResponseStatus status = HttpResponseStatus::OK; QJsonDocument jsonDocument; if(result.contains(ClassHandler::HttpResponseStatusKey)) { status = HttpResponseStatus(result[ClassHandler::HttpResponseStatusKey].toInt()); //The response will either be an JsonObject, or a JsonArray if(result[ClassHandler::JsonResponseKey].isArray()) { jsonDocument.setArray(result[ClassHandler::JsonResponseKey].toArray()); } else { jsonDocument = QJsonDocument(result[ClassHandler::JsonResponseKey].toObject()); } } response.writeHead(status); response.headers().replace("Content-Type", "application/json"); response.end(jsonDocument.toJson()); } } bool ClassHandlerManager::processRequest(HttpServerRequest & request, HttpServerResponse & response, const QString className, const QString methodName, const QHash<QString, QString> arguments) { bool handled = false; bool canHandle = true; int methodIndex = selectMethod(className, methodName, arguments); if(methodIndex > -1) { ClassHandlerManager::PluginDescriptor *handler = priv->handlers[className]; QMetaMethod method = handler->handler->metaObject()->method(methodIndex); // Create the arguments QGenericArgument argumentTable[10]; argumentTable[0] = Q_ARG(Tufao::HttpServerRequest, request); argumentTable[1] = Q_ARG(Tufao::HttpServerResponse, response); // We need this to keep objects in scope until the actual invoke() call. QVariant variants[10]; int argumentIndex = 2; while(argumentIndex < method.parameterCount()){ QString parameterName = method.parameterNames()[argumentIndex]; // qDebug() << "Processing " << parameterName; variants[argumentIndex] = QVariant::fromValue(arguments.value(parameterName)); int methodType = method.parameterType(argumentIndex); if(variants[argumentIndex].canConvert(methodType)) { variants[argumentIndex].convert(methodType); argumentTable[argumentIndex] = QGenericArgument(variants[argumentIndex].typeName(), variants[argumentIndex].data()); // qDebug() << "Converted " // << arguments.value(parameterName) // << " to type " // << QVariant::typeToName(methodType) // << " index " // << argumentIndex; } else { qWarning() << "Can not convert " << arguments.value(parameterName) << " to type " << QVariant::typeToName(methodType); } argumentIndex+=1; } if(canHandle) { if(method.returnType() == QMetaType::QJsonObject) { this->dispatchJSONMethod(response, method, handler->handler, argumentTable); } else { this->dispatchVoidMethod(method, handler->handler, argumentTable); } handled = true; } } else { qWarning() << "Cound not find a method named with a matching signature."; } return handled; } void ClassHandlerManager::registerHandler(ClassHandler * handler) { // Only process plugins that have not already been registered. if (!priv->handlers.contains(handler->objectName())){ qDebug() << "Registering " << handler->objectName() << " as a handler."; bool canDispathTo = false; const QMetaObject* metaObject = handler->metaObject(); for(int methodIndex = metaObject->methodOffset(); methodIndex < metaObject->methodCount(); ++methodIndex) { QMetaMethod method = metaObject->method(methodIndex); // We only want public slots whos first two arguements are request & response if(method.methodType() == QMetaMethod::Slot && method.access() == QMetaMethod::Public) { QList<QByteArray> parameterNames = method.parameterNames(); if(parameterNames[0] == QByteArray("request") && parameterNames[1] == QByteArray("response")) { canDispathTo = true; ClassHandlerManager::PluginDescriptor *pluginDescriptor = priv->handlers[handler->objectName()]; if(pluginDescriptor == NULL) { pluginDescriptor = new ClassHandlerManager::PluginDescriptor(); priv->handlers[handler->objectName()] = pluginDescriptor; } pluginDescriptor->className = handler->objectName(); pluginDescriptor->handler = handler; uint parameterHash = qHash(QString::fromLatin1(method.name())); foreach (QByteArray nameBytes, parameterNames) { parameterHash += qHash(QString::fromLatin1(nameBytes)); } pluginDescriptor->methods.insert(parameterHash, methodIndex); pluginDescriptor->methodNames.append(QString::fromLatin1(method.name())); QString signature = QString::fromLatin1(method.methodSignature()); qDebug() << signature << " is a dispatchable endpoint."; } } } if(canDispathTo) { handler->init(); } } } int ClassHandlerManager::selectMethod(const QString className, const QString methodName, const QHash<QString, QString> arguments) const { int methodIndex = -1; uint parameterHash = qHash(methodName); parameterHash += qHash(QString("request")); parameterHash += qHash(QString("response")); foreach (QString key, arguments.keys()) { parameterHash += qHash(key); } PluginDescriptor *pluginDescriptor = priv->handlers[className]; if (pluginDescriptor->methods.contains(parameterHash)) { methodIndex = pluginDescriptor->methods.value(parameterHash); } return methodIndex; } /* ************************************************************************** */ /* Override Tufao::AbstractHttpServerRequestHandler Methods */ /* ************************************************************************** */ bool ClassHandlerManager::handleRequest(Tufao::HttpServerRequest & request, Tufao::HttpServerResponse & response) { /* Apply urlNamespace and resume request dispatching or abort if request has a different urlNamespace */ const QUrl originalUrl = request.url(); const QString originalPath = originalUrl.path(); if (!priv->urlNamespace.isEmpty()) { if (!(originalPath.size() > priv->urlNamespace.size() && originalPath.startsWith(priv->urlNamespace) && originalPath[priv->urlNamespace.size()] == '/')) { return false; } } const QString namespacedPath = [&originalPath,this]() { return originalPath.mid(priv->urlNamespace.size()); }(); /* The user MUST NOT view the original url. This design ease the implementation of nested handlers. request.setUrl(namespacedUrl) MUST be called before pass the request to the user and the previous url (originalUrl) MUST be restored if the dispatch failed and we'll return the request to HttpServerRequestRouter. */ const QUrl namespacedUrl = [&originalUrl,&namespacedPath]() { QUrl ret = originalUrl; ret.setPath(namespacedPath); return ret; }(); QStringList pathComponents = namespacedPath.split("/", QString::SkipEmptyParts); // There must be at least two path components (class & method) const int minimumPathComponents = 2; if (pathComponents.length() < minimumPathComponents) { qWarning() << "Request was dispatched to handler, but too few path" " components found. The path components are" << pathComponents; return false; } if (pathComponents.length() > minimumPathComponents + 16) { // We also can not have too many arguments; 16 is max, as that is 8 // argumetns plus request & response qWarning() << "Request was dispatched to handler, but too many path" " components found. The path components are" << pathComponents; return false; } int pathIndex = 0; QString className = pathComponents[pathIndex++]; QString methodName = pathComponents[pathIndex++]; // We need to have an even number of path components left if ((pathComponents.length() - pathIndex) % 2 != 0) { qWarning() << "Can not dispath as an odd number of parameter components" " were supplied."; return false; } // See if we have a class handler with a matching method if (!(priv->handlers.contains(className) && priv->handlers[className]->methodNames.contains(methodName))) { if (priv->handlers.contains(className)) { qWarning() << "The class" << className << "has no method named" << methodName; } } // Convert the remaining path components into an argument hash QHash<QString, QString> arguments; while(pathIndex < pathComponents.length()){ arguments[pathComponents[pathIndex]] = pathComponents[pathIndex + 1]; pathIndex += 2; } request.setUrl(namespacedUrl); if (!processRequest(request, response, className, methodName, arguments)) { request.setUrl(originalUrl); return false; } return true; } } // namespace Tufao <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string> #include <cstring> #include <iostream> #include <sstream> #include <vector> //Include available regex headers #ifdef HAVE_PCRE_H #include <pcre.h> #endif #ifdef HAVE_REGEX_H #include <regex.h> #endif #include "regex.hxx" //Determine support level. //First check for specific requests from the configuration. #if defined(FORCE_REGEX_PCRE16) # if defined(HAVE_PCRE_H) && defined(PCRE_SUPPORTS_16_BIT) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE16 # elif !defined(HAVE_PCRE_H) # error Configuration forces REGEX_PCRE16, but you do not have PCRE # else # error Configuration forces REGEX_PCRE16, but 16-bit not supported # endif #elif defined(FORCE_REGEX_PCRE8) # if defined(HAVE_PCRE_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE8 # else # error Configuration forces REGEX_PCRE8, but you do not have PCRE # endif #elif defined(FORCE_REGEX_POSIX) # if defined(HAVE_REGEX_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_POSIX # else # error Configuration forces REGEX_POSIX, but your system does not have it # endif #elif defined(FORCE_REGEX_NONE) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_NONE //Not forced, determine automatically #elif defined(HAVE_PCRE_H) && defined(PCRE_SUPPORTS_16_BIT) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE16 #elif defined(HAVE_PCRE_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE8 #elif defined(HAVE_REGEX_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_POSIX #else # define TGLNG_REGEX_LEVEL TGLNG_REGEX_NONE #endif using namespace std; namespace tglng { const unsigned regexLevel = TGLNG_REGEX_LEVEL; #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_NONE const wstring regexLevelName(L"NONE"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX const wstring regexLevelName(L"POSIX"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 const wstring regexLevelName(L"PCRE8"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 const wstring regexLevelName(L"PCRE16"); #endif //Functions to convert natvie wstrings to the type needed by the backend. #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 typedef vector<PCRE_UCHAR16> rstring; static void convertString(rstring& dst, const wstring& src) { dst.resize(src.size()+1); for (unsigned i = 0; i < src.size(); ++i) if (src[i] <= 0xFFFF) dst[i] = src[i]; else dst[i] = 0x001A; dst[src.size()] = 0; } #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 || \ TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX typedef vector<char> rstring; static void convertString(rstring& dst, const wstring& src) { dst.resize(src.size()+1); for (unsigned i = 0; i < src.size(); ++i) if (src[i] <= 0xFF) dst[i] = (src[i] & 0xFF); else dst[i] = 0x1A; dst[src.size()] = 0; } #endif #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_NONE //Null implementation; always fails at everything Regex::Regex(const wstring&, const wstring&) : data(*(RegexData*)NULL) {} Regex::~Regex() {} Regex::operator bool() const { return false; } void Regex::showWhy() const { wcerr << L"regular expressions not supported in this build." << endl; } void Regex::input(const wstring&) {} bool Regex::match() { return false; } unsigned Regex::groupCount() const { return 0; } void Regex::group(wstring&, unsigned) const {} void Regex::tail(wstring&) const {} #endif /* NONE */ #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX //POSIX.1-2001 implementation struct RegexData { regex_t rx; int status; //0=OK, others=error rstring input; wstring rawInput; unsigned inputOffset, headBegin, headEnd; string why; regmatch_t matches[10]; }; Regex::Regex(const wstring& pattern, const wstring& options) : data(*new RegexData) { rstring rpattern; convertString(rpattern, pattern); int flags = REG_EXTENDED; //Parse options for (unsigned i = 0; i < options.size(); ++i) switch (options[i]) { case L'i': flags |= REG_ICASE; break; case L'l': flags |= REG_NEWLINE; break; } data.status = regcomp(&data.rx, &rpattern[0], flags); if (data.status) { //Save error message data.why.resize(regerror(data.status, &data.rx, NULL, 0)); regerror(data.status, &data.rx, &data.why[0], data.why.size()); } } Regex::~Regex() { if (data.status == 0) regfree(&data.rx); delete &data; } Regex::operator bool() const { return !data.status; } void Regex::showWhy() const { wcerr << "POSIX extended regular expression: " << &data.why[0] << endl; } void Regex::input(const std::wstring& str) { convertString(data.input, str); data.inputOffset = 0; data.rawInput = str; } bool Regex::match() { data.status = regexec(&data.rx, &data.input[data.inputOffset], sizeof(data.matches)/sizeof(data.matches[0]), data.matches, 0); if (data.status == REG_NOMATCH) { //Transform to a more uniform result //(Nothing went wrong, no error should be returned, in theory) data.status = 0; memset(data.matches, -1, sizeof(data.matches)); } if (data.status) { //Failed for some reason data.why.resize(regerror(data.status, &data.rx, NULL, 0)); regerror(data.status, &data.rx, &data.why[0], data.why.size()); //Free the pattern now, since the destructor won't think it exists regfree(&data.rx); return false; } //Matched if the zeroth group is not -1 if (-1 != data.matches[0].rm_eo) { //Update offsets data.headBegin = data.inputOffset; data.headEnd = data.matches[0].rm_so; data.inputOffset = data.matches[0].rm_eo; } return -1 != data.matches[0].rm_eo; } unsigned Regex::groupCount() const { //Elements in the middle may be unmatched if that particular group was //excluded, so search for the last group. unsigned last; for (unsigned i = 0; i < sizeof(data.matches)/sizeof(data.matches[0]); ++i) if (-1 != data.matches[i].rm_so) last = i; return last+1; } void Regex::group(wstring& dst, unsigned ix) const { //Indices may be negative if this group didn't match if (data.matches[ix].rm_so == -1) dst.clear(); else dst.assign(data.rawInput, data.matches[ix].rm_so, data.matches[ix].rm_eo - data.matches[ix].rm_so); } void Regex::tail(wstring& dst) const { dst.assign(data.rawInput, data.inputOffset, data.rawInput.size() - data.inputOffset); } void Regex::head(wstring& dst) const { dst.assign(data.rawInput, data.headBegin, data.headEnd - data.headBegin); } #endif /* POSIX */ #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 || \ TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 # if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 # define pcreN pcre # define pcreN_compile pcre_compile # define pcreN_exec pcre_exec # define pcreN_free pcre_free # define pcreN_maketables pcre_maketables # else # define pcreN pcre16 # define pcreN_compile pcre16_compile # define pcreN_exec pcre16_exec # define pcreN_free pcre16_free # define pcreN_maketables pcre16_maketables # endif /* By default, PCRE only classifies characters based on ASCII (some builds * may instead automatically rebuild the tables according to the "C" locale * (why not the system locale?), but we can't count on that. * * Whenever the current C locale (by setlocale(LC_ALL,NULL)) differs from the * lastPcreTableLocale, generate a new table. */ static string lastPcreTableLocale("C"); static const unsigned char* localPcreTable(NULL); struct RegexData { pcreN* rx; unsigned errorOffset; /* We want ten matches. Each match takes two entries. Additionally, PCRE * requires that we allocate an extra entry at the end for each match. */ #define MAX_MATCHES 10 signed matches[MAX_MATCHES*3]; rstring input; wstring rawInput; unsigned inputOffset, headBegin, headEnd; string errorMessage; }; Regex::Regex(const wstring& pattern, const wstring& options) : data(*new RegexData) { rstring rpattern; const char* errorMessage = NULL; convertString(rpattern, pattern); //Parse the options int flags = PCRE_DOTALL | PCRE_DOLLAR_ENDONLY; for (unsigned i = 0; i < options.size(); ++i) switch (options[i]) { case L'i': flags |= PCRE_CASELESS; break; case L'l': flags &= ~(PCRE_DOTALL | PCRE_DOLLAR_ENDONLY); //Would be nice if there were a constant for this //(Then again, // flags &= ~(`[PCRE_NEWLINE_`E{CR LF CRLF ANYCRLF ANY}| |`]); flags &= ~(PCRE_NEWLINE_CR | PCRE_NEWLINE_LF | PCRE_NEWLINE_CRLF | PCRE_NEWLINE_ANYCRLF | PCRE_NEWLINE_ANY); flags |= PCRE_MULTILINE | PCRE_NEWLINE_ANYCRLF; break; } //Generate a table if necessary if (lastPcreTableLocale != setlocale(LC_ALL, NULL)) { lastPcreTableLocale = setlocale(LC_ALL, NULL); if (localPcreTable) pcreN_free(const_cast<void*>(static_cast<const void*>(localPcreTable))); localPcreTable = pcreN_maketables(); } data.rx = pcreN_compile(&rpattern[0], flags, &errorMessage, (int*)&data.errorOffset, localPcreTable); if (!data.rx) data.errorMessage = errorMessage; } Regex::~Regex() { if (data.rx) pcreN_free(data.rx); delete &data; } Regex::operator bool() const { return !!data.rx; } void Regex::showWhy() const { wcerr << L"Perl-Compatible Regular Expression: " << data.errorMessage.c_str() << endl; } void Regex::input(const wstring& str) { convertString(data.input, str); data.rawInput = str; data.inputOffset = 0; } bool Regex::match() { //Set all elements to -1 memset(data.matches, -1, sizeof(data.matches)); int status = pcreN_exec(data.rx, NULL, &data.input[0], //Subtract one for term NUL data.input.size() - 1, data.inputOffset, PCRE_NOTEMPTY, data.matches, sizeof(data.matches)/sizeof(data.matches[0])); if (status < 0) { //Error (there doesn't seem to be any way to get an error message) ostringstream msg; msg << "Perl-Compatible Regular Expression: error code " << status; data.errorMessage = msg.str(); //Free the rx so that operator bool() returns false pcreN_free(data.rx); data.rx = NULL; return false; } //PCRE can return 0 even for successful matches (eg, there were more groups //than provided), so check for success manually. //Any group which was not matched will have entries of -1. If matching is //successful, group 0 is defined. if (data.matches[0] != -1) { //Advance input data.headBegin = data.inputOffset; data.headEnd = data.matches[0]; data.inputOffset = data.matches[1]; return true; } else { return false; } } unsigned Regex::groupCount() const { //PCRE groups are indexed by occurrance within the pattern, so some groups //might not match; find the last matched group. unsigned last = 0; for (unsigned i = 0; i < MAX_MATCHES; ++i) if (data.matches[i*2] != -1) last = i; return last+1; } void Regex::group(wstring& dst, unsigned ix) const { //Some middle groups may be unmatched, so return an empty string if -1 if (data.matches[ix*2] == -1) dst.clear(); else dst.assign(data.rawInput, data.matches[ix*2], data.matches[ix*2+1] - data.matches[ix*2]); } void Regex::head(wstring& dst) const { dst.assign(data.rawInput, data.headBegin, data.headEnd - data.headBegin); } void Regex::tail(wstring& dst) const { dst.assign(data.rawInput, data.inputOffset, data.rawInput.size() - data.inputOffset); } #endif /* PCRE* */ } <commit_msg>Fix missing Regex::head() in no-op regex engine wrapper.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string> #include <cstring> #include <iostream> #include <sstream> #include <vector> //Include available regex headers #ifdef HAVE_PCRE_H #include <pcre.h> #endif #ifdef HAVE_REGEX_H #include <regex.h> #endif #include "regex.hxx" //Determine support level. //First check for specific requests from the configuration. #if defined(FORCE_REGEX_PCRE16) # if defined(HAVE_PCRE_H) && defined(PCRE_SUPPORTS_16_BIT) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE16 # elif !defined(HAVE_PCRE_H) # error Configuration forces REGEX_PCRE16, but you do not have PCRE # else # error Configuration forces REGEX_PCRE16, but 16-bit not supported # endif #elif defined(FORCE_REGEX_PCRE8) # if defined(HAVE_PCRE_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE8 # else # error Configuration forces REGEX_PCRE8, but you do not have PCRE # endif #elif defined(FORCE_REGEX_POSIX) # if defined(HAVE_REGEX_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_POSIX # else # error Configuration forces REGEX_POSIX, but your system does not have it # endif #elif defined(FORCE_REGEX_NONE) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_NONE //Not forced, determine automatically #elif defined(HAVE_PCRE_H) && defined(PCRE_SUPPORTS_16_BIT) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE16 #elif defined(HAVE_PCRE_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_PCRE8 #elif defined(HAVE_REGEX_H) # define TGLNG_REGEX_LEVEL TGLNG_REGEX_POSIX #else # define TGLNG_REGEX_LEVEL TGLNG_REGEX_NONE #endif using namespace std; namespace tglng { const unsigned regexLevel = TGLNG_REGEX_LEVEL; #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_NONE const wstring regexLevelName(L"NONE"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX const wstring regexLevelName(L"POSIX"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 const wstring regexLevelName(L"PCRE8"); #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 const wstring regexLevelName(L"PCRE16"); #endif //Functions to convert natvie wstrings to the type needed by the backend. #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 typedef vector<PCRE_UCHAR16> rstring; static void convertString(rstring& dst, const wstring& src) { dst.resize(src.size()+1); for (unsigned i = 0; i < src.size(); ++i) if (src[i] <= 0xFFFF) dst[i] = src[i]; else dst[i] = 0x001A; dst[src.size()] = 0; } #elif TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 || \ TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX typedef vector<char> rstring; static void convertString(rstring& dst, const wstring& src) { dst.resize(src.size()+1); for (unsigned i = 0; i < src.size(); ++i) if (src[i] <= 0xFF) dst[i] = (src[i] & 0xFF); else dst[i] = 0x1A; dst[src.size()] = 0; } #endif #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_NONE //Null implementation; always fails at everything Regex::Regex(const wstring&, const wstring&) : data(*(RegexData*)NULL) {} Regex::~Regex() {} Regex::operator bool() const { return false; } void Regex::showWhy() const { wcerr << L"regular expressions not supported in this build." << endl; } void Regex::input(const wstring&) {} bool Regex::match() { return false; } unsigned Regex::groupCount() const { return 0; } void Regex::group(wstring&, unsigned) const {} void Regex::tail(wstring&) const {} void Regex::head(wstring&) const {} #endif /* NONE */ #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_POSIX //POSIX.1-2001 implementation struct RegexData { regex_t rx; int status; //0=OK, others=error rstring input; wstring rawInput; unsigned inputOffset, headBegin, headEnd; string why; regmatch_t matches[10]; }; Regex::Regex(const wstring& pattern, const wstring& options) : data(*new RegexData) { rstring rpattern; convertString(rpattern, pattern); int flags = REG_EXTENDED; //Parse options for (unsigned i = 0; i < options.size(); ++i) switch (options[i]) { case L'i': flags |= REG_ICASE; break; case L'l': flags |= REG_NEWLINE; break; } data.status = regcomp(&data.rx, &rpattern[0], flags); if (data.status) { //Save error message data.why.resize(regerror(data.status, &data.rx, NULL, 0)); regerror(data.status, &data.rx, &data.why[0], data.why.size()); } } Regex::~Regex() { if (data.status == 0) regfree(&data.rx); delete &data; } Regex::operator bool() const { return !data.status; } void Regex::showWhy() const { wcerr << "POSIX extended regular expression: " << &data.why[0] << endl; } void Regex::input(const std::wstring& str) { convertString(data.input, str); data.inputOffset = 0; data.rawInput = str; } bool Regex::match() { data.status = regexec(&data.rx, &data.input[data.inputOffset], sizeof(data.matches)/sizeof(data.matches[0]), data.matches, 0); if (data.status == REG_NOMATCH) { //Transform to a more uniform result //(Nothing went wrong, no error should be returned, in theory) data.status = 0; memset(data.matches, -1, sizeof(data.matches)); } if (data.status) { //Failed for some reason data.why.resize(regerror(data.status, &data.rx, NULL, 0)); regerror(data.status, &data.rx, &data.why[0], data.why.size()); //Free the pattern now, since the destructor won't think it exists regfree(&data.rx); return false; } //Matched if the zeroth group is not -1 if (-1 != data.matches[0].rm_eo) { //Update offsets data.headBegin = data.inputOffset; data.headEnd = data.matches[0].rm_so; data.inputOffset = data.matches[0].rm_eo; } return -1 != data.matches[0].rm_eo; } unsigned Regex::groupCount() const { //Elements in the middle may be unmatched if that particular group was //excluded, so search for the last group. unsigned last; for (unsigned i = 0; i < sizeof(data.matches)/sizeof(data.matches[0]); ++i) if (-1 != data.matches[i].rm_so) last = i; return last+1; } void Regex::group(wstring& dst, unsigned ix) const { //Indices may be negative if this group didn't match if (data.matches[ix].rm_so == -1) dst.clear(); else dst.assign(data.rawInput, data.matches[ix].rm_so, data.matches[ix].rm_eo - data.matches[ix].rm_so); } void Regex::tail(wstring& dst) const { dst.assign(data.rawInput, data.inputOffset, data.rawInput.size() - data.inputOffset); } void Regex::head(wstring& dst) const { dst.assign(data.rawInput, data.headBegin, data.headEnd - data.headBegin); } #endif /* POSIX */ #if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 || \ TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE16 # if TGLNG_REGEX_LEVEL == TGLNG_REGEX_PCRE8 # define pcreN pcre # define pcreN_compile pcre_compile # define pcreN_exec pcre_exec # define pcreN_free pcre_free # define pcreN_maketables pcre_maketables # else # define pcreN pcre16 # define pcreN_compile pcre16_compile # define pcreN_exec pcre16_exec # define pcreN_free pcre16_free # define pcreN_maketables pcre16_maketables # endif /* By default, PCRE only classifies characters based on ASCII (some builds * may instead automatically rebuild the tables according to the "C" locale * (why not the system locale?), but we can't count on that. * * Whenever the current C locale (by setlocale(LC_ALL,NULL)) differs from the * lastPcreTableLocale, generate a new table. */ static string lastPcreTableLocale("C"); static const unsigned char* localPcreTable(NULL); struct RegexData { pcreN* rx; unsigned errorOffset; /* We want ten matches. Each match takes two entries. Additionally, PCRE * requires that we allocate an extra entry at the end for each match. */ #define MAX_MATCHES 10 signed matches[MAX_MATCHES*3]; rstring input; wstring rawInput; unsigned inputOffset, headBegin, headEnd; string errorMessage; }; Regex::Regex(const wstring& pattern, const wstring& options) : data(*new RegexData) { rstring rpattern; const char* errorMessage = NULL; convertString(rpattern, pattern); //Parse the options int flags = PCRE_DOTALL | PCRE_DOLLAR_ENDONLY; for (unsigned i = 0; i < options.size(); ++i) switch (options[i]) { case L'i': flags |= PCRE_CASELESS; break; case L'l': flags &= ~(PCRE_DOTALL | PCRE_DOLLAR_ENDONLY); //Would be nice if there were a constant for this //(Then again, // flags &= ~(`[PCRE_NEWLINE_`E{CR LF CRLF ANYCRLF ANY}| |`]); flags &= ~(PCRE_NEWLINE_CR | PCRE_NEWLINE_LF | PCRE_NEWLINE_CRLF | PCRE_NEWLINE_ANYCRLF | PCRE_NEWLINE_ANY); flags |= PCRE_MULTILINE | PCRE_NEWLINE_ANYCRLF; break; } //Generate a table if necessary if (lastPcreTableLocale != setlocale(LC_ALL, NULL)) { lastPcreTableLocale = setlocale(LC_ALL, NULL); if (localPcreTable) pcreN_free(const_cast<void*>(static_cast<const void*>(localPcreTable))); localPcreTable = pcreN_maketables(); } data.rx = pcreN_compile(&rpattern[0], flags, &errorMessage, (int*)&data.errorOffset, localPcreTable); if (!data.rx) data.errorMessage = errorMessage; } Regex::~Regex() { if (data.rx) pcreN_free(data.rx); delete &data; } Regex::operator bool() const { return !!data.rx; } void Regex::showWhy() const { wcerr << L"Perl-Compatible Regular Expression: " << data.errorMessage.c_str() << endl; } void Regex::input(const wstring& str) { convertString(data.input, str); data.rawInput = str; data.inputOffset = 0; } bool Regex::match() { //Set all elements to -1 memset(data.matches, -1, sizeof(data.matches)); int status = pcreN_exec(data.rx, NULL, &data.input[0], //Subtract one for term NUL data.input.size() - 1, data.inputOffset, PCRE_NOTEMPTY, data.matches, sizeof(data.matches)/sizeof(data.matches[0])); if (status < 0) { //Error (there doesn't seem to be any way to get an error message) ostringstream msg; msg << "Perl-Compatible Regular Expression: error code " << status; data.errorMessage = msg.str(); //Free the rx so that operator bool() returns false pcreN_free(data.rx); data.rx = NULL; return false; } //PCRE can return 0 even for successful matches (eg, there were more groups //than provided), so check for success manually. //Any group which was not matched will have entries of -1. If matching is //successful, group 0 is defined. if (data.matches[0] != -1) { //Advance input data.headBegin = data.inputOffset; data.headEnd = data.matches[0]; data.inputOffset = data.matches[1]; return true; } else { return false; } } unsigned Regex::groupCount() const { //PCRE groups are indexed by occurrance within the pattern, so some groups //might not match; find the last matched group. unsigned last = 0; for (unsigned i = 0; i < MAX_MATCHES; ++i) if (data.matches[i*2] != -1) last = i; return last+1; } void Regex::group(wstring& dst, unsigned ix) const { //Some middle groups may be unmatched, so return an empty string if -1 if (data.matches[ix*2] == -1) dst.clear(); else dst.assign(data.rawInput, data.matches[ix*2], data.matches[ix*2+1] - data.matches[ix*2]); } void Regex::head(wstring& dst) const { dst.assign(data.rawInput, data.headBegin, data.headEnd - data.headBegin); } void Regex::tail(wstring& dst) const { dst.assign(data.rawInput, data.inputOffset, data.rawInput.size() - data.inputOffset); } #endif /* PCRE* */ } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "SaveDataReaction.h" #include "ActiveObjects.h" #include "DataSource.h" #include "ModuleManager.h" #include "pqActiveObjects.h" #include "pqCoreUtilities.h" #include "pqSaveDataReaction.h" #include "pqPipelineSource.h" #include "pqProxyWidgetDialog.h" #include "pqFileDialog.h" #include "pqWriterDialog.h" #include "vtkSMCoreUtilities.h" #include "vtkSMParaViewPipelineController.h" #include "vtkSMPropertyHelper.h" #include "vtkSMProxyManager.h" #include "vtkSMSessionProxyManager.h" #include "vtkSMSourceProxy.h" #include "vtkSMWriterFactory.h" #include <QDebug> namespace tomviz { //----------------------------------------------------------------------------- SaveDataReaction::SaveDataReaction(QAction* parentObject) : Superclass(parentObject) { } //----------------------------------------------------------------------------- SaveDataReaction::~SaveDataReaction() { } //----------------------------------------------------------------------------- void SaveDataReaction::onTriggered() { pqServer* server = pqActiveObjects::instance().activeServer(); DataSource *source = ActiveObjects::instance().activeDataSource(); vtkSMWriterFactory* writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); QString filters = writerFactory->GetSupportedFileTypes(source->producer()); if (filters.isEmpty()) { qCritical("Cannot determine writer to use."); return; } pqFileDialog fileDialog(server, pqCoreUtilities::mainWidget(), tr("Save File:"), QString(), filters); // FIXME: fileDialog.setRecentlyUsedExtension(this->DataExtension); fileDialog.setObjectName("FileSaveDialog"); fileDialog.setFileMode(pqFileDialog::AnyFile); if (fileDialog.exec() == QDialog::Accepted) { this->saveData(fileDialog.getSelectedFiles()[0]); } } bool SaveDataReaction::saveData(const QString &filename) { pqServer* server = pqActiveObjects::instance().activeServer(); DataSource *source = ActiveObjects::instance().activeDataSource(); if (!server || !source) { qCritical("No active source located."); return false; } vtkSMWriterFactory* writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); vtkSmartPointer<vtkSMProxy> proxy; proxy.TakeReference(writerFactory->CreateWriter(filename.toLatin1().data(), source->producer())); vtkSMSourceProxy* writer = vtkSMSourceProxy::SafeDownCast(proxy); if (!writer) { qCritical() << "Failed to create writer for: " << filename; return false; } pqWriterDialog dialog(writer); // Check to see if this writer has any properties that can be configured by // the user. If it does, display the dialog. if (dialog.hasConfigurableProperties()) { dialog.exec(); if(dialog.result() == QDialog::Rejected) { // The user pressed Cancel so don't write return false; } } writer->UpdateVTKObjects(); writer->UpdatePipeline(); return true; } } // end of namespace tomviz <commit_msg>Default to saving data as tiff files -- fixes #155<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "SaveDataReaction.h" #include "ActiveObjects.h" #include "DataSource.h" #include "ModuleManager.h" #include "pqActiveObjects.h" #include "pqCoreUtilities.h" #include "pqSaveDataReaction.h" #include "pqPipelineSource.h" #include "pqProxyWidgetDialog.h" #include "pqFileDialog.h" #include "pqWriterDialog.h" #include "vtkSMCoreUtilities.h" #include "vtkSMParaViewPipelineController.h" #include "vtkSMPropertyHelper.h" #include "vtkSMProxyManager.h" #include "vtkSMSessionProxyManager.h" #include "vtkSMSourceProxy.h" #include "vtkSMWriterFactory.h" #include <QDebug> namespace tomviz { //----------------------------------------------------------------------------- SaveDataReaction::SaveDataReaction(QAction* parentObject) : Superclass(parentObject) { } //----------------------------------------------------------------------------- SaveDataReaction::~SaveDataReaction() { } //----------------------------------------------------------------------------- void SaveDataReaction::onTriggered() { pqServer* server = pqActiveObjects::instance().activeServer(); DataSource *source = ActiveObjects::instance().activeDataSource(); vtkSMWriterFactory* writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); QString filters = writerFactory->GetSupportedFileTypes(source->producer()); if (filters.isEmpty()) { qCritical("Cannot determine writer to use."); return; } pqFileDialog fileDialog(server, pqCoreUtilities::mainWidget(), tr("Save File:"), QString(), filters); fileDialog.setObjectName("FileSaveDialog"); fileDialog.setFileMode(pqFileDialog::AnyFile); // Default to saving tiff files fileDialog.setRecentlyUsedExtension(".tiff"); if (fileDialog.exec() == QDialog::Accepted) { this->saveData(fileDialog.getSelectedFiles()[0]); } } bool SaveDataReaction::saveData(const QString &filename) { pqServer* server = pqActiveObjects::instance().activeServer(); DataSource *source = ActiveObjects::instance().activeDataSource(); if (!server || !source) { qCritical("No active source located."); return false; } vtkSMWriterFactory* writerFactory = vtkSMProxyManager::GetProxyManager()->GetWriterFactory(); vtkSmartPointer<vtkSMProxy> proxy; proxy.TakeReference(writerFactory->CreateWriter(filename.toLatin1().data(), source->producer())); vtkSMSourceProxy* writer = vtkSMSourceProxy::SafeDownCast(proxy); if (!writer) { qCritical() << "Failed to create writer for: " << filename; return false; } pqWriterDialog dialog(writer); // Check to see if this writer has any properties that can be configured by // the user. If it does, display the dialog. if (dialog.hasConfigurableProperties()) { dialog.exec(); if(dialog.result() == QDialog::Rejected) { // The user pressed Cancel so don't write return false; } } writer->UpdateVTKObjects(); writer->UpdatePipeline(); return true; } } // end of namespace tomviz <|endoftext|>
<commit_before><commit_msg>remove unused struct<commit_after><|endoftext|>
<commit_before>#include "DialogoEditarConcepto.h" #include "ui_DialogoEditarConcepto.h" // utiles #include <utiles/include/FuncionesString.h> DialogoEditarConcepto::DialogoEditarConcepto(visualizador::modelo::Concepto * concepto_a_editar, visualizador::aplicacion::GestorEntidades * gestor_terminos, QWidget *parent) : concepto_a_editar(concepto_a_editar), gestor_terminos(gestor_terminos), QDialog(parent) { ui = new Ui::DialogoEditarConcepto(); ui->setupUi(this); this->conectar_componentes(); aplicacion::Logger::info("Iniciando dialogo Editar Conceptos."); this->setAttribute(Qt::WA_DeleteOnClose); this->ui->lineedit_etiqueta->setText(concepto_a_editar->getEtiqueta().c_str()); this->etiqueta_original = concepto_a_editar->getEtiqueta(); this->cargarListaTerminos(concepto_a_editar); } DialogoEditarConcepto::~DialogoEditarConcepto() { this->descargarListaTerminos(); aplicacion::Logger::info("Cerrando dialogo Conceptos."); delete ui; } void DialogoEditarConcepto::eliminar() { QList<QListWidgetItem*> items = ui->lista->selectedItems(); foreach(QListWidgetItem * item, items) { QVariant data = item->data(Qt::UserRole); modelo::Termino* termino = data.value<modelo::Termino*>(); this->gestor_terminos_de_concepto.eliminar(termino); aplicacion::Logger::info("Termino eliminado: { " + aplicacion::Logger::infoLog(termino) + " }."); if (0 == termino->restarReferencia()) { delete termino; } delete this->ui->lista->takeItem(ui->lista->row(item)); } } void DialogoEditarConcepto::nuevo() { std::string texto_nuevo_valor = "<nuevo valor>"; this->termino_sin_editar = texto_nuevo_valor; visualizador::modelo::Termino * nuevo_termino = new visualizador::modelo::Termino(texto_nuevo_valor); nuevo_termino->sumarReferencia(); QListWidgetItem* item = new QListWidgetItem(); item->setText(texto_nuevo_valor.c_str()); item->setFlags(item->flags() | Qt::ItemIsEditable); QVariant data = QVariant::fromValue(nuevo_termino); this->ui->lista->blockSignals(true); item->setData(Qt::UserRole, data); this->ui->lista->blockSignals(false); this->ui->lista->insertItem(0, item); this->ui->lista->editItem(item); } void DialogoEditarConcepto::guardar() { if (false == this->etiquetaModificada() && false == this->listaDeTerminosModificada()) { this->close(); return; } if (this->ui->lineedit_etiqueta->text().isEmpty()) { QMessageBox * informacion_etiqueta_vacia = this->crearInformacionEtiquetaVacia(); informacion_etiqueta_vacia->exec(); delete informacion_etiqueta_vacia; return; } if (0 == this->ui->lista->count()) { QMessageBox * informacion_lista_de_terminos_vacia = this->crearInformacionListaDeTerminosVacia(); informacion_lista_de_terminos_vacia->exec(); delete informacion_lista_de_terminos_vacia; return; } this->concepto_a_editar->setEtiqueta(this->ui->lineedit_etiqueta->text().toStdString()); std::vector<visualizador::modelo::IEntidad*> entidades_a_almacenar = this->gestor_terminos_de_concepto.getEntidadesAAlmacenar(); for (std::vector<visualizador::modelo::IEntidad*>::iterator it = entidades_a_almacenar.begin(); it != entidades_a_almacenar.end(); it++) { this->gestor_terminos->almacenar(*it); this->concepto_a_editar->agregarTermino(this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it)); } std::vector<visualizador::modelo::IEntidad*> entidades_a_eliminar = this->gestor_terminos_de_concepto.getEntidadesAEliminar(); for (std::vector<visualizador::modelo::IEntidad*>::iterator it = entidades_a_eliminar.begin(); it != entidades_a_eliminar.end(); it++) { visualizador::modelo::Termino * termino_a_sacar = this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it); this->concepto_a_editar->sacarTermino(termino_a_sacar); delete termino_a_sacar; } this->accept(); } void DialogoEditarConcepto::termino_actualizado(QListWidgetItem * item_actualizado) { std::string termino_normalizado = item_actualizado->text().toStdString(); if (false == this->normalizar(&termino_normalizado)) { QMessageBox * informacion_termino_invalido = this->crearInformacionTerminoInvalido(); informacion_termino_invalido->exec(); this->ui->lista->blockSignals(true); item_actualizado->setText(QString(this->termino_sin_editar.c_str())); this->ui->lista->blockSignals(false); return; } visualizador::modelo::Termino * nuevo_termino = new visualizador::modelo::Termino(termino_normalizado); if (this->termino_sin_editar == nuevo_termino->getValor()) {// si se deja el mismo valor, entonces no se hace nada. delete nuevo_termino; return; } if (this->gestor_terminos_de_concepto.existe(nuevo_termino)) {// si ya hay un termino con el mismo valor, entonces se vuelve al valor anterior. QMessageBox * informacion_termino_existente = this->crearInformacionTerminoExistente(); informacion_termino_existente->exec(); this->ui->lista->blockSignals(true); item_actualizado->setText(QString(this->termino_sin_editar.c_str())); this->ui->lista->blockSignals(false); delete informacion_termino_existente; delete nuevo_termino; return; } item_actualizado->setText(QString(termino_normalizado.c_str())); visualizador::modelo::Termino * termino_a_agregar_a_lista = NULL; visualizador::modelo::Termino * termino_encontrado = this->gestor_terminos->encontrar(nuevo_termino); if (NULL != termino_encontrado) {// si lo encontro, entonces el termino ya existe. lo que hago es clonarlo y usar el clon, y dsp reemplazarlo en la lista visible. termino_a_agregar_a_lista = this->gestor_terminos->clonar<visualizador::modelo::Termino>(termino_encontrado); delete nuevo_termino; } else {// si no lo encontro, entonces el termino es nuevo. lo agrego a la lista de terminos a agregar. termino_a_agregar_a_lista = nuevo_termino; } this->gestor_terminos_de_concepto.almacenar(termino_a_agregar_a_lista); termino_a_agregar_a_lista->sumarReferencia(); visualizador::modelo::Termino * termino_lista = item_actualizado->data(Qt::UserRole).value<visualizador::modelo::Termino*>(); if (NULL != termino_lista && 0 == termino_lista->restarReferencia()) {// si el item ya tiene asignado un termino, entonces lo elimino. delete termino_lista; } QVariant data = QVariant::fromValue(termino_a_agregar_a_lista); this->ui->lista->blockSignals(true); item_actualizado->setData(Qt::UserRole, data); this->ui->lista->blockSignals(false); } void DialogoEditarConcepto::guardar_termino_sin_editar(QListWidgetItem * item_actual, QListWidgetItem * item_previo) { if(NULL != item_actual) { this->termino_sin_editar = item_actual->text().toStdString(); } } // METODOS INTERNOS bool DialogoEditarConcepto::normalizar(std::string * termino) { std::string termino_original = *termino; herramientas::utiles::FuncionesString::eliminar_tildes_utf8(termino); herramientas::utiles::FuncionesString::todoMinuscula(*termino); herramientas::utiles::FuncionesString::eliminarSignosYPuntuacion(*termino, { "*" }); herramientas::utiles::FuncionesString::eliminarCaracteresDeControl(*termino); herramientas::utiles::FuncionesString::eliminarEspaciosRedundantes(*termino); herramientas::utiles::FuncionesString::recortar(termino); if (herramientas::utiles::FuncionesString::separar(*termino).size() > 3) { *termino = termino_original; return false; } return true; } bool DialogoEditarConcepto::etiquetaModificada() { return this->ui->lineedit_etiqueta->text().toStdString() != this->etiqueta_original; } bool DialogoEditarConcepto::listaDeTerminosModificada() { return (this->gestor_terminos_de_concepto.getEntidadesAAlmacenar().size() != 0 || this->gestor_terminos_de_concepto.getEntidadesAEliminar().size() != 0); } void DialogoEditarConcepto::cargarListaTerminos(visualizador::modelo::Concepto * concepto_a_editar) { std::vector<visualizador::modelo::Termino*> terminos_actuales = concepto_a_editar->getTerminos(); for (std::vector<visualizador::modelo::Termino*>::iterator it = terminos_actuales.begin(); it != terminos_actuales.end(); it++) { //(*it)->sumarReferencia(); std::string texto_termino = (*it)->getValor(); QListWidgetItem* item = new QListWidgetItem(); visualizador::modelo::Termino* termino_item = this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it); termino_item->sumarReferencia(); QVariant data = QVariant::fromValue(termino_item); item->setData(Qt::UserRole, data); item->setText(texto_termino.c_str()); item->setFlags(item->flags() | Qt::ItemIsEditable); this->ui->lista->insertItem(0, item); } this->gestor_terminos_de_concepto.gestionar<visualizador::modelo::Termino>(terminos_actuales); aplicacion::Logger::info(std::to_string(terminos_actuales.size()) + " terminos cargados."); this->ui->lista->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection); } void DialogoEditarConcepto::descargarListaTerminos() { QListWidgetItem * item = nullptr; // elimino los terminos de la lista visualizador::modelo::Termino * termino_lista = nullptr; unsigned int count = ui->lista->count(); while (0 != ui->lista->count()) { count = ui->lista->count(); termino_lista = this->ui->lista->item(0)->data(Qt::UserRole).value<visualizador::modelo::Termino*>(); if (0 == termino_lista->restarReferencia()) { delete termino_lista; } item = this->ui->lista->takeItem(0); delete item; } aplicacion::Logger::info(std::to_string(count) + " terminos descargados."); } // mensajes QMessageBox * DialogoEditarConcepto::crearInformacionTerminoExistente() { std::string texto = u8"El trmino que se quiere agregar ya existe."; visualizador::aplicacion::comunicacion::Informacion informacion_termino_existente(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_termino_existente, this); } QMessageBox * DialogoEditarConcepto::crearInformacionTerminoInvalido() { std::string texto = u8"Imposible crear trmino con ms de una palabra. El trmino debe ser exactamente de una sola palabra."; visualizador::aplicacion::comunicacion::Informacion informacion_termino_invalido(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_termino_invalido, this); } QMessageBox * DialogoEditarConcepto::crearInformacionEtiquetaVacia() { std::string texto = u8"No se asigno la etiqueta. La etiqueta sirve para describir e identificar al concepto en las consultas."; visualizador::aplicacion::comunicacion::Informacion informacion_etiqueta_vacia(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_etiqueta_vacia, this); } QMessageBox * DialogoEditarConcepto::crearInformacionListaDeTerminosVacia() { std::string texto = u8"El concepto no tiene trminos. La lista de trminos no puede estar vaca."; visualizador::aplicacion::comunicacion::Informacion informacion_etiqueta_vacia(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_etiqueta_vacia, this); } void DialogoEditarConcepto::conectar_componentes() { QObject::connect(this->ui->btn_nuevo, &QPushButton::released, this, &DialogoEditarConcepto::nuevo); QObject::connect(this->ui->btn_eliminar, &QPushButton::released, this, &DialogoEditarConcepto::eliminar); QObject::connect(this->ui->btn_guardar, &QPushButton::released, this, &DialogoEditarConcepto::guardar); QObject::connect(this->ui->btn_cancelar, &QPushButton::released, this, &DialogoEditarConcepto::close); QObject::connect(this->ui->lista, &QListWidget::itemChanged, this, &DialogoEditarConcepto::termino_actualizado); QObject::connect(this->ui->lista, &QListWidget::currentItemChanged, this, &DialogoEditarConcepto::guardar_termino_sin_editar); }<commit_msg>termino acepta hasta 3 palabras<commit_after>#include "DialogoEditarConcepto.h" #include "ui_DialogoEditarConcepto.h" // utiles #include <utiles/include/FuncionesString.h> DialogoEditarConcepto::DialogoEditarConcepto(visualizador::modelo::Concepto * concepto_a_editar, visualizador::aplicacion::GestorEntidades * gestor_terminos, QWidget *parent) : concepto_a_editar(concepto_a_editar), gestor_terminos(gestor_terminos), QDialog(parent) { ui = new Ui::DialogoEditarConcepto(); ui->setupUi(this); this->conectar_componentes(); aplicacion::Logger::info("Iniciando dialogo Editar Conceptos."); this->setAttribute(Qt::WA_DeleteOnClose); this->ui->lineedit_etiqueta->setText(concepto_a_editar->getEtiqueta().c_str()); this->etiqueta_original = concepto_a_editar->getEtiqueta(); this->cargarListaTerminos(concepto_a_editar); } DialogoEditarConcepto::~DialogoEditarConcepto() { this->descargarListaTerminos(); aplicacion::Logger::info("Cerrando dialogo Conceptos."); delete ui; } void DialogoEditarConcepto::eliminar() { QList<QListWidgetItem*> items = ui->lista->selectedItems(); foreach(QListWidgetItem * item, items) { QVariant data = item->data(Qt::UserRole); modelo::Termino* termino = data.value<modelo::Termino*>(); this->gestor_terminos_de_concepto.eliminar(termino); aplicacion::Logger::info("Termino eliminado: { " + aplicacion::Logger::infoLog(termino) + " }."); if (0 == termino->restarReferencia()) { delete termino; } delete this->ui->lista->takeItem(ui->lista->row(item)); } } void DialogoEditarConcepto::nuevo() { std::string texto_nuevo_valor = "<nuevo valor>"; this->termino_sin_editar = texto_nuevo_valor; visualizador::modelo::Termino * nuevo_termino = new visualizador::modelo::Termino(texto_nuevo_valor); nuevo_termino->sumarReferencia(); QListWidgetItem* item = new QListWidgetItem(); item->setText(texto_nuevo_valor.c_str()); item->setFlags(item->flags() | Qt::ItemIsEditable); QVariant data = QVariant::fromValue(nuevo_termino); this->ui->lista->blockSignals(true); item->setData(Qt::UserRole, data); this->ui->lista->blockSignals(false); this->ui->lista->insertItem(0, item); this->ui->lista->editItem(item); } void DialogoEditarConcepto::guardar() { if (false == this->etiquetaModificada() && false == this->listaDeTerminosModificada()) { this->close(); return; } if (this->ui->lineedit_etiqueta->text().isEmpty()) { QMessageBox * informacion_etiqueta_vacia = this->crearInformacionEtiquetaVacia(); informacion_etiqueta_vacia->exec(); delete informacion_etiqueta_vacia; return; } if (0 == this->ui->lista->count()) { QMessageBox * informacion_lista_de_terminos_vacia = this->crearInformacionListaDeTerminosVacia(); informacion_lista_de_terminos_vacia->exec(); delete informacion_lista_de_terminos_vacia; return; } this->concepto_a_editar->setEtiqueta(this->ui->lineedit_etiqueta->text().toStdString()); std::vector<visualizador::modelo::IEntidad*> entidades_a_almacenar = this->gestor_terminos_de_concepto.getEntidadesAAlmacenar(); for (std::vector<visualizador::modelo::IEntidad*>::iterator it = entidades_a_almacenar.begin(); it != entidades_a_almacenar.end(); it++) { this->gestor_terminos->almacenar(*it); this->concepto_a_editar->agregarTermino(this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it)); } std::vector<visualizador::modelo::IEntidad*> entidades_a_eliminar = this->gestor_terminos_de_concepto.getEntidadesAEliminar(); for (std::vector<visualizador::modelo::IEntidad*>::iterator it = entidades_a_eliminar.begin(); it != entidades_a_eliminar.end(); it++) { visualizador::modelo::Termino * termino_a_sacar = this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it); this->concepto_a_editar->sacarTermino(termino_a_sacar); delete termino_a_sacar; } this->accept(); } void DialogoEditarConcepto::termino_actualizado(QListWidgetItem * item_actualizado) { std::string termino_normalizado = item_actualizado->text().toStdString(); if (false == this->normalizar(&termino_normalizado)) { QMessageBox * informacion_termino_invalido = this->crearInformacionTerminoInvalido(); informacion_termino_invalido->exec(); this->ui->lista->blockSignals(true); item_actualizado->setText(QString(this->termino_sin_editar.c_str())); this->ui->lista->blockSignals(false); return; } visualizador::modelo::Termino * nuevo_termino = new visualizador::modelo::Termino(termino_normalizado); if (this->termino_sin_editar == nuevo_termino->getValor()) {// si se deja el mismo valor, entonces no se hace nada. delete nuevo_termino; return; } if (this->gestor_terminos_de_concepto.existe(nuevo_termino)) {// si ya hay un termino con el mismo valor, entonces se vuelve al valor anterior. QMessageBox * informacion_termino_existente = this->crearInformacionTerminoExistente(); informacion_termino_existente->exec(); this->ui->lista->blockSignals(true); item_actualizado->setText(QString(this->termino_sin_editar.c_str())); this->ui->lista->blockSignals(false); delete informacion_termino_existente; delete nuevo_termino; return; } item_actualizado->setText(QString(termino_normalizado.c_str())); visualizador::modelo::Termino * termino_a_agregar_a_lista = NULL; visualizador::modelo::Termino * termino_encontrado = this->gestor_terminos->encontrar(nuevo_termino); if (NULL != termino_encontrado) {// si lo encontro, entonces el termino ya existe. lo que hago es clonarlo y usar el clon, y dsp reemplazarlo en la lista visible. termino_a_agregar_a_lista = this->gestor_terminos->clonar<visualizador::modelo::Termino>(termino_encontrado); delete nuevo_termino; } else {// si no lo encontro, entonces el termino es nuevo. lo agrego a la lista de terminos a agregar. termino_a_agregar_a_lista = nuevo_termino; } this->gestor_terminos_de_concepto.almacenar(termino_a_agregar_a_lista); termino_a_agregar_a_lista->sumarReferencia(); visualizador::modelo::Termino * termino_lista = item_actualizado->data(Qt::UserRole).value<visualizador::modelo::Termino*>(); if (NULL != termino_lista && 0 == termino_lista->restarReferencia()) {// si el item ya tiene asignado un termino, entonces lo elimino. delete termino_lista; } QVariant data = QVariant::fromValue(termino_a_agregar_a_lista); this->ui->lista->blockSignals(true); item_actualizado->setData(Qt::UserRole, data); this->ui->lista->blockSignals(false); } void DialogoEditarConcepto::guardar_termino_sin_editar(QListWidgetItem * item_actual, QListWidgetItem * item_previo) { if(NULL != item_actual) { this->termino_sin_editar = item_actual->text().toStdString(); } } // METODOS INTERNOS bool DialogoEditarConcepto::normalizar(std::string * termino) { std::string termino_original = *termino; herramientas::utiles::FuncionesString::eliminar_tildes_utf8(termino); herramientas::utiles::FuncionesString::todoMinuscula(*termino); herramientas::utiles::FuncionesString::eliminarSignosYPuntuacion(*termino, { "*" }); herramientas::utiles::FuncionesString::eliminarCaracteresDeControl(*termino); herramientas::utiles::FuncionesString::eliminarEspaciosRedundantes(*termino); herramientas::utiles::FuncionesString::recortar(termino); if (herramientas::utiles::FuncionesString::separar(*termino).size() > 3) { *termino = termino_original; return false; } return true; } bool DialogoEditarConcepto::etiquetaModificada() { return this->ui->lineedit_etiqueta->text().toStdString() != this->etiqueta_original; } bool DialogoEditarConcepto::listaDeTerminosModificada() { return (this->gestor_terminos_de_concepto.getEntidadesAAlmacenar().size() != 0 || this->gestor_terminos_de_concepto.getEntidadesAEliminar().size() != 0); } void DialogoEditarConcepto::cargarListaTerminos(visualizador::modelo::Concepto * concepto_a_editar) { std::vector<visualizador::modelo::Termino*> terminos_actuales = concepto_a_editar->getTerminos(); for (std::vector<visualizador::modelo::Termino*>::iterator it = terminos_actuales.begin(); it != terminos_actuales.end(); it++) { //(*it)->sumarReferencia(); std::string texto_termino = (*it)->getValor(); QListWidgetItem* item = new QListWidgetItem(); visualizador::modelo::Termino* termino_item = this->gestor_terminos->clonar<visualizador::modelo::Termino>(*it); termino_item->sumarReferencia(); QVariant data = QVariant::fromValue(termino_item); item->setData(Qt::UserRole, data); item->setText(texto_termino.c_str()); item->setFlags(item->flags() | Qt::ItemIsEditable); this->ui->lista->insertItem(0, item); } this->gestor_terminos_de_concepto.gestionar<visualizador::modelo::Termino>(terminos_actuales); aplicacion::Logger::info(std::to_string(terminos_actuales.size()) + " terminos cargados."); this->ui->lista->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection); } void DialogoEditarConcepto::descargarListaTerminos() { QListWidgetItem * item = nullptr; // elimino los terminos de la lista visualizador::modelo::Termino * termino_lista = nullptr; unsigned int count = ui->lista->count(); while (0 != ui->lista->count()) { count = ui->lista->count(); termino_lista = this->ui->lista->item(0)->data(Qt::UserRole).value<visualizador::modelo::Termino*>(); if (0 == termino_lista->restarReferencia()) { delete termino_lista; } item = this->ui->lista->takeItem(0); delete item; } aplicacion::Logger::info(std::to_string(count) + " terminos descargados."); } // mensajes QMessageBox * DialogoEditarConcepto::crearInformacionTerminoExistente() { std::string texto = u8"El trmino que se quiere agregar ya existe."; visualizador::aplicacion::comunicacion::Informacion informacion_termino_existente(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_termino_existente, this); } QMessageBox * DialogoEditarConcepto::crearInformacionTerminoInvalido() { std::string texto = u8"Imposible crear trmino con ms de tres palabras. Cada trmino contiene una, dos o tres palabras como mximo."; visualizador::aplicacion::comunicacion::Informacion informacion_termino_invalido(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_termino_invalido, this); } QMessageBox * DialogoEditarConcepto::crearInformacionEtiquetaVacia() { std::string texto = u8"No se asigno la etiqueta. La etiqueta sirve para describir e identificar al concepto en las consultas."; visualizador::aplicacion::comunicacion::Informacion informacion_etiqueta_vacia(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_etiqueta_vacia, this); } QMessageBox * DialogoEditarConcepto::crearInformacionListaDeTerminosVacia() { std::string texto = u8"El concepto no tiene trminos. La lista de trminos no puede estar vaca."; visualizador::aplicacion::comunicacion::Informacion informacion_etiqueta_vacia(texto); return comunicacion::FabricaMensajes::fabricar(&informacion_etiqueta_vacia, this); } void DialogoEditarConcepto::conectar_componentes() { QObject::connect(this->ui->btn_nuevo, &QPushButton::released, this, &DialogoEditarConcepto::nuevo); QObject::connect(this->ui->btn_eliminar, &QPushButton::released, this, &DialogoEditarConcepto::eliminar); QObject::connect(this->ui->btn_guardar, &QPushButton::released, this, &DialogoEditarConcepto::guardar); QObject::connect(this->ui->btn_cancelar, &QPushButton::released, this, &DialogoEditarConcepto::close); QObject::connect(this->ui->lista, &QListWidget::itemChanged, this, &DialogoEditarConcepto::termino_actualizado); QObject::connect(this->ui->lista, &QListWidget::currentItemChanged, this, &DialogoEditarConcepto::guardar_termino_sin_editar); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: indexentrysupplier_common.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-01-31 18:37:38 $ * * 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 <indexentrysupplier_common.hxx> #include <com/sun/star/i18n/CollatorOptions.hpp> #include <localedata.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { IndexEntrySupplier_Common::IndexEntrySupplier_Common(const Reference < lang::XMultiServiceFactory >& rxMSF) { implementationName = "com.sun.star.i18n.IndexEntrySupplier_Common"; collator = new CollatorImpl(rxMSF); usePhonetic = sal_False; } IndexEntrySupplier_Common::~IndexEntrySupplier_Common() { delete collator; } Sequence < lang::Locale > SAL_CALL IndexEntrySupplier_Common::getLocaleList() throw (RuntimeException) { throw RuntimeException(); } Sequence < OUString > SAL_CALL IndexEntrySupplier_Common::getAlgorithmList( const lang::Locale& rLocale ) throw (RuntimeException) { throw RuntimeException(); } OUString SAL_CALL IndexEntrySupplier_Common::getPhoneticCandidate( const OUString& rIndexEntry, const lang::Locale& rLocale ) throw (RuntimeException) { return OUString(); } sal_Bool SAL_CALL IndexEntrySupplier_Common::usePhoneticEntry( const lang::Locale& rLocale ) throw (RuntimeException) { throw RuntimeException(); } sal_Bool SAL_CALL IndexEntrySupplier_Common::loadAlgorithm( const lang::Locale& rLocale, const OUString& rAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException) { usePhonetic = LocaleData().isPhonetic(rLocale, rAlgorithm); collator->loadCollatorAlgorithm(rAlgorithm, rLocale, collatorOptions); aLocale = rLocale; aAlgorithm = rAlgorithm; return sal_True; } OUString SAL_CALL IndexEntrySupplier_Common::getIndexKey( const OUString& rIndexEntry, const OUString& rPhoneticEntry, const lang::Locale& rLocale ) throw (RuntimeException) { return rIndexEntry.copy(0, 1); } sal_Int16 SAL_CALL IndexEntrySupplier_Common::compareIndexEntry( const OUString& rIndexEntry1, const OUString& rPhoneticEntry1, const lang::Locale& rLocale1, const OUString& rIndexEntry2, const OUString& rPhoneticEntry2, const lang::Locale& rLocale2 ) throw (RuntimeException) { return collator->compareString(rIndexEntry1, rIndexEntry2); } OUString SAL_CALL IndexEntrySupplier_Common::getIndexCharacter( const OUString& rIndexEntry, const lang::Locale& rLocale, const OUString& rAlgorithm ) throw (RuntimeException) { return rIndexEntry.copy(0, 1); } OUString SAL_CALL IndexEntrySupplier_Common::getIndexFollowPageWord( sal_Bool bMorePages, const lang::Locale& rLocale ) throw (RuntimeException) { throw RuntimeException(); } const OUString& SAL_CALL IndexEntrySupplier_Common::getEntry( const OUString& IndexEntry, const OUString& PhoneticEntry, const lang::Locale& rLocale ) throw (RuntimeException) { // The condition for using phonetic entry is: // usePhonetic is set for the algorithm; // rLocale for phonetic entry is same as aLocale for algorithm, // which means Chinese phonetic will not be used for Japanese algorithm; // phonetic entry is not blank. if (usePhonetic && PhoneticEntry.getLength() > 0 && rLocale.Language == aLocale.Language && rLocale.Country == aLocale.Country && rLocale.Variant == aLocale.Variant) return PhoneticEntry; else return IndexEntry; } OUString SAL_CALL IndexEntrySupplier_Common::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii( implementationName ); } sal_Bool SAL_CALL IndexEntrySupplier_Common::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return rServiceName.compareToAscii(implementationName) == 0; } Sequence< OUString > SAL_CALL IndexEntrySupplier_Common::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii( implementationName ); return aRet; } } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.3.14); FILE MERGED 2006/04/21 09:13:23 sb 1.3.14.5: #i53898# Made code compile and/or warning-free again after resync to SRC680m162. 2006/04/20 15:23:15 sb 1.3.14.4: #i53898# Made code compile and/or warning-free again after resync to SRC680m162. 2006/04/07 21:07:34 sb 1.3.14.3: RESYNC: (1.3-1.4); FILE MERGED 2006/03/08 13:19:10 nn 1.3.14.2: #i53898# warning-free code 2005/11/09 20:21:57 pl 1.3.14.1: #i53898# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: indexentrysupplier_common.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:45:18 $ * * 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 <indexentrysupplier_common.hxx> #include <com/sun/star/i18n/CollatorOptions.hpp> #include <localedata.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { IndexEntrySupplier_Common::IndexEntrySupplier_Common(const Reference < lang::XMultiServiceFactory >& rxMSF) { implementationName = "com.sun.star.i18n.IndexEntrySupplier_Common"; collator = new CollatorImpl(rxMSF); usePhonetic = sal_False; } IndexEntrySupplier_Common::~IndexEntrySupplier_Common() { delete collator; } Sequence < lang::Locale > SAL_CALL IndexEntrySupplier_Common::getLocaleList() throw (RuntimeException) { throw RuntimeException(); } Sequence < OUString > SAL_CALL IndexEntrySupplier_Common::getAlgorithmList( const lang::Locale& ) throw (RuntimeException) { throw RuntimeException(); } OUString SAL_CALL IndexEntrySupplier_Common::getPhoneticCandidate( const OUString&, const lang::Locale& ) throw (RuntimeException) { return OUString(); } sal_Bool SAL_CALL IndexEntrySupplier_Common::usePhoneticEntry( const lang::Locale& ) throw (RuntimeException) { throw RuntimeException(); } sal_Bool SAL_CALL IndexEntrySupplier_Common::loadAlgorithm( const lang::Locale& rLocale, const OUString& rAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException) { usePhonetic = LocaleData().isPhonetic(rLocale, rAlgorithm); collator->loadCollatorAlgorithm(rAlgorithm, rLocale, collatorOptions); aLocale = rLocale; aAlgorithm = rAlgorithm; return sal_True; } OUString SAL_CALL IndexEntrySupplier_Common::getIndexKey( const OUString& rIndexEntry, const OUString&, const lang::Locale& ) throw (RuntimeException) { return rIndexEntry.copy(0, 1); } sal_Int16 SAL_CALL IndexEntrySupplier_Common::compareIndexEntry( const OUString& rIndexEntry1, const OUString&, const lang::Locale&, const OUString& rIndexEntry2, const OUString&, const lang::Locale& ) throw (RuntimeException) { return sal::static_int_cast< sal_Int16 >( collator->compareString(rIndexEntry1, rIndexEntry2)); // return value of compareString in { -1, 0, 1 } } OUString SAL_CALL IndexEntrySupplier_Common::getIndexCharacter( const OUString& rIndexEntry, const lang::Locale&, const OUString& ) throw (RuntimeException) { return rIndexEntry.copy(0, 1); } OUString SAL_CALL IndexEntrySupplier_Common::getIndexFollowPageWord( sal_Bool, const lang::Locale& ) throw (RuntimeException) { throw RuntimeException(); } const OUString& SAL_CALL IndexEntrySupplier_Common::getEntry( const OUString& IndexEntry, const OUString& PhoneticEntry, const lang::Locale& rLocale ) throw (RuntimeException) { // The condition for using phonetic entry is: // usePhonetic is set for the algorithm; // rLocale for phonetic entry is same as aLocale for algorithm, // which means Chinese phonetic will not be used for Japanese algorithm; // phonetic entry is not blank. if (usePhonetic && PhoneticEntry.getLength() > 0 && rLocale.Language == aLocale.Language && rLocale.Country == aLocale.Country && rLocale.Variant == aLocale.Variant) return PhoneticEntry; else return IndexEntry; } OUString SAL_CALL IndexEntrySupplier_Common::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii( implementationName ); } sal_Bool SAL_CALL IndexEntrySupplier_Common::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return rServiceName.compareToAscii(implementationName) == 0; } Sequence< OUString > SAL_CALL IndexEntrySupplier_Common::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii( implementationName ); return aRet; } } } } } <|endoftext|>
<commit_before> #include "clay.hpp" #include "llvm/PassManager.h" #include "llvm/ADT/Triple.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/LinkAllVMCore.h" #include "llvm/Target/TargetData.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/StandardPasses.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/Target/TargetRegistry.h" #include <iostream> #include <cstring> #ifdef WIN32 #define DEFAULT_EXE "a.exe" #else #define DEFAULT_EXE "a.out" #endif using namespace std; static void addOptimizationPasses(llvm::PassManager &passes, llvm::FunctionPassManager &fpasses, unsigned optLevel) { llvm::createStandardFunctionPasses(&fpasses, optLevel); llvm::Pass *inliningPass = 0; if (optLevel) { unsigned threshold = 200; if (optLevel > 2) threshold = 250; inliningPass = llvm::createFunctionInliningPass(threshold); } else { inliningPass = llvm::createAlwaysInlinerPass(); } llvm::createStandardModulePasses(&passes, optLevel, /*OptimizeSize=*/ false, /*UnitAtATime=*/ false, /*UnrollLoops=*/ optLevel > 1, /*SimplifyLibCalls=*/ true, /*HaveExceptions=*/ true, inliningPass); llvm::createStandardLTOPasses(&passes, /*Internalize=*/ true, /*RunInliner=*/ true, /*VerifyEach=*/ false); } static void optimizeLLVM(llvm::Module *module) { llvm::PassManager passes; string moduleDataLayout = module->getDataLayout(); llvm::TargetData *td = new llvm::TargetData(moduleDataLayout); passes.add(td); llvm::FunctionPassManager fpasses(module); fpasses.add(new llvm::TargetData(*td)); addOptimizationPasses(passes, fpasses, 3); fpasses.doInitialization(); for (llvm::Module::iterator i = module->begin(), e = module->end(); i != e; ++i) { fpasses.run(*i); } passes.add(llvm::createVerifierPass()); passes.run(*module); } static void generateLLVM(llvm::Module *module, llvm::raw_ostream *out) { llvm::PassManager passes; passes.add(llvm::createPrintModulePass(out)); passes.run(*module); } static void generateAssembly(llvm::Module *module, llvm::raw_ostream *out) { llvm::Triple theTriple(module->getTargetTriple()); string err; const llvm::Target *theTarget = llvm::TargetRegistry::lookupTarget(theTriple.getTriple(), err); assert(theTarget != NULL); llvm::TargetMachine *target = theTarget->createTargetMachine(theTriple.getTriple(), ""); assert(target != NULL); llvm::CodeGenOpt::Level optLevel = llvm::CodeGenOpt::Aggressive; llvm::FunctionPassManager fpasses(module); fpasses.add(new llvm::TargetData(module)); fpasses.add(llvm::createVerifierPass()); target->setAsmVerbosityDefault(true); llvm::formatted_raw_ostream fout(*out); bool result = target->addPassesToEmitFile(fpasses, fout, llvm::TargetMachine::CGFT_AssemblyFile, optLevel); assert(!result); fpasses.doInitialization(); for (llvm::Module::iterator i = module->begin(), e = module->end(); i != e; ++i) { fpasses.run(*i); } fpasses.doFinalization(); } static bool generateExe(llvm::Module *module, const string &outputFile, const llvm::sys::Path &gccPath) { llvm::sys::Path tempAsm("clayasm"); string errMsg; if (tempAsm.createTemporaryFileOnDisk(false, &errMsg)) { cerr << "error: " << errMsg << '\n'; return false; } llvm::sys::RemoveFileOnSignal(tempAsm); errMsg.clear(); llvm::raw_fd_ostream asmOut(tempAsm.c_str(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) { cerr << "error: " << errMsg << '\n'; return false; } generateAssembly(module, &asmOut); asmOut.close(); const char *gccArgs[] = {"gcc", "-m32", "-o", outputFile.c_str(), "-x", "assembler", tempAsm.c_str(), NULL}; llvm::sys::Program::ExecuteAndWait(gccPath, gccArgs); if (tempAsm.eraseFromDisk(false, &errMsg)) { cerr << "error: " << errMsg << '\n'; return false; } return true; } static void usage() { cerr << "usage: clay <options> <clayfile>\n"; cerr << "options:\n"; cerr << " -o <file> - specify output file\n"; cerr << " --unoptimized - generate unoptimized code\n"; cerr << " --emit-llvm - emit llvm code\n"; cerr << " --emit-asm - emit assember code\n"; } int main(int argc, char **argv) { if (argc == 1) { usage(); return -1; } bool optimize = true; bool emitLLVM = false; bool emitAsm = false; string clayFile; string outputFile; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--unoptimized") == 0) { optimize = false; } else if (strcmp(argv[i], "--emit-llvm") == 0) { emitLLVM = true; } else if (strcmp(argv[i], "--emit-asm") == 0) { emitAsm = true; } else if (strcmp(argv[i], "-o") == 0) { if (i+1 == argc) { cerr << "error: filename missing after -o\n"; return -1; } if (!outputFile.empty()) { cerr << "error: output file already specified: " << outputFile << ", specified again as " << argv[i] << '\n'; return -1; } ++i; outputFile = argv[i]; } else if (strstr(argv[i], "-") != argv[i]) { if (!clayFile.empty()) { cerr << "error: clay file already specified: " << clayFile << ", unrecognized parameter: " << argv[i] << '\n'; return -1; } clayFile = argv[i]; } else { cerr << "error: unrecognized option " << argv[i] << '\n'; return -1; } } if (clayFile.empty()) { cerr << "error: clay file not specified\n"; return -1; } if (emitLLVM && emitAsm) { cerr << "error: use either --emit-llvm or --emit-asm, not both\n"; return -1; } llvm::InitializeAllTargets(); llvm::InitializeAllAsmPrinters(); initLLVM(); llvmModule->setTargetTriple(llvm::sys::getHostTriple()); initTypes(); llvm::sys::Path clayExe = llvm::sys::Path::GetMainExecutable(argv[0], (void *)&main); llvm::sys::Path clayDir(clayExe.getDirname()); llvm::sys::Path libDir(clayDir); bool result = libDir.appendComponent("lib-clay"); assert(result); addSearchPath(libDir.str()); if (outputFile.empty()) { if (emitLLVM) outputFile = "a.ll"; else if (emitAsm) outputFile = "a.s"; else outputFile = DEFAULT_EXE; } llvm::sys::RemoveFileOnSignal(llvm::sys::Path(outputFile)); ModulePtr m = loadProgram(clayFile); codegenMain(m); if (optimize) optimizeLLVM(llvmModule); if (emitLLVM || emitAsm) { string errorInfo; llvm::raw_fd_ostream out(outputFile.c_str(), errorInfo, llvm::raw_fd_ostream::F_Binary); if (!errorInfo.empty()) { cerr << "error: " << errorInfo << '\n'; return -1; } if (emitLLVM) generateLLVM(llvmModule, &out); else if (emitAsm) generateAssembly(llvmModule, &out); } else { bool result; llvm::sys::Path gccPath; #ifdef WIN32 gccPath = clayDir; result = gccPath.appendComponent("mingw"); assert(result); result = gccPath.appendComponent("bin"); assert(result); result = gccPath.appendComponent("gcc.exe"); assert(result); if (!gccPath.exists()) gccPath = llvm::sys::Path(); #endif if (!gccPath.isValid()) { gccPath = llvm::sys::Program::FindProgramByName("gcc"); } if (!gccPath.isValid()) { cerr << "error: unable to find gcc on the path\n"; return false; } result = generateExe(llvmModule, outputFile, gccPath); if (!result) return -1; } return 0; } <commit_msg>when invoking gcc, set argv[0] to full path.<commit_after> #include "clay.hpp" #include "llvm/PassManager.h" #include "llvm/ADT/Triple.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/LinkAllVMCore.h" #include "llvm/Target/TargetData.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/StandardPasses.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/Target/TargetRegistry.h" #include <iostream> #include <cstring> #ifdef WIN32 #define DEFAULT_EXE "a.exe" #else #define DEFAULT_EXE "a.out" #endif using namespace std; static void addOptimizationPasses(llvm::PassManager &passes, llvm::FunctionPassManager &fpasses, unsigned optLevel) { llvm::createStandardFunctionPasses(&fpasses, optLevel); llvm::Pass *inliningPass = 0; if (optLevel) { unsigned threshold = 200; if (optLevel > 2) threshold = 250; inliningPass = llvm::createFunctionInliningPass(threshold); } else { inliningPass = llvm::createAlwaysInlinerPass(); } llvm::createStandardModulePasses(&passes, optLevel, /*OptimizeSize=*/ false, /*UnitAtATime=*/ false, /*UnrollLoops=*/ optLevel > 1, /*SimplifyLibCalls=*/ true, /*HaveExceptions=*/ true, inliningPass); llvm::createStandardLTOPasses(&passes, /*Internalize=*/ true, /*RunInliner=*/ true, /*VerifyEach=*/ false); } static void optimizeLLVM(llvm::Module *module) { llvm::PassManager passes; string moduleDataLayout = module->getDataLayout(); llvm::TargetData *td = new llvm::TargetData(moduleDataLayout); passes.add(td); llvm::FunctionPassManager fpasses(module); fpasses.add(new llvm::TargetData(*td)); addOptimizationPasses(passes, fpasses, 3); fpasses.doInitialization(); for (llvm::Module::iterator i = module->begin(), e = module->end(); i != e; ++i) { fpasses.run(*i); } passes.add(llvm::createVerifierPass()); passes.run(*module); } static void generateLLVM(llvm::Module *module, llvm::raw_ostream *out) { llvm::PassManager passes; passes.add(llvm::createPrintModulePass(out)); passes.run(*module); } static void generateAssembly(llvm::Module *module, llvm::raw_ostream *out) { llvm::Triple theTriple(module->getTargetTriple()); string err; const llvm::Target *theTarget = llvm::TargetRegistry::lookupTarget(theTriple.getTriple(), err); assert(theTarget != NULL); llvm::TargetMachine *target = theTarget->createTargetMachine(theTriple.getTriple(), ""); assert(target != NULL); llvm::CodeGenOpt::Level optLevel = llvm::CodeGenOpt::Aggressive; llvm::FunctionPassManager fpasses(module); fpasses.add(new llvm::TargetData(module)); fpasses.add(llvm::createVerifierPass()); target->setAsmVerbosityDefault(true); llvm::formatted_raw_ostream fout(*out); bool result = target->addPassesToEmitFile(fpasses, fout, llvm::TargetMachine::CGFT_AssemblyFile, optLevel); assert(!result); fpasses.doInitialization(); for (llvm::Module::iterator i = module->begin(), e = module->end(); i != e; ++i) { fpasses.run(*i); } fpasses.doFinalization(); } static bool generateExe(llvm::Module *module, const string &outputFile, const llvm::sys::Path &gccPath) { llvm::sys::Path tempAsm("clayasm"); string errMsg; if (tempAsm.createTemporaryFileOnDisk(false, &errMsg)) { cerr << "error: " << errMsg << '\n'; return false; } llvm::sys::RemoveFileOnSignal(tempAsm); errMsg.clear(); llvm::raw_fd_ostream asmOut(tempAsm.c_str(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) { cerr << "error: " << errMsg << '\n'; return false; } generateAssembly(module, &asmOut); asmOut.close(); const char *gccArgs[] = {gccPath.c_str(), "-m32", "-o", outputFile.c_str(), "-x", "assembler", tempAsm.c_str(), NULL}; llvm::sys::Program::ExecuteAndWait(gccPath, gccArgs); if (tempAsm.eraseFromDisk(false, &errMsg)) { cerr << "error: " << errMsg << '\n'; return false; } return true; } static void usage() { cerr << "usage: clay <options> <clayfile>\n"; cerr << "options:\n"; cerr << " -o <file> - specify output file\n"; cerr << " --unoptimized - generate unoptimized code\n"; cerr << " --emit-llvm - emit llvm code\n"; cerr << " --emit-asm - emit assember code\n"; } int main(int argc, char **argv) { if (argc == 1) { usage(); return -1; } bool optimize = true; bool emitLLVM = false; bool emitAsm = false; string clayFile; string outputFile; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--unoptimized") == 0) { optimize = false; } else if (strcmp(argv[i], "--emit-llvm") == 0) { emitLLVM = true; } else if (strcmp(argv[i], "--emit-asm") == 0) { emitAsm = true; } else if (strcmp(argv[i], "-o") == 0) { if (i+1 == argc) { cerr << "error: filename missing after -o\n"; return -1; } if (!outputFile.empty()) { cerr << "error: output file already specified: " << outputFile << ", specified again as " << argv[i] << '\n'; return -1; } ++i; outputFile = argv[i]; } else if (strstr(argv[i], "-") != argv[i]) { if (!clayFile.empty()) { cerr << "error: clay file already specified: " << clayFile << ", unrecognized parameter: " << argv[i] << '\n'; return -1; } clayFile = argv[i]; } else { cerr << "error: unrecognized option " << argv[i] << '\n'; return -1; } } if (clayFile.empty()) { cerr << "error: clay file not specified\n"; return -1; } if (emitLLVM && emitAsm) { cerr << "error: use either --emit-llvm or --emit-asm, not both\n"; return -1; } llvm::InitializeAllTargets(); llvm::InitializeAllAsmPrinters(); initLLVM(); llvmModule->setTargetTriple(llvm::sys::getHostTriple()); initTypes(); llvm::sys::Path clayExe = llvm::sys::Path::GetMainExecutable(argv[0], (void *)&main); llvm::sys::Path clayDir(clayExe.getDirname()); llvm::sys::Path libDir(clayDir); bool result = libDir.appendComponent("lib-clay"); assert(result); addSearchPath(libDir.str()); if (outputFile.empty()) { if (emitLLVM) outputFile = "a.ll"; else if (emitAsm) outputFile = "a.s"; else outputFile = DEFAULT_EXE; } llvm::sys::RemoveFileOnSignal(llvm::sys::Path(outputFile)); ModulePtr m = loadProgram(clayFile); codegenMain(m); if (optimize) optimizeLLVM(llvmModule); if (emitLLVM || emitAsm) { string errorInfo; llvm::raw_fd_ostream out(outputFile.c_str(), errorInfo, llvm::raw_fd_ostream::F_Binary); if (!errorInfo.empty()) { cerr << "error: " << errorInfo << '\n'; return -1; } if (emitLLVM) generateLLVM(llvmModule, &out); else if (emitAsm) generateAssembly(llvmModule, &out); } else { bool result; llvm::sys::Path gccPath; #ifdef WIN32 gccPath = clayDir; result = gccPath.appendComponent("mingw"); assert(result); result = gccPath.appendComponent("bin"); assert(result); result = gccPath.appendComponent("gcc.exe"); assert(result); if (!gccPath.exists()) gccPath = llvm::sys::Path(); #endif if (!gccPath.isValid()) { gccPath = llvm::sys::Program::FindProgramByName("gcc"); } if (!gccPath.isValid()) { cerr << "error: unable to find gcc on the path\n"; return false; } result = generateExe(llvmModule, outputFile, gccPath); if (!result) return -1; } return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; template <class Simplex> std::string formatSimplex( const Simplex& s ) { std::ostringstream stream; stream << "["; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) stream << ","; stream << *it; } stream << "]"; return stream.str(); } void usage() { std::cerr << "Usage: clique_communities FILE THRESHOLD K\n" << "\n" << "Extracts clique communities from FILE, which is supposed to be\n" << "a weighted graph. In the subsequent calculation, an edge whose\n" << "weight is larger than THRESHOLD will be ignored. K denotes the\n" << "maximum dimension of a simplex for the clique graph extraction\n" << "and the clique community calculation. This does not correspond\n" << "to the dimensionality of the clique. Hence, a parameter of K=2\n" << "will result in calculating 3-clique communities because all of\n" << "the 2-simplices have 3 vertices.\n\n"; } int main( int argc, char** argv ) { if( argc <= 3 ) { usage(); return -1; } std::string filename = argv[1]; double threshold = std::stod( argv[2] ); unsigned maxK = static_cast<unsigned>( std::stoul( argv[3] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- // // TODO: This is copied from the clique persistence diagram // calculation. It would make sense to share some functions // between the two applications. std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; // Thresholding ------------------------------------------------------ { std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "..."; std::vector<Simplex> simplices; std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ), [&threshold] ( const Simplex& s ) { return s.data() > threshold; } ); K = SimplicialComplex( simplices.begin(), simplices.end() ); std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); std::cout << "{\n" << " \"" << threshold << "\": {\n"; for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; auto uf = aleph::topology::calculateConnectedComponents( C ); std::set<VertexType> roots; uf.roots( std::inserter( roots, roots.begin() ) ); std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n"; std::cout << " \"" << (k+1) << "\": [\n"; for( auto&& root : roots ) { // The vertex IDs stored in the Union--Find data structure // correspond to the indices of the simplicial complex. It // thus suffices to map them back. std::set<VertexType> vertices; uf.get( root, std::inserter( vertices, vertices.begin() ) ); std::vector<Simplex> simplices; std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ), [&K] ( VertexType v ) { return K.at(v); } ); std::sort( simplices.begin(), simplices.end() ); std::cout << " ["; for( auto it = simplices.begin(); it != simplices.end(); ++it ) { if( it != simplices.begin() ) std::cout << ","; std::cout << formatSimplex( *it ); } std::cout << " ]"; if( root != *roots.rbegin() ) std::cout << ","; std::cout << "\n"; } std::cout << " ]"; if( k < maxK ) std::cout << " ,"; std::cout << "\n"; } std::cout << " }\n" << "}\n"; } <commit_msg>Minor cosmetic change in JSON output<commit_after>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; template <class Simplex> std::string formatSimplex( const Simplex& s ) { std::ostringstream stream; stream << "["; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) stream << ","; stream << *it; } stream << "]"; return stream.str(); } void usage() { std::cerr << "Usage: clique_communities FILE THRESHOLD K\n" << "\n" << "Extracts clique communities from FILE, which is supposed to be\n" << "a weighted graph. In the subsequent calculation, an edge whose\n" << "weight is larger than THRESHOLD will be ignored. K denotes the\n" << "maximum dimension of a simplex for the clique graph extraction\n" << "and the clique community calculation. This does not correspond\n" << "to the dimensionality of the clique. Hence, a parameter of K=2\n" << "will result in calculating 3-clique communities because all of\n" << "the 2-simplices have 3 vertices.\n\n"; } int main( int argc, char** argv ) { if( argc <= 3 ) { usage(); return -1; } std::string filename = argv[1]; double threshold = std::stod( argv[2] ); unsigned maxK = static_cast<unsigned>( std::stoul( argv[3] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- // // TODO: This is copied from the clique persistence diagram // calculation. It would make sense to share some functions // between the two applications. std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; // Thresholding ------------------------------------------------------ { std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "..."; std::vector<Simplex> simplices; std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ), [&threshold] ( const Simplex& s ) { return s.data() > threshold; } ); K = SimplicialComplex( simplices.begin(), simplices.end() ); std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); std::cout << "{\n" << " \"" << threshold << "\": {\n"; for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; auto uf = aleph::topology::calculateConnectedComponents( C ); std::set<VertexType> roots; uf.roots( std::inserter( roots, roots.begin() ) ); std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n"; std::cout << " \"" << (k+1) << "\": [\n"; for( auto&& root : roots ) { // The vertex IDs stored in the Union--Find data structure // correspond to the indices of the simplicial complex. It // thus suffices to map them back. std::set<VertexType> vertices; uf.get( root, std::inserter( vertices, vertices.begin() ) ); std::vector<Simplex> simplices; std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ), [&K] ( VertexType v ) { return K.at(v); } ); std::sort( simplices.begin(), simplices.end() ); std::cout << " ["; for( auto it = simplices.begin(); it != simplices.end(); ++it ) { if( it != simplices.begin() ) std::cout << ","; std::cout << formatSimplex( *it ); } std::cout << "]"; if( root != *roots.rbegin() ) std::cout << ","; std::cout << "\n"; } std::cout << " ]"; if( k < maxK ) std::cout << " ,"; std::cout << "\n"; } std::cout << " }\n" << "}\n"; } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #ifdef HOST_PYTHON_MODULE #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace py = pybind11; #endif #define MAX_OBJECTS (20) enum TrackingStatus { NEW = 0, /**< The object is newly added. */ TRACKED, /**< The object is being tracked. */ LOST /**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short term and zero term tracking). */ }; typedef struct ImgRoi { int32_t left; int32_t top; int32_t right; int32_t bottom; }ImgRoi; struct Tracklet { ImgRoi roi; int64_t id; int32_t label; int32_t status; private: public: int64_t getId(void){ return id; } int32_t getLabel(void){ return label; } std::string getStatus(void){ std::vector<std::string> status_str = {"NEW", "TRACKED", "LOST"}; if(status < 0 || status > 3) assert(0); return status_str.at(status); } int32_t getLeftCoord(void){ return roi.left; } int32_t getTopCoord(void){ return roi.top; } int32_t getRightCoord(void){ return roi.right; } int32_t getBottomCoord(void){ return roi.bottom; } }; struct ObjectTracker { int nr_tracklets; Tracklet tracklet[MAX_OBJECTS]; private: public: int getNrTracklets(){ assert(nr_tracklets < MAX_OBJECTS); return nr_tracklets; } #ifdef HOST_PYTHON_MODULE py::object getTracklet(int tracklet_nr) { assert(tracklet_nr < nr_tracklets); return py::cast<Tracklet>(tracklet[tracklet_nr]); } #else Tracklet getTracklet(int tracklet_nr) { assert(tracklet_nr < nr_tracklets); return tracklet[tracklet_nr]; } #endif };<commit_msg>Updated object tracker<commit_after>#pragma once #include <cstdint> #ifdef HOST_PYTHON_MODULE #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace py = pybind11; #endif #define MAX_OBJECTS (20) enum TrackingStatus { NEW = 0, /**< The object is newly added. */ TRACKED, /**< The object is being tracked. */ LOST /**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short term and zero term tracking). */ }; typedef struct ImgRoi { int32_t left; int32_t top; int32_t right; int32_t bottom; }ImgRoi; struct Tracklet { ImgRoi roi; int64_t id; int32_t label; int32_t status; private: public: int64_t getId(void){ return id; } int32_t getLabel(void){ return label; } std::string getStatus(void){ std::vector<std::string> status_str = {"NEW", "TRACKED", "LOST"}; if(status < 0 || status > 3) assert(0); return status_str.at(status); } int32_t getLeftCoord(void){ return roi.left; } int32_t getTopCoord(void){ return roi.top; } int32_t getRightCoord(void){ return roi.right; } int32_t getBottomCoord(void){ return roi.bottom; } }; struct ObjectTracker { int nr_tracklets; Tracklet tracklet[MAX_OBJECTS]; private: public: int getNrTracklets(){ assert(nr_tracklets <= MAX_OBJECTS); return nr_tracklets; } #ifdef HOST_PYTHON_MODULE py::object getTracklet(int tracklet_nr) { assert(tracklet_nr < nr_tracklets); return py::cast<Tracklet>(tracklet[tracklet_nr]); } #else Tracklet getTracklet(int tracklet_nr) { assert(tracklet_nr < nr_tracklets); return tracklet[tracklet_nr]; } #endif };<|endoftext|>
<commit_before>#include "dockmanagermodel.h" #include <QString> #include <QMainWindow> #include "dockmanager.h" #include "dock.h" DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data) : TreeModel<DockedInfo>(parent, data) , m_manager(mgr) { qDebug("%s", __FUNCTION__); } DockManagerModel::~DockManagerModel () { qDebug("%s", __FUNCTION__); } QModelIndex DockManagerModel::testItemWithPath (QStringList const & path) { QString const name = path.join("/"); DockedInfo const * i = 0; if (node_t const * node = m_tree_data->is_present(name, i)) return indexFromItem(node); else return QModelIndex(); } QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked) { QString const name = path.join("/"); DockedInfo const * i = 0; node_t const * node = m_tree_data->is_present(name, i); if (node) { //qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str()); return indexFromItem(node); } else { //qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str()); DockedInfo i; i.m_state = checked ? Qt::Checked : Qt::Unchecked; i.m_collapsed = false; //i.m_path = path; node_t * const n = m_tree_data->set_to_state(name, i); QModelIndex const parent_idx = indexFromItem(n->parent); //int const last = n->parent->count_childs() - 1; beginInsertRows(parent_idx, 0, 0); n->data.m_path = path; QModelIndex const idx = indexFromItem(n); endInsertRows(); initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); //QModelIndex const parent_idx = idx.parent(); //if (parent_idx.isValid()) // emit dataChanged(parent_idx, parent_idx); return idx; } } int DockManagerModel::columnCount (QModelIndex const & parent) const { return DockManager::e_max_dockmgr_column; } Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; } /*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const { DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/")); return dwb; } DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) { DockManager * const mgr = static_cast<DockManager *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase * dwb = m_manager.findDockable(p.join("/")); return dwb; }*/ QVariant DockManagerModel::data (QModelIndex const & index, int role) const { if (!index.isValid()) return QVariant(); int const col = index.column(); if (col == DockManager::e_Column_Name) return TreeModel<DockedInfo>::data(index, role); return QVariant(); } bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role) { if (!index.isValid()) return false; if (role == Qt::CheckStateRole) { node_t const * const n = itemFromIndex(index); QStringList const & dst = n->data.m_path; Action a; a.m_type = e_Visibility; a.m_src_path = m_manager.path(); a.m_src = &m_manager; a.m_dst_path = dst; int const state = value.toInt(); a.m_args.push_back(state); m_manager.handleAction(&a, e_Sync); } return TreeModel<DockedInfo>::setData(index, value, role); } bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role) { return TreeModel<DockedInfo>::setData(index, value, role); } <commit_msg>* fixed row insert<commit_after>#include "dockmanagermodel.h" #include <QString> #include <QMainWindow> #include "dockmanager.h" #include "dock.h" DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data) : TreeModel<DockedInfo>(parent, data) , m_manager(mgr) { qDebug("%s", __FUNCTION__); } DockManagerModel::~DockManagerModel () { qDebug("%s", __FUNCTION__); } QModelIndex DockManagerModel::testItemWithPath (QStringList const & path) { QString const name = path.join("/"); DockedInfo const * i = 0; if (node_t const * node = m_tree_data->is_present(name, i)) return indexFromItem(node); else return QModelIndex(); } QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked) { QString const name = path.join("/"); DockedInfo const * i = 0; node_t const * node = m_tree_data->is_present(name, i); if (node) { //qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str()); return indexFromItem(node); } else { //qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str()); DockedInfo i; i.m_state = checked ? Qt::Checked : Qt::Unchecked; i.m_collapsed = false; //i.m_path = path; node_t * const n = m_tree_data->set_to_state(name, i); QModelIndex const parent_idx = indexFromItem(n->parent); int const last = n->parent->count_childs() - 1; beginInsertRows(parent_idx, last, last); n->data.m_path = path; QModelIndex const idx = indexFromItem(n); endInsertRows(); initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); //QModelIndex const parent_idx = idx.parent(); //if (parent_idx.isValid()) // emit dataChanged(parent_idx, parent_idx); return idx; } } int DockManagerModel::columnCount (QModelIndex const & parent) const { return DockManager::e_max_dockmgr_column; } Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; } /*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const { DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/")); return dwb; } DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) { DockManager * const mgr = static_cast<DockManager *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase * dwb = m_manager.findDockable(p.join("/")); return dwb; }*/ QVariant DockManagerModel::data (QModelIndex const & index, int role) const { if (!index.isValid()) return QVariant(); int const col = index.column(); if (col == DockManager::e_Column_Name) return TreeModel<DockedInfo>::data(index, role); return QVariant(); } bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role) { if (!index.isValid()) return false; if (role == Qt::CheckStateRole) { node_t const * const n = itemFromIndex(index); QStringList const & dst = n->data.m_path; Action a; a.m_type = e_Visibility; a.m_src_path = m_manager.path(); a.m_src = &m_manager; a.m_dst_path = dst; int const state = value.toInt(); a.m_args.push_back(state); m_manager.handleAction(&a, e_Sync); } return TreeModel<DockedInfo>::setData(index, value, role); } bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role) { return TreeModel<DockedInfo>::setData(index, value, role); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fstat.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:16: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 * ************************************************************************/ #if defined( WIN) #include <stdio.h> #include <dos.h> #endif #ifdef UNX #include <errno.h> #endif #include <limits.h> #include <string.h> #include "comdep.hxx" #include <fsys.hxx> /************************************************************************* |* |* FileStat::FileStat() |* |* Beschreibung FSYS.SDW |* Ersterstellung MI 11.06.91 |* Letzte Aenderung MI 11.06.91 |* *************************************************************************/ FileStat::FileStat() : // don't use Default-Ctors! aDateCreated( ULONG(0) ), aTimeCreated( ULONG(0) ), aDateModified( ULONG(0) ), aTimeModified( ULONG(0) ), aDateAccessed( ULONG(0) ), aTimeAccessed( ULONG(0) ) { nSize = 0; nKindFlags = FSYS_KIND_UNKNOWN; nError = FSYS_ERR_OK; } /************************************************************************* |* |* FileStat::FileStat() |* |* Beschreibung FSYS.SDW |* Ersterstellung MI 11.06.91 |* Letzte Aenderung MI 11.06.91 |* *************************************************************************/ FileStat::FileStat( const DirEntry& rDirEntry, FSysAccess nAccess ) : // don't use Default-Ctors! aDateCreated( ULONG(0) ), aTimeCreated( ULONG(0) ), aDateModified( ULONG(0) ), aTimeModified( ULONG(0) ), aDateAccessed( ULONG(0) ), aTimeAccessed( ULONG(0) ) { BOOL bCached = FSYS_ACCESS_CACHED == (nAccess & FSYS_ACCESS_CACHED); BOOL bFloppy = FSYS_ACCESS_FLOPPY == (nAccess & FSYS_ACCESS_FLOPPY); #ifdef FEAT_FSYS_DOUBLESPEED const FileStat *pStatFromDir = bCached ? rDirEntry.ImpGetStat() : 0; if ( pStatFromDir ) { nError = pStatFromDir->nError; nKindFlags = pStatFromDir->nKindFlags; nSize = pStatFromDir->nSize; aCreator = pStatFromDir->aCreator; aType = pStatFromDir->aType; aDateCreated = pStatFromDir->aDateCreated; aTimeCreated = pStatFromDir->aTimeCreated; aDateModified = pStatFromDir->aDateModified; aTimeModified = pStatFromDir->aTimeModified; aDateAccessed = pStatFromDir->aDateAccessed; aTimeAccessed = pStatFromDir->aTimeAccessed; } else #endif Update( rDirEntry, bFloppy ); } /************************************************************************* |* |* FileStat::IsYounger() |* |* Beschreibung FSYS.SDW |* Ersterstellung MA 11.11.91 |* Letzte Aenderung MA 11.11.91 |* *************************************************************************/ // TRUE wenn die Instanz j"unger als rIsOlder ist. // FALSE wenn die Instanz "alter oder gleich alt wie rIsOlder ist. BOOL FileStat::IsYounger( const FileStat& rIsOlder ) const { if ( aDateModified > rIsOlder.aDateModified ) return TRUE; if ( ( aDateModified == rIsOlder.aDateModified ) && ( aTimeModified > rIsOlder.aTimeModified ) ) return TRUE; return FALSE; } /************************************************************************* |* |* FileStat::IsKind() |* |* Ersterstellung MA 11.11.91 (?) |* Letzte Aenderung KH 16.01.95 |* *************************************************************************/ BOOL FileStat::IsKind( DirEntryKind nKind ) const { BOOL bRet = ( ( nKind == FSYS_KIND_UNKNOWN ) && ( nKindFlags == FSYS_KIND_UNKNOWN ) ) || ( ( nKindFlags & nKind ) == nKind ); return bRet; } /************************************************************************* |* |* FileStat::HasReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 01.07.98 |* *************************************************************************/ BOOL FileStat::HasReadOnlyFlag() { #if defined(WNT) || defined(OS2) || defined(UNX) return TRUE; #else return FALSE; #endif } /************************************************************************* |* |* FileStat::GetReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 02.07.98 |* *************************************************************************/ BOOL FileStat::GetReadOnlyFlag( const DirEntry &rEntry ) { ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding()); #ifdef WNT DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() ); return ULONG_MAX != nRes && ( FILE_ATTRIBUTE_READONLY & nRes ) == FILE_ATTRIBUTE_READONLY; #endif #ifdef OS2 FILESTATUS3 aFileStat; APIRET nRet = DosQueryPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat) ); switch ( nRet ) { case NO_ERROR: return FILE_READONLY == ( aFileStat.attrFile & FILE_READONLY ); case ERROR_SHARING_VIOLATION: return ERRCODE_IO_LOCKVIOLATION; default: return ERRCODE_IO_NOTEXISTS; } #endif #ifdef UNX /* could we stat the object? */ struct stat aBuf; if (stat(aFPath.GetBuffer(), &aBuf)) return FALSE; /* jupp, is writable for user? */ return((aBuf.st_mode & S_IWUSR) != S_IWUSR); #endif return FALSE; } /************************************************************************* |* |* FileStat::SetReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 01.07.98 |* *************************************************************************/ ULONG FileStat::SetReadOnlyFlag( const DirEntry &rEntry, BOOL bRO ) { ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding()); #ifdef WNT DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() ); if ( ULONG_MAX != nRes ) nRes = SetFileAttributes( (LPCTSTR) aFPath.GetBuffer(), ( nRes & ~FILE_ATTRIBUTE_READONLY ) | ( bRO ? FILE_ATTRIBUTE_READONLY : 0 ) ); return ( ULONG_MAX == nRes ) ? ERRCODE_IO_UNKNOWN : 0; #endif #ifdef OS2 FILESTATUS3 aFileStat; APIRET nRet = DosQueryPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat) ); if ( !nRet ) { aFileStat.attrFile = ( aFileStat.attrFile & ~FILE_READONLY ) | ( bRO ? FILE_READONLY : 0 ); nRet = DosSetPathInfo( (PSZ)aFPath.GetBuffer(), 1, &aFileStat, sizeof(aFileStat), 0 ); } switch ( nRet ) { case NO_ERROR: return ERRCODE_NONE; case ERROR_SHARING_VIOLATION: return ERRCODE_IO_LOCKVIOLATION; default: return ERRCODE_IO_NOTEXISTS; } #endif #ifdef UNX /* first, stat the object to get permissions */ struct stat aBuf; if (stat(aFPath.GetBuffer(), &aBuf)) return ERRCODE_IO_NOTEXISTS; /* set or clear write bit for user */ mode_t nMode; if (bRO) { nMode = aBuf.st_mode & ~S_IWUSR; nMode = aBuf.st_mode & ~S_IWGRP; nMode = aBuf.st_mode & ~S_IWOTH; } else nMode = aBuf.st_mode | S_IWUSR; /* change it on fs */ if (chmod(aFPath.GetBuffer(), nMode)) { switch (errno) { case EPERM : case EROFS : return ERRCODE_IO_ACCESSDENIED; default : return ERRCODE_IO_NOTEXISTS; } } else return ERRCODE_NONE; #endif return ERRCODE_IO_NOTSUPPORTED; } /************************************************************************* |* |* FileStat::SetDateTime |* |* Ersterstellung PB 27.06.97 |* Letzte Aenderung |* *************************************************************************/ #if defined(WIN) | defined(WNT) | defined(OS2) void FileStat::SetDateTime( const String& rFileName, const DateTime& rNewDateTime ) { ByteString aFileName(rFileName, osl_getThreadTextEncoding()); Date aNewDate = rNewDateTime; Time aNewTime = rNewDateTime; #if defined(WIN) unsigned date = 0; unsigned time = 0; date = (unsigned) aNewDate.GetDay(); date |= (unsigned)(aNewDate.GetMonth() << 5); date |= (unsigned)((aNewDate.GetYear() - 1980) << 9); time = (unsigned)(aNewTime.GetSec() / 2); time |= (unsigned)(aNewTime.GetMin() << 5); time |= (unsigned)(aNewTime.GetHour() << 11); FILE* pFile = fopen( aFileName.GetBuffer(), "a" ); if ( pFile != NULL ) { _dos_setftime( fileno(pFile), date, time ); fclose( pFile ); } #elif defined( WNT ) TIME_ZONE_INFORMATION aTZI; DWORD dwTZI = GetTimeZoneInformation( &aTZI ); if ( dwTZI != (DWORD)-1 && dwTZI != TIME_ZONE_ID_UNKNOWN ) { // 1. Korrektur der Zeitzone short nDiff = (short)aTZI.Bias; Time aOldTime = aNewTime; // alte Zeit merken // 2. evt. Korrektur Sommer-/Winterzeit if ( dwTZI == TIME_ZONE_ID_DAYLIGHT ) nDiff += (short)aTZI.DaylightBias; Time aDiff( abs( nDiff / 60 /*Min -> Std*/ ), 0 ); if ( nDiff > 0 ) { aNewTime += aDiff; // Stundenkorrektur // bei "Uberlauf korrigieren if ( aNewTime >= Time( 24, 0 ) ) aNewTime -= Time( 24, 0 ); // Tages"uberlauf? if ( aOldTime == Time( 0, 0 ) || // 00:00 -> 01:00 aNewTime < aOldTime ) // 23:00 -> 00:00 | 01:00 ... aNewDate++; } else if ( nDiff < 0 ) { aNewTime -= aDiff; // Stundenkorrektur // negative Zeit (-1:00) korrigieren: 23:00 if (aNewTime < Time( 0, 0 ) ) aNewTime += Time( 24, 0 ); // Tagesunterlauf ? if ( aOldTime == Time( 0, 0 ) || // 00:00 -> 23:00 aNewTime > aOldTime ) // 01:00 -> 23:00 | 22:00 ... aNewDate--; } } SYSTEMTIME aTime; aTime.wYear = aNewDate.GetYear(); aTime.wMonth = aNewDate.GetMonth(); aTime.wDayOfWeek = 0; aTime.wDay = aNewDate.GetDay(); aTime.wHour = aNewTime.GetHour(); aTime.wMinute = aNewTime.GetMin(); aTime.wSecond = aNewTime.GetSec(); aTime.wMilliseconds = 0; FILETIME aFileTime; SystemTimeToFileTime( &aTime, &aFileTime ); HANDLE hFile = CreateFile( aFileName.GetBuffer(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( hFile != INVALID_HANDLE_VALUE ) { SetFileTime( hFile, &aFileTime, &aFileTime, &aFileTime ); CloseHandle( hFile ); } #endif #ifdef OS2 // open file ULONG nAction = FILE_EXISTED; HFILE hFile = 0; ULONG nFlags = OPEN_FLAGS_WRITE_THROUGH | OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_NO_CACHE | OPEN_FLAGS_RANDOM | OPEN_FLAGS_NOINHERIT | OPEN_SHARE_DENYNONE | OPEN_ACCESS_READWRITE; APIRET nRet = DosOpen((PSZ)aFileName.GetBuffer(), &hFile, (PULONG)&nAction, 0/*size*/, FILE_NORMAL, OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS, nFlags, 0/*ea*/); if ( nRet == 0 ) { FILESTATUS3 FileInfoBuffer; nRet = DosQueryFileInfo( hFile, 1, &FileInfoBuffer, sizeof(FileInfoBuffer)); if ( nRet == 0 ) { FDATE aNewDate; FTIME aNewTime; // create date and time words aNewDate.day = rNewDateTime.GetDay(); aNewDate.month = rNewDateTime.GetMonth(); aNewDate.year = rNewDateTime.GetYear() - 1980; aNewTime.twosecs = rNewDateTime.GetSec() / 2; aNewTime.minutes = rNewDateTime.GetMin(); aNewTime.hours = rNewDateTime.GetHour(); // set file date and time FileInfoBuffer.fdateCreation = aNewDate; FileInfoBuffer.ftimeCreation = aNewTime; FileInfoBuffer.fdateLastAccess = aNewDate; FileInfoBuffer.ftimeLastAccess = aNewTime; FileInfoBuffer.fdateLastWrite = aNewDate; FileInfoBuffer.ftimeLastWrite = aNewTime; DosSetFileInfo(hFile, 1, &FileInfoBuffer, sizeof(FileInfoBuffer)); } DosClose(hFile); } #endif } #endif /* FileStatMembers *FileStat::GetAllMembers() { FileStatMembers *members = new FileStatMembers; members->nError = nError; members->nKindFlags = nKindFlags; members->nSize = nSize; members->aCreator = aCreator; members->aType = aType; members->aDateCreated = aDateCreated.GetDate(); members->aTimeCreated = aTimeCreated.GetTime(); members->aDateAccessed = aDateAccessed.GetDate(); members->aTimeAccessed = aTimeAccessed.GetTime(); members->aDateModified = aDateModified.GetDate(); members->aTimeModified = aTimeModified.GetTime(); return members; } void FileStat::InitMembers(FileStatMembers *members) { nError = members->nError; members->nKindFlags = nKindFlags; members->nSize = nSize; members->aCreator = aCreator; members->aType = aType; aDateCreated.SetDate(members->aDateCreated); aTimeCreated.SetTime(members->aTimeCreated); aDateAccessed.SetDate(members->aDateAccessed); aTimeAccessed.SetTime(members->aTimeAccessed); aDateModified.SetDate(members->aDateModified); aTimeModified.SetTime(members->aTimeModified); } */ <commit_msg>INTEGRATION: CWS warnings01 (1.2.8); FILE MERGED 2006/02/24 14:48:53 sb 1.2.8.3: #i53898# Made code warning-free; removed dead code. 2005/10/14 11:19:33 sb 1.2.8.2: #i53898# Made code warning-free; cleanup. 2005/10/13 13:24:28 sb 1.2.8.1: #i53898# Removed code for obsolete platforms.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fstat.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 13:41:19 $ * * 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 * ************************************************************************/ #if defined( WIN) #include <stdio.h> #include <dos.h> #endif #ifdef UNX #include <errno.h> #endif #include <limits.h> #include <string.h> #include "comdep.hxx" #include <fsys.hxx> /************************************************************************* |* |* FileStat::FileStat() |* |* Beschreibung FSYS.SDW |* Ersterstellung MI 11.06.91 |* Letzte Aenderung MI 11.06.91 |* *************************************************************************/ FileStat::FileStat() : // don't use Default-Ctors! aDateCreated( ULONG(0) ), aTimeCreated( ULONG(0) ), aDateModified( ULONG(0) ), aTimeModified( ULONG(0) ), aDateAccessed( ULONG(0) ), aTimeAccessed( ULONG(0) ) { nSize = 0; nKindFlags = FSYS_KIND_UNKNOWN; nError = FSYS_ERR_OK; } /************************************************************************* |* |* FileStat::FileStat() |* |* Beschreibung FSYS.SDW |* Ersterstellung MI 11.06.91 |* Letzte Aenderung MI 11.06.91 |* *************************************************************************/ FileStat::FileStat( const DirEntry& rDirEntry, FSysAccess nAccess ) : // don't use Default-Ctors! aDateCreated( ULONG(0) ), aTimeCreated( ULONG(0) ), aDateModified( ULONG(0) ), aTimeModified( ULONG(0) ), aDateAccessed( ULONG(0) ), aTimeAccessed( ULONG(0) ) { BOOL bCached = FSYS_ACCESS_CACHED == (nAccess & FSYS_ACCESS_CACHED); BOOL bFloppy = FSYS_ACCESS_FLOPPY == (nAccess & FSYS_ACCESS_FLOPPY); #ifdef FEAT_FSYS_DOUBLESPEED const FileStat *pStatFromDir = bCached ? rDirEntry.ImpGetStat() : 0; if ( pStatFromDir ) { nError = pStatFromDir->nError; nKindFlags = pStatFromDir->nKindFlags; nSize = pStatFromDir->nSize; aCreator = pStatFromDir->aCreator; aType = pStatFromDir->aType; aDateCreated = pStatFromDir->aDateCreated; aTimeCreated = pStatFromDir->aTimeCreated; aDateModified = pStatFromDir->aDateModified; aTimeModified = pStatFromDir->aTimeModified; aDateAccessed = pStatFromDir->aDateAccessed; aTimeAccessed = pStatFromDir->aTimeAccessed; } else #endif Update( rDirEntry, bFloppy ); } /************************************************************************* |* |* FileStat::IsYounger() |* |* Beschreibung FSYS.SDW |* Ersterstellung MA 11.11.91 |* Letzte Aenderung MA 11.11.91 |* *************************************************************************/ // TRUE wenn die Instanz j"unger als rIsOlder ist. // FALSE wenn die Instanz "alter oder gleich alt wie rIsOlder ist. BOOL FileStat::IsYounger( const FileStat& rIsOlder ) const { if ( aDateModified > rIsOlder.aDateModified ) return TRUE; if ( ( aDateModified == rIsOlder.aDateModified ) && ( aTimeModified > rIsOlder.aTimeModified ) ) return TRUE; return FALSE; } /************************************************************************* |* |* FileStat::IsKind() |* |* Ersterstellung MA 11.11.91 (?) |* Letzte Aenderung KH 16.01.95 |* *************************************************************************/ BOOL FileStat::IsKind( DirEntryKind nKind ) const { BOOL bRet = ( ( nKind == FSYS_KIND_UNKNOWN ) && ( nKindFlags == FSYS_KIND_UNKNOWN ) ) || ( ( nKindFlags & nKind ) == nKind ); return bRet; } /************************************************************************* |* |* FileStat::HasReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 01.07.98 |* *************************************************************************/ BOOL FileStat::HasReadOnlyFlag() { #if defined WNT || defined UNX return TRUE; #else return FALSE; #endif } /************************************************************************* |* |* FileStat::GetReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 02.07.98 |* *************************************************************************/ BOOL FileStat::GetReadOnlyFlag( const DirEntry &rEntry ) { ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding()); #if defined WNT DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() ); return ULONG_MAX != nRes && ( FILE_ATTRIBUTE_READONLY & nRes ) == FILE_ATTRIBUTE_READONLY; #elif defined UNX /* could we stat the object? */ struct stat aBuf; if (stat(aFPath.GetBuffer(), &aBuf)) return FALSE; /* jupp, is writable for user? */ return((aBuf.st_mode & S_IWUSR) != S_IWUSR); #else return FALSE; #endif } /************************************************************************* |* |* FileStat::SetReadOnlyFlag() |* |* Ersterstellung MI 06.03.97 |* Letzte Aenderung UT 01.07.98 |* *************************************************************************/ ULONG FileStat::SetReadOnlyFlag( const DirEntry &rEntry, BOOL bRO ) { ByteString aFPath(rEntry.GetFull(), osl_getThreadTextEncoding()); #if defined WNT DWORD nRes = GetFileAttributes( (LPCTSTR) aFPath.GetBuffer() ); if ( ULONG_MAX != nRes ) nRes = SetFileAttributes( (LPCTSTR) aFPath.GetBuffer(), ( nRes & ~FILE_ATTRIBUTE_READONLY ) | ( bRO ? FILE_ATTRIBUTE_READONLY : 0 ) ); return ( ULONG_MAX == nRes ) ? ERRCODE_IO_UNKNOWN : 0; #elif defined UNX /* first, stat the object to get permissions */ struct stat aBuf; if (stat(aFPath.GetBuffer(), &aBuf)) return ERRCODE_IO_NOTEXISTS; /* set or clear write bit for user */ mode_t nMode; if (bRO) { nMode = aBuf.st_mode & ~S_IWUSR; nMode = aBuf.st_mode & ~S_IWGRP; nMode = aBuf.st_mode & ~S_IWOTH; } else nMode = aBuf.st_mode | S_IWUSR; /* change it on fs */ if (chmod(aFPath.GetBuffer(), nMode)) { switch (errno) { case EPERM : case EROFS : return ERRCODE_IO_ACCESSDENIED; default : return ERRCODE_IO_NOTEXISTS; } } else return ERRCODE_NONE; #else return ERRCODE_IO_NOTSUPPORTED; #endif } /************************************************************************* |* |* FileStat::SetDateTime |* |* Ersterstellung PB 27.06.97 |* Letzte Aenderung |* *************************************************************************/ #if defined WNT void FileStat::SetDateTime( const String& rFileName, const DateTime& rNewDateTime ) { ByteString aFileName(rFileName, osl_getThreadTextEncoding()); Date aNewDate = rNewDateTime; Time aNewTime = rNewDateTime; TIME_ZONE_INFORMATION aTZI; DWORD dwTZI = GetTimeZoneInformation( &aTZI ); if ( dwTZI != (DWORD)-1 && dwTZI != TIME_ZONE_ID_UNKNOWN ) { // 1. Korrektur der Zeitzone LONG nDiff = aTZI.Bias; Time aOldTime = aNewTime; // alte Zeit merken // 2. evt. Korrektur Sommer-/Winterzeit if ( dwTZI == TIME_ZONE_ID_DAYLIGHT ) nDiff += aTZI.DaylightBias; Time aDiff( abs( nDiff / 60 /*Min -> Std*/ ), 0 ); if ( nDiff > 0 ) { aNewTime += aDiff; // Stundenkorrektur // bei "Uberlauf korrigieren if ( aNewTime >= Time( 24, 0 ) ) aNewTime -= Time( 24, 0 ); // Tages"uberlauf? if ( aOldTime == Time( 0, 0 ) || // 00:00 -> 01:00 aNewTime < aOldTime ) // 23:00 -> 00:00 | 01:00 ... aNewDate++; } else if ( nDiff < 0 ) { aNewTime -= aDiff; // Stundenkorrektur // negative Zeit (-1:00) korrigieren: 23:00 if (aNewTime < Time( 0, 0 ) ) aNewTime += Time( 24, 0 ); // Tagesunterlauf ? if ( aOldTime == Time( 0, 0 ) || // 00:00 -> 23:00 aNewTime > aOldTime ) // 01:00 -> 23:00 | 22:00 ... aNewDate--; } } SYSTEMTIME aTime; aTime.wYear = aNewDate.GetYear(); aTime.wMonth = aNewDate.GetMonth(); aTime.wDayOfWeek = 0; aTime.wDay = aNewDate.GetDay(); aTime.wHour = aNewTime.GetHour(); aTime.wMinute = aNewTime.GetMin(); aTime.wSecond = aNewTime.GetSec(); aTime.wMilliseconds = 0; FILETIME aFileTime; SystemTimeToFileTime( &aTime, &aFileTime ); HANDLE hFile = CreateFile( aFileName.GetBuffer(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( hFile != INVALID_HANDLE_VALUE ) { SetFileTime( hFile, &aFileTime, &aFileTime, &aFileTime ); CloseHandle( hFile ); } } #endif <|endoftext|>
<commit_before>// Copyright (C) 2017 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. #define USE_LAYOUT 1 #define USE_RENDER 1 #include <sbml/packages/render/sbml/RenderInformationBase.h> #include <sbml/packages/render/sbml/ColorDefinition.h> #include <sbml/packages/render/sbml/GradientBase.h> #include <sbml/packages/render/sbml/LinearGradient.h> #include <sbml/packages/render/sbml/RadialGradient.h> #include <sbml/packages/render/sbml/LineEnding.h> #include "CLRenderInformationBase.h" #include "CLGradientBase.h" #include "CLLinearGradient.h" #include "CLRadialGradient.h" #include "copasi/core/CRootContainer.h" #include "copasi/report/CKeyFactory.h" /** * Constructor. */ CLRenderInformationBase::CLRenderInformationBase(const std::string& name, CDataContainer* pParent): CLBase(), CDataContainer(name, pParent), mKey(""), mName("") { } /** * Copy constructor. */ CLRenderInformationBase::CLRenderInformationBase(const CLRenderInformationBase& source, CDataContainer* pParent): CLBase(source), CDataContainer(source, pParent), mReferenceRenderInformation(source.mReferenceRenderInformation), mBackgroundColor(source.mBackgroundColor), mListOfColorDefinitions(source.mListOfColorDefinitions, this), mListOfGradientDefinitions(source.mListOfGradientDefinitions, this), mListOfLineEndings(source.mListOfLineEndings, this), mKey(""), mName(source.mName) { } /** * Constructor to generate object from the corresponding SBML object. */ CLRenderInformationBase::CLRenderInformationBase(const RenderInformationBase& source, const std::string& name, /* std::map<std::string,std::string>& colorIdToKeyMap, std::map<std::string,std::string>& gradientIdToKeyMap, std::map<std::string,std::string>& lineEndingIdToKeyMap, */ CDataContainer* pParent): CLBase(), CDataContainer(name, pParent), mReferenceRenderInformation(source.getReferenceRenderInformationId()), mBackgroundColor(source.getBackgroundColor()), mKey(""), mName(source.getName()) { size_t i, iMax = source.getNumColorDefinitions(); const ColorDefinition* pCD = NULL; CLColorDefinition* pLCD = NULL; for (i = 0; i < iMax; ++i) { pCD = source.getColorDefinition((unsigned int) i); pLCD = new CLColorDefinition(*pCD); this->mListOfColorDefinitions.add(pLCD, true); //colorIdToKeyMap.insert(std::pair<std::string,std::string>(pCD->getId(),pLCD->getKey())); } const GradientBase* pGD = NULL; CLGradientBase* pLGD = NULL; iMax = source.getNumGradientDefinitions(); for (i = 0; i < iMax; ++i) { pGD = source.getGradientDefinition((unsigned int) i); if (dynamic_cast<const LinearGradient*>(pGD)) { pLGD = new CLLinearGradient(*static_cast<const LinearGradient*>(pGD)); this->mListOfGradientDefinitions.add(pLGD, true); } else if (dynamic_cast<const RadialGradient*>(source.getGradientDefinition((unsigned int) i))) { pLGD = new CLRadialGradient(*static_cast<const RadialGradient*>(pGD)); this->mListOfGradientDefinitions.add(pLGD, true); } //gradientIdToKeyMap.insert(std::pair<std::string,std::string>(pGD->getId(),pLGD->getKey())); } const LineEnding* pLE = NULL; CLLineEnding* pLLE = NULL; iMax = source.getNumLineEndings(); for (i = 0; i < iMax; ++i) { pLE = source.getLineEnding((unsigned int) i); pLLE = new CLLineEnding(*pLE); this->mListOfLineEndings.add(pLLE, true); //lineEndingIdToKeyMap.insert(std::pair<std::string,std::string>(pLE->getId(),pLLE->getKey())); } } /** * Destructor */ CLRenderInformationBase::~CLRenderInformationBase() { CRootContainer::getKeyFactory()->remove(this->mKey); } /** * Returns the id of the referenced render information object.. */ const std::string& CLRenderInformationBase::getReferenceRenderInformationKey() const { return this->mReferenceRenderInformation; } /** * Sets the id of the referenced render information object. */ void CLRenderInformationBase::setReferenceRenderInformationKey(const std::string& key) { this->mReferenceRenderInformation = key; } /** * Returns the number of color definitions. */ size_t CLRenderInformationBase::getNumColorDefinitions() const { return this->mListOfColorDefinitions.size(); } /** * Returns a pointer to the list of color definitions. */ CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() { return &(this->mListOfColorDefinitions); } /** * Returns a const pointer to the list of color definitions. */ const CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() const { return &(this->mListOfColorDefinitions); } /** * Returns a pointer to the color definition with the given index, or NULL *if the index is invalid. */ CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) { return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL; } /** * Returns a const pointer to the color definition with the given index, or NULL *if the index is invalid. */ const CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) const { return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL; } /** * Creates a new color definition. */ CLColorDefinition* CLRenderInformationBase::createColorDefinition() { CLColorDefinition* pCD = new CLColorDefinition(); this->mListOfColorDefinitions.add(pCD, true); return pCD; } /** * Removes the color definition with the given index. */ void CLRenderInformationBase::removeColorDefinition(size_t index) { if (index < this->mListOfColorDefinitions.size()) { this->mListOfColorDefinitions.remove(index); } } /** * Adds a copy of the given color definition to the end of the list of * color definitions. */ void CLRenderInformationBase::addColorDefinition(const CLColorDefinition* pCD) { this->mListOfColorDefinitions.add(new CLColorDefinition(*pCD), true); } /** * Returns the number of gradient definitions. */ size_t CLRenderInformationBase::getNumGradientDefinitions() const { return this->mListOfGradientDefinitions.size(); } /** * Returns a pointer to the list of gradient definitions. */ CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() { return &(this->mListOfGradientDefinitions); } /** * Returns a const pointer to the list of gradient definitions. */ const CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() const { return &(this->mListOfGradientDefinitions); } /** * Returns a pointer to the gradient definition with the given index, or NULL *if the index is invalid. */ CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) { return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL; } /** * Returns a const pointer to the gradient definition with the given index, or NULL *if the index is invalid. */ const CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) const { return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL; } /** * Creates a new radial gradient definition. */ CLRadialGradient* CLRenderInformationBase::createRadialGradientDefinition() { CLRadialGradient* pRG = new CLRadialGradient(); this->mListOfGradientDefinitions.add(pRG, true); return pRG; } /** * Creates a new linear gradient definition. */ CLLinearGradient* CLRenderInformationBase::createLinearGradientDefinition() { CLLinearGradient* pLG = new CLLinearGradient(); this->mListOfGradientDefinitions.add(pLG, true); return pLG; } /** * Removes the gradient definition with the given index. */ void CLRenderInformationBase::removeGradientDefinition(size_t index) { if (index < this->mListOfGradientDefinitions.size()) { this->mListOfGradientDefinitions.remove(index); } } /** * Adds a copy of the given gradient definition to the end of the list of * gradient definitions. */ void CLRenderInformationBase::addGradientDefinition(const CLGradientBase* pGradient) { if (dynamic_cast<const CLLinearGradient*>(pGradient)) { this->mListOfGradientDefinitions.add(new CLLinearGradient(*static_cast<const CLLinearGradient*>(pGradient)), true); } else if (dynamic_cast<const CLRadialGradient*>(pGradient)) { this->mListOfGradientDefinitions.add(new CLRadialGradient(*static_cast<const CLRadialGradient*>(pGradient)), true); } } /** * Returns the number of line endings. */ size_t CLRenderInformationBase::getNumLineEndings() const { return this->mListOfLineEndings.size(); } /** * Returns a pointer to the list of line endings. */ CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() { return &(this->mListOfLineEndings); } /** * Returns a const pointer to the list of line endings. */ const CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() const { return &(this->mListOfLineEndings); } /** * Returns a pointer to the line ending with the given index, or NULL *if the index is invalid. */ CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) { return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL; } /** * Returns a const pointer to the line ending with the given index, or NULL *if the index is invalid. */ const CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) const { return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL; } /** * Creates a new line ending. */ CLLineEnding* CLRenderInformationBase::createLineEnding() { CLLineEnding* pLE = new CLLineEnding(); this->mListOfLineEndings.add(pLE, true); return pLE; } /** * Removes the line ending with the given index. */ void CLRenderInformationBase::removeLineEnding(size_t index) { if (index < this->mListOfLineEndings.size()) { this->mListOfLineEndings.remove(index); } } /** * Adds a copy of the given line ending to the end of the list of line *endings. */ void CLRenderInformationBase::addLineEnding(const CLLineEnding* pLE) { this->mListOfLineEndings.add(new CLLineEnding(*pLE), true); } const std::string& CLRenderInformationBase::getBackgroundColor() const { return mBackgroundColor; } void CLRenderInformationBase::setBackgroundColor(const std::string& bg) { this->mBackgroundColor = bg; } /** * Returns the key of the color definition. */ const std::string& CLRenderInformationBase::getKey() const { return this->mKey; } /** * Adds the attributes for a graphical primitive 1D object to the passed in. * object. */ void CLRenderInformationBase::addSBMLAttributes(RenderInformationBase* pBase /* ,std::map<std::string,std::string>& colorKeyToIdMap ,std::map<std::string,std::string>& gradientKeyToIdMap ,std::map<std::string,std::string>& lineEndingKeyToIdMap */ ) const { pBase->setReferenceRenderInformationId(this->getReferenceRenderInformationKey()); pBase->setBackgroundColor(this->getBackgroundColor()); pBase->setId(getKey()); if (!mName.empty()) { pBase->setName(mName); } size_t i, iMax = this->mListOfColorDefinitions.size(); int result; unsigned int level = pBase->getLevel(); unsigned int version = pBase->getVersion(); for (i = 0; i < iMax; ++i) { ColorDefinition* pCD = this->getColorDefinition(i)->toSBML(level, version); result = pBase->addColorDefinition(pCD); assert(result == LIBSBML_OPERATION_SUCCESS); //colorKeyToIdMap.insert(std::pair<std::string,std::string>(this->getColorDefinition(i)->getKey(),pCD->getId())); delete pCD; } iMax = this->mListOfGradientDefinitions.size(); GradientBase* pGB = NULL; const CLGradientBase* pLGB = NULL; for (i = 0; i < iMax; ++i) { pLGB = this->getGradientDefinition(i); if (dynamic_cast<const CLRadialGradient*>(pLGB)) { pGB = static_cast<const CLRadialGradient*>(pLGB)->toSBML(level, version); } else { pGB = static_cast<const CLLinearGradient*>(pLGB)->toSBML(level, version); } result = pBase->addGradientDefinition(pGB); assert(result == LIBSBML_OPERATION_SUCCESS); //gradientKeyToIdMap.insert(std::pair<std::string,std::string>(pLGB->getKey(),pGB->getId())); delete pGB; } iMax = this->mListOfLineEndings.size(); for (i = 0; i < iMax; ++i) { const CLLineEnding* lineEnding = this->getLineEnding(i); LineEnding* pLE = lineEnding->toSBML(level, version); result = pBase->addLineEnding(pLE); assert(result == LIBSBML_OPERATION_SUCCESS); //lineEndingKeyToIdMap.insert(std::pair<std::string,std::string>(this->getLineEnding(i)->getKey(),pLE->getId())); delete pLE; } } /** * Sets the name of the object. */ void CLRenderInformationBase::setName(const std::string& name) { this->mName = name; } /** * Returns the name of the object. */ const std::string& CLRenderInformationBase::getName() const { return this->mName; } <commit_msg>- issue 2572: create a bounding box when none exists before reading<commit_after>// 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. #define USE_LAYOUT 1 #define USE_RENDER 1 #include <sbml/packages/render/sbml/RenderInformationBase.h> #include <sbml/packages/render/sbml/ColorDefinition.h> #include <sbml/packages/render/sbml/GradientBase.h> #include <sbml/packages/render/sbml/LinearGradient.h> #include <sbml/packages/render/sbml/RadialGradient.h> #include <sbml/packages/render/sbml/LineEnding.h> #include "CLRenderInformationBase.h" #include "CLGradientBase.h" #include "CLLinearGradient.h" #include "CLRadialGradient.h" #include "copasi/core/CRootContainer.h" #include "copasi/report/CKeyFactory.h" /** * Constructor. */ CLRenderInformationBase::CLRenderInformationBase(const std::string& name, CDataContainer* pParent): CLBase(), CDataContainer(name, pParent), mKey(""), mName("") { } /** * Copy constructor. */ CLRenderInformationBase::CLRenderInformationBase(const CLRenderInformationBase& source, CDataContainer* pParent): CLBase(source), CDataContainer(source, pParent), mReferenceRenderInformation(source.mReferenceRenderInformation), mBackgroundColor(source.mBackgroundColor), mListOfColorDefinitions(source.mListOfColorDefinitions, this), mListOfGradientDefinitions(source.mListOfGradientDefinitions, this), mListOfLineEndings(source.mListOfLineEndings, this), mKey(""), mName(source.mName) { } /** * Constructor to generate object from the corresponding SBML object. */ CLRenderInformationBase::CLRenderInformationBase(const RenderInformationBase& source, const std::string& name, /* std::map<std::string,std::string>& colorIdToKeyMap, std::map<std::string,std::string>& gradientIdToKeyMap, std::map<std::string,std::string>& lineEndingIdToKeyMap, */ CDataContainer* pParent): CLBase(), CDataContainer(name, pParent), mReferenceRenderInformation(source.getReferenceRenderInformationId()), mBackgroundColor(source.getBackgroundColor()), mKey(""), mName(source.getName()) { size_t i, iMax = source.getNumColorDefinitions(); const ColorDefinition* pCD = NULL; CLColorDefinition* pLCD = NULL; for (i = 0; i < iMax; ++i) { pCD = source.getColorDefinition((unsigned int) i); pLCD = new CLColorDefinition(*pCD); this->mListOfColorDefinitions.add(pLCD, true); //colorIdToKeyMap.insert(std::pair<std::string,std::string>(pCD->getId(),pLCD->getKey())); } const GradientBase* pGD = NULL; CLGradientBase* pLGD = NULL; iMax = source.getNumGradientDefinitions(); for (i = 0; i < iMax; ++i) { pGD = source.getGradientDefinition((unsigned int) i); if (dynamic_cast<const LinearGradient*>(pGD)) { pLGD = new CLLinearGradient(*static_cast<const LinearGradient*>(pGD)); this->mListOfGradientDefinitions.add(pLGD, true); } else if (dynamic_cast<const RadialGradient*>(source.getGradientDefinition((unsigned int) i))) { pLGD = new CLRadialGradient(*static_cast<const RadialGradient*>(pGD)); this->mListOfGradientDefinitions.add(pLGD, true); } //gradientIdToKeyMap.insert(std::pair<std::string,std::string>(pGD->getId(),pLGD->getKey())); } const LineEnding* pLE = NULL; CLLineEnding* pLLE = NULL; iMax = source.getNumLineEndings(); for (i = 0; i < iMax; ++i) { pLE = source.getLineEnding((unsigned int) i); #if LIBSBML_VERSION > 51600 if (!pLE->isSetBoundingBox()) const_cast<LineEnding*>(pLE)->createBoundingBox(); #endif pLLE = new CLLineEnding(*pLE); this->mListOfLineEndings.add(pLLE, true); //lineEndingIdToKeyMap.insert(std::pair<std::string,std::string>(pLE->getId(),pLLE->getKey())); } } /** * Destructor */ CLRenderInformationBase::~CLRenderInformationBase() { CRootContainer::getKeyFactory()->remove(this->mKey); } /** * Returns the id of the referenced render information object.. */ const std::string& CLRenderInformationBase::getReferenceRenderInformationKey() const { return this->mReferenceRenderInformation; } /** * Sets the id of the referenced render information object. */ void CLRenderInformationBase::setReferenceRenderInformationKey(const std::string& key) { this->mReferenceRenderInformation = key; } /** * Returns the number of color definitions. */ size_t CLRenderInformationBase::getNumColorDefinitions() const { return this->mListOfColorDefinitions.size(); } /** * Returns a pointer to the list of color definitions. */ CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() { return &(this->mListOfColorDefinitions); } /** * Returns a const pointer to the list of color definitions. */ const CDataVector<CLColorDefinition>* CLRenderInformationBase::getListOfColorDefinitions() const { return &(this->mListOfColorDefinitions); } /** * Returns a pointer to the color definition with the given index, or NULL *if the index is invalid. */ CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) { return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL; } /** * Returns a const pointer to the color definition with the given index, or NULL *if the index is invalid. */ const CLColorDefinition* CLRenderInformationBase::getColorDefinition(size_t index) const { return (index < this->mListOfColorDefinitions.size()) ? &this->mListOfColorDefinitions[index] : NULL; } /** * Creates a new color definition. */ CLColorDefinition* CLRenderInformationBase::createColorDefinition() { CLColorDefinition* pCD = new CLColorDefinition(); this->mListOfColorDefinitions.add(pCD, true); return pCD; } /** * Removes the color definition with the given index. */ void CLRenderInformationBase::removeColorDefinition(size_t index) { if (index < this->mListOfColorDefinitions.size()) { this->mListOfColorDefinitions.remove(index); } } /** * Adds a copy of the given color definition to the end of the list of * color definitions. */ void CLRenderInformationBase::addColorDefinition(const CLColorDefinition* pCD) { this->mListOfColorDefinitions.add(new CLColorDefinition(*pCD), true); } /** * Returns the number of gradient definitions. */ size_t CLRenderInformationBase::getNumGradientDefinitions() const { return this->mListOfGradientDefinitions.size(); } /** * Returns a pointer to the list of gradient definitions. */ CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() { return &(this->mListOfGradientDefinitions); } /** * Returns a const pointer to the list of gradient definitions. */ const CDataVector<CLGradientBase>* CLRenderInformationBase::getListOfGradientDefinitions() const { return &(this->mListOfGradientDefinitions); } /** * Returns a pointer to the gradient definition with the given index, or NULL *if the index is invalid. */ CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) { return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL; } /** * Returns a const pointer to the gradient definition with the given index, or NULL *if the index is invalid. */ const CLGradientBase* CLRenderInformationBase::getGradientDefinition(size_t index) const { return (index < this->mListOfGradientDefinitions.size()) ? &this->mListOfGradientDefinitions[index] : NULL; } /** * Creates a new radial gradient definition. */ CLRadialGradient* CLRenderInformationBase::createRadialGradientDefinition() { CLRadialGradient* pRG = new CLRadialGradient(); this->mListOfGradientDefinitions.add(pRG, true); return pRG; } /** * Creates a new linear gradient definition. */ CLLinearGradient* CLRenderInformationBase::createLinearGradientDefinition() { CLLinearGradient* pLG = new CLLinearGradient(); this->mListOfGradientDefinitions.add(pLG, true); return pLG; } /** * Removes the gradient definition with the given index. */ void CLRenderInformationBase::removeGradientDefinition(size_t index) { if (index < this->mListOfGradientDefinitions.size()) { this->mListOfGradientDefinitions.remove(index); } } /** * Adds a copy of the given gradient definition to the end of the list of * gradient definitions. */ void CLRenderInformationBase::addGradientDefinition(const CLGradientBase* pGradient) { if (dynamic_cast<const CLLinearGradient*>(pGradient)) { this->mListOfGradientDefinitions.add(new CLLinearGradient(*static_cast<const CLLinearGradient*>(pGradient)), true); } else if (dynamic_cast<const CLRadialGradient*>(pGradient)) { this->mListOfGradientDefinitions.add(new CLRadialGradient(*static_cast<const CLRadialGradient*>(pGradient)), true); } } /** * Returns the number of line endings. */ size_t CLRenderInformationBase::getNumLineEndings() const { return this->mListOfLineEndings.size(); } /** * Returns a pointer to the list of line endings. */ CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() { return &(this->mListOfLineEndings); } /** * Returns a const pointer to the list of line endings. */ const CDataVector<CLLineEnding>* CLRenderInformationBase::getListOfLineEndings() const { return &(this->mListOfLineEndings); } /** * Returns a pointer to the line ending with the given index, or NULL *if the index is invalid. */ CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) { return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL; } /** * Returns a const pointer to the line ending with the given index, or NULL *if the index is invalid. */ const CLLineEnding* CLRenderInformationBase::getLineEnding(size_t index) const { return (index < this->mListOfLineEndings.size()) ? &this->mListOfLineEndings[index] : NULL; } /** * Creates a new line ending. */ CLLineEnding* CLRenderInformationBase::createLineEnding() { CLLineEnding* pLE = new CLLineEnding(); this->mListOfLineEndings.add(pLE, true); return pLE; } /** * Removes the line ending with the given index. */ void CLRenderInformationBase::removeLineEnding(size_t index) { if (index < this->mListOfLineEndings.size()) { this->mListOfLineEndings.remove(index); } } /** * Adds a copy of the given line ending to the end of the list of line *endings. */ void CLRenderInformationBase::addLineEnding(const CLLineEnding* pLE) { this->mListOfLineEndings.add(new CLLineEnding(*pLE), true); } const std::string& CLRenderInformationBase::getBackgroundColor() const { return mBackgroundColor; } void CLRenderInformationBase::setBackgroundColor(const std::string& bg) { this->mBackgroundColor = bg; } /** * Returns the key of the color definition. */ const std::string& CLRenderInformationBase::getKey() const { return this->mKey; } /** * Adds the attributes for a graphical primitive 1D object to the passed in. * object. */ void CLRenderInformationBase::addSBMLAttributes(RenderInformationBase* pBase /* ,std::map<std::string,std::string>& colorKeyToIdMap ,std::map<std::string,std::string>& gradientKeyToIdMap ,std::map<std::string,std::string>& lineEndingKeyToIdMap */ ) const { pBase->setReferenceRenderInformationId(this->getReferenceRenderInformationKey()); pBase->setBackgroundColor(this->getBackgroundColor()); pBase->setId(getKey()); if (!mName.empty()) { pBase->setName(mName); } size_t i, iMax = this->mListOfColorDefinitions.size(); int result; unsigned int level = pBase->getLevel(); unsigned int version = pBase->getVersion(); for (i = 0; i < iMax; ++i) { ColorDefinition* pCD = this->getColorDefinition(i)->toSBML(level, version); result = pBase->addColorDefinition(pCD); assert(result == LIBSBML_OPERATION_SUCCESS); //colorKeyToIdMap.insert(std::pair<std::string,std::string>(this->getColorDefinition(i)->getKey(),pCD->getId())); delete pCD; } iMax = this->mListOfGradientDefinitions.size(); GradientBase* pGB = NULL; const CLGradientBase* pLGB = NULL; for (i = 0; i < iMax; ++i) { pLGB = this->getGradientDefinition(i); if (dynamic_cast<const CLRadialGradient*>(pLGB)) { pGB = static_cast<const CLRadialGradient*>(pLGB)->toSBML(level, version); } else { pGB = static_cast<const CLLinearGradient*>(pLGB)->toSBML(level, version); } result = pBase->addGradientDefinition(pGB); assert(result == LIBSBML_OPERATION_SUCCESS); //gradientKeyToIdMap.insert(std::pair<std::string,std::string>(pLGB->getKey(),pGB->getId())); delete pGB; } iMax = this->mListOfLineEndings.size(); for (i = 0; i < iMax; ++i) { const CLLineEnding* lineEnding = this->getLineEnding(i); LineEnding* pLE = lineEnding->toSBML(level, version); result = pBase->addLineEnding(pLE); assert(result == LIBSBML_OPERATION_SUCCESS); //lineEndingKeyToIdMap.insert(std::pair<std::string,std::string>(this->getLineEnding(i)->getKey(),pLE->getId())); delete pLE; } } /** * Sets the name of the object. */ void CLRenderInformationBase::setName(const std::string& name) { this->mName = name; } /** * Returns the name of the object. */ const std::string& CLRenderInformationBase::getName() const { return this->mName; } <|endoftext|>
<commit_before>#include "renderer-pre.hpp" namespace col { PixFont FontTiny; using ResMap = std::unordered_map<ResKey, Texture>; ResMap res_map; ResKey make_reskey(ResCat cat, ResNum num) { return (ResKey(cat) << 16) | ResKey(num); } ResCat get_rescat(ResKey k) { return k >> 16; } ResNum get_resnum(ResKey k) { return (k << 16) >> 16; } Path get_res_dir(ResCat cat) { // categories, *xxx* -- generated to memory image switch (cat) { case TERR: return "TERRAIN_SS"; case ICON: return "ICONS_SS"; case PHYS: return "PHYS0_SS"; case ARCH: return "PARCH_SS"; case COLONY: return "COLONY_PIK"; case BUILD: return "BUILDING_SS"; case WOODTILE: return "WOODTILE_SS"; case DIFFUSE: return "*DIFFUSE*"; case COAST: return "*COAST*"; case ZZ: return "ZZ"; } fail("unknown resource category: %||\n", cat); } Path get_res_path(ResCat cat, ResNum num) { return conf.tile_path / get_res_dir(cat) / format("%|03|.png", num); } Path get_res_path_key(ResKey key) { return get_res_path(get_rescat(key), get_resnum(key)); } // Get resource from global cache (load on demand) Texture const& res(Front & fr, ResCat cat, ResNum num) { auto key = make_reskey(cat, num); auto p = res_map.find(key); if (p != res_map.end()) { return (*p).second; } else { auto path = get_res_path(cat, num); auto & img = res_map[key]; img = fr.make_texture(path); return img; } } void preload(ResCat cat, ResNum num, Texture && tex) { auto key = make_reskey(cat, num); res_map[key] = std::move(tex); } Image replace_black(Image const& inn, Image const& tex, v2s toff) { /* Create new surface mask colors meaning: black -> take from tex else -> take from mask toff -- tex offset vector */ //print("replace_black: %|| + %|| <- %||\n", inn.dim, toff, tex.dim); auto dim = inn.get_dim(); auto out = Image(dim); for (int j = 0; j < dim[1]; ++j) { for (int i = 0; i < dim[0]; ++i) { auto c = inn({i,j}); auto pos = v2s(i,j); //print("c = %||\n", c); if (c.a == 0) { out(pos) = Color(0,0,0,0); } else if (c == Color(0,0,0,255)) { out(pos) = tex(toff + pos); } else { out(pos) = inn(pos); } } } return out; } //void render_fields(Front &win, Env const& env, Console const& con, // v2s pix, Coords const& pos); v2s get_loffset(int l) { switch(l){ case 0: return v2s(0,0) * ly.scale; case 1: return v2s(8,0) * ly.scale; case 2: return v2s(8,8) * ly.scale; case 3: return v2s(0,8) * ly.scale; } fail("invalid 'l'"); } Texture make_combined_texture( Front & fr, std::pair<ResCat, ResNum> p, std::pair<ResCat, ResNum> b, v2s off ) { auto p_img = front::load_png( get_res_path(p.first, p.second) ); auto b_img = front::load_png( get_res_path(b.first, b.second) ); auto surf = replace_black(p_img, b_img, off); return fr.make_texture(surf); } void preload_coast(Front & fr, Biome bio, int start) { for (int k = 0; k < 8; ++k) { for (int l = 0; l < 4; ++l) { int ind = (k<<2) + l; preload(COAST, start + ind, make_combined_texture(fr, {PHYS, 109+ind}, {TERR, bio}, get_loffset(l) ) ); } } } int const TextureOceanId = 11; int const TextureSeaLaneId = 11; void preload_coast(Front & back) { // 109 - 140 preload_coast(back, TextureOceanId, 0); preload_coast(back, TextureSeaLaneId, 50); } void preload_terrain(Front & fr) { for (int i=1; i<13; ++i) { preload(DIFFUSE, 0+i, make_combined_texture(fr, {PHYS, 105}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 50+i, make_combined_texture(fr, {PHYS, 106}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 100+i, make_combined_texture(fr, {PHYS, 107}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 150+i, make_combined_texture(fr, {PHYS, 108}, {TERR, i}, {0,0}) ); } preload_coast(fr); } void preload_renderer(Front & fr) { preload_terrain(fr); FontTiny.load(fr, conf.font_tiny_path, -1 * ly.scale); } } <commit_msg>preload<commit_after>#include "renderer-pre.hpp" namespace col { PixFont FontTiny; using ResMap = std::unordered_map<ResKey, Texture>; ResMap res_map; ResKey make_reskey(ResCat cat, ResNum num) { return (ResKey(cat) << 16) | ResKey(num); } ResCat get_rescat(ResKey k) { return k >> 16; } ResNum get_resnum(ResKey k) { return (k << 16) >> 16; } Path get_res_dir(ResCat cat) { // categories, *xxx* -- generated to memory image switch (cat) { case TERR: return "TERRAIN_SS"; case ICON: return "ICONS_SS"; case PHYS: return "PHYS0_SS"; case ARCH: return "PARCH_SS"; case COLONY: return "COLONY_PIK"; case BUILD: return "BUILDING_SS"; case WOODTILE: return "WOODTILE_SS"; case DIFFUSE: return "*DIFFUSE*"; case COAST: return "*COAST*"; case ZZ: return "ZZ"; } fail("unknown resource category: %||\n", cat); } Path get_res_path(ResCat cat, ResNum num) { return conf.tile_path / get_res_dir(cat) / format("%|03|.png", num); } Path get_res_path_key(ResKey key) { return get_res_path(get_rescat(key), get_resnum(key)); } // Get resource from global cache (load on demand) Texture const& res(Front & fr, ResCat cat, ResNum num) { //print("res %|d| %|d|\n", cat, num); auto key = make_reskey(cat, num); auto p = res_map.find(key); if (p != res_map.end()) { return (*p).second; } else { auto path = get_res_path(cat, num); auto & img = res_map[key]; img = fr.make_texture(path); return img; } } void preload(ResCat cat, ResNum num, Texture && tex) { auto key = make_reskey(cat, num); res_map[key] = std::move(tex); } Image replace_black(Image const& inn, Image const& tex, v2s toff) { /* Create new surface mask colors meaning: black -> take from tex else -> take from mask toff -- tex offset vector */ //print("replace_black: %|| + %|| <- %||\n", inn.dim, toff, tex.dim); auto dim = inn.get_dim(); auto out = Image(dim); for (int16_t j = 0; j < dim[1]; ++j) { for (int16_t i = 0; i < dim[0]; ++i) { auto c = inn({i,j}); auto pos = v2s(i,j); //print("c = %||\n", c); if (c.a == 0) { out(pos) = Color(0,0,0,0); } else if (c == Color(0,0,0,255)) { out(pos) = tex(toff + pos); } else { out(pos) = inn(pos); } } } return out; } //void render_fields(Front &win, Env const& env, Console const& con, // v2s pix, Coords const& pos); v2s get_loffset(int l) { switch(l){ case 0: return v2s(0,0) * ly.scale; case 1: return v2s(8,0) * ly.scale; case 2: return v2s(8,8) * ly.scale; case 3: return v2s(0,8) * ly.scale; } fail("invalid 'l'"); } Texture make_combined_texture( Front & fr, std::pair<ResCat, ResNum> p, std::pair<ResCat, ResNum> b, v2s off ) { auto p_img = front::load_png( get_res_path(p.first, p.second) ); auto b_img = front::load_png( get_res_path(b.first, b.second) ); auto surf = replace_black(p_img, b_img, off); return fr.make_texture(surf); } void preload_coast(Front & fr, Biome bio, int start) { for (int k = 0; k < 8; ++k) { for (int l = 0; l < 4; ++l) { int ind = (k<<2) + l; preload(COAST, start + ind, make_combined_texture(fr, {PHYS, 109+ind}, {TERR, bio}, get_loffset(l) ) ); } } } int const TextureOceanId = 11; int const TextureSeaLaneId = 11; void preload_coast(Front & back) { // 109 - 140 preload_coast(back, TextureOceanId, 0); preload_coast(back, TextureSeaLaneId, 50); } void preload_terrain(Front & fr) { for (int i=1; i<13; ++i) { // TODO: skip if file not exists if (i == 9 or i == 12) { continue; } preload(DIFFUSE, 0+i, make_combined_texture(fr, {PHYS, 105}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 50+i, make_combined_texture(fr, {PHYS, 106}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 100+i, make_combined_texture(fr, {PHYS, 107}, {TERR, i}, {0,0}) ); preload(DIFFUSE, 150+i, make_combined_texture(fr, {PHYS, 108}, {TERR, i}, {0,0}) ); } preload_coast(fr); } void preload_renderer(Front & fr) { preload_terrain(fr); FontTiny.load(fr, conf.font_tiny_path, -1 * ly.scale); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadImplementationsRegister.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight 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. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkVisitorDispatcher.h" #include "itkFEMLoadPoint.h" #include "itkFEMLoadGrav.h" #include "itkFEMLoadEdge.h" #include "itkFEMLoadLandmark.h" #include "itkFEMLoadImplementationGenericBodyLoad.h" #include "itkFEMLoadImplementationGenericLandmarkLoad.h" #include "itkFEMElement2DC0LinearLineStress.h" #include "itkFEMElement2DC1Beam.h" #include "itkFEMElement2DC0LinearTriangularStress.h" #include "itkFEMElement2DC0LinearQuadrilateralStress.h" #include "itkFEMElement2DC0LinearQuadrilateralMembrane.h" #include "itkFEMElement3DC0LinearTetrahedronStrain.h" #include "itkFEMElement3DC0LinearHexahedronStrain.h" namespace itk { namespace fem { /* This macro makes registering Load implementations easier. */ #define REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) \ VisitorDispatcher<ElementClass, ElementClass::LoadType, ElementClass::LoadImplementationFunctionPointer> \ ::RegisterVisitor((LoadClass*)0, &FunctionName); /* Use this macro to also automatically declare load implementation function. */ #define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \ extern void FunctionName(ElementClass::ConstPointer, ElementClass::LoadPointer, ElementClass::VectorType& ); \ REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) /** * Registers all Load classes in the FEM library with VisitorDispatcher. * This function must be called before the FEM library is functional!. */ void LoadImplementationsRegister(void) { // Loads acting on LineStress element REGISTER_LOAD_EX(Element2DC0LinearLineStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); // Loads acting on Beam element REGISTER_LOAD_EX(Element2DC1Beam,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); // Loads acting on QuadrilateralStress element REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on QuadrilateralMembrane element REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on TriangularStress element REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on HexahedronStrain element REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on TetrahedronStrain element REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Add any additional loads here in a similar fashion... // Make sure that the pointer to the visit function is the correct one!!! } }} // end namespace itk::fem <commit_msg>adding new membrane elements to cmakelists<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadImplementationsRegister.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight 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. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkVisitorDispatcher.h" #include "itkFEMLoadPoint.h" #include "itkFEMLoadGrav.h" #include "itkFEMLoadEdge.h" #include "itkFEMLoadLandmark.h" #include "itkFEMLoadImplementationGenericBodyLoad.h" #include "itkFEMLoadImplementationGenericLandmarkLoad.h" #include "itkFEMElement2DC0LinearLineStress.h" #include "itkFEMElement2DC1Beam.h" #include "itkFEMElement2DC0LinearTriangularStress.h" #include "itkFEMElement2DC0LinearTriangularMembrane.h" #include "itkFEMElement2DC0LinearQuadrilateralStress.h" #include "itkFEMElement2DC0LinearQuadrilateralMembrane.h" #include "itkFEMElement3DC0LinearTetrahedronStrain.h" #include "itkFEMElement3DC0LinearHexahedronStrain.h" #include "itkFEMElement3DC0LinearTetrahedronMembrane.h" #include "itkFEMElement3DC0LinearHexahedronMembrane.h" namespace itk { namespace fem { /* This macro makes registering Load implementations easier. */ #define REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) \ VisitorDispatcher<ElementClass, ElementClass::LoadType, ElementClass::LoadImplementationFunctionPointer> \ ::RegisterVisitor((LoadClass*)0, &FunctionName); /* Use this macro to also automatically declare load implementation function. */ #define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \ extern void FunctionName(ElementClass::ConstPointer, ElementClass::LoadPointer, ElementClass::VectorType& ); \ REGISTER_LOAD_EX(ElementClass,LoadClass,FunctionName) /** * Registers all Load classes in the FEM library with VisitorDispatcher. * This function must be called before the FEM library is functional!. */ void LoadImplementationsRegister(void) { // Loads acting on LineStress element REGISTER_LOAD_EX(Element2DC0LinearLineStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); // Loads acting on Beam element REGISTER_LOAD_EX(Element2DC1Beam,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); // Loads acting on QuadrilateralStress element REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on QuadrilateralMembrane element REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearQuadrilateralMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on TriangularStress element REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearTriangularStress,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on TriangularMembrane element REGISTER_LOAD_EX(Element2DC0LinearTriangularMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element2DC0LinearTriangularMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on HexahedronStrain element REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearHexahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on HexahedronMembrane element REGISTER_LOAD_EX(Element3DC0LinearHexahedronMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearHexahedronMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Loads acting on Tetrahedron element REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearTetrahedronStrain,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearTetrahedronMembrane,LoadGravConst,LoadImplementationGenericBodyLoad::HandleLoad); REGISTER_LOAD_EX(Element3DC0LinearTetrahedronMembrane,LoadLandmark,LoadImplementationGenericLandmarkLoad::HandleLoad); // Add any additional loads here in a similar fashion... // Make sure that the pointer to the visit function is the correct one!!! } }} // end namespace itk::fem <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2006 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "BaseLocalPlayer.h" /* common implementation headers */ #include "BZDBCache.h" BaseLocalPlayer::BaseLocalPlayer(const PlayerId& _id, const char* name, const char* _email, const PlayerType _type) : Player(_id, RogueTeam, name, _email, _type), lastTime(TimeKeeper::getTick()), salt(0) { lastPosition[0] = 0.0f; lastPosition[1] = 0.0f; lastPosition[2] = 0.0f; bbox[0][0] = bbox[1][0] = 0.0f; bbox[0][1] = bbox[1][1] = 0.0f; bbox[0][2] = bbox[1][2] = 0.0f; } BaseLocalPlayer::~BaseLocalPlayer() { // do nothing } int BaseLocalPlayer::getSalt() { salt = (salt + 1) & 127; return salt << 8; } void BaseLocalPlayer::update( float inputDT ) { // save last position const float* oldPosition = getPosition(); lastPosition[0] = oldPosition[0]; lastPosition[1] = oldPosition[1]; lastPosition[2] = oldPosition[2]; // update by time step float dt = float(TimeKeeper::getTick() - lastTime); lastTime = TimeKeeper::getTick(); if (inputDT > 0) dt = inputDT; if (dt < 0.001f) dt = 0.001f; float fullDT = dt; float dtLimit = 0.1f; float doneDT = fullDT; if ( fullDT > dtLimit ) { dt = dtLimit; doneDT-= dtLimit; } while (doneDT > 0) { doUpdateMotion(dt); // compute motion's bounding box around center of tank const float* newVelocity = getVelocity(); bbox[0][0] = bbox[1][0] = oldPosition[0]; bbox[0][1] = bbox[1][1] = oldPosition[1]; bbox[0][2] = bbox[1][2] = oldPosition[2]; if (newVelocity[0] > 0.0f) bbox[1][0] += dt * newVelocity[0]; else bbox[0][0] += dt * newVelocity[0]; if (newVelocity[1] > 0.0f) bbox[1][1] += dt * newVelocity[1]; else bbox[0][1] += dt * newVelocity[1]; if (newVelocity[2] > 0.0f) bbox[1][2] += dt * newVelocity[2]; else bbox[0][2] += dt * newVelocity[2]; // expand bounding box to include entire tank float size = BZDBCache::tankRadius; if (getFlag() == Flags::Obesity) size *= BZDB.eval(StateDatabase::BZDB_OBESEFACTOR); else if (getFlag() == Flags::Tiny) size *= BZDB.eval(StateDatabase::BZDB_TINYFACTOR); else if (getFlag() == Flags::Thief) size *= BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR); bbox[0][0] -= size; bbox[1][0] += size; bbox[0][1] -= size; bbox[1][1] += size; bbox[1][2] += BZDBCache::tankHeight; // do remaining update stuff doUpdate(dt); // subtract another chunk doneDT =- dtLimit; if ( doneDT < dtLimit) // if we only have a nubby left, don't do a full dt. dt = doneDT; } } Ray BaseLocalPlayer::getLastMotion() const { return Ray(lastPosition, getVelocity()); } const float (*BaseLocalPlayer::getLastMotionBBox() const)[3] { return bbox; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>=- ~= -=<commit_after>/* bzflag * Copyright (c) 1993 - 2006 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "BaseLocalPlayer.h" /* common implementation headers */ #include "BZDBCache.h" BaseLocalPlayer::BaseLocalPlayer(const PlayerId& _id, const char* name, const char* _email, const PlayerType _type) : Player(_id, RogueTeam, name, _email, _type), lastTime(TimeKeeper::getTick()), salt(0) { lastPosition[0] = 0.0f; lastPosition[1] = 0.0f; lastPosition[2] = 0.0f; bbox[0][0] = bbox[1][0] = 0.0f; bbox[0][1] = bbox[1][1] = 0.0f; bbox[0][2] = bbox[1][2] = 0.0f; } BaseLocalPlayer::~BaseLocalPlayer() { // do nothing } int BaseLocalPlayer::getSalt() { salt = (salt + 1) & 127; return salt << 8; } void BaseLocalPlayer::update( float inputDT ) { // save last position const float* oldPosition = getPosition(); lastPosition[0] = oldPosition[0]; lastPosition[1] = oldPosition[1]; lastPosition[2] = oldPosition[2]; // update by time step float dt = float(TimeKeeper::getTick() - lastTime); lastTime = TimeKeeper::getTick(); if (inputDT > 0) dt = inputDT; if (dt < 0.001f) dt = 0.001f; float fullDT = dt; float dtLimit = 0.1f; float doneDT = fullDT; if ( fullDT > dtLimit ) { dt = dtLimit; doneDT -= dtLimit; } while (doneDT > 0) { doUpdateMotion(dt); // compute motion's bounding box around center of tank const float* newVelocity = getVelocity(); bbox[0][0] = bbox[1][0] = oldPosition[0]; bbox[0][1] = bbox[1][1] = oldPosition[1]; bbox[0][2] = bbox[1][2] = oldPosition[2]; if (newVelocity[0] > 0.0f) bbox[1][0] += dt * newVelocity[0]; else bbox[0][0] += dt * newVelocity[0]; if (newVelocity[1] > 0.0f) bbox[1][1] += dt * newVelocity[1]; else bbox[0][1] += dt * newVelocity[1]; if (newVelocity[2] > 0.0f) bbox[1][2] += dt * newVelocity[2]; else bbox[0][2] += dt * newVelocity[2]; // expand bounding box to include entire tank float size = BZDBCache::tankRadius; if (getFlag() == Flags::Obesity) size *= BZDB.eval(StateDatabase::BZDB_OBESEFACTOR); else if (getFlag() == Flags::Tiny) size *= BZDB.eval(StateDatabase::BZDB_TINYFACTOR); else if (getFlag() == Flags::Thief) size *= BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR); bbox[0][0] -= size; bbox[1][0] += size; bbox[0][1] -= size; bbox[1][1] += size; bbox[1][2] += BZDBCache::tankHeight; // do remaining update stuff doUpdate(dt); // subtract another chunk doneDT -= dtLimit; if ( doneDT < dtLimit) // if we only have a nubby left, don't do a full dt. dt = doneDT; } } Ray BaseLocalPlayer::getLastMotion() const { return Ray(lastPosition, getVelocity()); } const float (*BaseLocalPlayer::getLastMotionBBox() const)[3] { return bbox; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // bzflag global common header #include "common.h" #include "global.h" // interface header #include "effectsRenderer.h" // system headers #include <string> #include <vector> // common impl headers #include "bzfgl.h" #include "OpenGLGState.h" #include "OpenGLMaterial.h" #include "TextureManager.h" #include "StateDatabase.h" #include "BZDBCache.h" #include "TimeKeeper.h" #include "TextUtils.h" #include "ParseColor.h" // local impl headers #include "SceneRenderer.h" #include "Intersect.h" #include "RoofTops.h" EffectsRenderer::EffectsRenderer() { } EffectsRenderer::~EffectsRenderer() { for ( unsigned int i = 0; i < effectsList.size(); i++ ) delete(effectsList[i]); effectsList.clear(); } void EffectsRenderer::init(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) delete(effectsList[i]); effectsList.clear(); } void EffectsRenderer::update(void) { tvEffectsList::iterator itr = effectsList.begin(); float time = (float)TimeKeeper::getCurrent().getSeconds(); while ( itr != effectsList.end() ) { if ( (*itr)->update(time) ) { delete((*itr)); itr = effectsList.erase(itr); } else itr++; } } void EffectsRenderer::draw(const SceneRenderer& sr) { // really should check here for only the things that are VISIBILE!!! for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->draw(sr); } void EffectsRenderer::freeContext(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->freeContext(); } void EffectsRenderer::rebuildContext(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->rebuildContext(); } void EffectsRenderer::addSpawnFlash ( int team, float* pos ) { SpawnFlashEffect *flash = new SpawnFlashEffect; flash->setPos(pos,NULL); flash->setStartTime((float)TimeKeeper::getCurrent().getSeconds()); flash->setTeam(team); effectsList.push_back(flash); } //****************** effects base class******************************* BasicEffect::BasicEffect() { position[0] = position[1] = position[2] = 0.0f; rotation[0] = rotation[1] = rotation[2] = 0.0f; teamColor = -1; startTime = (float)TimeKeeper::getCurrent().getSeconds(); lifetime = 0; lastTime = startTime; deltaTime = 0; } void BasicEffect::setPos ( float *pos, float *rot ) { if (pos) { position[0] = pos[0]; position[1] = pos[1]; position[2] = pos[2]; } if (rot) { rotation[0] = rot[0]; rotation[1] = rot[1]; rotation[2] = rot[2]; } } void BasicEffect::setTeam ( int team ) { teamColor = team; } void BasicEffect::setStartTime ( float time ) { startTime = time; lastTime = time; deltaTime = 0; } bool BasicEffect::update( float time ) { age = time - startTime; if ( age >= lifetime) return true; deltaTime = time - lastTime; lastTime = time; return false; } SpawnFlashEffect::SpawnFlashEffect() : BasicEffect() { texture = TextureManager::instance().getTextureID("blend_flash",false); lifetime = 2.5f; radius = 1.75f; OpenGLGStateBuilder gstate; gstate.reset(); gstate.setShading(); gstate.setBlending((GLenum) GL_SRC_ALPHA,(GLenum) GL_ONE_MINUS_SRC_ALPHA); gstate.setAlphaFunc(); if (texture >-1) gstate.setTexture(texture); ringState = gstate.getState(); } SpawnFlashEffect::~SpawnFlashEffect() { } bool SpawnFlashEffect::update ( float time ) { // see if it's time to die // if not update all those fun times if ( BasicEffect::update(time)) return true; // nope it's not. // we live another day // do stuff that maybe need to be done every time to animage radius += deltaTime*4; return false; } void SpawnFlashEffect::draw ( const SceneRenderer& sr ) { glPushMatrix(); glTranslatef(position[0],position[1],position[2]+0.1f); ringState.setState(); glColor4f(1,1,1,1.0f-(age/lifetime)); glDepthMask(0); drawRing(radius*0.1f,1.5f+(age*2)); drawRing(radius*0.5f,1.5f,0.5f,0.5f); drawRing(radius,2); glColor4f(1,1,1,1); glDepthMask(1); glPopMatrix(); } #define deg2Rad 0.017453292519943295769236907684886f void RadialToCartesian ( float angle, float rad, float *pos ) { pos[0] = sin(angle*deg2Rad)*rad; pos[1] = cos(angle*deg2Rad)*rad; } void SpawnFlashEffect::drawRing ( float rad, float z, float topsideOffset, float bottomUV ) { int segements = 32; for ( int i = 0; i < segements; i ++) { float thisAng = 360.0f/segements * i; float nextAng = 360.0f/segements * (i+1); if ( i+1 >= segements ) nextAng = 0; float thispos[2]; float nextPos[2]; float thispos2[2]; float nextPos2[2]; float thisNormal[3] = {0}; float nextNormal[3] = {0}; RadialToCartesian(thisAng,rad,thispos); RadialToCartesian(thisAng,1,thisNormal); RadialToCartesian(nextAng,rad,nextPos); RadialToCartesian(nextAng,1,nextNormal); RadialToCartesian(thisAng,rad+topsideOffset,thispos2); RadialToCartesian(nextAng,rad+topsideOffset,nextPos2); glBegin(GL_QUADS); // the "inside" glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); glTexCoord2f(0,bottomUV); glVertex3f(thispos[0],thispos[1],0); glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); glTexCoord2f(1,bottomUV); glVertex3f(nextPos[0],nextPos[1],0); glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); glTexCoord2f(1,1); glVertex3f(nextPos2[0],nextPos2[1],z); glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); glTexCoord2f(0,1); glVertex3f(thispos2[0],thispos2[1],z); // the "outside" glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); glTexCoord2f(0,1); glVertex3f(thispos2[0],thispos2[1],z); glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); glTexCoord2f(1,1); glVertex3f(nextPos2[0],nextPos2[1],z); glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); glTexCoord2f(1,bottomUV); glVertex3f(nextPos[0],nextPos[1],0); glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); glTexCoord2f(0,bottomUV); glVertex3f(thispos[0],thispos[1],0); glEnd(); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>make spawn effect use team color<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // bzflag global common header #include "common.h" #include "global.h" // interface header #include "effectsRenderer.h" // system headers #include <string> #include <vector> // common impl headers #include "bzfgl.h" #include "OpenGLGState.h" #include "OpenGLMaterial.h" #include "TextureManager.h" #include "StateDatabase.h" #include "BZDBCache.h" #include "TimeKeeper.h" #include "TextUtils.h" #include "ParseColor.h" // local impl headers #include "SceneRenderer.h" #include "Intersect.h" #include "RoofTops.h" EffectsRenderer::EffectsRenderer() { } EffectsRenderer::~EffectsRenderer() { for ( unsigned int i = 0; i < effectsList.size(); i++ ) delete(effectsList[i]); effectsList.clear(); } void EffectsRenderer::init(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) delete(effectsList[i]); effectsList.clear(); } void EffectsRenderer::update(void) { tvEffectsList::iterator itr = effectsList.begin(); float time = (float)TimeKeeper::getCurrent().getSeconds(); while ( itr != effectsList.end() ) { if ( (*itr)->update(time) ) { delete((*itr)); itr = effectsList.erase(itr); } else itr++; } } void EffectsRenderer::draw(const SceneRenderer& sr) { // really should check here for only the things that are VISIBILE!!! for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->draw(sr); } void EffectsRenderer::freeContext(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->freeContext(); } void EffectsRenderer::rebuildContext(void) { for ( unsigned int i = 0; i < effectsList.size(); i++ ) effectsList[i]->rebuildContext(); } void EffectsRenderer::addSpawnFlash ( int team, float* pos ) { SpawnFlashEffect *flash = new SpawnFlashEffect; flash->setPos(pos,NULL); flash->setStartTime((float)TimeKeeper::getCurrent().getSeconds()); flash->setTeam(team); effectsList.push_back(flash); } //****************** effects base class******************************* BasicEffect::BasicEffect() { position[0] = position[1] = position[2] = 0.0f; rotation[0] = rotation[1] = rotation[2] = 0.0f; teamColor = -1; startTime = (float)TimeKeeper::getCurrent().getSeconds(); lifetime = 0; lastTime = startTime; deltaTime = 0; } void BasicEffect::setPos ( float *pos, float *rot ) { if (pos) { position[0] = pos[0]; position[1] = pos[1]; position[2] = pos[2]; } if (rot) { rotation[0] = rot[0]; rotation[1] = rot[1]; rotation[2] = rot[2]; } } void BasicEffect::setTeam ( int team ) { teamColor = team; } void BasicEffect::setStartTime ( float time ) { startTime = time; lastTime = time; deltaTime = 0; } bool BasicEffect::update( float time ) { age = time - startTime; if ( age >= lifetime) return true; deltaTime = time - lastTime; lastTime = time; return false; } SpawnFlashEffect::SpawnFlashEffect() : BasicEffect() { texture = TextureManager::instance().getTextureID("blend_flash",false); lifetime = 2.5f; radius = 1.75f; OpenGLGStateBuilder gstate; gstate.reset(); gstate.setShading(); gstate.setBlending((GLenum) GL_SRC_ALPHA,(GLenum) GL_ONE_MINUS_SRC_ALPHA); gstate.setAlphaFunc(); if (texture >-1) gstate.setTexture(texture); ringState = gstate.getState(); } SpawnFlashEffect::~SpawnFlashEffect() { } bool SpawnFlashEffect::update ( float time ) { // see if it's time to die // if not update all those fun times if ( BasicEffect::update(time)) return true; // nope it's not. // we live another day // do stuff that maybe need to be done every time to animage radius += deltaTime*4; return false; } void SpawnFlashEffect::draw ( const SceneRenderer& sr ) { glPushMatrix(); glTranslatef(position[0],position[1],position[2]+0.1f); ringState.setState(); float color[3] = {0}; switch(teamColor) { default: color[0] = color[1] = color[2] = 1; break; case BlueTeam: color[0] = 0.25f; color[1] = 0.25f; color[2] = 1; break; case GreenTeam: color[0] = 0.25f; color[1] = 1; color[2] = 0.25f; break; case RedTeam: color[0] = 1; color[1] = 0.25f; color[2] = 0.25f; break; case PurpleTeam: color[0] = 1; color[1] = 0.25f; color[2] = 1.0f; break; case RogueTeam: color[0] = 0.25; color[1] = 0.25f; color[2] = 0.25f; break; } glColor4f(color[0],color[1],color[2],1.0f-(age/lifetime)); glDepthMask(0); drawRing(radius*0.1f,1.5f+(age*2)); drawRing(radius*0.5f,1.5f,0.5f,0.5f); drawRing(radius,2); glColor4f(1,1,1,1); glDepthMask(1); glPopMatrix(); } #define deg2Rad 0.017453292519943295769236907684886f void RadialToCartesian ( float angle, float rad, float *pos ) { pos[0] = sin(angle*deg2Rad)*rad; pos[1] = cos(angle*deg2Rad)*rad; } void SpawnFlashEffect::drawRing ( float rad, float z, float topsideOffset, float bottomUV ) { int segements = 32; for ( int i = 0; i < segements; i ++) { float thisAng = 360.0f/segements * i; float nextAng = 360.0f/segements * (i+1); if ( i+1 >= segements ) nextAng = 0; float thispos[2]; float nextPos[2]; float thispos2[2]; float nextPos2[2]; float thisNormal[3] = {0}; float nextNormal[3] = {0}; RadialToCartesian(thisAng,rad,thispos); RadialToCartesian(thisAng,1,thisNormal); RadialToCartesian(nextAng,rad,nextPos); RadialToCartesian(nextAng,1,nextNormal); RadialToCartesian(thisAng,rad+topsideOffset,thispos2); RadialToCartesian(nextAng,rad+topsideOffset,nextPos2); glBegin(GL_QUADS); // the "inside" glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); glTexCoord2f(0,bottomUV); glVertex3f(thispos[0],thispos[1],0); glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); glTexCoord2f(1,bottomUV); glVertex3f(nextPos[0],nextPos[1],0); glNormal3f(-nextNormal[0],-nextNormal[1],-nextNormal[2]); glTexCoord2f(1,1); glVertex3f(nextPos2[0],nextPos2[1],z); glNormal3f(-thisNormal[0],-thisNormal[1],-thisNormal[2]); glTexCoord2f(0,1); glVertex3f(thispos2[0],thispos2[1],z); // the "outside" glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); glTexCoord2f(0,1); glVertex3f(thispos2[0],thispos2[1],z); glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); glTexCoord2f(1,1); glVertex3f(nextPos2[0],nextPos2[1],z); glNormal3f(nextNormal[0],nextNormal[1],nextNormal[2]); glTexCoord2f(1,bottomUV); glVertex3f(nextPos[0],nextPos[1],0); glNormal3f(thisNormal[0],thisNormal[1],thisNormal[2]); glTexCoord2f(0,bottomUV); glVertex3f(thispos[0],thispos[1],0); glEnd(); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _linebufsize; int _contentbufsize; int _leftOversLen; char *_linebuf; char *_contentbuf; char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _linebufsize(args._maxLineSize), _contentbufsize(0), _leftOversLen(0), _linebuf(new char[_linebufsize]), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _linebufsize; _contentbuf = new char[_contentbufsize]; } } int nextUrl(); int getContent(); char *url() const { return _linebuf; } char *contents() const { return _contentbuf; } ~UrlReader() {} }; int UrlReader::nextUrl() { char *buf = _linebuf; int buflen = _linebufsize; if (_leftOvers) { if (_leftOversLen < buflen) { strncpy(buf, _leftOvers, _leftOversLen); buf[_leftOversLen] = '\0'; } else { strncpy(buf, _leftOvers, buflen); buf[buflen-1] = '\0'; } _leftOvers = NULL; return _leftOversLen; } // Read maximum to _queryfileOffsetEnd if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { _reader.SetFilePos(_args._queryfileOffset); if (_restarts == _args._restartLimit) { return 0; } else if (_args._restartLimit > 0) { _restarts++; } } int ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } if (_restarts == _args._restartLimit) { return 0; } else if (_args._restartLimit > 0) { _restarts++; } if (ll < 0) { _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } } ll = _reader.ReadLine(buf, buflen); while (ll > 0 && _args._usePostMode && buf[0] != '/') { ll = _reader.ReadLine(buf, buflen); } if (ll > 0 && (buf[0] == '/' || !_args._usePostMode)) { return ll; } return 0; } int UrlReader::getContent() { char *buf = _contentbuf; int bufLen = _contentbufsize; int totLen = 0; while (totLen < bufLen) { int len = _reader.ReadLine(buf, bufLen); if (len > 0) { if (buf[0] == '/') { _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; bufLen -= len; totLen += len; } else { return totLen; } } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { char *linebuf = urlSource.url(); if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.getContent() : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(linebuf, _output.get(), _args->_usePostMode, urlSource.contents(), cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <commit_msg>refactor loop for url reading<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _linebufsize; int _contentbufsize; int _leftOversLen; char *_linebuf; char *_contentbuf; char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _linebufsize(args._maxLineSize), _contentbufsize(0), _leftOversLen(0), _linebuf(new char[_linebufsize]), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _linebufsize; _contentbuf = new char[_contentbufsize]; } } bool reset(); int nextUrl(); int getContent(); char *url() const { return _linebuf; } char *contents() const { return _contentbuf; } ~UrlReader() {} }; bool UrlReader::reset() { _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } if (_restarts == _args._restartLimit) { return false; } else if (_args._restartLimit > 0) { _restarts++; } return true; } int UrlReader::nextUrl() { char *buf = _linebuf; int buflen = _linebufsize; if (_leftOvers) { if (_leftOversLen < buflen) { strncpy(buf, _leftOvers, _leftOversLen); buf[_leftOversLen] = '\0'; } else { strncpy(buf, _leftOvers, buflen); buf[buflen-1] = '\0'; } _leftOvers = NULL; return _leftOversLen; } bool again = true; for (int retry = 0; again && retry < 100; ++retry) { // Read maximum to _queryfileEndOffset if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { again = reset(); } int ll = _reader.ReadLine(buf, buflen); if (ll > 0) { if (buf[0] == '/' || !_args._usePostMode) { return ll; } } if (ll < 0) { // reached EOF again = reset(); } } return 0; } int UrlReader::getContent() { char *buf = _contentbuf; int bufLen = _contentbufsize; int totLen = 0; while (totLen < bufLen) { int len = _reader.ReadLine(buf, bufLen); if (len > 0) { if (buf[0] == '/') { _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; bufLen -= len; totLen += len; } else { return totLen; } } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { char *linebuf = urlSource.url(); if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.getContent() : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(linebuf, _output.get(), _args->_usePostMode, urlSource.contents(), cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <|endoftext|>
<commit_before>#include <Servo.h> #include "Msg.h" #include "Device.h" #include "MrlServo.h" MrlServo::MrlServo(int deviceId) : Device(deviceId, DEVICE_TYPE_SERVO) { isMoving = false; isSweeping = false; // create the servo servo = new Servo(); lastUpdate = 0; currentPosUs = 0.0; targetPosUs = 0; velocity = -1; acceleration = -1; moveStart = 0; } MrlServo::~MrlServo() { if (servo){ servo->detach(); delete servo; } } // this method "may" be called with a pin or pin & pos depending on // config size bool MrlServo::attach(byte pin, int initPosUs, int initVelocity){ // msg->publishDebug("MrlServo.deviceAttach !"); servo->writeMicroseconds(initPosUs); currentPosUs = initPosUs; targetPosUs = initPosUs; velocity = initVelocity; this->pin = pin; servo->attach(pin); //publishServoEvent(SERVO_EVENT_STOPPED); return true; } // This method is equivalent to Arduino's Servo.attach(pin) - (no pos) void MrlServo::attachPin(int pin){ attach(pin, currentPosUs, velocity); } void MrlServo::detachPin(){ servo->detach(); } // FIXME - what happened to events ? void MrlServo::update() { //it may have an imprecision of +- 1 due to the conversion of currentPosUs to int if (isMoving) { if ((int)currentPosUs != targetPosUs) { long deltaTime = millis() - lastUpdate; lastUpdate = millis(); float _velocity = velocity; if (acceleration != -1) { _velocity *= acceleration * pow(((float)(millis()- moveStart)) / 1000,2) / 10; //msg->publishDebug(String(_velocity)); if (_velocity > velocity) { _velocity = velocity; } } if(targetPosUs > 500) { _velocity = map(_velocity, 0, 180, 544, 2400) - 544; } float step = _velocity * deltaTime; step /= 1000; //for deg/ms; if (isSweeping) { step = sweepStep; } if (velocity < 0) { // when velocity < 0, it mean full speed ahead step = targetPosUs - (int)currentPosUs; } else if (currentPosUs > targetPosUs) { step *=-1; } int previousCurrentPosUs = (int)currentPosUs; currentPosUs += step; if ((step > 0.0 && (int)currentPosUs > targetPosUs) || (step < 0.0 && (int)currentPosUs < targetPosUs)) { currentPosUs = targetPosUs; } if (!(previousCurrentPosUs == (int)currentPosUs)) { servo->writeMicroseconds((int)currentPosUs); if ((int)currentPosUs == targetPosUs) { publishServoEvent(SERVO_EVENT_STOPPED); } else { publishServoEvent(SERVO_EVENT_POSITION_UPDATE); } } } else { if (isSweeping) { if (targetPosUs == minUs) { targetPosUs = maxUs; } else { targetPosUs = minUs; } sweepStep *= -1; } else { isMoving = false; publishServoEvent(SERVO_EVENT_STOPPED); } } } } void MrlServo::moveToMicroseconds(int posUs) { if (servo == NULL){ return; } targetPosUs = posUs; isMoving = true; lastUpdate = millis(); moveStart = lastUpdate; publishServoEvent(SERVO_EVENT_POSITION_UPDATE); } void MrlServo::startSweep(int minUs, int maxUs, int step) { this->minUs = minUs; this->maxUs = maxUs; sweepStep = step; targetPosUs = maxUs; isMoving = true; isSweeping = true; } void MrlServo::stopSweep() { isMoving = false; isSweeping = false; } void MrlServo::setVelocity(int velocity) { this->velocity = velocity; } void MrlServo::setAcceleration(int acceleration) { this->acceleration = acceleration; } void MrlServo::publishServoEvent(int type) { msg->publishServoEvent(id, type, (int)currentPosUs, targetPosUs); } <commit_msg>forgot one<commit_after>#include <Servo.h> #include "Msg.h" #include "Device.h" #include "MrlServo.h" MrlServo::MrlServo(int deviceId) : Device(deviceId, DEVICE_TYPE_SERVO) { isMoving = false; isSweeping = false; // create the servo servo = new Servo(); lastUpdate = 0; currentPosUs = 0.0; targetPosUs = 0; velocity = -1; acceleration = -1; moveStart = 0; } MrlServo::~MrlServo() { if (servo){ servo->detach(); delete servo; } } // this method "may" be called with a pin or pin & pos depending on // config size bool MrlServo::attach(byte pin, int initPosUs, int initVelocity){ // msg->publishDebug("MrlServo.deviceAttach !"); servo->writeMicroseconds(initPosUs); currentPosUs = initPosUs; targetPosUs = initPosUs; velocity = initVelocity; this->pin = pin; servo->attach(pin); //publishServoEvent(SERVO_EVENT_STOPPED); return true; } // This method is equivalent to Arduino's Servo.attach(pin) - (no pos) void MrlServo::attachPin(int pin){ attach(pin, currentPosUs, velocity); } void MrlServo::detachPin(){ servo->detach(); } // FIXME - what happened to events ? void MrlServo::update() { //it may have an imprecision of +- 1 due to the conversion of currentPosUs to int if (isMoving) { if ((int)currentPosUs != targetPosUs) { long deltaTime = millis() - lastUpdate; lastUpdate = millis(); float _velocity = velocity; if (acceleration != -1) { _velocity *= acceleration * pow(((float)(millis()- moveStart)) / 1000,2) / 10; //msg->publishDebug(String(_velocity)); if (_velocity > velocity) { _velocity = velocity; } } if(targetPosUs > 500) { _velocity = map(_velocity, 0, 180, 544, 2400) - 544; } float step = _velocity * deltaTime; step /= 1000; //for deg/ms; if (isSweeping) { step = sweepStep; } if (velocity < 0) { // when velocity < 0, it mean full speed ahead step = targetPosUs - (int)currentPosUs; } else if (currentPosUs > targetPosUs) { step *=-1; } int previousCurrentPosUs = (int)currentPosUs; currentPosUs += step; if ((step > 0.0 && (int)currentPosUs > targetPosUs) || (step < 0.0 && (int)currentPosUs < targetPosUs)) { currentPosUs = targetPosUs; } if (!(previousCurrentPosUs == (int)currentPosUs)) { servo->writeMicroseconds((int)currentPosUs); if ((int)currentPosUs == targetPosUs) { publishServoEvent(SERVO_EVENT_STOPPED); } else { publishServoEvent(SERVO_EVENT_POSITION_UPDATE); } } } else { if (isSweeping) { if (targetPosUs == minUs) { targetPosUs = maxUs; } else { targetPosUs = minUs; } sweepStep *= -1; } else { isMoving = false; publishServoEvent(SERVO_EVENT_STOPPED); } } } } void MrlServo::moveToMicroseconds(int posUs) { if (servo == NULL){ return; } targetPosUs = posUs; isMoving = true; lastUpdate = millis(); moveStart = lastUpdate; publishServoEvent(SERVO_EVENT_POSITION_UPDATE); } void MrlServo::startSweep(int minUs, int maxUs, int step) { this->minUs = minUs; this->maxUs = maxUs; sweepStep = step; targetPosUs = maxUs; isMoving = true; isSweeping = true; } void MrlServo::stop() { isMoving = false; isSweeping = false; } void MrlServo::stopSweep() { isMoving = false; isSweeping = false; } void MrlServo::setVelocity(int velocity) { this->velocity = velocity; } void MrlServo::setAcceleration(int acceleration) { this->acceleration = acceleration; } void MrlServo::publishServoEvent(int type) { msg->publishServoEvent(id, type, (int)currentPosUs, targetPosUs); } <|endoftext|>
<commit_before>/* Copyright (c) 2020 ANON authors, see AUTHORS file. 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 "sync_teflon_app.h" #include "log.h" #include "sproc_mgr.h" #include <sys/stat.h> #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/GetItemRequest.h> namespace { struct tef_app { tef_app(const Aws::String& id, const Aws::Vector<Aws::String>& filesv, Aws::Map<Aws::String, const std::shared_ptr<Aws::DynamoDB::Model::AttributeValue>>& fids) : id(id) { for (auto &f : filesv) { files[fids[f]->GetS()] = f; } } Aws::String id; std::map<Aws::String, Aws::String> files; }; bool exe_cmd(const std::string &str) { auto f = popen(str.c_str(), "r"); if (f) { auto exit_code = pclose(f); if (exit_code != 0) { anon_log_error("command: " << str << " exited non-zero: " << error_string(exit_code)); return false; } } else { anon_log_error("popen failed: " << errno_string()); return false; } return true; } bool create_empty_directory(const ec2_info &ec2i, const Aws::String &id) { auto dir = ec2i.root_dir; if (id.size() != 0) { dir += "/"; dir += id.c_str(); } std::ostringstream str; str << "rm -rf " << id << " && mkdir " << id; return exe_cmd(str.str()); } void remove_directory(const ec2_info &ec2i, const Aws::String &id) { auto dir = ec2i.root_dir; if (id.size() != 0) { dir += "/"; dir += id.c_str(); } std::ostringstream str; str << "rm -rf " << id; if (!exe_cmd(str.str())) anon_log_error("failed to remove " << id << " directory"); } std::shared_ptr<tef_app> curr_app; } // namespace teflon_state sync_teflon_app(const ec2_info &ec2i) { if (ec2i.user_data_js.find("current_server_primary_key_value") == ec2i.user_data_js.end() || ec2i.user_data_js.find("current_server_primary_key_name") == ec2i.user_data_js.end()) { anon_log_error("no current server info specified in user data - cannot start teflon app"); return teflon_server_failed; } if (!curr_app) { if (!create_empty_directory(ec2i, "")) return teflon_server_failed; } Aws::Client::ClientConfiguration ddb_config; if (ec2i.user_data_js.find("current_server_region") != ec2i.user_data_js.end()) ddb_config.region = ec2i.user_data_js["current_server_region"]; else ddb_config.region = ec2i.default_region; Aws::DynamoDB::DynamoDBClient ddbc(ddb_config); Aws::DynamoDB::Model::AttributeValue primary_key; std::string cs_primary_key = ec2i.user_data_js["current_server_primary_key_value"]; primary_key.SetS(cs_primary_key.c_str()); Aws::DynamoDB::Model::GetItemRequest req; std::string cs_table_name = ec2i.user_data_js["current_server_table_name"]; std::string cs_key_name = ec2i.user_data_js["current_server_primary_key_name"]; req.WithTableName(cs_table_name.c_str()) .AddKey(cs_key_name.c_str(), primary_key); auto outcome = ddbc.GetItem(req); if (!outcome.IsSuccess()) { anon_log_error("GetItem failed: " << outcome.GetError()); return teflon_server_failed; } auto &map = outcome.GetResult().GetItem(); auto state_it = map.find("state"); if (state_it == map.end()) { anon_log_error("current_server record missing required \"state\" field"); return teflon_server_failed; } auto state = state_it->second.GetS(); if (state == "stop") { anon_log("stopping server"); return teflon_shut_down; } if (state != "run") { anon_log_error("unknown teflon server state: " << state); return teflon_server_failed; } auto id_it = map.find("current_server_id"); auto end = map.end(); if (id_it == end) { anon_log_error("current_server record missing required \"current_server_id\" field"); return teflon_server_failed; } auto current_server_id = id_it->second.GetS(); if (curr_app && current_server_id == curr_app->id) { anon_log("current server definition matches running server, no-op"); return teflon_server_running; } auto files_it = map.find("files"); auto exe_it = map.find("entry"); auto ids_it = map.find("fids"); if (files_it == end || exe_it == end || ids_it == end) { anon_log_error("current_server record missing required \"files\", \"entry\", and/or \"fids\" field(s)"); return teflon_server_failed; } auto files_needed = files_it->second.GetSS(); auto file_to_execute = exe_it->second.GetS(); auto ids = ids_it->second.GetM(); if (ec2i.user_data_js.find("current_server_artifacts_bucket") == ec2i.user_data_js.end() || ec2i.user_data_js.find("current_server_artifacts_key") == ec2i.user_data_js.end()) { anon_log_error("user data missing required fields \"current_server_artifacts_bucket\" and/or \"current_server_artifacts_key\""); return teflon_server_failed; } std::string bucket = ec2i.user_data_js["current_server_artifacts_bucket"]; std::string key = ec2i.user_data_js["current_server_artifacts_key"]; std::ostringstream files_cmd; files_cmd << "FAIL=0\n"; for (const auto &f : files_needed) { if (ids.find(f) == ids.end()) { anon_log_error("file: \"" << f << "\" missing in fids"); return teflon_server_failed; } if (curr_app && curr_app->files.find(f) != curr_app->files.end()) { // f matches a file we have already downloaded, so just hard link it // to the new directory auto existing_file = curr_app->files[f]; files_cmd << "ln " << ec2i.root_dir << "/" << curr_app->id << "/" << curr_app->files[f] << " " << ec2i.root_dir << "/" << current_server_id << "/" << f << " &\n"; } else { // does not match an existing file, so download it from s3 files_cmd << "aws s3 --region " << ec2i.default_region << " cp s3://" << bucket << "/" << key << "/" << f << " " << ec2i.root_dir << "/" << current_server_id << "/" << f << " --quiet &\n"; } } if (!create_empty_directory(ec2i, current_server_id)) return teflon_server_failed; files_cmd << "for job in `jobs -p`\n" << "do\n" << " wait $job || let \"FAIL+=1\"\n" << "done\n" << "f [ \"$FAIL\" == \"0\" ];\n" << "then\n" << " exit 0\n" << "else\n" << " exit 1"; if (!exe_cmd(files_cmd.str())) return teflon_server_failed; std::ostringstream ef; ef << ec2i.root_dir << "/" << current_server_id << "/" << file_to_execute; chmod(ef.str().c_str(), ACCESSPERMS); try { auto new_app = std::make_shared<tef_app>(current_server_id, files_needed, ids); start_server(file_to_execute.c_str(), false/*do_tls*/, std::vector<std::string>()); if (curr_app) remove_directory(ec2i, curr_app->id); curr_app = new_app; } catch(const std::exception& exc) { anon_log_error("start_server failed: " << exc.what()); remove_directory(ec2i, current_server_id); return teflon_server_failed; } catch(...) { anon_log_error("start_server"); remove_directory(ec2i, current_server_id); return teflon_server_failed; } return teflon_server_running; }<commit_msg>debugging<commit_after>/* Copyright (c) 2020 ANON authors, see AUTHORS file. 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 "sync_teflon_app.h" #include "log.h" #include "sproc_mgr.h" #include <sys/stat.h> #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/GetItemRequest.h> namespace { struct tef_app { tef_app(const Aws::String& id, const Aws::Vector<Aws::String>& filesv, Aws::Map<Aws::String, const std::shared_ptr<Aws::DynamoDB::Model::AttributeValue>>& fids) : id(id) { for (auto &f : filesv) { files[fids[f]->GetS()] = f; } } Aws::String id; std::map<Aws::String, Aws::String> files; }; bool exe_cmd(const std::string &str) { auto f = popen(str.c_str(), "r"); if (f) { auto exit_code = pclose(f); if (exit_code != 0) { anon_log_error("command: " << str << " exited non-zero: " << error_string(exit_code)); return false; } } else { anon_log_error("popen failed: " << errno_string()); return false; } return true; } bool create_empty_directory(const ec2_info &ec2i, const Aws::String &id) { auto dir = ec2i.root_dir; if (id.size() != 0) { dir += "/"; dir += id.c_str(); } std::ostringstream str; str << "rm -rf " << dir << " && mkdir " << dir; return exe_cmd(str.str()); } void remove_directory(const ec2_info &ec2i, const Aws::String &id) { auto dir = ec2i.root_dir; if (id.size() != 0) { dir += "/"; dir += id.c_str(); } std::ostringstream str; str << "rm -rf " << id; if (!exe_cmd(str.str())) anon_log_error("failed to remove " << id << " directory"); } std::shared_ptr<tef_app> curr_app; } // namespace teflon_state sync_teflon_app(const ec2_info &ec2i) { if (ec2i.user_data_js.find("current_server_primary_key_value") == ec2i.user_data_js.end() || ec2i.user_data_js.find("current_server_primary_key_name") == ec2i.user_data_js.end()) { anon_log_error("no current server info specified in user data - cannot start teflon app"); return teflon_server_failed; } if (!curr_app) { if (!create_empty_directory(ec2i, "")) return teflon_server_failed; } Aws::Client::ClientConfiguration ddb_config; if (ec2i.user_data_js.find("current_server_region") != ec2i.user_data_js.end()) ddb_config.region = ec2i.user_data_js["current_server_region"]; else ddb_config.region = ec2i.default_region; Aws::DynamoDB::DynamoDBClient ddbc(ddb_config); Aws::DynamoDB::Model::AttributeValue primary_key; std::string cs_primary_key = ec2i.user_data_js["current_server_primary_key_value"]; primary_key.SetS(cs_primary_key.c_str()); Aws::DynamoDB::Model::GetItemRequest req; std::string cs_table_name = ec2i.user_data_js["current_server_table_name"]; std::string cs_key_name = ec2i.user_data_js["current_server_primary_key_name"]; req.WithTableName(cs_table_name.c_str()) .AddKey(cs_key_name.c_str(), primary_key); auto outcome = ddbc.GetItem(req); if (!outcome.IsSuccess()) { anon_log_error("GetItem failed: " << outcome.GetError()); return teflon_server_failed; } auto &map = outcome.GetResult().GetItem(); auto state_it = map.find("state"); if (state_it == map.end()) { anon_log_error("current_server record missing required \"state\" field"); return teflon_server_failed; } auto state = state_it->second.GetS(); if (state == "stop") { anon_log("stopping server"); return teflon_shut_down; } if (state != "run") { anon_log_error("unknown teflon server state: " << state); return teflon_server_failed; } auto id_it = map.find("current_server_id"); auto end = map.end(); if (id_it == end) { anon_log_error("current_server record missing required \"current_server_id\" field"); return teflon_server_failed; } auto current_server_id = id_it->second.GetS(); if (curr_app && current_server_id == curr_app->id) { anon_log("current server definition matches running server, no-op"); return teflon_server_running; } auto files_it = map.find("files"); auto exe_it = map.find("entry"); auto ids_it = map.find("fids"); if (files_it == end || exe_it == end || ids_it == end) { anon_log_error("current_server record missing required \"files\", \"entry\", and/or \"fids\" field(s)"); return teflon_server_failed; } auto files_needed = files_it->second.GetSS(); auto file_to_execute = exe_it->second.GetS(); auto ids = ids_it->second.GetM(); if (ec2i.user_data_js.find("current_server_artifacts_bucket") == ec2i.user_data_js.end() || ec2i.user_data_js.find("current_server_artifacts_key") == ec2i.user_data_js.end()) { anon_log_error("user data missing required fields \"current_server_artifacts_bucket\" and/or \"current_server_artifacts_key\""); return teflon_server_failed; } std::string bucket = ec2i.user_data_js["current_server_artifacts_bucket"]; std::string key = ec2i.user_data_js["current_server_artifacts_key"]; std::ostringstream files_cmd; files_cmd << "FAIL=0\n"; for (const auto &f : files_needed) { if (ids.find(f) == ids.end()) { anon_log_error("file: \"" << f << "\" missing in fids"); return teflon_server_failed; } if (curr_app && curr_app->files.find(f) != curr_app->files.end()) { // f matches a file we have already downloaded, so just hard link it // to the new directory auto existing_file = curr_app->files[f]; files_cmd << "ln " << ec2i.root_dir << "/" << curr_app->id << "/" << curr_app->files[f] << " " << ec2i.root_dir << "/" << current_server_id << "/" << f << " &\n"; } else { // does not match an existing file, so download it from s3 files_cmd << "aws s3 --region " << ec2i.default_region << " cp s3://" << bucket << "/" << key << "/" << f << " " << ec2i.root_dir << "/" << current_server_id << "/" << f << " --quiet &\n"; } } if (!create_empty_directory(ec2i, current_server_id)) return teflon_server_failed; files_cmd << "for job in `jobs -p`\n" << "do\n" << " wait $job || let \"FAIL+=1\"\n" << "done\n" << "if [ \"$FAIL\" == \"0\" ];\n" << "then\n" << " exit 0\n" << "else\n" << " exit 1"; anon_log("executing script:\n" << files_cmd.str()); if (!exe_cmd(files_cmd.str())) return teflon_server_failed; std::ostringstream ef; ef << ec2i.root_dir << "/" << current_server_id << "/" << file_to_execute; chmod(ef.str().c_str(), ACCESSPERMS); try { auto new_app = std::make_shared<tef_app>(current_server_id, files_needed, ids); start_server(file_to_execute.c_str(), false/*do_tls*/, std::vector<std::string>()); if (curr_app) remove_directory(ec2i, curr_app->id); curr_app = new_app; } catch(const std::exception& exc) { anon_log_error("start_server failed: " << exc.what()); remove_directory(ec2i, current_server_id); return teflon_server_failed; } catch(...) { anon_log_error("start_server"); remove_directory(ec2i, current_server_id); return teflon_server_failed; } return teflon_server_running; } <|endoftext|>
<commit_before>#include <ros/ros.h> //ROS libraries #include <tf/transform_datatypes.h> //ROS messages #include <std_msgs/Float32.h> #include <std_msgs/String.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/QuaternionStamped.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/Range.h> //Package include #include <usbSerial.h> using namespace std; //aBridge functions void cmdHandler(const geometry_msgs::Twist::ConstPtr& message); void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle); void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle); void serialActivityTimer(const ros::TimerEvent& e); void publishRosTopics(); void parseData(string data); //Globals geometry_msgs::QuaternionStamped fingerAngle; geometry_msgs::QuaternionStamped wristAngle; sensor_msgs::Imu imu; nav_msgs::Odometry odom; sensor_msgs::Range sonarLeft; sensor_msgs::Range sonarCenter; sensor_msgs::Range sonarRight; USBSerial usb; const int baud = 115200; char dataCmd[] = "d\n"; char moveCmd[16]; char host[128]; float linearSpeed = 0.; float turnSpeed = 0.; const float deltaTime = 0.1; //Publishers ros::Publisher fingerAnglePublish; ros::Publisher wristAnglePublish; ros::Publisher imuPublish; ros::Publisher odomPublish; ros::Publisher sonarLeftPublish; ros::Publisher sonarCenterPublish; ros::Publisher sonarRightPublish; //Subscribers ros::Subscriber velocitySubscriber; ros::Subscriber fingerAngleSubscriber; ros::Subscriber wristAngleSubscriber; //Timers ros::Timer publishTimer; int main(int argc, char **argv) { gethostname(host, sizeof (host)); string hostname(host); string publishedName; ros::init(argc, argv, (hostname + "_ABRIDGE")); ros::NodeHandle param("~"); string devicePath; param.param("device", devicePath, string("/dev/ttyUSB0")); usb.openUSBPort(devicePath, baud); sleep(5); ros::NodeHandle aNH; if (argc >= 2) { publishedName = argv[1]; cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl; } else { publishedName = hostname; cout << "No Name Selected. Default is: " << publishedName << endl; } fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10); wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10); imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10); odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10); sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10); sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10); sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10); velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler); fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler); wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler); publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer); imu.header.frame_id = publishedName+"/base_link"; odom.header.frame_id = publishedName+"/odom"; odom.child_frame_id = publishedName+"/base_link"; ros::spin(); return EXIT_SUCCESS; } void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) { // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0 linearSpeed = (message->linear.x); // / 1.5; turnSpeed = (message->angular.z); // / 8; if (linearSpeed != 0.) { sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255)); usb.sendData(moveCmd); } else if (turnSpeed != 0.) { sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255)); usb.sendData(moveCmd); } else { sprintf(moveCmd, "s\n"); usb.sendData(moveCmd); } memset(&moveCmd, '\0', sizeof (moveCmd)); } // The finger and wrist handlers receive gripper angle commands in floating point // radians, write them to a string and send that to the arduino // for processing. void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) { char cmd[16]={'\0'}; // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small if (angle->data < 0.01) { // 'f' indicates this is a finger command to the arduino sprintf(cmd, "f,0\n"); } else { sprintf(cmd, "f,%.4g\n", angle->data); } usb.sendData(cmd); memset(&cmd, '\0', sizeof (cmd)); } void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) { char cmd[16]={'\0'}; // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small if (angle->data < 0.01) { // 'w' indicates this is a wrist command to the arduino sprintf(cmd, "w,0\n"); } else { sprintf(cmd, "w,%.4g\n", angle->data); } usb.sendData(cmd); memset(&cmd, '\0', sizeof (cmd)); } void serialActivityTimer(const ros::TimerEvent& e) { usb.sendData(dataCmd); parseData(usb.readData()); publishRosTopics(); } void publishRosTopics() { fingerAnglePublish.publish(fingerAngle); wristAnglePublish.publish(wristAngle); imuPublish.publish(imu); odomPublish.publish(odom); sonarLeftPublish.publish(sonarLeft); sonarCenterPublish.publish(sonarCenter); sonarRightPublish.publish(sonarRight); } void parseData(string str) { istringstream oss(str); string sentence; while (getline(oss, sentence, '\n')) { istringstream wss(sentence); string word; vector<string> dataSet; while (getline(wss, word, ',')) { dataSet.push_back(word); } if (dataSet.size() >= 3 && dataSet.at(1) == "1") { if (dataSet.at(0) == "GRF") { fingerAngle.header.stamp = ros::Time::now(); fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0); } else if (dataSet.at(0) == "GRW") { wristAngle.header.stamp = ros::Time::now(); wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0); } else if (dataSet.at(0) == "IMU") { imu.header.stamp = ros::Time::now(); imu.linear_acceleration.x = atof(dataSet.at(2).c_str()); imu.linear_acceleration.y = atof(dataSet.at(3).c_str()); imu.linear_acceleration.z = atof(dataSet.at(4).c_str()); imu.angular_velocity.x = atof(dataSet.at(5).c_str()); imu.angular_velocity.y = atof(dataSet.at(6).c_str()); imu.angular_velocity.z = atof(dataSet.at(7).c_str()); imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str())); } else if (dataSet.at(0) == "ODOM") { odom.header.stamp = ros::Time::now(); odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0; odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str())); odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0; odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0; odom.twist.twist.angular.z = atof(dataSet.at(7).c_str()); } else if (dataSet.at(0) == "USL") { sonarLeft.header.stamp = ros::Time::now(); sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0; } else if (dataSet.at(0) == "USC") { sonarCenter.header.stamp = ros::Time::now(); sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0; } else if (dataSet.at(0) == "USR") { sonarRight.header.stamp = ros::Time::now(); sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0; } } } } <commit_msg>Added PID for driving Added a PID in abridge to control all aspects of movment. It attempts to maintain a target velocity and make the yaw error that is passed in 0. Currently no operable due to mobility and arduino code notbeing setup to work with the PID This also means the pid is not tuned or run time testead.<commit_after>#include <ros/ros.h> //ROS libraries #include <tf/transform_datatypes.h> //ROS messages #include <std_msgs/Float32.h> #include <std_msgs/String.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/QuaternionStamped.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/Range.h> //Package include #include <usbSerial.h> using namespace std; //aBridge functions void cmdHandler(const geometry_msgs::Twist::ConstPtr& message); void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle); void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle); void serialActivityTimer(const ros::TimerEvent& e); void publishRosTopics(); void parseData(string data); //Globals geometry_msgs::QuaternionStamped fingerAngle; geometry_msgs::QuaternionStamped wristAngle; sensor_msgs::Imu imu; nav_msgs::Odometry odom; sensor_msgs::Range sonarLeft; sensor_msgs::Range sonarCenter; sensor_msgs::Range sonarRight; USBSerial usb; const int baud = 115200; char dataCmd[] = "d\n"; char moveCmd[16]; char host[128]; float linearSpeed = 0.; float yawError = 0.; const float deltaTime = 0.1; //PID constants and arrays float Kpv = 0; //Proportinal Velocity float Kiv = 0; //Integral Velocity float Kdv = 0; //Derivative Velocity int stepV = 0; //keeps track of the point in the array for adding new error each update cycle. float evArray[1000]; //array of previous error for (arraySize/hz) seconds (error Velocity Array) float pvError = 0; //previouse velocity error float Kpy = 0; //Proportinal Yaw float Kiy = 0; //Inegral Yaw float Kdy = 0; //Derivative Yaw int stepY = 0; //keeps track of the point in the array for adding new error each update cycle. float eyArray[1000]; //array of previous error for (arraySize/hz) seconds (error Yaw Array) float pyError = 0; //previouse yaw error //Publishers ros::Publisher fingerAnglePublish; ros::Publisher wristAnglePublish; ros::Publisher imuPublish; ros::Publisher odomPublish; ros::Publisher sonarLeftPublish; ros::Publisher sonarCenterPublish; ros::Publisher sonarRightPublish; //Subscribers ros::Subscriber velocitySubscriber; ros::Subscriber fingerAngleSubscriber; ros::Subscriber wristAngleSubscriber; //Timers ros::Timer publishTimer; int main(int argc, char **argv) { gethostname(host, sizeof (host)); string hostname(host); string publishedName; ros::init(argc, argv, (hostname + "_ABRIDGE")); ros::NodeHandle param("~"); string devicePath; param.param("device", devicePath, string("/dev/ttyUSB0")); usb.openUSBPort(devicePath, baud); sleep(5); ros::NodeHandle aNH; if (argc >= 2) { publishedName = argv[1]; cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl; } else { publishedName = hostname; cout << "No Name Selected. Default is: " << publishedName << endl; } fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10); wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10); imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10); odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10); sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10); sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10); sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10); velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler); fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler); wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler); publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer); imu.header.frame_id = publishedName+"/base_link"; odom.header.frame_id = publishedName+"/odom"; odom.child_frame_id = publishedName+"/base_link"; ros::spin(); for (int i = 0; i < 1000; i++) { evArray[i] = 0; eyArray[i] = 0; } return EXIT_SUCCESS; } void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) { // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0 linearSpeed = (message->linear.x); // / 1.5; yawError = (message->angular.z); // / 8; //PID Code { float sat = 255; //Saturation point //Velocity-------------------------- float xVel = odom.twist.twist.linear.x; float yVel = odom.twist.twist.linear.y; float vel = sqrt(xVel*xVel + yVel*yVel); float velError = linearSpeed - vel; //calculate the error float IV = 0; //Propotinal float PV = Kpv * velError; if (PV > sat) //limit the max and minimum output of proportinal PV = sat; if (PV < -sat) PV= -sat; //Integral if (velError > 1 || velError < -1) //only use integral when error is larger than presumed noise. { evArray[stepV] = velError; //add error into the error Array. stepV++; if (stepV >= 1000) stepV = 0; float sumV= 0; for (int i= 0; i < 1000; i++) //sum the array to get the error over time from t = 0 to present. { sumV += evArray[i]; } IV = Kiv * sumV; } //anti windup //if PV is already commanding greater than half power dont use the integrel if (fabs(IV) > sat/2 || fabs(PV) > sat/2) //reset the integral to 0 if it hits its cap of half max power { for (int i= 0; i < 1000; i++) { evArray[i] = 0; } IV = 0; } float DV = 0; if (!(fabs(PV) > sat/2)) { //Derivative DV = Kdv * (velError - pvError) * 10; //10 being the frequency of the system giving us a one second prediction base. } pvError = velError; //set previouse error to current error float velOut = PV + IV + DV; if (velOut > sat) //cap vel command { velOut = sat; } else if (velOut < -sat) { velOut = -sat; } //Yaw----------------------------- float IY = 0; //Propotinal float PY = Kpv * yawError; if (PY > sat) //limit the max and minimum output of proportinal PY = sat; if (PY < -sat) PY= -sat; //Integral if (yawError > 0.1 || yawError < -0.1) //only use integral when error is larger than presumed noise. { eyArray[stepY] = yawError; //add error into the error Array. stepY++; if (stepY >= 1000) stepY = 0; float sumY= 0; for (int i= 0; i < 1000; i++) //sum the array to get the error over time from t = 0 to present. { sumY += eyArray[i]; } IY = Kiy * sumY; } //anti windup //if PV is already commanding greater than half power dont use the integrel; if (fabs(IY) > sat/2 || fabs(PY) > sat/2) //reset the integral to 0 if it hits its cap { for (int i= 0; i < 1000; i++) { eyArray[i] = 0; } IY = 0; } float DY = 0; if (!(fabs(PY) > sat/2)) { //Derivative DY = Kdy * (yawError - pyError) * 10; //10 being the frequency of the system giving us a one second prediction base. } pyError = yawError; float yawOut = PY + IY + DY; if (yawOut > sat) //cap yaw command { yawOut = sat; } else if (yawOut < -sat) { yawOut = -sat; } // } end PID int left = velOut + yawOut; int right = velOut - yawOut; if (left > sat) {left = sat;} if (left < -sat) {left = -sat;} if (right > sat) {right = sat;} if (right < -sat){right = -sat;} sprintf(moveCmd, "v,%d%d\n", left, right); usb.sendData(moveCmd); memset(&moveCmd, '\0', sizeof (moveCmd)); } // The finger and wrist handlers receive gripper angle commands in floating point // radians, write them to a string and send that to the arduino // for processing. void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) { char cmd[16]={'\0'}; // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small if (angle->data < 0.01) { // 'f' indicates this is a finger command to the arduino sprintf(cmd, "f,0\n"); } else { sprintf(cmd, "f,%.4g\n", angle->data); } usb.sendData(cmd); memset(&cmd, '\0', sizeof (cmd)); } void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) { char cmd[16]={'\0'}; // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small if (angle->data < 0.01) { // 'w' indicates this is a wrist command to the arduino sprintf(cmd, "w,0\n"); } else { sprintf(cmd, "w,%.4g\n", angle->data); } usb.sendData(cmd); memset(&cmd, '\0', sizeof (cmd)); } void serialActivityTimer(const ros::TimerEvent& e) { usb.sendData(dataCmd); parseData(usb.readData()); publishRosTopics(); } void publishRosTopics() { fingerAnglePublish.publish(fingerAngle); wristAnglePublish.publish(wristAngle); imuPublish.publish(imu); odomPublish.publish(odom); sonarLeftPublish.publish(sonarLeft); sonarCenterPublish.publish(sonarCenter); sonarRightPublish.publish(sonarRight); } void parseData(string str) { istringstream oss(str); string sentence; while (getline(oss, sentence, '\n')) { istringstream wss(sentence); string word; vector<string> dataSet; while (getline(wss, word, ',')) { dataSet.push_back(word); } if (dataSet.size() >= 3 && dataSet.at(1) == "1") { if (dataSet.at(0) == "GRF") { fingerAngle.header.stamp = ros::Time::now(); fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0); } else if (dataSet.at(0) == "GRW") { wristAngle.header.stamp = ros::Time::now(); wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0); } else if (dataSet.at(0) == "IMU") { imu.header.stamp = ros::Time::now(); imu.linear_acceleration.x = atof(dataSet.at(2).c_str()); imu.linear_acceleration.y = atof(dataSet.at(3).c_str()); imu.linear_acceleration.z = atof(dataSet.at(4).c_str()); imu.angular_velocity.x = atof(dataSet.at(5).c_str()); imu.angular_velocity.y = atof(dataSet.at(6).c_str()); imu.angular_velocity.z = atof(dataSet.at(7).c_str()); imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str())); } else if (dataSet.at(0) == "ODOM") { odom.header.stamp = ros::Time::now(); odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0; odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str())); odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0; odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0; odom.twist.twist.angular.z = atof(dataSet.at(7).c_str()); } else if (dataSet.at(0) == "USL") { sonarLeft.header.stamp = ros::Time::now(); sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0; } else if (dataSet.at(0) == "USC") { sonarCenter.header.stamp = ros::Time::now(); sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0; } else if (dataSet.at(0) == "USR") { sonarRight.header.stamp = ros::Time::now(); sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0; } } } } <|endoftext|>
<commit_before>#include "pacman.hh" #include <fnmatch.h> #include <glob.h> #include <algorithm> #include <fstream> #include <iterator> #include <sstream> #include <string> #include <vector> namespace std { template <> struct default_delete<glob_t> { void operator()(glob_t* globbuf) { globfree(globbuf); delete globbuf; } }; } // namespace std namespace { std::string* ltrim(std::string* s) { s->erase(s->begin(), std::find_if(s->begin(), s->end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } std::string* rtrim(std::string* s) { s->erase(std::find_if(s->rbegin(), s->rend(), std::not1(std::ptr_fun<int, int>(std::isspace))) .base(), s->end()); return s; } std::string* trim(std::string* s) { return ltrim(rtrim(s)); } bool IsSection(const std::string& s) { return s.size() > 2 && s[0] == '[' && s[s.size() - 1] == ']'; } } // namespace namespace auracle { Pacman::Pacman(alpm_handle_t* alpm, std::vector<std::string> ignored_packages) : alpm_(alpm), local_db_(alpm_get_localdb(alpm_)), ignored_packages_(std::move(ignored_packages)) {} Pacman::~Pacman() { alpm_release(alpm_); } struct ParseState { alpm_handle_t* alpm; std::string dbpath = "/var/lib/pacman"; std::string rootdir = "/"; std::string section; std::vector<std::string> ignorepkgs; std::vector<std::string> repos; }; bool ParseOneFile(const std::string& path, ParseState* state) { std::ifstream file(path); std::string line; while (std::getline(file, line)) { trim(&line); if (line.empty() || line[0] == '#') { continue; } if (IsSection(line)) { state->section = line.substr(1, line.size() - 2); continue; } auto equals = line.find('='); if (equals == std::string::npos) { // There aren't any directives we care about which are valueless. continue; } auto key = line.substr(0, equals); trim(&key); auto value = line.substr(equals + 1); trim(&value); if (state->section == "options") { if (key == "IgnorePkg") { std::istringstream iss(value); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(state->ignorepkgs)); } else if (key == "DBPath") { state->dbpath = value; } else if (key == "RootDir") { state->rootdir = value; } } else { state->repos.emplace_back(state->section); } if (key == "Include") { auto globbuf = std::make_unique<glob_t>(); if (glob(value.c_str(), GLOB_NOCHECK, nullptr, globbuf.get()) != 0) { return false; } for (size_t i = 0; i < globbuf->gl_pathc; ++i) { if (!ParseOneFile(globbuf->gl_pathv[i], state)) { return false; } } } } file.close(); return true; } // static std::unique_ptr<Pacman> Pacman::NewFromConfig(const std::string& config_file) { ParseState state; if (!ParseOneFile(config_file, &state)) { return nullptr; } alpm_errno_t err; state.alpm = alpm_initialize("/", state.dbpath.c_str(), &err); if (state.alpm == nullptr) { return nullptr; } for (const auto& repo : state.repos) { alpm_register_syncdb(state.alpm, repo.c_str(), static_cast<alpm_siglevel_t>(0)); } return std::unique_ptr<Pacman>( new Pacman(state.alpm, std::move(state.ignorepkgs))); } bool Pacman::ShouldIgnorePackage(const std::string& package) const { return std::find_if(ignored_packages_.cbegin(), ignored_packages_.cend(), [&package](const std::string& p) { return fnmatch(p.c_str(), package.c_str(), 0) == 0; }) != ignored_packages_.cend(); } std::string Pacman::RepoForPackage(const std::string& package) const { for (auto i = alpm_get_syncdbs(alpm_); i != nullptr; i = i->next) { auto db = static_cast<alpm_db_t*>(i->data); auto pkgcache = alpm_db_get_pkgcache(db); if (alpm_find_satisfier(pkgcache, package.c_str()) != nullptr) { return alpm_db_get_name(db); } } return std::string(); } bool Pacman::DependencyIsSatisfied(const std::string& package) const { auto* cache = alpm_db_get_pkgcache(local_db_); return alpm_find_satisfier(cache, package.c_str()) != nullptr; } std::optional<Pacman::Package> Pacman::GetLocalPackage( const std::string& name) const { auto* pkg = alpm_db_get_pkg(local_db_, name.c_str()); if (pkg == nullptr) { return std::nullopt; } return Package{alpm_pkg_get_name(pkg), alpm_pkg_get_version(pkg)}; } std::vector<Pacman::Package> Pacman::ForeignPackages() const { std::vector<Package> packages; for (auto i = alpm_db_get_pkgcache(local_db_); i != nullptr; i = i->next) { const auto pkg = static_cast<alpm_pkg_t*>(i->data); std::string pkgname(alpm_pkg_get_name(pkg)); if (RepoForPackage(pkgname).empty()) { packages.emplace_back(std::move(pkgname), alpm_pkg_get_version(pkg)); } } return packages; } // static int Pacman::Vercmp(const std::string& a, const std::string& b) { return alpm_pkg_vercmp(a.c_str(), b.c_str()); } } // namespace auracle <commit_msg>Avoid use of deprecated/removed functions<commit_after>#include "pacman.hh" #include <fnmatch.h> #include <glob.h> #include <algorithm> #include <fstream> #include <iterator> #include <sstream> #include <string> #include <vector> namespace std { template <> struct default_delete<glob_t> { void operator()(glob_t* globbuf) { globfree(globbuf); delete globbuf; } }; } // namespace std namespace { bool notspace(char c) { return !std::isspace(c); } std::string* ltrim(std::string* s) { s->erase(s->begin(), std::find_if(s->begin(), s->end(), &notspace)); return s; } std::string* rtrim(std::string* s) { s->erase(std::find_if(s->rbegin(), s->rend(), &notspace).base(), s->end()); return s; } std::string* trim(std::string* s) { return ltrim(rtrim(s)); } bool IsSection(const std::string& s) { return s.size() > 2 && s[0] == '[' && s[s.size() - 1] == ']'; } } // namespace namespace auracle { Pacman::Pacman(alpm_handle_t* alpm, std::vector<std::string> ignored_packages) : alpm_(alpm), local_db_(alpm_get_localdb(alpm_)), ignored_packages_(std::move(ignored_packages)) {} Pacman::~Pacman() { alpm_release(alpm_); } struct ParseState { alpm_handle_t* alpm; std::string dbpath = "/var/lib/pacman"; std::string rootdir = "/"; std::string section; std::vector<std::string> ignorepkgs; std::vector<std::string> repos; }; bool ParseOneFile(const std::string& path, ParseState* state) { std::ifstream file(path); std::string line; while (std::getline(file, line)) { trim(&line); if (line.empty() || line[0] == '#') { continue; } if (IsSection(line)) { state->section = line.substr(1, line.size() - 2); continue; } auto equals = line.find('='); if (equals == std::string::npos) { // There aren't any directives we care about which are valueless. continue; } auto key = line.substr(0, equals); trim(&key); auto value = line.substr(equals + 1); trim(&value); if (state->section == "options") { if (key == "IgnorePkg") { std::istringstream iss(value); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(state->ignorepkgs)); } else if (key == "DBPath") { state->dbpath = value; } else if (key == "RootDir") { state->rootdir = value; } } else { state->repos.emplace_back(state->section); } if (key == "Include") { auto globbuf = std::make_unique<glob_t>(); if (glob(value.c_str(), GLOB_NOCHECK, nullptr, globbuf.get()) != 0) { return false; } for (size_t i = 0; i < globbuf->gl_pathc; ++i) { if (!ParseOneFile(globbuf->gl_pathv[i], state)) { return false; } } } } file.close(); return true; } // static std::unique_ptr<Pacman> Pacman::NewFromConfig(const std::string& config_file) { ParseState state; if (!ParseOneFile(config_file, &state)) { return nullptr; } alpm_errno_t err; state.alpm = alpm_initialize("/", state.dbpath.c_str(), &err); if (state.alpm == nullptr) { return nullptr; } for (const auto& repo : state.repos) { alpm_register_syncdb(state.alpm, repo.c_str(), static_cast<alpm_siglevel_t>(0)); } return std::unique_ptr<Pacman>( new Pacman(state.alpm, std::move(state.ignorepkgs))); } bool Pacman::ShouldIgnorePackage(const std::string& package) const { return std::find_if(ignored_packages_.cbegin(), ignored_packages_.cend(), [&package](const std::string& p) { return fnmatch(p.c_str(), package.c_str(), 0) == 0; }) != ignored_packages_.cend(); } std::string Pacman::RepoForPackage(const std::string& package) const { for (auto i = alpm_get_syncdbs(alpm_); i != nullptr; i = i->next) { auto db = static_cast<alpm_db_t*>(i->data); auto pkgcache = alpm_db_get_pkgcache(db); if (alpm_find_satisfier(pkgcache, package.c_str()) != nullptr) { return alpm_db_get_name(db); } } return std::string(); } bool Pacman::DependencyIsSatisfied(const std::string& package) const { auto* cache = alpm_db_get_pkgcache(local_db_); return alpm_find_satisfier(cache, package.c_str()) != nullptr; } std::optional<Pacman::Package> Pacman::GetLocalPackage( const std::string& name) const { auto* pkg = alpm_db_get_pkg(local_db_, name.c_str()); if (pkg == nullptr) { return std::nullopt; } return Package{alpm_pkg_get_name(pkg), alpm_pkg_get_version(pkg)}; } std::vector<Pacman::Package> Pacman::ForeignPackages() const { std::vector<Package> packages; for (auto i = alpm_db_get_pkgcache(local_db_); i != nullptr; i = i->next) { const auto pkg = static_cast<alpm_pkg_t*>(i->data); std::string pkgname(alpm_pkg_get_name(pkg)); if (RepoForPackage(pkgname).empty()) { packages.emplace_back(std::move(pkgname), alpm_pkg_get_version(pkg)); } } return packages; } // static int Pacman::Vercmp(const std::string& a, const std::string& b) { return alpm_pkg_vercmp(a.c_str(), b.c_str()); } } // namespace auracle <|endoftext|>
<commit_before>#include "playsong.h" //#include "mary.mid.h" //byte dir = HIGH; void playSong(const uint32_t *const *song) { if (!song) return; WaitTime wt[4] = { }; uint32_t indx[4] = { 0 }; uint32_t freq[] = { song[0] ? getElement(song[0], 0) : DONE, song[1] ? getElement(song[1], 0) : DONE, song[2] ? getElement(song[2], 0) : DONE, song[3] ? getElement(song[3], 0) : DONE, }; uint32_t len[] = { song[0] ? getElement(song[0], 1) : DONE, song[1] ? getElement(song[1], 1) : DONE, song[2] ? getElement(song[2], 1) : DONE, song[3] ? getElement(song[3], 1) : DONE, }; uint64_t currentTime = 0; while (!(isDone(freq[0], len[0]) && isDone(freq[1], len[1]) && isDone(freq[2], len[2]) && isDone(freq[3], len[3]))) { for (uint8_t d = 0; d < 4; ++d) { currentTime = (uint64_t)micros(); if (!isDone(freq[d], len[d])) { if (wt[d].nextStep < currentTime) { if (freq[d] != REST) pulse(d); wt[d].nextStep = currentTime + (freq[d] = (uint64_t)(getElement(song[d], indx[d]))); } if (!wt[d].stopTime) { wt[d].stopTime = currentTime + (len[d] = (uint64_t)(getElement(song[d], indx[d] + 1))); } if (wt[d].stopTime < currentTime) { indx[d] += 2; wt[d].nextStep = currentTime + (freq[d] = (uint64_t)(getElement(song[d], indx[d]))); wt[d].stopTime = currentTime + (len[d] = (uint64_t)(getElement(song[d], indx[d] + 1))); } } } } } <commit_msg>i have no idea<commit_after>#include "playsong.h" void playSong(const uint32_t *const *song) { if (!song) return; WaitTime wt[4] = { }; uint32_t indx[4] = { 0 }; uint32_t freq[] = { song[0] ? getElement(song[0], 0) : DONE, song[1] ? getElement(song[1], 0) : DONE, song[2] ? getElement(song[2], 0) : DONE, song[3] ? getElement(song[3], 0) : DONE, }; uint32_t len[] = { song[0] ? getElement(song[0], 1) : DONE, song[1] ? getElement(song[1], 1) : DONE, song[2] ? getElement(song[2], 1) : DONE, song[3] ? getElement(song[3], 1) : DONE, }; uint64_t currentTime = 0; while (!(isDone(freq[0], len[0]) && isDone(freq[1], len[1]) && isDone(freq[2], len[2]) && isDone(freq[3], len[3]))) { for (uint8_t d = 0; d < 4; ++d) { currentTime = (uint64_t)micros(); if (!isDone(freq[d], len[d])) { if (wt[d].nextStep < currentTime) { if (freq[d] != REST) pulse(d); wt[d].nextStep = currentTime + (freq[d] = (uint64_t)(getElement(song[d], indx[d]))); } if (!wt[d].stopTime) { wt[d].stopTime = currentTime + (len[d] = (uint64_t)(getElement(song[d], indx[d] + 1))); } if (wt[d].stopTime < currentTime) { indx[d] += 2; wt[d].nextStep = currentTime + (freq[d] = (uint64_t)(getElement(song[d], indx[d]))); wt[d].stopTime = currentTime + (len[d] = (uint64_t)(getElement(song[d], indx[d] + 1))); } } } } } <|endoftext|>
<commit_before>#include "guard.h" #include "core/level.h" #include "core/environment.h" #include "core/keyboardevent.h" #include <iostream> using namespace std; Guard::Guard(Object *parent, ObjectID id, double x, double y, int mass, bool walkable, string t, int dir) : Object(parent, id, x, y), m_animation (new Animation("res/sprites/idle.png", 0, 0, 70, 70, 2, 1000, true)), m_direction((Direction) dir), m_last(0), type(t) { this->set_w(70); this->set_h(70); this->set_walkable(walkable); update_vision(); } Guard::~Guard() { } Guard::Direction Guard::direction() { return m_direction; } void Guard::update_vision() { const list<Object *> filhos = this->children(); for (auto filho : filhos) { if(filho->id() == "visao") { remove_child(filho); } } if(direction() == Guard::RIGHT) { Sight *visao = new Sight(this, "visao", this->x()+40, this->y(), 200, 80); add_child(visao); } else if(direction() == Guard::LEFT) { Sight *visao = new Sight(this, "visao", this->x() - 200, this->y(), 240, 80); add_child(visao); } else if(direction() == Guard::UP) { Sight *visao = new Sight(this, "visao", this->x(), this->y() - 200, 80, 240); add_child(visao); } else if(direction() == Guard::DOWN) { Sight *visao = new Sight(this, "visao", this->x(), this->y() + 40, 80, 200); add_child(visao); } } void Guard::set_direction(Direction direction) { m_direction = direction; } void Guard::draw_self() { m_animation->draw(x(), y()); } void Guard::walk(unsigned long elapsed) { double speed = 0.3; if(type == "easy") return; else if(type == "normal") { if(elapsed - m_last > 3000) { if(direction() == Guard::RIGHT || direction() == Guard::LEFT) { set_x(x() - speed + (speed * direction())); } if(direction() == Guard::UP || direction() == Guard::DOWN) { set_y(y() - 2 * speed + (speed * direction())); } } } else if(type == "hard") { if(player_posx < this->x()) set_x(x() - speed); else set_x(x() + speed); if(player_posy < this->y()) set_y(y() - speed); else set_y(y() + speed); } return; } void Guard::update_direction(unsigned long elapsed) { if(type == "easy") { if(elapsed - m_last > 1000) { int random = rand()%100; if(random < 25) set_direction(Guard::LEFT); else if(random < 50) set_direction(Guard::UP); else if(random < 75) set_direction(Guard::RIGHT); else set_direction(Guard::DOWN); m_last = elapsed; } } else if (type == "normal") { if(elapsed - m_last > 5000) { int test = ((int)direction() + 2) % 4; Direction new_direction = (Direction)test; set_direction(new_direction); m_last = elapsed; } } else if(type == "hard") { if(elapsed - m_last > 5000) { int random = rand()%100; if(random < 25) set_direction(Guard::LEFT); else if(random < 50) set_direction(Guard::UP); else if(random < 75) set_direction(Guard::RIGHT); else set_direction(Guard::DOWN); m_last = elapsed; } } m_animation->set_row(this->direction()); } void Guard::get_playerx(int pos_x) { player_posx = pos_x; } void Guard::get_playery(int pos_y) { player_posy = pos_y; } void Guard::update_self(unsigned long elapsed) { set_x(this->x()); set_y(this->y()); update_direction(elapsed); m_animation->update(elapsed); walk(elapsed); update_vision(); } <commit_msg>Melhorando a IA do guarda no modo hard.<commit_after>#include "guard.h" #include "core/level.h" #include "core/environment.h" #include "core/keyboardevent.h" #include <iostream> using namespace std; Guard::Guard(Object *parent, ObjectID id, double x, double y, int mass, bool walkable, string t, int dir) : Object(parent, id, x, y), m_animation (new Animation("res/sprites/idle.png", 0, 0, 70, 70, 2, 1000, true)), m_direction((Direction) dir), m_last(0), type(t) { this->set_w(70); this->set_h(70); this->set_walkable(walkable); update_vision(); } Guard::~Guard() { } Guard::Direction Guard::direction() { return m_direction; } void Guard::update_vision() { const list<Object *> filhos = this->children(); for (auto filho : filhos) { if(filho->id() == "visao") { remove_child(filho); } } if(direction() == Guard::RIGHT) { Sight *visao = new Sight(this, "visao", this->x()+40, this->y(), 200, 80); add_child(visao); } else if(direction() == Guard::LEFT) { Sight *visao = new Sight(this, "visao", this->x() - 200, this->y(), 240, 80); add_child(visao); } else if(direction() == Guard::UP) { Sight *visao = new Sight(this, "visao", this->x(), this->y() - 200, 80, 240); add_child(visao); } else if(direction() == Guard::DOWN) { Sight *visao = new Sight(this, "visao", this->x(), this->y() + 40, 80, 200); add_child(visao); } } void Guard::set_direction(Direction direction) { m_direction = direction; } void Guard::draw_self() { m_animation->draw(x(), y()); } void Guard::walk(unsigned long elapsed) { double speed = 0.3; if(type == "easy") return; else if(type == "normal") { if(elapsed - m_last > 3000) { if(direction() == Guard::RIGHT || direction() == Guard::LEFT) { set_x(x() - speed + (speed * direction())); } if(direction() == Guard::UP || direction() == Guard::DOWN) { set_y(y() - 2 * speed + (speed * direction())); } } } else if(type == "hard") { if(player_posx < this->x()) set_x(x() - speed); else set_x(x() + speed); if(player_posy < this->y()) set_y(y() - speed); else set_y(y() + speed); if(player_posx > this->x() - 100 && player_posx < this->x() + 100 && player_posy < this->y()) set_direction(Guard::UP); else if(player_posx > this->x() - 100 && player_posx < this->x() + 100 && player_posy > this->y()) set_direction(Guard::DOWN); else if(player_posx < this->x()) set_direction(Guard::LEFT); else set_direction(Guard::RIGHT); } return; } void Guard::update_direction(unsigned long elapsed) { if(type == "easy") { if(elapsed - m_last > 1000) { int random = rand()%100; if(random < 25) set_direction(Guard::LEFT); else if(random < 50) set_direction(Guard::UP); else if(random < 75) set_direction(Guard::RIGHT); else set_direction(Guard::DOWN); m_last = elapsed; } } else if (type == "normal") { if(elapsed - m_last > 5000) { int test = ((int)direction() + 2) % 4; Direction new_direction = (Direction)test; set_direction(new_direction); m_last = elapsed; } } else if(type == "hard") { if(elapsed - m_last > 5000) { int random = rand()%100; if(random < 25) set_direction(Guard::LEFT); else if(random < 50) set_direction(Guard::UP); else if(random < 75) set_direction(Guard::RIGHT); else set_direction(Guard::DOWN); m_last = elapsed; } } m_animation->set_row(this->direction()); } void Guard::get_playerx(int pos_x) { player_posx = pos_x; } void Guard::get_playery(int pos_y) { player_posy = pos_y; } void Guard::update_self(unsigned long elapsed) { set_x(this->x()); set_y(this->y()); update_direction(elapsed); m_animation->update(elapsed); walk(elapsed); update_vision(); } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <appbase/application.hpp> #include <eosio/chain/asset.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/block.hpp> #include <eosio/chain/chain_controller.hpp> #include <eosio/chain/contracts/contract_table_objects.hpp> #include <eosio/chain/transaction.hpp> #include <eosio/chain/contracts/abi_serializer.hpp> #include <boost/container/flat_set.hpp> namespace fc { class variant; } namespace eosio { using chain::chain_controller; using std::unique_ptr; using namespace appbase; using chain::name; using chain::uint128_t; using chain::public_key_type; using fc::optional; using boost::container::flat_set; using chain::asset; using chain::authority; using chain::account_name; using chain::contracts::abi_def; using chain::contracts::abi_serializer; namespace chain_apis { struct empty{}; struct permission { name perm_name; name parent; authority required_auth; }; class read_only { const chain_controller& db; public: static const string KEYi64; static const string KEYstr; static const string KEYi128i128; static const string KEYi64i64i64; static const string PRIMARY; static const string SECONDARY; static const string TERTIARY; read_only(const chain_controller& db) : db(db) {} using get_info_params = empty; struct get_info_results { string server_version; uint32_t head_block_num = 0; uint32_t last_irreversible_block_num = 0; chain::block_id_type head_block_id; fc::time_point_sec head_block_time; account_name head_block_producer; string recent_slots; double participation_rate = 0; }; get_info_results get_info(const get_info_params&) const; struct producer_info { name producer_name; }; struct get_account_results { name account_name; asset eos_balance = asset(0,EOS_SYMBOL); asset staked_balance; asset unstaking_balance; fc::time_point_sec last_unstaking_time; vector<permission> permissions; optional<producer_info> producer; }; struct get_account_params { name account_name; }; get_account_results get_account( const get_account_params& params )const; struct get_code_results { name account_name; string wast; fc::sha256 code_hash; optional<abi_def> abi; }; struct get_code_params { name account_name; }; get_code_results get_code( const get_code_params& params )const; struct abi_json_to_bin_params { name code; name action; fc::variant args; }; struct abi_json_to_bin_result { vector<char> binargs; vector<name> required_scope; vector<name> required_auth; }; abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const; struct abi_bin_to_json_params { name code; name action; vector<char> binargs; }; struct abi_bin_to_json_result { fc::variant args; vector<name> required_scope; vector<name> required_auth; }; abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const; struct get_required_keys_params { fc::variant transaction; flat_set<public_key_type> available_keys; }; struct get_required_keys_result { flat_set<public_key_type> required_keys; }; get_required_keys_result get_required_keys( const get_required_keys_params& params)const; struct get_block_params { string block_num_or_id; }; struct get_block_results : public chain::signed_block { get_block_results( const chain::signed_block& b ) :signed_block(b), id(b.id()), block_num(b.block_num()), ref_block_prefix( id._hash[1] ) {} chain::block_id_type id; uint32_t block_num = 0; uint32_t ref_block_prefix = 0; }; get_block_results get_block(const get_block_params& params) const; struct get_table_rows_params { bool json = false; name scope; name code; name table; // string table_type; string table_key; string lower_bound; string upper_bound; uint32_t limit = 10; }; struct get_table_rows_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object bool more; ///< true if last element in data is not the end and sizeof data() < limit }; get_table_rows_result get_table_rows( const get_table_rows_params& params )const; void copy_row(const chain::contracts::key_value_object& obj, vector<char>& data)const { data.resize( sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::contracts::keystr_value_object& obj, vector<char>& data)const { data.resize( obj.primary_key.size() + obj.value.size() + 8 ); fc::datastream<char*> ds(data.data(), data.size()); fc::raw::pack(ds, obj.primary_key); ds.write(obj.value.data(), obj.value.size()); data.resize(ds.tellp()); } void copy_row(const chain::contracts::key128x128_value_object& obj, vector<char>& data)const { data.resize( 2*sizeof(uint128_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint128_t) ); memcpy( data.data()+sizeof(uint128_t), &obj.secondary_key, sizeof(uint128_t) ); memcpy( data.data()+2*sizeof(uint128_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::contracts::key64x64x64_value_object& obj, vector<char>& data)const { data.resize( 3*sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), &obj.secondary_key, sizeof(uint64_t) ); memcpy( data.data()+2*sizeof(uint64_t), &obj.tertiary_key, sizeof(uint64_t) ); memcpy( data.data()+3*sizeof(uint64_t), obj.value.data(), obj.value.size() ); } template <typename IndexType, typename Scope> read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p, const abi_def& abi )const { read_only::get_table_rows_result result; const auto& d = db.get_database(); abi_serializer abis; abis.set_abi(abi); const auto* t_id = d.find<chain::contracts::table_id_object, chain::contracts::by_scope_code_table>(boost::make_tuple(p.scope, p.code, p.table)); if (t_id != nullptr) { const auto &idx = d.get_index<IndexType, Scope>(); decltype(t_id->id) next_tid(t_id->id._id + 1); auto lower = idx.lower_bound(boost::make_tuple(t_id->id)); auto upper = idx.lower_bound(boost::make_tuple(next_tid)); if (p.lower_bound.size()) { lower = idx.lower_bound(boost::make_tuple(t_id->id, fc::variant( p.lower_bound).as<typename IndexType::value_type::key_type>())); } if (p.upper_bound.size()) { upper = idx.lower_bound(boost::make_tuple(t_id->id, fc::variant( p.upper_bound).as<typename IndexType::value_type::key_type>())); } vector<char> data; auto end = fc::time_point::now() + fc::microseconds(1000 * 10); /// 10ms max time unsigned int count = 0; auto itr = lower; for (itr = lower; itr != upper; ++itr) { copy_row(*itr, data); if (p.json) { result.rows.emplace_back(abis.binary_to_variant(abis.get_table_type(p.table), data)); } else { result.rows.emplace_back(fc::variant(data)); } if (++count == p.limit || fc::time_point::now() > end) { break; } } if (itr != upper) { result.more = true; } } return result; } }; class read_write { chain_controller& db; uint32_t skip_flags; public: read_write(chain_controller& db, uint32_t skip_flags) : db(db), skip_flags(skip_flags) {} using push_block_params = chain::signed_block; using push_block_results = empty; push_block_results push_block(const push_block_params& params); using push_transaction_params = fc::variant_object; struct push_transaction_results { chain::transaction_id_type transaction_id; fc::variant processed; }; push_transaction_results push_transaction(const push_transaction_params& params); using push_transactions_params = vector<push_transaction_params>; using push_transactions_results = vector<push_transaction_results>; push_transactions_results push_transactions(const push_transactions_params& params); }; } // namespace chain_apis class chain_plugin : public plugin<chain_plugin> { public: APPBASE_PLUGIN_REQUIRES() chain_plugin(); virtual ~chain_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain()); } chain_apis::read_write get_read_write_api(); bool accept_block(const chain::signed_block& block, bool currently_syncing); void accept_transaction(const chain::signed_transaction& trx); bool block_is_on_preferred_chain(const chain::block_id_type& block_id); // return true if --skip-transaction-signatures passed to eosd bool is_skipping_transaction_signatures() const; // Only call this in plugin_initialize() to modify chain_controller constructor configuration chain_controller::controller_config& chain_config(); // Only call this after plugin_startup()! chain_controller& chain(); // Only call this after plugin_startup()! const chain_controller& chain() const; void get_chain_id (chain::chain_id_type &cid) const; static const uint32_t default_received_block_transaction_execution_time; static const uint32_t default_transaction_execution_time; static const uint32_t default_create_block_transaction_execution_time; private: unique_ptr<class chain_plugin_impl> my; }; } FC_REFLECT( eosio::chain_apis::permission, (perm_name)(parent)(required_auth) ) FC_REFLECT(eosio::chain_apis::empty, ) FC_REFLECT(eosio::chain_apis::read_only::get_info_results, (server_version)(head_block_num)(last_irreversible_block_num)(head_block_id)(head_block_time)(head_block_producer) (recent_slots)(participation_rate)) FC_REFLECT(eosio::chain_apis::read_only::get_block_params, (block_num_or_id)) FC_REFLECT_DERIVED( eosio::chain_apis::read_only::get_block_results, (eosio::chain::signed_block), (id)(block_num)(ref_block_prefix) ); FC_REFLECT( eosio::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_params, (json)(table_key)(scope)(code)(table)(lower_bound)(upper_bound)(limit) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_result, (rows)(more) ); FC_REFLECT( eosio::chain_apis::read_only::get_account_results, (account_name)(eos_balance)(staked_balance)(unstaking_balance)(last_unstaking_time)(permissions)(producer) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_results, (account_name)(code_hash)(wast)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::get_account_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::producer_info, (producer_name) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_result, (binargs)(required_scope)(required_auth) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_result, (args)(required_scope)(required_auth) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_params, (transaction)(available_keys) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_result, (required_keys) ) <commit_msg>Update FC_REFLECT get_table_rows_params to match struct declaration. #1139<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <appbase/application.hpp> #include <eosio/chain/asset.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/block.hpp> #include <eosio/chain/chain_controller.hpp> #include <eosio/chain/contracts/contract_table_objects.hpp> #include <eosio/chain/transaction.hpp> #include <eosio/chain/contracts/abi_serializer.hpp> #include <boost/container/flat_set.hpp> namespace fc { class variant; } namespace eosio { using chain::chain_controller; using std::unique_ptr; using namespace appbase; using chain::name; using chain::uint128_t; using chain::public_key_type; using fc::optional; using boost::container::flat_set; using chain::asset; using chain::authority; using chain::account_name; using chain::contracts::abi_def; using chain::contracts::abi_serializer; namespace chain_apis { struct empty{}; struct permission { name perm_name; name parent; authority required_auth; }; class read_only { const chain_controller& db; public: static const string KEYi64; static const string KEYstr; static const string KEYi128i128; static const string KEYi64i64i64; static const string PRIMARY; static const string SECONDARY; static const string TERTIARY; read_only(const chain_controller& db) : db(db) {} using get_info_params = empty; struct get_info_results { string server_version; uint32_t head_block_num = 0; uint32_t last_irreversible_block_num = 0; chain::block_id_type head_block_id; fc::time_point_sec head_block_time; account_name head_block_producer; string recent_slots; double participation_rate = 0; }; get_info_results get_info(const get_info_params&) const; struct producer_info { name producer_name; }; struct get_account_results { name account_name; asset eos_balance = asset(0,EOS_SYMBOL); asset staked_balance; asset unstaking_balance; fc::time_point_sec last_unstaking_time; vector<permission> permissions; optional<producer_info> producer; }; struct get_account_params { name account_name; }; get_account_results get_account( const get_account_params& params )const; struct get_code_results { name account_name; string wast; fc::sha256 code_hash; optional<abi_def> abi; }; struct get_code_params { name account_name; }; get_code_results get_code( const get_code_params& params )const; struct abi_json_to_bin_params { name code; name action; fc::variant args; }; struct abi_json_to_bin_result { vector<char> binargs; vector<name> required_scope; vector<name> required_auth; }; abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const; struct abi_bin_to_json_params { name code; name action; vector<char> binargs; }; struct abi_bin_to_json_result { fc::variant args; vector<name> required_scope; vector<name> required_auth; }; abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const; struct get_required_keys_params { fc::variant transaction; flat_set<public_key_type> available_keys; }; struct get_required_keys_result { flat_set<public_key_type> required_keys; }; get_required_keys_result get_required_keys( const get_required_keys_params& params)const; struct get_block_params { string block_num_or_id; }; struct get_block_results : public chain::signed_block { get_block_results( const chain::signed_block& b ) :signed_block(b), id(b.id()), block_num(b.block_num()), ref_block_prefix( id._hash[1] ) {} chain::block_id_type id; uint32_t block_num = 0; uint32_t ref_block_prefix = 0; }; get_block_results get_block(const get_block_params& params) const; struct get_table_rows_params { bool json = false; name scope; name code; name table; // string table_type; string table_key; string lower_bound; string upper_bound; uint32_t limit = 10; }; struct get_table_rows_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object bool more = false; ///< true if last element in data is not the end and sizeof data() < limit }; get_table_rows_result get_table_rows( const get_table_rows_params& params )const; void copy_row(const chain::contracts::key_value_object& obj, vector<char>& data)const { data.resize( sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::contracts::keystr_value_object& obj, vector<char>& data)const { data.resize( obj.primary_key.size() + obj.value.size() + 8 ); fc::datastream<char*> ds(data.data(), data.size()); fc::raw::pack(ds, obj.primary_key); ds.write(obj.value.data(), obj.value.size()); data.resize(ds.tellp()); } void copy_row(const chain::contracts::key128x128_value_object& obj, vector<char>& data)const { data.resize( 2*sizeof(uint128_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint128_t) ); memcpy( data.data()+sizeof(uint128_t), &obj.secondary_key, sizeof(uint128_t) ); memcpy( data.data()+2*sizeof(uint128_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::contracts::key64x64x64_value_object& obj, vector<char>& data)const { data.resize( 3*sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), &obj.secondary_key, sizeof(uint64_t) ); memcpy( data.data()+2*sizeof(uint64_t), &obj.tertiary_key, sizeof(uint64_t) ); memcpy( data.data()+3*sizeof(uint64_t), obj.value.data(), obj.value.size() ); } template <typename IndexType, typename Scope> read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p, const abi_def& abi )const { read_only::get_table_rows_result result; const auto& d = db.get_database(); abi_serializer abis; abis.set_abi(abi); const auto* t_id = d.find<chain::contracts::table_id_object, chain::contracts::by_scope_code_table>(boost::make_tuple(p.scope, p.code, p.table)); if (t_id != nullptr) { const auto &idx = d.get_index<IndexType, Scope>(); decltype(t_id->id) next_tid(t_id->id._id + 1); auto lower = idx.lower_bound(boost::make_tuple(t_id->id)); auto upper = idx.lower_bound(boost::make_tuple(next_tid)); if (p.lower_bound.size()) { lower = idx.lower_bound(boost::make_tuple(t_id->id, fc::variant( p.lower_bound).as<typename IndexType::value_type::key_type>())); } if (p.upper_bound.size()) { upper = idx.lower_bound(boost::make_tuple(t_id->id, fc::variant( p.upper_bound).as<typename IndexType::value_type::key_type>())); } vector<char> data; auto end = fc::time_point::now() + fc::microseconds(1000 * 10); /// 10ms max time unsigned int count = 0; auto itr = lower; for (itr = lower; itr != upper; ++itr) { copy_row(*itr, data); if (p.json) { result.rows.emplace_back(abis.binary_to_variant(abis.get_table_type(p.table), data)); } else { result.rows.emplace_back(fc::variant(data)); } if (++count == p.limit || fc::time_point::now() > end) { break; } } if (itr != upper) { result.more = true; } } return result; } }; class read_write { chain_controller& db; uint32_t skip_flags; public: read_write(chain_controller& db, uint32_t skip_flags) : db(db), skip_flags(skip_flags) {} using push_block_params = chain::signed_block; using push_block_results = empty; push_block_results push_block(const push_block_params& params); using push_transaction_params = fc::variant_object; struct push_transaction_results { chain::transaction_id_type transaction_id; fc::variant processed; }; push_transaction_results push_transaction(const push_transaction_params& params); using push_transactions_params = vector<push_transaction_params>; using push_transactions_results = vector<push_transaction_results>; push_transactions_results push_transactions(const push_transactions_params& params); }; } // namespace chain_apis class chain_plugin : public plugin<chain_plugin> { public: APPBASE_PLUGIN_REQUIRES() chain_plugin(); virtual ~chain_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain()); } chain_apis::read_write get_read_write_api(); bool accept_block(const chain::signed_block& block, bool currently_syncing); void accept_transaction(const chain::signed_transaction& trx); bool block_is_on_preferred_chain(const chain::block_id_type& block_id); // return true if --skip-transaction-signatures passed to eosd bool is_skipping_transaction_signatures() const; // Only call this in plugin_initialize() to modify chain_controller constructor configuration chain_controller::controller_config& chain_config(); // Only call this after plugin_startup()! chain_controller& chain(); // Only call this after plugin_startup()! const chain_controller& chain() const; void get_chain_id (chain::chain_id_type &cid) const; static const uint32_t default_received_block_transaction_execution_time; static const uint32_t default_transaction_execution_time; static const uint32_t default_create_block_transaction_execution_time; private: unique_ptr<class chain_plugin_impl> my; }; } FC_REFLECT( eosio::chain_apis::permission, (perm_name)(parent)(required_auth) ) FC_REFLECT(eosio::chain_apis::empty, ) FC_REFLECT(eosio::chain_apis::read_only::get_info_results, (server_version)(head_block_num)(last_irreversible_block_num)(head_block_id)(head_block_time)(head_block_producer) (recent_slots)(participation_rate)) FC_REFLECT(eosio::chain_apis::read_only::get_block_params, (block_num_or_id)) FC_REFLECT_DERIVED( eosio::chain_apis::read_only::get_block_results, (eosio::chain::signed_block), (id)(block_num)(ref_block_prefix) ); FC_REFLECT( eosio::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_params, (json)(scope)(code)(table)(table_key)(lower_bound)(upper_bound)(limit) ) FC_REFLECT( eosio::chain_apis::read_only::get_table_rows_result, (rows)(more) ); FC_REFLECT( eosio::chain_apis::read_only::get_account_results, (account_name)(eos_balance)(staked_balance)(unstaking_balance)(last_unstaking_time)(permissions)(producer) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_results, (account_name)(code_hash)(wast)(abi) ) FC_REFLECT( eosio::chain_apis::read_only::get_account_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::get_code_params, (account_name) ) FC_REFLECT( eosio::chain_apis::read_only::producer_info, (producer_name) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) ) FC_REFLECT( eosio::chain_apis::read_only::abi_json_to_bin_result, (binargs)(required_scope)(required_auth) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) ) FC_REFLECT( eosio::chain_apis::read_only::abi_bin_to_json_result, (args)(required_scope)(required_auth) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_params, (transaction)(available_keys) ) FC_REFLECT( eosio::chain_apis::read_only::get_required_keys_result, (required_keys) ) <|endoftext|>
<commit_before>// Copyright 2015 Matt Heard // http://mattheard.net // [email protected] // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 2; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const cv::Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } return 0; } <commit_msg>Update args list desc<commit_after>// Copyright 2015 Matt Heard // http://mattheard.net // [email protected] // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const cv::Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } return 0; } <|endoftext|>
<commit_before>// Copyright 2015 Matt Heard // http://mattheard.net // [email protected] // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; Mat buildLookUpTable(const int divideWith) { const int rows = 1; const int cols = 256; const int type = CV_8U; const Mat table(rows, cols, type); for (int i = 0; i < 256; ++i) { const int reduced = divideWith * (i / divideWith); table.data[i] = (uchar) reduced; } return table; } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::endl; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } const Mat lookUpTable = buildLookUpTable(divideWith); Mat dstImg; LUT(srcImg, lookUpTable, dstImg); const string outputFilename = "reduced.jpg"; imwrite(outputFilename, dstImg); return 0; } <commit_msg>Correct usage msg<commit_after>// Copyright 2015 Matt Heard // http://mattheard.net // [email protected] // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; Mat buildLookUpTable(const int divideWith) { const int rows = 1; const int cols = 256; const int type = CV_8U; const Mat table(rows, cols, type); for (int i = 0; i < 256; ++i) { const int reduced = divideWith * (i / divideWith); table.data[i] = (uchar) reduced; } return table; } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ReduceColours"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::endl; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } const Mat lookUpTable = buildLookUpTable(divideWith); Mat dstImg; LUT(srcImg, lookUpTable, dstImg); const string outputFilename = "reduced.jpg"; imwrite(outputFilename, dstImg); return 0; } <|endoftext|>
<commit_before>/* ** Copyright 2012 Centreon ** ** 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. ** ** For more information : [email protected] */ #ifndef CCB_TIMESTAMP_HH # define CCB_TIMESTAMP_HH # include <ctime> # include <istream> # include "com/centreon/broker/namespace.hh" CCB_BEGIN() /** * @class timestamp timestamp.hh "com/centreon/broker/timestamp.hh" * @brief Timestamp class. * * Holds the time. */ struct timestamp { public: /** * Default constructor. * * Time is not defined. */ timestamp() : _sec((time_t)-1) {} /** * Build from a time_t. * * @param[in] t Time expressed in time_t. */ timestamp(std::time_t t) : _sec(t) {} /** * Copy constructor. * * @param[in] right Object to copy. */ timestamp(timestamp const& right) : _sec(right._sec) {} /** * Destructor. */ ~timestamp() {} /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ timestamp& operator=(timestamp const& right) { if (this != &right) _sec = right._sec; return (*this); } /** * Get timestamp as time_t. * * @return Timestamp as time_t. */ operator std::time_t() const { return (_sec); } /** * Get timestamp as time_t. * * @return Timestamp as time_t. */ std::time_t get_time_t() const { return (_sec); } /** * Is this a null timestamp ? * * @return True if this is a null timestamp. */ bool is_null() const { return (_sec == (time_t)-1); } /** * Clear the timestamp. */ void clear() { _sec = (time_t)-1; } /** * Comparison function. * * @param[in] left The left object. * @param[in] right The right object. * * @return True if this object is less than the other. */ static bool less(timestamp const& left, timestamp const& right) { if (left.is_null() && !right.is_null()) return (false); else if (!left.is_null() && right.is_null()) return (true); else return (left._sec < right._sec); } /** * Return a timestamp from now. * * @return A timestamp set to present time, present day. */ static timestamp now() { return (::time(NULL)); } static timestamp max() { return (timestamp()); } // Data. std::time_t _sec; }; /** * Stream operator for timestamp. * * @param[in] stream The stream. * @param[in] ts The timestamp. * * @return Reference to the stream. */ inline std::istream& operator>>(std::istream& stream, timestamp& ts) { std::time_t s; stream >> s; ts = timestamp(s); return (stream); } CCB_END() #endif // !CCB_TIMESTAMP_HH <commit_msg>core: make 0 an invalid timestamp value.<commit_after>/* ** Copyright 2012,2015-2016 Centreon ** ** 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. ** ** For more information : [email protected] */ #ifndef CCB_TIMESTAMP_HH # define CCB_TIMESTAMP_HH # include <ctime> # include <istream> # include "com/centreon/broker/namespace.hh" CCB_BEGIN() /** * @class timestamp timestamp.hh "com/centreon/broker/timestamp.hh" * @brief Timestamp class. * * Holds the time. */ struct timestamp { public: /** * Default constructor. * * Time is not defined. */ timestamp() : _sec((time_t)-1) {} /** * Build from a time_t. * * @param[in] t Time expressed in time_t. */ timestamp(std::time_t t) : _sec(t) {} /** * Copy constructor. * * @param[in] right Object to copy. */ timestamp(timestamp const& right) : _sec(right._sec) {} /** * Destructor. */ ~timestamp() {} /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ timestamp& operator=(timestamp const& right) { if (this != &right) _sec = right._sec; return (*this); } /** * Get timestamp as time_t. * * @return Timestamp as time_t. */ operator std::time_t() const { return (_sec); } /** * Get timestamp as time_t. * * @return Timestamp as time_t. */ std::time_t get_time_t() const { return (_sec); } /** * Is this a null timestamp ? * * @return True if this is a null timestamp. */ bool is_null() const { return ((_sec == (time_t)-1) || (_sec == (time_t)0)); } /** * Clear the timestamp. */ void clear() { _sec = (time_t)-1; } /** * Comparison function. * * @param[in] left The left object. * @param[in] right The right object. * * @return True if this object is less than the other. */ static bool less(timestamp const& left, timestamp const& right) { if (left.is_null() && !right.is_null()) return (false); else if (!left.is_null() && right.is_null()) return (true); else return (left._sec < right._sec); } /** * Return a timestamp from now. * * @return A timestamp set to present time, present day. */ static timestamp now() { return (::time(NULL)); } static timestamp max() { return (timestamp()); } // Data. std::time_t _sec; }; /** * Stream operator for timestamp. * * @param[in] stream The stream. * @param[in] ts The timestamp. * * @return Reference to the stream. */ inline std::istream& operator>>(std::istream& stream, timestamp& ts) { std::time_t s; stream >> s; ts = timestamp(s); return (stream); } CCB_END() #endif // !CCB_TIMESTAMP_HH <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ /* * Zip alignment tool */ #include "ZipFile.h" #include <stdlib.h> #include <stdio.h> using namespace android; /* * Show program usage. */ void usage(void) { fprintf(stderr, "Zip alignment utility\n"); fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n"); fprintf(stderr, "Usage: zipalign [-f] [-v] <align> infile.zip outfile.zip\n" " zipalign -c [-v] <align> infile.zip\n\n" ); fprintf(stderr, " <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n"); fprintf(stderr, " -c: check alignment only (does not modify file)\n"); fprintf(stderr, " -f: overwrite existing outfile.zip\n"); fprintf(stderr, " -v: verbose output\n"); } /* * Copy all entries from "pZin" to "pZout", aligning as needed. */ static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment) { int numEntries = pZin->getNumEntries(); ZipEntry* pEntry; int bias = 0; status_t status; for (int i = 0; i < numEntries; i++) { ZipEntry* pNewEntry; int padding = 0; pEntry = pZin->getEntryByIndex(i); if (pEntry == NULL) { fprintf(stderr, "ERROR: unable to retrieve entry %d\n", i); return 1; } if (pEntry->isCompressed()) { /* copy the entry without padding */ //printf("--- %s: orig at %ld len=%ld (compressed)\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // (long) pEntry->getUncompressedLen()); } else { /* * Copy the entry, adjusting as required. We assume that the * file position in the new file will be equal to the file * position in the original. */ long newOffset = pEntry->getFileOffset() + bias; padding = (alignment - (newOffset % alignment)) % alignment; //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // bias, (long) pEntry->getUncompressedLen(), padding); } status = pZout->add(pZin, pEntry, padding, &pNewEntry); if (status != NO_ERROR) return 1; bias += padding; //printf(" added '%s' at %ld (pad=%d)\n", // pNewEntry->getFileName(), (long) pNewEntry->getFileOffset(), // padding); } return 0; } /* * Process a file. We open the input and output files, failing if the * output file exists and "force" wasn't specified. */ static int process(const char* inFileName, const char* outFileName, int alignment, bool force) { ZipFile zin, zout; //printf("PROCESS: align=%d in='%s' out='%s' force=%d\n", // alignment, inFileName, outFileName, force); /* this mode isn't supported -- do a trivial check */ if (strcmp(inFileName, outFileName) == 0) { fprintf(stderr, "Input and output can't be same file\n"); return 1; } /* don't overwrite existing unless given permission */ if (!force && access(outFileName, F_OK) == 0) { fprintf(stderr, "Output file '%s' exists\n", outFileName); return 1; } if (zin.open(inFileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } if (zout.open(outFileName, ZipFile::kOpenReadWrite|ZipFile::kOpenCreate|ZipFile::kOpenTruncate) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } int result = copyAndAlign(&zin, &zout, alignment); if (result != 0) { printf("zipalign: failed rewriting '%s' to '%s'\n", inFileName, outFileName); } return result; } /* * Verify the alignment of a zip archive. */ static int verify(const char* fileName, int alignment, bool verbose) { ZipFile zipFile; bool foundBad = false; if (verbose) printf("Verifying alignment of %s (%d)...\n", fileName, alignment); if (zipFile.open(fileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' for verification\n", fileName); return 1; } int numEntries = zipFile.getNumEntries(); ZipEntry* pEntry; for (int i = 0; i < numEntries; i++) { pEntry = zipFile.getEntryByIndex(i); if (pEntry->isCompressed()) { if (verbose) { printf("%8ld %s (OK - compressed)\n", (long) pEntry->getFileOffset(), pEntry->getFileName()); } } else { long offset = pEntry->getFileOffset(); if ((offset % alignment) != 0) { if (verbose) { printf("%8ld %s (BAD - %ld)\n", (long) offset, pEntry->getFileName(), offset % alignment); } foundBad = true; } else { if (verbose) { printf("%8ld %s (OK)\n", (long) offset, pEntry->getFileName()); } } } } if (verbose) printf("Verification %s\n", foundBad ? "FAILED" : "succesful"); return foundBad ? 1 : 0; } /* * Parse args. */ int main(int argc, char* const argv[]) { bool wantUsage = false; bool check = false; bool force = false; bool verbose = false; int result = 1; int alignment; char* endp; if (argc < 4) { wantUsage = true; goto bail; } argc--; argv++; while (argc && argv[0][0] == '-') { const char* cp = argv[0] +1; while (*cp != '\0') { switch (*cp) { case 'c': check = true; break; case 'f': force = true; break; case 'v': verbose = true; break; default: fprintf(stderr, "ERROR: unknown flag -%c\n", *cp); wantUsage = true; goto bail; } cp++; } argc--; argv++; } if (!((check && argc == 2) || (!check && argc == 3))) { wantUsage = true; goto bail; } alignment = strtol(argv[0], &endp, 10); if (*endp != '\0' || alignment <= 0) { fprintf(stderr, "Invalid value for alignment: %s\n", argv[0]); wantUsage = true; goto bail; } if (check) { /* check existing archive for correct alignment */ result = verify(argv[1], alignment, verbose); } else { /* create the new archive */ result = process(argv[1], argv[2], alignment, force); /* trust, but verify */ if (result == 0) result = verify(argv[2], alignment, verbose); } bail: if (wantUsage) { usage(); result = 2; } return result; } <commit_msg>Fix reporting wrong error message for zipalign output file<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ /* * Zip alignment tool */ #include "ZipFile.h" #include <stdlib.h> #include <stdio.h> using namespace android; /* * Show program usage. */ void usage(void) { fprintf(stderr, "Zip alignment utility\n"); fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n"); fprintf(stderr, "Usage: zipalign [-f] [-v] <align> infile.zip outfile.zip\n" " zipalign -c [-v] <align> infile.zip\n\n" ); fprintf(stderr, " <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n"); fprintf(stderr, " -c: check alignment only (does not modify file)\n"); fprintf(stderr, " -f: overwrite existing outfile.zip\n"); fprintf(stderr, " -v: verbose output\n"); } /* * Copy all entries from "pZin" to "pZout", aligning as needed. */ static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment) { int numEntries = pZin->getNumEntries(); ZipEntry* pEntry; int bias = 0; status_t status; for (int i = 0; i < numEntries; i++) { ZipEntry* pNewEntry; int padding = 0; pEntry = pZin->getEntryByIndex(i); if (pEntry == NULL) { fprintf(stderr, "ERROR: unable to retrieve entry %d\n", i); return 1; } if (pEntry->isCompressed()) { /* copy the entry without padding */ //printf("--- %s: orig at %ld len=%ld (compressed)\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // (long) pEntry->getUncompressedLen()); } else { /* * Copy the entry, adjusting as required. We assume that the * file position in the new file will be equal to the file * position in the original. */ long newOffset = pEntry->getFileOffset() + bias; padding = (alignment - (newOffset % alignment)) % alignment; //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // bias, (long) pEntry->getUncompressedLen(), padding); } status = pZout->add(pZin, pEntry, padding, &pNewEntry); if (status != NO_ERROR) return 1; bias += padding; //printf(" added '%s' at %ld (pad=%d)\n", // pNewEntry->getFileName(), (long) pNewEntry->getFileOffset(), // padding); } return 0; } /* * Process a file. We open the input and output files, failing if the * output file exists and "force" wasn't specified. */ static int process(const char* inFileName, const char* outFileName, int alignment, bool force) { ZipFile zin, zout; //printf("PROCESS: align=%d in='%s' out='%s' force=%d\n", // alignment, inFileName, outFileName, force); /* this mode isn't supported -- do a trivial check */ if (strcmp(inFileName, outFileName) == 0) { fprintf(stderr, "Input and output can't be same file\n"); return 1; } /* don't overwrite existing unless given permission */ if (!force && access(outFileName, F_OK) == 0) { fprintf(stderr, "Output file '%s' exists\n", outFileName); return 1; } if (zin.open(inFileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } if (zout.open(outFileName, ZipFile::kOpenReadWrite|ZipFile::kOpenCreate|ZipFile::kOpenTruncate) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", outFileName); return 1; } int result = copyAndAlign(&zin, &zout, alignment); if (result != 0) { printf("zipalign: failed rewriting '%s' to '%s'\n", inFileName, outFileName); } return result; } /* * Verify the alignment of a zip archive. */ static int verify(const char* fileName, int alignment, bool verbose) { ZipFile zipFile; bool foundBad = false; if (verbose) printf("Verifying alignment of %s (%d)...\n", fileName, alignment); if (zipFile.open(fileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' for verification\n", fileName); return 1; } int numEntries = zipFile.getNumEntries(); ZipEntry* pEntry; for (int i = 0; i < numEntries; i++) { pEntry = zipFile.getEntryByIndex(i); if (pEntry->isCompressed()) { if (verbose) { printf("%8ld %s (OK - compressed)\n", (long) pEntry->getFileOffset(), pEntry->getFileName()); } } else { long offset = pEntry->getFileOffset(); if ((offset % alignment) != 0) { if (verbose) { printf("%8ld %s (BAD - %ld)\n", (long) offset, pEntry->getFileName(), offset % alignment); } foundBad = true; } else { if (verbose) { printf("%8ld %s (OK)\n", (long) offset, pEntry->getFileName()); } } } } if (verbose) printf("Verification %s\n", foundBad ? "FAILED" : "succesful"); return foundBad ? 1 : 0; } /* * Parse args. */ int main(int argc, char* const argv[]) { bool wantUsage = false; bool check = false; bool force = false; bool verbose = false; int result = 1; int alignment; char* endp; if (argc < 4) { wantUsage = true; goto bail; } argc--; argv++; while (argc && argv[0][0] == '-') { const char* cp = argv[0] +1; while (*cp != '\0') { switch (*cp) { case 'c': check = true; break; case 'f': force = true; break; case 'v': verbose = true; break; default: fprintf(stderr, "ERROR: unknown flag -%c\n", *cp); wantUsage = true; goto bail; } cp++; } argc--; argv++; } if (!((check && argc == 2) || (!check && argc == 3))) { wantUsage = true; goto bail; } alignment = strtol(argv[0], &endp, 10); if (*endp != '\0' || alignment <= 0) { fprintf(stderr, "Invalid value for alignment: %s\n", argv[0]); wantUsage = true; goto bail; } if (check) { /* check existing archive for correct alignment */ result = verify(argv[1], alignment, verbose); } else { /* create the new archive */ result = process(argv[1], argv[2], alignment, force); /* trust, but verify */ if (result == 0) result = verify(argv[2], alignment, verbose); } bail: if (wantUsage) { usage(); result = 2; } return result; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include <windows.h> #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); // Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if // error occurs. std::string Utf16ToUtf8(const WCHAR* str) { int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (len_utf8 <= 0) return std::string(); std::string result(len_utf8, '\0'); int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1, &*(result.begin()), len_utf8, NULL, NULL); if (rv != len_utf8) assert(false); return result; } BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = Utf16ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; return true; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been minimized or hidden. if (IsIconic(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } RECT rect; if (!GetWindowRect(window_, &rect)) { LOG(LS_WARNING) << "Failed to get window size: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( DesktopSize(rect.right - rect.left, rect.bottom - rect.top), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. if (!IsAeroEnabled()) result = PrintWindow(window_, mem_dc, 0); // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, 0, 0, SRCCOPY); } if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } SelectObject(mem_dc, NULL); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create() { return new WindowCapturerWin(); } } // namespace webrtc <commit_msg>Fix WindowCapturerWin to capture window decorations after window size changes.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include <windows.h> #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); // Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if // error occurs. std::string Utf16ToUtf8(const WCHAR* str) { int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (len_utf8 <= 0) return std::string(); std::string result(len_utf8, '\0'); int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1, &*(result.begin()), len_utf8, NULL, NULL); if (rv != len_utf8) assert(false); return result; } BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = Utf16ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been minimized or hidden. if (IsIconic(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } RECT rect; if (!GetWindowRect(window_, &rect)) { LOG(LS_WARNING) << "Failed to get window size: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( DesktopSize(rect.right - rect.left, rect.bottom - rect.top), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes - it somehow affects what we // get from BitBlt() on the subsequent captures. if (!IsAeroEnabled() || (!previous_size_.is_empty() && !previous_size_.equals(frame->size()))) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, 0, 0, SRCCOPY); } SelectObject(mem_dc, NULL); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create() { return new WindowCapturerWin(); } } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/utility/quality_scaler.h" #include <algorithm> #include <cmath> namespace webrtc { namespace { // Threshold constant used until first downscale (to permit fast rampup). static const int kMeasureSecondsFastUpscale = 2; static const int kMeasureSecondsUpscale = 5; static const int kMeasureSecondsDownscale = 5; static const int kFramedropPercentThreshold = 60; // Min width/height to downscale to, set to not go below QVGA, but with some // margin to permit "almost-QVGA" resolutions, such as QCIF. static const int kMinDownscaleDimension = 140; // Initial resolutions corresponding to a bitrate. Aa bit above their actual // values to permit near-VGA and near-QVGA resolutions to use the same // mechanism. static const int kVgaBitrateThresholdKbps = 500; static const int kVgaNumPixels = 700 * 500; // 640x480 static const int kQvgaBitrateThresholdKbps = 250; static const int kQvgaNumPixels = 400 * 300; // 320x240 } // namespace // QP thresholds are chosen to be high enough to be hit in practice when quality // is good, but also low enough to not cause a flip-flop behavior (e.g. going up // in resolution shouldn't give so bad quality that we should go back down). const int QualityScaler::kLowVp8QpThreshold = 29; const int QualityScaler::kBadVp8QpThreshold = 95; #if defined(WEBRTC_IOS) const int QualityScaler::kLowH264QpThreshold = 32; const int QualityScaler::kBadH264QpThreshold = 42; #else const int QualityScaler::kLowH264QpThreshold = 24; const int QualityScaler::kBadH264QpThreshold = 37; #endif // Default values. Should immediately get set to something more sensible. QualityScaler::QualityScaler() : average_qp_(kMeasureSecondsUpscale * 30), framedrop_percent_(kMeasureSecondsUpscale * 30), low_qp_threshold_(-1) {} void QualityScaler::Init(int low_qp_threshold, int high_qp_threshold, int initial_bitrate_kbps, int width, int height, int fps) { low_qp_threshold_ = low_qp_threshold; high_qp_threshold_ = high_qp_threshold; downscale_shift_ = 0; fast_rampup_ = true; ClearSamples(); ReportFramerate(fps); const int init_width = width; const int init_height = height; if (initial_bitrate_kbps > 0) { int init_num_pixels = width * height; if (initial_bitrate_kbps < kVgaBitrateThresholdKbps) init_num_pixels = kVgaNumPixels; if (initial_bitrate_kbps < kQvgaBitrateThresholdKbps) init_num_pixels = kQvgaNumPixels; while (width * height > init_num_pixels) { ++downscale_shift_; width /= 2; height /= 2; } } UpdateTargetResolution(init_width, init_height); ReportFramerate(fps); } // Report framerate(fps) to estimate # of samples. void QualityScaler::ReportFramerate(int framerate) { // Use a faster window for upscaling initially. // This enables faster initial rampups without risking strong up-down // behavior later. num_samples_upscale_ = framerate * (fast_rampup_ ? kMeasureSecondsFastUpscale : kMeasureSecondsUpscale); num_samples_downscale_ = framerate * kMeasureSecondsDownscale; average_qp_ = MovingAverage(std::max(num_samples_upscale_, num_samples_downscale_)); framedrop_percent_ = MovingAverage(std::max(num_samples_upscale_, num_samples_downscale_)); } void QualityScaler::ReportQP(int qp) { framedrop_percent_.AddSample(0); average_qp_.AddSample(qp); } void QualityScaler::ReportDroppedFrame() { framedrop_percent_.AddSample(100); } void QualityScaler::OnEncodeFrame(int width, int height) { // Should be set through InitEncode -> Should be set by now. RTC_DCHECK_GE(low_qp_threshold_, 0); if (target_res_.width != width || target_res_.height != height) { UpdateTargetResolution(width, height); } // Check if we should scale down due to high frame drop. const auto drop_rate = framedrop_percent_.GetAverage(num_samples_downscale_); if (drop_rate && *drop_rate >= kFramedropPercentThreshold) { ScaleDown(); return; } // Check if we should scale up or down based on QP. const auto avg_qp_down = average_qp_.GetAverage(num_samples_downscale_); if (avg_qp_down && *avg_qp_down > high_qp_threshold_) { ScaleDown(); return; } const auto avg_qp_up = average_qp_.GetAverage(num_samples_upscale_); if (avg_qp_up && *avg_qp_up <= low_qp_threshold_) { // QP has been low. We want to try a higher resolution. ScaleUp(); return; } } void QualityScaler::ScaleUp() { downscale_shift_ = std::max(0, downscale_shift_ - 1); ClearSamples(); } void QualityScaler::ScaleDown() { downscale_shift_ = std::min(maximum_shift_, downscale_shift_ + 1); ClearSamples(); // If we've scaled down, wait longer before scaling up again. if (fast_rampup_) { fast_rampup_ = false; num_samples_upscale_ = (num_samples_upscale_ / kMeasureSecondsFastUpscale) * kMeasureSecondsUpscale; } } QualityScaler::Resolution QualityScaler::GetScaledResolution() const { const int frame_width = target_res_.width >> downscale_shift_; const int frame_height = target_res_.height >> downscale_shift_; return Resolution{frame_width, frame_height}; } rtc::scoped_refptr<VideoFrameBuffer> QualityScaler::GetScaledBuffer( const rtc::scoped_refptr<VideoFrameBuffer>& frame) { Resolution res = GetScaledResolution(); const int src_width = frame->width(); const int src_height = frame->height(); if (res.width == src_width && res.height == src_height) return frame; rtc::scoped_refptr<I420Buffer> scaled_buffer = pool_.CreateBuffer(res.width, res.height); scaled_buffer->ScaleFrom(frame); return scaled_buffer; } void QualityScaler::UpdateTargetResolution(int width, int height) { if (width < kMinDownscaleDimension || height < kMinDownscaleDimension) { maximum_shift_ = 0; } else { maximum_shift_ = static_cast<int>( std::log2(std::min(width, height) / kMinDownscaleDimension)); } target_res_ = Resolution{width, height}; } void QualityScaler::ClearSamples() { framedrop_percent_.Reset(); average_qp_.Reset(); } } // namespace webrtc <commit_msg>Fix undefined reference to log2 on android<commit_after>/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/utility/quality_scaler.h" #include <math.h> #include <algorithm> // TODO(kthelgason): Some versions of Android have issues with log2. // See https://code.google.com/p/android/issues/detail?id=212634 for details #if defined(WEBRTC_ANDROID) #define log2(x) (log(x) / log(2)) #endif namespace webrtc { namespace { // Threshold constant used until first downscale (to permit fast rampup). static const int kMeasureSecondsFastUpscale = 2; static const int kMeasureSecondsUpscale = 5; static const int kMeasureSecondsDownscale = 5; static const int kFramedropPercentThreshold = 60; // Min width/height to downscale to, set to not go below QVGA, but with some // margin to permit "almost-QVGA" resolutions, such as QCIF. static const int kMinDownscaleDimension = 140; // Initial resolutions corresponding to a bitrate. Aa bit above their actual // values to permit near-VGA and near-QVGA resolutions to use the same // mechanism. static const int kVgaBitrateThresholdKbps = 500; static const int kVgaNumPixels = 700 * 500; // 640x480 static const int kQvgaBitrateThresholdKbps = 250; static const int kQvgaNumPixels = 400 * 300; // 320x240 } // namespace // QP thresholds are chosen to be high enough to be hit in practice when quality // is good, but also low enough to not cause a flip-flop behavior (e.g. going up // in resolution shouldn't give so bad quality that we should go back down). const int QualityScaler::kLowVp8QpThreshold = 29; const int QualityScaler::kBadVp8QpThreshold = 95; #if defined(WEBRTC_IOS) const int QualityScaler::kLowH264QpThreshold = 32; const int QualityScaler::kBadH264QpThreshold = 42; #else const int QualityScaler::kLowH264QpThreshold = 24; const int QualityScaler::kBadH264QpThreshold = 37; #endif // Default values. Should immediately get set to something more sensible. QualityScaler::QualityScaler() : average_qp_(kMeasureSecondsUpscale * 30), framedrop_percent_(kMeasureSecondsUpscale * 30), low_qp_threshold_(-1) {} void QualityScaler::Init(int low_qp_threshold, int high_qp_threshold, int initial_bitrate_kbps, int width, int height, int fps) { low_qp_threshold_ = low_qp_threshold; high_qp_threshold_ = high_qp_threshold; downscale_shift_ = 0; fast_rampup_ = true; ClearSamples(); ReportFramerate(fps); const int init_width = width; const int init_height = height; if (initial_bitrate_kbps > 0) { int init_num_pixels = width * height; if (initial_bitrate_kbps < kVgaBitrateThresholdKbps) init_num_pixels = kVgaNumPixels; if (initial_bitrate_kbps < kQvgaBitrateThresholdKbps) init_num_pixels = kQvgaNumPixels; while (width * height > init_num_pixels) { ++downscale_shift_; width /= 2; height /= 2; } } UpdateTargetResolution(init_width, init_height); ReportFramerate(fps); } // Report framerate(fps) to estimate # of samples. void QualityScaler::ReportFramerate(int framerate) { // Use a faster window for upscaling initially. // This enables faster initial rampups without risking strong up-down // behavior later. num_samples_upscale_ = framerate * (fast_rampup_ ? kMeasureSecondsFastUpscale : kMeasureSecondsUpscale); num_samples_downscale_ = framerate * kMeasureSecondsDownscale; average_qp_ = MovingAverage(std::max(num_samples_upscale_, num_samples_downscale_)); framedrop_percent_ = MovingAverage(std::max(num_samples_upscale_, num_samples_downscale_)); } void QualityScaler::ReportQP(int qp) { framedrop_percent_.AddSample(0); average_qp_.AddSample(qp); } void QualityScaler::ReportDroppedFrame() { framedrop_percent_.AddSample(100); } void QualityScaler::OnEncodeFrame(int width, int height) { // Should be set through InitEncode -> Should be set by now. RTC_DCHECK_GE(low_qp_threshold_, 0); if (target_res_.width != width || target_res_.height != height) { UpdateTargetResolution(width, height); } // Check if we should scale down due to high frame drop. const auto drop_rate = framedrop_percent_.GetAverage(num_samples_downscale_); if (drop_rate && *drop_rate >= kFramedropPercentThreshold) { ScaleDown(); return; } // Check if we should scale up or down based on QP. const auto avg_qp_down = average_qp_.GetAverage(num_samples_downscale_); if (avg_qp_down && *avg_qp_down > high_qp_threshold_) { ScaleDown(); return; } const auto avg_qp_up = average_qp_.GetAverage(num_samples_upscale_); if (avg_qp_up && *avg_qp_up <= low_qp_threshold_) { // QP has been low. We want to try a higher resolution. ScaleUp(); return; } } void QualityScaler::ScaleUp() { downscale_shift_ = std::max(0, downscale_shift_ - 1); ClearSamples(); } void QualityScaler::ScaleDown() { downscale_shift_ = std::min(maximum_shift_, downscale_shift_ + 1); ClearSamples(); // If we've scaled down, wait longer before scaling up again. if (fast_rampup_) { fast_rampup_ = false; num_samples_upscale_ = (num_samples_upscale_ / kMeasureSecondsFastUpscale) * kMeasureSecondsUpscale; } } QualityScaler::Resolution QualityScaler::GetScaledResolution() const { const int frame_width = target_res_.width >> downscale_shift_; const int frame_height = target_res_.height >> downscale_shift_; return Resolution{frame_width, frame_height}; } rtc::scoped_refptr<VideoFrameBuffer> QualityScaler::GetScaledBuffer( const rtc::scoped_refptr<VideoFrameBuffer>& frame) { Resolution res = GetScaledResolution(); const int src_width = frame->width(); const int src_height = frame->height(); if (res.width == src_width && res.height == src_height) return frame; rtc::scoped_refptr<I420Buffer> scaled_buffer = pool_.CreateBuffer(res.width, res.height); scaled_buffer->ScaleFrom(frame); return scaled_buffer; } void QualityScaler::UpdateTargetResolution(int width, int height) { if (width < kMinDownscaleDimension || height < kMinDownscaleDimension) { maximum_shift_ = 0; } else { maximum_shift_ = static_cast<int>( log2(std::min(width, height) / kMinDownscaleDimension)); } target_res_ = Resolution{width, height}; } void QualityScaler::ClearSamples() { framedrop_percent_.Reset(); average_qp_.Reset(); } } // namespace webrtc <|endoftext|>
<commit_before>#include <cmath> #include <Eigen/Eigenvalues> #include <esn/create_network_nsli.h> #include <network_nsli.h> namespace ESN { std::unique_ptr< Network > CreateNetwork( const NetworkParamsNSLI & params ) { return std::unique_ptr< NetworkNSLI >( new NetworkNSLI( params ) ); } NetworkNSLI::NetworkNSLI( const NetworkParamsNSLI & params ) : mParams( params ) , mIn( params.inputCount ) , mWIn( params.neuronCount, params.inputCount ) , mX( params.neuronCount ) , mW( params.neuronCount, params.neuronCount ) , mOut( params.outputCount ) , mWOut( params.outputCount, params.neuronCount ) { if ( params.inputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::inputCount must be not null" ); if ( params.neuronCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::neuronCount must be not null" ); if ( params.outputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::outputCount must be not null" ); if ( !( params.leakingRate > 0.0 && params.leakingRate <= 1.0 ) ) throw std::invalid_argument( "NetworkParamsNSLI::leakingRate must be withing " "interval [0,1)" ); mWIn = Eigen::MatrixXf::Random( params.neuronCount, params.inputCount ).sparseView(); Eigen::MatrixXf randomWeights = Eigen::MatrixXf::Random( params.neuronCount, params.neuronCount ); float spectralRadius = randomWeights.eigenvalues().cwiseAbs().maxCoeff(); mW = ( randomWeights / spectralRadius ).sparseView() ; } NetworkNSLI::~NetworkNSLI() { } void NetworkNSLI::SetInputs( const std::vector< float > & inputs ) { if ( inputs.size() != mIn.rows() ) throw std::invalid_argument( "Wrong size of the input vector" ); mIn = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( inputs.data() ), inputs.size() ); } void NetworkNSLI::Step( float step ) { mX = ( 1 - mParams.leakingRate ) * mX + mParams.leakingRate * ( mWIn * mIn + mW * mX ).unaryExpr( [] ( float x ) -> float { return std::tanh( x ); } ); mOut = mWOut * mX; } void NetworkNSLI::Train( const std::vector< std::vector< float > > & inputs, const std::vector< std::vector< float > > & outputs ) { if ( inputs.size() == 0 ) throw std::invalid_argument( "Number of samples must be not null" ); if ( inputs.size() != outputs.size() ) throw std::invalid_argument( "Number of input and output samples must be equal" ); } } // namespace ESN <commit_msg>esn : NetworkNSLI : Step : check argument 'step'<commit_after>#include <cmath> #include <Eigen/Eigenvalues> #include <esn/create_network_nsli.h> #include <network_nsli.h> namespace ESN { std::unique_ptr< Network > CreateNetwork( const NetworkParamsNSLI & params ) { return std::unique_ptr< NetworkNSLI >( new NetworkNSLI( params ) ); } NetworkNSLI::NetworkNSLI( const NetworkParamsNSLI & params ) : mParams( params ) , mIn( params.inputCount ) , mWIn( params.neuronCount, params.inputCount ) , mX( params.neuronCount ) , mW( params.neuronCount, params.neuronCount ) , mOut( params.outputCount ) , mWOut( params.outputCount, params.neuronCount ) { if ( params.inputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::inputCount must be not null" ); if ( params.neuronCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::neuronCount must be not null" ); if ( params.outputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::outputCount must be not null" ); if ( !( params.leakingRate > 0.0 && params.leakingRate <= 1.0 ) ) throw std::invalid_argument( "NetworkParamsNSLI::leakingRate must be withing " "interval [0,1)" ); mWIn = Eigen::MatrixXf::Random( params.neuronCount, params.inputCount ).sparseView(); Eigen::MatrixXf randomWeights = Eigen::MatrixXf::Random( params.neuronCount, params.neuronCount ); float spectralRadius = randomWeights.eigenvalues().cwiseAbs().maxCoeff(); mW = ( randomWeights / spectralRadius ).sparseView() ; } NetworkNSLI::~NetworkNSLI() { } void NetworkNSLI::SetInputs( const std::vector< float > & inputs ) { if ( inputs.size() != mIn.rows() ) throw std::invalid_argument( "Wrong size of the input vector" ); mIn = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( inputs.data() ), inputs.size() ); } void NetworkNSLI::Step( float step ) { if ( step <= 0.0f ) throw std::invalid_argument( "Step size must be positive value" ); mX = ( 1 - mParams.leakingRate ) * mX + mParams.leakingRate * ( mWIn * mIn + mW * mX ).unaryExpr( [] ( float x ) -> float { return std::tanh( x ); } ); mOut = mWOut * mX; } void NetworkNSLI::Train( const std::vector< std::vector< float > > & inputs, const std::vector< std::vector< float > > & outputs ) { if ( inputs.size() == 0 ) throw std::invalid_argument( "Number of samples must be not null" ); if ( inputs.size() != outputs.size() ) throw std::invalid_argument( "Number of input and output samples must be equal" ); } } // namespace ESN <|endoftext|>
<commit_before>bool onSegment(Point p, Point q, Point r) { if (cross(toVec(p,r),toVec(p,q)) == 0 && q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false; } <commit_msg>arrumando identacao<commit_after>bool onSegment(Point p, Point q, Point r) { if (cross(toVec(p,r),toVec(p,q)) == 0 && q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMutexFunctionLock.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkMutexFunctionLock.h" // Description: // Construct a new vtkMutexFunctionLock vtkMutexFunctionLock::vtkMutexFunctionLock(void ) { this->mutex_var = vtkMutexLock::New(); } // Description: // Destruct the vtkMutexFunctionLock vtkMutexFunctionLock::~vtkMutexFunctionLock(void ) { delete this->mutex_var; } // Description: // Print method for vtkMutexFunctionLock void vtkMutexFunctionLock::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); this->mutex_var->PrintSelf(os,indent); } // Description: // Lock method for vtkMutexFunctionLock void vtkMutexFunctionLock::StartLock(void ) { if (this->mutex_var != NULL) this->mutex_var->Lock(); } // Description: // Unlock method for vtkMutexFunctionLock void vtkMutexFunctionLock::EndLock(void ) { if (this->mutex_var != NULL) this->mutex_var->Unlock(); } <commit_msg>FIX: Style Errors<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMutexFunctionLock.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkMutexFunctionLock.h" // Description: // Construct a new vtkMutexFunctionLock vtkMutexFunctionLock::vtkMutexFunctionLock(void ) { this->MutexVar = vtkMutexLock::New(); } // Description: // Destruct the vtkMutexFunctionLock vtkMutexFunctionLock::~vtkMutexFunctionLock(void ) { delete this->MutexVar; } // Description: // Print method for vtkMutexFunctionLock void vtkMutexFunctionLock::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); this->MutexVar->PrintSelf(os,indent); } // Description: // Lock method for vtkMutexFunctionLock void vtkMutexFunctionLock::StartLock(void ) { if (this->MutexVar != NULL) this->MutexVar->Lock(); } // Description: // Unlock method for vtkMutexFunctionLock void vtkMutexFunctionLock::EndLock(void ) { if (this->MutexVar != NULL) this->MutexVar->Unlock(); } <|endoftext|>
<commit_before>/**communications clients avec les sockets TCP en C. * AUTHORS: */ //Si nous sommes sous Windows #include <winsock2.h> typedef int socklen_t; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> //#include <conio.h> #define PORT 20019 void envoie(char *msg, SOCKET sock){ int taille = (int)strlen(msg)+1; if(send(sock, &taille, sizeof(taille), 0) != -1){ send(sock, msg, taille, 0); } } char* recoit(SOCKET* sock){ char *recu; int err, taille; err=recv(sock, &taille, sizeof(taille), 0); //la taille des donnees if(err != -1){ recv(sock, recu, sizeof(taille), 0); //reception des donnees } return res; } void interpretor(char *data){ } void* un_client(void * sock){ char* msg= ""; do{ msg = recoit((int) sock); }while( strcmp(msg, "EXIT")); //fermer la connexion printf("fermeture de la socket client\n"); closesocket(csock); } void main(int argc, char **args){ WSADATA WSAData; WSAStartup(MAKEWORD(2,2),&WSAData); //creation et parametrage du socket SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); SOCKET csock; SOCKADDR_IN ssin, ccsin; ssin.sin_addr.s_addr = inet_addr("127.0.0.1"); ssin.sin_family = AF_INET; ssin.sin_port = htons(PORT); //code a executer printf("Demarrage du serveur sur le port %d...\n", PORT); //etablir une communication int err_bind = bind(sock, (SOCKADDR*) &ssin, sizeof(ssin)); listen(sock, 5); socklen_t taille = sizeof(csin); while(true){ csock = accept(sock, (SOCKADDR*)&ccsin, &taille); printf("connexion du client %s:%d...\n", inet_ntoa(ccsin.sin_addr), htons(ccsin.sin_port)); //creation d'un thread pour gerer le client pthread_t client; int err_thr = pthread_create(&client, NULL, un_client, (void*) &csock); } printf("fermeture de la socket serveur\n"); closesocket(sock); WSACleanup(); } <commit_msg>socket<commit_after>/**communications clients avec les sockets TCP en C. * AUTHORS: */ //Si nous sommes sous Windows #include <winsock2.h> typedef int socklen_t; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> //#include <conio.h> #define PORT 20019 void envoie(char *msg, SOCKET sock){ int taille = (int)strlen(msg)+1; if(send(sock, &taille, sizeof(taille), 0) != -1){ send(sock, msg, taille, 0); } } char* recoit(SOCKET* sock){ char *recu; int err, taille; err=recv(sock, &taille, sizeof(taille), 0); //la taille des donnees if(err != -1){ recv(sock, recu, sizeof(taille), 0); //reception des donnees } return res; } void interpretor(char *data){ } void* un_client(void * sock){ char* msg= ""; do{ msg = recoit((int) sock); }while( strcmp(msg, "EXIT")); //fermer la connexion printf("fermeture de la socket client\n"); closesocket(csock); } void main(int argc, char **args){ WSADATA WSAData; WSAStartup(MAKEWORD(2,2),&WSAData); //creation et parametrage du socket SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); SOCKET csock; SOCKADDR_IN ssin, ccsin; ssin.sin_addr.s_addr = inet_addr("127.0.0.1"); ssin.sin_family = AF_INET; ssin.sin_port = htons(PORT); //code a executer printf("Demarrage du serveur sur le port %d...\n", PORT); //etablir une communication int err_bind = bind(sock, (SOCKADDR*) &ssin, sizeof(ssin)); listen(sock, 5); socklen_t taille = sizeof(csin); while(true){ csock = accept(sock, (SOCKADDR*)&ccsin, &taille); printf("connexion du client %s:%d...\n", inet_ntoa(ccsin.sin_addr), htons(ccsin.sin_port)); //reception system("pwd"); //creation d'un thread pour gerer le client pthread_t client; int err_thr = pthread_create(&client, NULL, un_client, (void*) &csock); } printf("fermeture de la socket serveur\n"); closesocket(sock); WSACleanup(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: export2.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: nf $ $Date: 2000-11-27 07:10:08 $ * * 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): _______________________________________ * * ************************************************************************/ #include "export.hxx" // // class ResData(); // /*****************************************************************************/ ResData::~ResData() /*****************************************************************************/ { if ( pStringList ) { // delete existing res. of type StringList for ( ULONG i = 0; i < pStringList->Count(); i++ ) { delete [] pStringList->GetObject( i ); } delete pStringList; } if ( pFilterList ) { // delete existing res. of type FilterList for ( ULONG i = 0; i < pFilterList->Count(); i++ ) { delete [] pFilterList->GetObject( i ); } delete pFilterList; } if ( pItemList ) { // delete existing res. of type ItemList for ( ULONG i = 0; i < pItemList->Count(); i++ ) { delete [] pItemList->GetObject( i ); } delete pItemList; } if ( pUIEntries ) { // delete existing res. of type UIEntries for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) { delete [] pUIEntries->GetObject( i ); } delete pUIEntries; } } // // class Export // /*****************************************************************************/ USHORT Export::LangId[ LANGUAGES ] = /*****************************************************************************/ { // translation table: Index <=> LangId COMMENT, ENGLISH_US, PORTUGUESE, GERMAN_DE, RUSSIAN, GREEK, DUTCH, FRENCH, SPANISH, FINNISH, HUNGARIAN, ITALIAN, CZECH, SLOVAK, ENGLISH, DANISH, SWEDISH, NORWEGIAN, POLISH, GERMAN, PORTUGUESE_BRAZILIAN, JAPANESE, KOREAN, CHINESE_SIMPLIFIED, CHINESE_TRADITIONAL, TURKISH, ARABIC, HEBREW }; /*****************************************************************************/ USHORT Export::GetLangIndex( USHORT nLangId ) /*****************************************************************************/ { for ( USHORT i = 0; i < LANGUAGES; i++ ) if ( nLangId == LangId[ i ] ) return i; return 0xFFFF; } /*****************************************************************************/ CharSet Export::GetCharSet( USHORT nLangId ) /*****************************************************************************/ { switch ( nLangId ) { case COMMENT: return RTL_TEXTENCODING_MS_1252; case ENGLISH_US: return RTL_TEXTENCODING_MS_1252; case PORTUGUESE: return RTL_TEXTENCODING_MS_1252; case RUSSIAN: return RTL_TEXTENCODING_MS_1251; case GREEK: return RTL_TEXTENCODING_MS_1253; case DUTCH: return RTL_TEXTENCODING_MS_1252; case FRENCH: return RTL_TEXTENCODING_MS_1252; case SPANISH: return RTL_TEXTENCODING_MS_1252; case FINNISH: return RTL_TEXTENCODING_MS_1252; case HUNGARIAN: return RTL_TEXTENCODING_MS_1250; case ITALIAN: return RTL_TEXTENCODING_MS_1252; case CZECH: return RTL_TEXTENCODING_MS_1250; case SLOVAK: return RTL_TEXTENCODING_MS_1250; case ENGLISH: return RTL_TEXTENCODING_MS_1252; case DANISH: return RTL_TEXTENCODING_MS_1252; case SWEDISH: return RTL_TEXTENCODING_MS_1252; case NORWEGIAN: return RTL_TEXTENCODING_MS_1252; case POLISH: return RTL_TEXTENCODING_MS_1250; case GERMAN: return RTL_TEXTENCODING_MS_1252; case PORTUGUESE_BRAZILIAN: return RTL_TEXTENCODING_MS_1252; case JAPANESE: return RTL_TEXTENCODING_MS_932; case KOREAN: return RTL_TEXTENCODING_MS_949; case CHINESE_SIMPLIFIED: return RTL_TEXTENCODING_MS_936; case CHINESE_TRADITIONAL: return RTL_TEXTENCODING_MS_950; case TURKISH: return RTL_TEXTENCODING_MS_1254; case ARABIC: return RTL_TEXTENCODING_MS_1256; case HEBREW: return RTL_TEXTENCODING_MS_1255; } return 0xFFFF; } /*****************************************************************************/ USHORT Export::GetLangByIsoLang( const ByteString &rIsoLang ) /*****************************************************************************/ { ByteString sLang( rIsoLang ); sLang.ToUpperAscii(); if ( sLang == ByteString( COMMENT_ISO ).ToUpperAscii()) return COMMENT; else if ( sLang == ByteString( ENGLISH_US_ISO ).ToUpperAscii()) return ENGLISH_US; else if ( sLang == ByteString( PORTUGUESE_ISO ).ToUpperAscii()) return PORTUGUESE; else if ( sLang == ByteString( RUSSIAN_ISO ).ToUpperAscii()) return RUSSIAN; else if ( sLang == ByteString( GREEK_ISO ).ToUpperAscii()) return GREEK; else if ( sLang == ByteString( DUTCH_ISO ).ToUpperAscii()) return DUTCH; else if ( sLang == ByteString( FRENCH_ISO ).ToUpperAscii()) return FRENCH; else if ( sLang == ByteString( SPANISH_ISO ).ToUpperAscii()) return SPANISH; else if ( sLang == ByteString( FINNISH_ISO ).ToUpperAscii()) return FINNISH; else if ( sLang == ByteString( HUNGARIAN_ISO ).ToUpperAscii()) return HUNGARIAN; else if ( sLang == ByteString( ITALIAN_ISO ).ToUpperAscii()) return ITALIAN; else if ( sLang == ByteString( CZECH_ISO ).ToUpperAscii()) return CZECH; else if ( sLang == ByteString( SLOVAK_ISO ).ToUpperAscii()) return SLOVAK; else if ( sLang == ByteString( ENGLISH_ISO ).ToUpperAscii()) return ENGLISH; else if ( sLang == ByteString( DANISH_ISO ).ToUpperAscii()) return DANISH; else if ( sLang == ByteString( SWEDISH_ISO ).ToUpperAscii()) return SWEDISH; else if ( sLang == ByteString( NORWEGIAN_ISO ).ToUpperAscii()) return NORWEGIAN; else if ( sLang == ByteString( POLISH_ISO ).ToUpperAscii()) return POLISH; else if ( sLang == ByteString( GERMAN_ISO ).ToUpperAscii()) return GERMAN; else if ( sLang == ByteString( PORTUGUESE_BRAZILIAN_ISO ).ToUpperAscii()) return PORTUGUESE_BRAZILIAN; else if ( sLang == ByteString( JAPANESE_ISO ).ToUpperAscii()) return JAPANESE; else if ( sLang == ByteString( KOREAN_ISO ).ToUpperAscii()) return KOREAN; else if ( sLang == ByteString( CHINESE_SIMPLIFIED_ISO ).ToUpperAscii()) return CHINESE_SIMPLIFIED; else if ( sLang == ByteString( CHINESE_TRADITIONAL_ISO ).ToUpperAscii()) return CHINESE_TRADITIONAL; else if ( sLang == ByteString( TURKISH_ISO ).ToUpperAscii()) return TURKISH; else if ( sLang == ByteString( ARABIC_ISO ).ToUpperAscii()) return ARABIC; else if ( sLang == ByteString( HEBREW_ISO ).ToUpperAscii()) return HEBREW; return 0xFFFF; } /*****************************************************************************/ ByteString Export::GetIsoLangByIndex( USHORT nIndex ) /*****************************************************************************/ { switch ( nIndex ) { case COMMENT_INDEX: return COMMENT_ISO; case ENGLISH_US_INDEX: return ENGLISH_US_ISO; case PORTUGUESE_INDEX: return PORTUGUESE_ISO; case RUSSIAN_INDEX: return RUSSIAN_ISO; case GREEK_INDEX: return GREEK_ISO; case DUTCH_INDEX: return DUTCH_ISO; case FRENCH_INDEX: return FRENCH_ISO; case SPANISH_INDEX: return SPANISH_ISO; case FINNISH_INDEX: return FINNISH_ISO; case HUNGARIAN_INDEX: return HUNGARIAN_ISO; case ITALIAN_INDEX: return ITALIAN_ISO; case CZECH_INDEX: return CZECH_ISO; case SLOVAK_INDEX: return SLOVAK_ISO; case ENGLISH_INDEX: return ENGLISH_ISO; case DANISH_INDEX: return DANISH_ISO; case SWEDISH_INDEX: return SWEDISH_ISO; case NORWEGIAN_INDEX: return NORWEGIAN_ISO; case POLISH_INDEX: return POLISH_ISO; case GERMAN_INDEX: return GERMAN_ISO; case PORTUGUESE_BRAZILIAN_INDEX: return PORTUGUESE_BRAZILIAN_ISO; case JAPANESE_INDEX: return JAPANESE_ISO; case KOREAN_INDEX: return KOREAN_ISO; case CHINESE_SIMPLIFIED_INDEX: return CHINESE_SIMPLIFIED_ISO; case CHINESE_TRADITIONAL_INDEX: return CHINESE_TRADITIONAL_ISO; case TURKISH_INDEX: return TURKISH_ISO; case ARABIC_INDEX: return ARABIC_ISO; case HEBREW_INDEX: return HEBREW_ISO; } return ""; } /*****************************************************************************/ void Export::QuotHTML( ByteString &rString ) /*****************************************************************************/ { ByteString sReturn; for ( ULONG i = 0; i < rString.Len(); i++ ) { switch ( rString.GetChar( i )) { case '<': sReturn += "&lt;"; break; case '>': sReturn += "&gt;"; break; case '\"': sReturn += "&quot;"; break; case '\'': sReturn += "&apos;"; break; case '&': if ((( i + 4 ) < rString.Len()) && ( rString.Copy( i, 5 ) == "&amp;" )) sReturn += rString.GetChar( i ); else sReturn += "&amp;"; break; default: sReturn += rString.GetChar( i ); break; } } rString = sReturn; } /*****************************************************************************/ void Export::UnquotHTML( ByteString &rString ) /*****************************************************************************/ { ByteString sReturn; while ( rString.Len()) { if ( rString.Copy( 0, 5 ) == "&amp;" ) { sReturn += "&"; rString.Erase( 0, 5 ); } else if ( rString.Copy( 0, 4 ) == "&lt;" ) { sReturn += "<"; rString.Erase( 0, 4 ); } else if ( rString.Copy( 0, 4 ) == "&gt;" ) { sReturn += ">"; rString.Erase( 0, 4 ); } else if ( rString.Copy( 0, 6 ) == "&quot;" ) { sReturn += "\""; rString.Erase( 0, 6 ); } else if ( rString.Copy( 0, 6 ) == "&apos;" ) { sReturn += "\'"; rString.Erase( 0, 6 ); } else { sReturn += rString.GetChar( 0 ); rString.Erase( 0, 1 ); } } rString = sReturn; } /*****************************************************************************/ const ByteString Export::LangName[ LANGUAGES ] = /*****************************************************************************/ { "language_user1", "english_us", "portuguese", "german_de", "russian", "greek", "dutch", "french", "spanish", "finnish", "hungarian", "italian", "czech", "slovak", "english", "danish", "swedish", "norwegian", "polish", "german", "portuguese_brazilian", "japanese", "korean", "chinese_simplified", "chinese_traditional", "turkish", "arabic", "hebrew" }; <commit_msg>Fix #81620#<commit_after>/************************************************************************* * * $RCSfile: export2.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: nf $ $Date: 2000-12-08 12:49:25 $ * * 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): _______________________________________ * * ************************************************************************/ #include "export.hxx" // // class ResData(); // /*****************************************************************************/ ResData::~ResData() /*****************************************************************************/ { if ( pStringList ) { // delete existing res. of type StringList for ( ULONG i = 0; i < pStringList->Count(); i++ ) { delete [] pStringList->GetObject( i ); } delete pStringList; } if ( pFilterList ) { // delete existing res. of type FilterList for ( ULONG i = 0; i < pFilterList->Count(); i++ ) { delete [] pFilterList->GetObject( i ); } delete pFilterList; } if ( pItemList ) { // delete existing res. of type ItemList for ( ULONG i = 0; i < pItemList->Count(); i++ ) { delete [] pItemList->GetObject( i ); } delete pItemList; } if ( pUIEntries ) { // delete existing res. of type UIEntries for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) { delete [] pUIEntries->GetObject( i ); } delete pUIEntries; } } // // class Export // /*****************************************************************************/ USHORT Export::LangId[ LANGUAGES ] = /*****************************************************************************/ { // translation table: Index <=> LangId COMMENT, ENGLISH_US, PORTUGUESE, GERMAN_DE, RUSSIAN, GREEK, DUTCH, FRENCH, SPANISH, FINNISH, HUNGARIAN, ITALIAN, CZECH, SLOVAK, ENGLISH, DANISH, SWEDISH, NORWEGIAN, POLISH, GERMAN, PORTUGUESE_BRAZILIAN, JAPANESE, KOREAN, CHINESE_SIMPLIFIED, CHINESE_TRADITIONAL, TURKISH, ARABIC, HEBREW }; /*****************************************************************************/ USHORT Export::GetLangIndex( USHORT nLangId ) /*****************************************************************************/ { for ( USHORT i = 0; i < LANGUAGES; i++ ) if ( nLangId == LangId[ i ] ) return i; return 0xFFFF; } /*****************************************************************************/ CharSet Export::GetCharSet( USHORT nLangId ) /*****************************************************************************/ { switch ( nLangId ) { case COMMENT: return RTL_TEXTENCODING_MS_1252; case ENGLISH_US: return RTL_TEXTENCODING_MS_1252; case PORTUGUESE: return RTL_TEXTENCODING_MS_1252; case RUSSIAN: return RTL_TEXTENCODING_MS_1251; case GREEK: return RTL_TEXTENCODING_MS_1253; case DUTCH: return RTL_TEXTENCODING_MS_1252; case FRENCH: return RTL_TEXTENCODING_MS_1252; case SPANISH: return RTL_TEXTENCODING_MS_1252; case FINNISH: return RTL_TEXTENCODING_MS_1252; case HUNGARIAN: return RTL_TEXTENCODING_MS_1250; case ITALIAN: return RTL_TEXTENCODING_MS_1252; case CZECH: return RTL_TEXTENCODING_MS_1250; case SLOVAK: return RTL_TEXTENCODING_MS_1250; case ENGLISH: return RTL_TEXTENCODING_MS_1252; case DANISH: return RTL_TEXTENCODING_MS_1252; case SWEDISH: return RTL_TEXTENCODING_MS_1252; case NORWEGIAN: return RTL_TEXTENCODING_MS_1252; case POLISH: return RTL_TEXTENCODING_MS_1250; case GERMAN: return RTL_TEXTENCODING_MS_1252; case PORTUGUESE_BRAZILIAN: return RTL_TEXTENCODING_MS_1252; case JAPANESE: return RTL_TEXTENCODING_MS_932; case KOREAN: return RTL_TEXTENCODING_MS_949; case CHINESE_SIMPLIFIED: return RTL_TEXTENCODING_MS_936; case CHINESE_TRADITIONAL: return RTL_TEXTENCODING_MS_950; case TURKISH: return RTL_TEXTENCODING_MS_1254; case ARABIC: return RTL_TEXTENCODING_MS_1256; case HEBREW: return RTL_TEXTENCODING_MS_1255; } return 0xFFFF; } /*****************************************************************************/ USHORT Export::GetLangByIsoLang( const ByteString &rIsoLang ) /*****************************************************************************/ { ByteString sLang( rIsoLang ); sLang.ToUpperAscii(); if ( sLang == ByteString( COMMENT_ISO ).ToUpperAscii()) return COMMENT; else if ( sLang == ByteString( ENGLISH_US_ISO ).ToUpperAscii()) return ENGLISH_US; else if ( sLang == ByteString( PORTUGUESE_ISO ).ToUpperAscii()) return PORTUGUESE; else if ( sLang == ByteString( RUSSIAN_ISO ).ToUpperAscii()) return RUSSIAN; else if ( sLang == ByteString( GREEK_ISO ).ToUpperAscii()) return GREEK; else if ( sLang == ByteString( DUTCH_ISO ).ToUpperAscii()) return DUTCH; else if ( sLang == ByteString( FRENCH_ISO ).ToUpperAscii()) return FRENCH; else if ( sLang == ByteString( SPANISH_ISO ).ToUpperAscii()) return SPANISH; else if ( sLang == ByteString( FINNISH_ISO ).ToUpperAscii()) return FINNISH; else if ( sLang == ByteString( HUNGARIAN_ISO ).ToUpperAscii()) return HUNGARIAN; else if ( sLang == ByteString( ITALIAN_ISO ).ToUpperAscii()) return ITALIAN; else if ( sLang == ByteString( CZECH_ISO ).ToUpperAscii()) return CZECH; else if ( sLang == ByteString( SLOVAK_ISO ).ToUpperAscii()) return SLOVAK; else if ( sLang == ByteString( ENGLISH_ISO ).ToUpperAscii()) return ENGLISH; else if ( sLang == ByteString( DANISH_ISO ).ToUpperAscii()) return DANISH; else if ( sLang == ByteString( SWEDISH_ISO ).ToUpperAscii()) return SWEDISH; else if ( sLang == ByteString( NORWEGIAN_ISO ).ToUpperAscii()) return NORWEGIAN; else if ( sLang == ByteString( POLISH_ISO ).ToUpperAscii()) return POLISH; else if ( sLang == ByteString( GERMAN_ISO ).ToUpperAscii()) return GERMAN; else if ( sLang == ByteString( PORTUGUESE_BRAZILIAN_ISO ).ToUpperAscii()) return PORTUGUESE_BRAZILIAN; else if ( sLang == ByteString( JAPANESE_ISO ).ToUpperAscii()) return JAPANESE; else if ( sLang == ByteString( KOREAN_ISO ).ToUpperAscii()) return KOREAN; else if ( sLang == ByteString( CHINESE_SIMPLIFIED_ISO ).ToUpperAscii()) return CHINESE_SIMPLIFIED; else if ( sLang == ByteString( CHINESE_TRADITIONAL_ISO ).ToUpperAscii()) return CHINESE_TRADITIONAL; else if ( sLang == ByteString( TURKISH_ISO ).ToUpperAscii()) return TURKISH; else if ( sLang == ByteString( ARABIC_ISO ).ToUpperAscii()) return ARABIC; else if ( sLang == ByteString( HEBREW_ISO ).ToUpperAscii()) return HEBREW; return 0xFFFF; } /*****************************************************************************/ ByteString Export::GetIsoLangByIndex( USHORT nIndex ) /*****************************************************************************/ { switch ( nIndex ) { case COMMENT_INDEX: return COMMENT_ISO; case ENGLISH_US_INDEX: return ENGLISH_US_ISO; case PORTUGUESE_INDEX: return PORTUGUESE_ISO; case RUSSIAN_INDEX: return RUSSIAN_ISO; case GREEK_INDEX: return GREEK_ISO; case DUTCH_INDEX: return DUTCH_ISO; case FRENCH_INDEX: return FRENCH_ISO; case SPANISH_INDEX: return SPANISH_ISO; case FINNISH_INDEX: return FINNISH_ISO; case HUNGARIAN_INDEX: return HUNGARIAN_ISO; case ITALIAN_INDEX: return ITALIAN_ISO; case CZECH_INDEX: return CZECH_ISO; case SLOVAK_INDEX: return SLOVAK_ISO; case ENGLISH_INDEX: return ENGLISH_ISO; case DANISH_INDEX: return DANISH_ISO; case SWEDISH_INDEX: return SWEDISH_ISO; case NORWEGIAN_INDEX: return NORWEGIAN_ISO; case POLISH_INDEX: return POLISH_ISO; case GERMAN_INDEX: return GERMAN_ISO; case PORTUGUESE_BRAZILIAN_INDEX: return PORTUGUESE_BRAZILIAN_ISO; case JAPANESE_INDEX: return JAPANESE_ISO; case KOREAN_INDEX: return KOREAN_ISO; case CHINESE_SIMPLIFIED_INDEX: return CHINESE_SIMPLIFIED_ISO; case CHINESE_TRADITIONAL_INDEX: return CHINESE_TRADITIONAL_ISO; case TURKISH_INDEX: return TURKISH_ISO; case ARABIC_INDEX: return ARABIC_ISO; case HEBREW_INDEX: return HEBREW_ISO; } return ""; } /*****************************************************************************/ void Export::QuotHTML( ByteString &rString ) /*****************************************************************************/ { ByteString sReturn; BOOL bBreak = FALSE; for ( ULONG i = 0; i < rString.Len(); i++ ) { ByteString sTemp = rString.Copy( i ); if ( sTemp.Search( "<Arg n=" ) == 0 ) { while ( i == rString.Len() || rString.GetChar( i ) == '>' ) { sReturn += rString.GetChar( i ); i++; } } if ( i < rString.Len()) { switch ( rString.GetChar( i )) { case '<': sReturn += "&lt;"; break; case '>': sReturn += "&gt;"; break; case '\"': sReturn += "&quot;"; break; case '\'': sReturn += "&apos;"; break; case '&': if ((( i + 4 ) < rString.Len()) && ( rString.Copy( i, 5 ) == "&amp;" )) sReturn += rString.GetChar( i ); else sReturn += "&amp;"; break; default: sReturn += rString.GetChar( i ); break; } } } rString = sReturn; } /*****************************************************************************/ void Export::UnquotHTML( ByteString &rString ) /*****************************************************************************/ { ByteString sReturn; while ( rString.Len()) { if ( rString.Copy( 0, 5 ) == "&amp;" ) { sReturn += "&"; rString.Erase( 0, 5 ); } else if ( rString.Copy( 0, 4 ) == "&lt;" ) { sReturn += "<"; rString.Erase( 0, 4 ); } else if ( rString.Copy( 0, 4 ) == "&gt;" ) { sReturn += ">"; rString.Erase( 0, 4 ); } else if ( rString.Copy( 0, 6 ) == "&quot;" ) { sReturn += "\""; rString.Erase( 0, 6 ); } else if ( rString.Copy( 0, 6 ) == "&apos;" ) { sReturn += "\'"; rString.Erase( 0, 6 ); } else { sReturn += rString.GetChar( 0 ); rString.Erase( 0, 1 ); } } rString = sReturn; } /*****************************************************************************/ const ByteString Export::LangName[ LANGUAGES ] = /*****************************************************************************/ { "language_user1", "english_us", "portuguese", "german_de", "russian", "greek", "dutch", "french", "spanish", "finnish", "hungarian", "italian", "czech", "slovak", "english", "danish", "swedish", "norwegian", "polish", "german", "portuguese_brazilian", "japanese", "korean", "chinese_simplified", "chinese_traditional", "turkish", "arabic", "hebrew" }; <|endoftext|>
<commit_before>/* * Copyright 2014 Jose Fonseca * * 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. * * 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 */ /* * Simple addr2line like utility. */ #define __STDC_FORMAT_MACROS 1 #include <assert.h> #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <windows.h> #include <dbghelp.h> #include <getopt.h> #include "symbols.h" #include "wine.h" static void usage(const char *argv0) { fprintf(stderr, "usage: %s -e EXECUTABLE ADDRESS ...\n" "\n" "options:\n" " -C demangle C++ function names\n" " -D enables debugging output (for debugging addr2line itself)\n" " -e EXECUTABLE specify the EXE/DLL\n" " -f show functions\n" " -H displays command line help text\n" " -p pretty print\n", argv0); } static BOOL CALLBACK callback(HANDLE hProcess, ULONG ActionCode, ULONG64 CallbackData, ULONG64 UserContext) { if (ActionCode == CBA_DEBUG_INFO) { fputs((LPCSTR)(UINT_PTR)CallbackData, stderr); return TRUE; } return FALSE; } int main(int argc, char **argv) { BOOL bRet; DWORD dwRet; bool debug = false; char *szModule = nullptr; bool functions = false; bool demangle = false; bool pretty = false; while (1) { int opt = getopt(argc, argv, "?CDe:fHp"); switch (opt) { case 'C': demangle = true; break; case 'D': debug = true; break; case 'e': szModule = optarg; break; case 'f': functions = true; break; case 'H': usage(argv[0]); return EXIT_SUCCESS; case 'p': pretty = true; break; case '?': fprintf(stderr, "error: invalid option `%c`\n", optopt); /* pass-through */ default: usage(argv[0]); return EXIT_FAILURE; case -1: break; } if (opt == -1) { break; } } if (szModule == nullptr) { usage(argv[0]); return EXIT_FAILURE; } // Load the module HMODULE hModule = nullptr; #ifdef _WIN64 // XXX: The GetModuleFileName function does not retrieve the path for // modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag hModule = LoadLibraryExA(szModule, NULL, LOAD_LIBRARY_AS_DATAFILE); #endif if (!hModule) { hModule = LoadLibraryExA(szModule, NULL, DONT_RESOLVE_DLL_REFERENCES); } if (!hModule) { fprintf(stderr, "error: failed to load %s\n", szModule); return EXIT_FAILURE; } // Handles for modules loaded with DATAFILE/IMAGE_RESOURCE flags have lower // bits set DWORD64 BaseOfDll = (DWORD64)(UINT_PTR)hModule; BaseOfDll &= ~DWORD64(3); DWORD dwSymOptions = SymGetOptions(); dwSymOptions |= SYMOPT_LOAD_LINES; #ifndef NDEBUG dwSymOptions |= SYMOPT_DEBUG; #endif // We can get more information by calling UnDecorateSymbolName() ourselves. dwSymOptions &= ~SYMOPT_UNDNAME; SymSetOptions(dwSymOptions); HANDLE hProcess = GetCurrentProcess(); bRet = InitializeSym(hProcess, FALSE); assert(bRet); if (debug) { SymRegisterCallback64(hProcess, &callback, 0); } dwRet = SymLoadModuleEx(hProcess, NULL, szModule, NULL, BaseOfDll, 0, NULL, 0); if (!dwRet) { fprintf(stderr, "warning: failed to load module symbols\n"); } if (!GetModuleHandleA("symsrv.dll")) { fprintf(stderr, "warning: symbol server not loaded\n"); } while (optind < argc) { const char *arg = argv[optind++]; DWORD64 dwRelAddr; if (arg[0] == '0' && arg[1] == 'x') { sscanf(&arg[2], "%08" PRIX64, &dwRelAddr); } else { dwRelAddr = atol(arg); } UINT_PTR dwAddr = BaseOfDll + dwRelAddr; if (functions) { struct { SYMBOL_INFO Symbol; CHAR Name[512]; } sym; char UnDecoratedName[512]; const char *function = "??"; ZeroMemory(&sym, sizeof sym); sym.Symbol.SizeOfStruct = sizeof sym.Symbol; sym.Symbol.MaxNameLen = sizeof sym.Symbol.Name + sizeof sym.Name; DWORD64 dwSymDisplacement = 0; bRet = SymFromAddr(hProcess, dwAddr, &dwSymDisplacement, &sym.Symbol); if (bRet) { function = sym.Symbol.Name; if (demangle) { if (UnDecorateSymbolName(sym.Symbol.Name, UnDecoratedName, sizeof UnDecoratedName, UNDNAME_COMPLETE)) { function = UnDecoratedName; } } } fputs(function, stdout); fputs(pretty ? " at " : "\n", stdout); } IMAGEHLP_LINE64 line; ZeroMemory(&line, sizeof line); line.SizeOfStruct = sizeof line; DWORD dwLineDisplacement = 0; bRet = SymGetLineFromAddr64(hProcess, dwAddr, &dwLineDisplacement, &line); if (bRet) { fprintf(stdout, "%s:%lu\n", line.FileName, line.LineNumber); } else { fputs("??:?\n", stdout); } fflush(stdout); } SymCleanup(hProcess); FreeLibrary(hModule); return 0; } <commit_msg>addr2line: Check InitializeSym result.<commit_after>/* * Copyright 2014 Jose Fonseca * * 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. * * 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 */ /* * Simple addr2line like utility. */ #define __STDC_FORMAT_MACROS 1 #include <assert.h> #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <windows.h> #include <dbghelp.h> #include <getopt.h> #include "symbols.h" #include "wine.h" static void usage(const char *argv0) { fprintf(stderr, "usage: %s -e EXECUTABLE ADDRESS ...\n" "\n" "options:\n" " -C demangle C++ function names\n" " -D enables debugging output (for debugging addr2line itself)\n" " -e EXECUTABLE specify the EXE/DLL\n" " -f show functions\n" " -H displays command line help text\n" " -p pretty print\n", argv0); } static BOOL CALLBACK callback(HANDLE hProcess, ULONG ActionCode, ULONG64 CallbackData, ULONG64 UserContext) { if (ActionCode == CBA_DEBUG_INFO) { fputs((LPCSTR)(UINT_PTR)CallbackData, stderr); return TRUE; } return FALSE; } int main(int argc, char **argv) { BOOL bRet; DWORD dwRet; bool debug = false; char *szModule = nullptr; bool functions = false; bool demangle = false; bool pretty = false; while (1) { int opt = getopt(argc, argv, "?CDe:fHp"); switch (opt) { case 'C': demangle = true; break; case 'D': debug = true; break; case 'e': szModule = optarg; break; case 'f': functions = true; break; case 'H': usage(argv[0]); return EXIT_SUCCESS; case 'p': pretty = true; break; case '?': fprintf(stderr, "error: invalid option `%c`\n", optopt); /* pass-through */ default: usage(argv[0]); return EXIT_FAILURE; case -1: break; } if (opt == -1) { break; } } if (szModule == nullptr) { usage(argv[0]); return EXIT_FAILURE; } // Load the module HMODULE hModule = nullptr; #ifdef _WIN64 // XXX: The GetModuleFileName function does not retrieve the path for // modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag hModule = LoadLibraryExA(szModule, NULL, LOAD_LIBRARY_AS_DATAFILE); #endif if (!hModule) { hModule = LoadLibraryExA(szModule, NULL, DONT_RESOLVE_DLL_REFERENCES); } if (!hModule) { fprintf(stderr, "error: failed to load %s\n", szModule); return EXIT_FAILURE; } // Handles for modules loaded with DATAFILE/IMAGE_RESOURCE flags have lower // bits set DWORD64 BaseOfDll = (DWORD64)(UINT_PTR)hModule; BaseOfDll &= ~DWORD64(3); DWORD dwSymOptions = SymGetOptions(); dwSymOptions |= SYMOPT_LOAD_LINES; #ifndef NDEBUG dwSymOptions |= SYMOPT_DEBUG; #endif // We can get more information by calling UnDecorateSymbolName() ourselves. dwSymOptions &= ~SYMOPT_UNDNAME; SymSetOptions(dwSymOptions); HANDLE hProcess = GetCurrentProcess(); bRet = InitializeSym(hProcess, FALSE); if (!bRet) { fprintf(stderr, "warning: failed to initialize DbgHelp\n"); return EXIT_FAILURE; } if (debug) { SymRegisterCallback64(hProcess, &callback, 0); } dwRet = SymLoadModuleEx(hProcess, NULL, szModule, NULL, BaseOfDll, 0, NULL, 0); if (!dwRet) { fprintf(stderr, "warning: failed to load module symbols\n"); } if (!GetModuleHandleA("symsrv.dll")) { fprintf(stderr, "warning: symbol server not loaded\n"); } while (optind < argc) { const char *arg = argv[optind++]; DWORD64 dwRelAddr; if (arg[0] == '0' && arg[1] == 'x') { sscanf(&arg[2], "%08" PRIX64, &dwRelAddr); } else { dwRelAddr = atol(arg); } UINT_PTR dwAddr = BaseOfDll + dwRelAddr; if (functions) { struct { SYMBOL_INFO Symbol; CHAR Name[512]; } sym; char UnDecoratedName[512]; const char *function = "??"; ZeroMemory(&sym, sizeof sym); sym.Symbol.SizeOfStruct = sizeof sym.Symbol; sym.Symbol.MaxNameLen = sizeof sym.Symbol.Name + sizeof sym.Name; DWORD64 dwSymDisplacement = 0; bRet = SymFromAddr(hProcess, dwAddr, &dwSymDisplacement, &sym.Symbol); if (bRet) { function = sym.Symbol.Name; if (demangle) { if (UnDecorateSymbolName(sym.Symbol.Name, UnDecoratedName, sizeof UnDecoratedName, UNDNAME_COMPLETE)) { function = UnDecoratedName; } } } fputs(function, stdout); fputs(pretty ? " at " : "\n", stdout); } IMAGEHLP_LINE64 line; ZeroMemory(&line, sizeof line); line.SizeOfStruct = sizeof line; DWORD dwLineDisplacement = 0; bRet = SymGetLineFromAddr64(hProcess, dwAddr, &dwLineDisplacement, &line); if (bRet) { fprintf(stdout, "%s:%lu\n", line.FileName, line.LineNumber); } else { fputs("??:?\n", stdout); } fflush(stdout); } SymCleanup(hProcess); FreeLibrary(hModule); return 0; } <|endoftext|>
<commit_before>//============================================================================= // File: px4muorb_KraitRpcWrapper.hpp // // @@-COPYRIGHT-START-@@ // // Copyright 2015 Qualcomm Technologies, Inc. All rights reserved. // Confidential & Proprietary - Qualcomm Technologies, Inc. ("QTI") // // The party receiving this software directly from QTI (the "Recipient") // may use this software as reasonably necessary solely for the purposes // set forth in the agreement between the Recipient and QTI (the // "Agreement"). The software may be used in source code form solely by // the Recipient's employees (if any) authorized by the Agreement. Unless // expressly authorized in the Agreement, the Recipient may not sublicense, // assign, transfer or otherwise provide the source code to any third // party. Qualcomm Technologies, Inc. retains all ownership rights in and // to the software // // This notice supersedes any other QTI notices contained within the software // except copyright notices indicating different years of publication for // different portions of the software. This notice does not supersede the // application of any third party copyright notice to that third party's // code. // // @@-COPYRIGHT-END-@@ // //============================================================================= #ifndef _px4muorb_KraitRpcWrapper_hpp_ #define _px4muorb_KraitRpcWrapper_hpp_ #include <stdint.h> namespace px4muorb { class KraitRpcWrapper; } class px4muorb::KraitRpcWrapper { public: /** * Constructor */ KraitRpcWrapper(); /** * destructor */ ~KraitRpcWrapper(); /** * Initiatizes the rpc channel px4 muorb */ bool Initialize(); /** * Terminate to clean up the resources. This should be called at program exit */ bool Terminate(); /** * Muorb related functions to pub/sub of orb topic from krait to adsp */ int32_t AddSubscriber(const char *topic); int32_t RemoveSubscriber(const char *topic); int32_t SendData(const char *topic, int32_t length_in_bytes, const uint8_t *data); int32_t ReceiveData(int32_t *msg_type, char **topic, int32_t *length_in_bytes, uint8_t **data); int32_t IsSubscriberPresent(const char *topic, int32_t *status); int32_t ReceiveBulkData(uint8_t **bulk_data, int32_t *length_in_bytes, int32_t *topic_count); int32_t UnblockReceiveData(); }; #endif // _px4muorb_KraitWrapper_hpp_ <commit_msg>Fixed copyright header<commit_after>/**************************************************************************** * * Copyright (c) 2016 Ramakrishna Kintada. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ #ifndef _px4muorb_KraitRpcWrapper_hpp_ #define _px4muorb_KraitRpcWrapper_hpp_ #include <stdint.h> namespace px4muorb { class KraitRpcWrapper; } class px4muorb::KraitRpcWrapper { public: /** * Constructor */ KraitRpcWrapper(); /** * destructor */ ~KraitRpcWrapper(); /** * Initiatizes the rpc channel px4 muorb */ bool Initialize(); /** * Terminate to clean up the resources. This should be called at program exit */ bool Terminate(); /** * Muorb related functions to pub/sub of orb topic from krait to adsp */ int32_t AddSubscriber(const char *topic); int32_t RemoveSubscriber(const char *topic); int32_t SendData(const char *topic, int32_t length_in_bytes, const uint8_t *data); int32_t ReceiveData(int32_t *msg_type, char **topic, int32_t *length_in_bytes, uint8_t **data); int32_t IsSubscriberPresent(const char *topic, int32_t *status); int32_t ReceiveBulkData(uint8_t **bulk_data, int32_t *length_in_bytes, int32_t *topic_count); int32_t UnblockReceiveData(); }; #endif // _px4muorb_KraitWrapper_hpp_ <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "..\uti.hpp" #include <fstream> using namespace Microsoft::VisualStudio::CppUnitTestFramework; template __declspec( dllexport ) class uti::UTF8String< >; typedef uti::UTF8String< > String; //template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( String* str ) //{ // RETURN_WIDE_STRING( str->c_str() ); //} template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( const String& str ) { RETURN_WIDE_STRING( str.c_str() ); } //template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString(const String* str ) //{ // RETURN_WIDE_STRING( str->c_str() ); //} namespace utiTest { TEST_CLASS( UTF8Test ) { public: TEST_METHOD( CTorTest ) { try { String::ReplacementChar = "|"; const char blah [] = { 0xFFu, 0xC0u, 0x00 }; String string( blah ); Assert::AreEqual( '|', string.c_str()[ 0 ] ); const char excpected [] = "||"; String test( excpected ); Assert::AreEqual( test, string ); } catch( ... ) { Assert::Fail(); } try { const char blah [] = "Some Test"; String string( blah ); Assert::AreEqual( 9U, string.CharCount() ); Assert::AreEqual( 9U, string.Size() ); } catch( ... ) { Assert::Fail(); } try { const char test [] = "Some Test"; String string1 = test; String string2 = string1; String string3; string3 = string2; Assert::IsTrue( string1 == string2 ); Assert::IsTrue( string2 == string3 ); unsigned int iterations = 0; for( auto it = string3.Begin(); it != string3.End(); ++it, ++iterations ) { Assert::AreEqual( *it, test[ iterations ] ); } Assert::AreEqual( 9U, iterations ); } catch( ... ) { Assert::Fail(); } } TEST_METHOD( CTorFailTest ) { try { String string( ( const char* )nullptr ); String string2 = string; String string3 = string + string2; Assert::IsTrue( string.Size() == 0 ); Assert::IsTrue( string.CharCount() == 0 ); Assert::IsTrue( string2.Size() == 0 ); Assert::IsTrue( string2.CharCount() == 0 ); Assert::IsTrue( string3.Size() == 0 ); Assert::IsTrue( string3.CharCount() == 0 ); } catch( ... ) { Assert::Fail( L"Nullptr crashed the string constructor" ); } } TEST_METHOD( IteratorTest ) { String bla( "Test" ); const char test [] = "Test"; unsigned int iterations = 0; auto it = bla.Begin(); #ifdef DEBUG try { it--; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG for( ; it != bla.End(); ++it, ++iterations ) { Assert::AreEqual( *it, test[ iterations ] ); } Assert::AreEqual( 4U, iterations ); #ifdef DEBUG try { it++; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG } TEST_METHOD( ReverseIterator ) { String bla( "Test" ); const char* test = "Test"; unsigned int iterations = 0; auto it = bla.rBegin(); #ifdef DEBUG try { it--; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG for( ; it != bla.rEnd(); ++it, ++iterations ) { Assert::AreEqual( test[ 3U - iterations ], *it ); } Assert::AreEqual( 4U, iterations ); #ifdef DEBUG try { it++; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG } TEST_METHOD( ConcatTest ) { String first( "Some" ); String second( "Test" ); String expected( "SomeTest" ); Assert::IsTrue( ( first + second ) == expected, ( ToString( first + second ) + ToString( " does not match " ) + ToString( expected ) ).c_str() ); } TEST_METHOD( ValidityTest ) { char surrogate [] = { 0xd8U, 0x00U }; Assert::AreEqual( String::ValidChar( surrogate ), 0U ); } TEST_METHOD( WCharTest ) { String myString = String::FromUTF16LE( L"" ); Assert::AreEqual( 0U, myString.CharCount(), L"Converting empty widechar didn't create an empty UTf string!" ); Assert::AreEqual( '\0', myString.Data()[ 0 ], L"Converting empty widechar didn't has an null terminated character!" ); myString = String::FromUTF16LE( L"WideChar" ); String myNotWideString( "WideChar" ); Assert::AreEqual( myNotWideString.Size(), myString.Size(), L"Converting empty widechar didn't produces correct size" ); Assert::AreEqual( myNotWideString.CharCount(), myString.CharCount(), L"Converting empty widechar didn't produces correct charCount" ); Assert::AreEqual( myNotWideString, myString, L"Creating the same ascii text in ascii and unicode did not match" ); } TEST_METHOD( CompleteCodePointTest ) { std::ifstream file; file.open( "../test.txt", std::ios::binary ); if( !file.is_open() ) { Assert::Fail( L"Could not open File 'test.txt'" ); } else { file.seekg( 0, std::ios::end ); size_t fileSize = (size_t)file.tellg().seekpos(); file.seekg( 0, std::ios::beg ); char* content = new char[ fileSize + 1 ]; content[ fileSize ] = '\0'; size_t pos = 0; do { file.read( content + pos, 1000 ); pos += (size_t)file.gcount(); }while( !file.eof() && file.gcount() != 0 ); if( pos < 4416047U ) //Exact Byte size of test.txt { Assert::Fail( ( std::wstring( L"Failed to read " ) + std::to_wstring( fileSize ) + std::wstring( L" Bytes of data, could only read " ) + std::to_wstring( pos ) + std::wstring( L" Bytes!" ) ).c_str() ); return; } file.close(); size_t charCount = 0; for( size_t i = 0; i < fileSize; ) { size_t length = String::ValidChar( content + i ); if( length == 0 ) { Assert::Fail( (std::wstring( L"Invalid Char at position " ) + std::to_wstring( i )).c_str() ); break; } else { i += length; charCount++; } } String completeUTF8( content ); Assert::AreEqual( fileSize, completeUTF8.Size() ); //TODO check CharCount as soon as its available; delete content; } } TEST_METHOD( SubstrTestOneParam ) { String string( "Hello World" ); String expected( "Hello" ); auto it = string.CharBegin(); for( size_t i = 0; i < 5; i++ ) { ++it; } String sub = string.Substr( it ); Assert::AreNotEqual( string, sub, L"Substring does match original string!" ); Assert::AreEqual( 5U, sub.CharCount(), L"Char Size of substring does not match!" ); Assert::AreEqual( 5U, sub.Size(), L"Byte Size of substring does not match!" ); Assert::AreEqual( expected, sub, L"Substring does not match expected string." ); } TEST_METHOD( SubstrTestTwoParam ) { String string( "Hello World" ); String expected( "Wo" ); auto beginIterator = string.CharBegin(); for( size_t i = 0; i < 6; i++ ) { ++beginIterator; } auto endIterator = beginIterator; for( size_t i = 0; i < 2; i++ ) { ++endIterator; } String sub = string.Substr( beginIterator, endIterator ); Assert::AreNotEqual( string, sub, L"Substring does match original string!" ); Assert::AreEqual( 2U, sub.CharCount(), L"Char Size of substring does not match!" ); Assert::AreEqual( 2U, sub.Size(), L"Byte Size of substring does not match!" ); Assert::IsTrue( sub.Data()[ 0 ] == 'W' ); Assert::IsTrue( sub.Data()[ 1 ] == 'o' ); Assert::AreEqual( expected, sub, L"Substring does not match expected string." ); } }; } <commit_msg>Added negative test for Substr.<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "..\uti.hpp" #include <fstream> using namespace Microsoft::VisualStudio::CppUnitTestFramework; template __declspec( dllexport ) class uti::UTF8String< >; typedef uti::UTF8String< > String; //template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( String* str ) //{ // RETURN_WIDE_STRING( str->c_str() ); //} template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( const String& str ) { RETURN_WIDE_STRING( str.c_str() ); } //template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString(const String* str ) //{ // RETURN_WIDE_STRING( str->c_str() ); //} namespace utiTest { TEST_CLASS( UTF8Test ) { public: TEST_METHOD( CTorTest ) { try { String::ReplacementChar = "|"; const char blah [] = { 0xFFu, 0xC0u, 0x00 }; String string( blah ); Assert::AreEqual( '|', string.c_str()[ 0 ] ); const char excpected [] = "||"; String test( excpected ); Assert::AreEqual( test, string ); } catch( ... ) { Assert::Fail(); } try { const char blah [] = "Some Test"; String string( blah ); Assert::AreEqual( 9U, string.CharCount() ); Assert::AreEqual( 9U, string.Size() ); } catch( ... ) { Assert::Fail(); } try { const char test [] = "Some Test"; String string1 = test; String string2 = string1; String string3; string3 = string2; Assert::IsTrue( string1 == string2 ); Assert::IsTrue( string2 == string3 ); unsigned int iterations = 0; for( auto it = string3.Begin(); it != string3.End(); ++it, ++iterations ) { Assert::AreEqual( *it, test[ iterations ] ); } Assert::AreEqual( 9U, iterations ); } catch( ... ) { Assert::Fail(); } } TEST_METHOD( CTorFailTest ) { try { String string( ( const char* )nullptr ); String string2 = string; String string3 = string + string2; Assert::IsTrue( string.Size() == 0 ); Assert::IsTrue( string.CharCount() == 0 ); Assert::IsTrue( string2.Size() == 0 ); Assert::IsTrue( string2.CharCount() == 0 ); Assert::IsTrue( string3.Size() == 0 ); Assert::IsTrue( string3.CharCount() == 0 ); } catch( ... ) { Assert::Fail( L"Nullptr crashed the string constructor" ); } } TEST_METHOD( IteratorTest ) { String bla( "Test" ); const char test [] = "Test"; unsigned int iterations = 0; auto it = bla.Begin(); #ifdef DEBUG try { it--; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG for( ; it != bla.End(); ++it, ++iterations ) { Assert::AreEqual( *it, test[ iterations ] ); } Assert::AreEqual( 4U, iterations ); #ifdef DEBUG try { it++; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG } TEST_METHOD( ReverseIterator ) { String bla( "Test" ); const char* test = "Test"; unsigned int iterations = 0; auto it = bla.rBegin(); #ifdef DEBUG try { it--; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG for( ; it != bla.rEnd(); ++it, ++iterations ) { Assert::AreEqual( test[ 3U - iterations ], *it ); } Assert::AreEqual( 4U, iterations ); #ifdef DEBUG try { it++; Assert::Fail(); } catch( uti::UTFException& ) { } #endif // DEBUG } TEST_METHOD( ConcatTest ) { String first( "Some" ); String second( "Test" ); String expected( "SomeTest" ); Assert::IsTrue( ( first + second ) == expected, ( ToString( first + second ) + ToString( " does not match " ) + ToString( expected ) ).c_str() ); } TEST_METHOD( ValidityTest ) { char surrogate [] = { 0xd8U, 0x00U }; Assert::AreEqual( String::ValidChar( surrogate ), 0U ); } TEST_METHOD( WCharTest ) { String myString = String::FromUTF16LE( L"" ); Assert::AreEqual( 0U, myString.CharCount(), L"Converting empty widechar didn't create an empty UTf string!" ); Assert::AreEqual( '\0', myString.Data()[ 0 ], L"Converting empty widechar didn't has an null terminated character!" ); myString = String::FromUTF16LE( L"WideChar" ); String myNotWideString( "WideChar" ); Assert::AreEqual( myNotWideString.Size(), myString.Size(), L"Converting empty widechar didn't produces correct size" ); Assert::AreEqual( myNotWideString.CharCount(), myString.CharCount(), L"Converting empty widechar didn't produces correct charCount" ); Assert::AreEqual( myNotWideString, myString, L"Creating the same ascii text in ascii and unicode did not match" ); } TEST_METHOD( CompleteCodePointTest ) { std::ifstream file; file.open( "../test.txt", std::ios::binary ); if( !file.is_open() ) { Assert::Fail( L"Could not open File 'test.txt'" ); } else { file.seekg( 0, std::ios::end ); size_t fileSize = (size_t)file.tellg().seekpos(); file.seekg( 0, std::ios::beg ); char* content = new char[ fileSize + 1 ]; content[ fileSize ] = '\0'; size_t pos = 0; do { file.read( content + pos, 1000 ); pos += (size_t)file.gcount(); }while( !file.eof() && file.gcount() != 0 ); if( pos < 4416047U ) //Exact Byte size of test.txt { Assert::Fail( ( std::wstring( L"Failed to read " ) + std::to_wstring( fileSize ) + std::wstring( L" Bytes of data, could only read " ) + std::to_wstring( pos ) + std::wstring( L" Bytes!" ) ).c_str() ); return; } file.close(); size_t charCount = 0; for( size_t i = 0; i < fileSize; ) { size_t length = String::ValidChar( content + i ); if( length == 0 ) { Assert::Fail( (std::wstring( L"Invalid Char at position " ) + std::to_wstring( i )).c_str() ); break; } else { i += length; charCount++; } } String completeUTF8( content ); Assert::AreEqual( fileSize, completeUTF8.Size() ); //TODO check CharCount as soon as its available; delete content; } } TEST_METHOD( SubstrTestOneParam ) { String string( "Hello World" ); String expected( "Hello" ); auto it = string.CharBegin(); for( size_t i = 0; i < 5; i++ ) { ++it; } String sub = string.Substr( it ); Assert::AreNotEqual( string, sub, L"Substring does match original string!" ); Assert::AreEqual( 5U, sub.CharCount(), L"Char Size of substring does not match!" ); Assert::AreEqual( 5U, sub.Size(), L"Byte Size of substring does not match!" ); Assert::AreEqual( expected, sub, L"Substring does not match expected string." ); } TEST_METHOD( SubstrTestTwoParam ) { String string( "Hello World" ); String expected( "Wo" ); auto beginIterator = string.CharBegin(); for( size_t i = 0; i < 6; i++ ) { ++beginIterator; } auto endIterator = beginIterator; for( size_t i = 0; i < 2; i++ ) { ++endIterator; } String sub = string.Substr( beginIterator, endIterator ); Assert::AreNotEqual( string, sub, L"Substring does match original string!" ); Assert::AreEqual( 2U, sub.CharCount(), L"Char Size of substring does not match!" ); Assert::AreEqual( 2U, sub.Size(), L"Byte Size of substring does not match!" ); Assert::IsTrue( sub.Data()[ 0 ] == 'W' ); Assert::IsTrue( sub.Data()[ 1 ] == 'o' ); Assert::AreEqual( expected, sub, L"Substring does not match expected string." ); } TEST_METHOD( SubstrFailTest ) { String str1( "FirstString" ); String str2( "SecondString" ); auto beginIterator = str2.CharBegin(); auto endIterator = str2.CharEnd(); // Using wrong iterator from other string should return empty string String sub = str1.Substr( beginIterator, endIterator ); Assert::AreEqual( 0U, sub.Size(), L"String with wrong iterator does not return empty string" ); Assert::AreNotEqual( str1, sub, L"Substring does match original string!" ); Assert::AreNotEqual( str2, sub, L"Substring does match second string!" ); // Using start Iterator which is greater than the end iterator should return empty string sub = str1.Substr( str1.CharEnd(), str1.CharBegin()); Assert::AreEqual( 0U, sub.Size(), L"String with wrong iterator does not return empty string" ); Assert::AreNotEqual( str1, sub, L"Substring does match original string!" ); Assert::AreNotEqual( str2, sub, L"Substring does match second string!" ); } }; } <|endoftext|>
<commit_before>/// /// @file S2_hard_mpi_LoadBalancer.cpp /// @brief The S2_hard_mpi_LoadBalancer evenly distributes the /// computation of the hard special leaves onto cluster nodes. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2_hard_mpi_LoadBalancer.hpp> #include <S2_hard_mpi_msg.hpp> #include <primecount-internal.hpp> #include <min_max.hpp> #include <stdint.h> #include <algorithm> using namespace std; namespace primecount { S2_hard_mpi_LoadBalancer::S2_hard_mpi_LoadBalancer(int64_t low, int64_t high, int64_t y, int64_t z, int slave_procs) : low_(low), high_(high), y_(y), z_(z), slave_procs_(slave_procs), max_finished_(0), segment_size_(isqrt(z)), segments_per_thread_(1), proc_interval_(0), start_time_(get_wtime()), seconds_(0) { } bool S2_hard_mpi_LoadBalancer::finished() const { return low_ > z_; } bool S2_hard_mpi_LoadBalancer::is_increase(double seconds, double percent) const { // calculate remaining time till finished double elapsed_time = get_wtime() - start_time_; double remaining_time = elapsed_time * (100 / max(1.0, percent)) - elapsed_time; // for performance reasons all processes should // finish nearly at the same time double near_finish_time = elapsed_time / 100; double divisor = 100 / pow(5.0, 100 / in_between(1, percent, 100)); double max_time = remaining_time / max(1.0, divisor); double is_increase = max3(0.1, max_time, near_finish_time); return seconds < is_increase; } void S2_hard_mpi_LoadBalancer::update(S2_hard_mpi_msg* msg, double percent) { if (msg->high() >= max_finished_) { max_finished_ = msg->high(); proc_interval_ = msg->high() - msg->low(); segment_size_ = msg->segment_size(); segments_per_thread_ = max(segments_per_thread_, msg->segments_per_thread()); seconds_ = msg->seconds(); } int64_t next_interval = proc_interval_; // balance load by increasing or decreasing the // next interval based on previous run-time if (is_increase(seconds_, percent)) next_interval *= 2; else next_interval = max(next_interval / 2, isqrt(z_)); low_ = high_ + 1; high_ = min(low_ + next_interval, z_); // udpate existing message with new work todo msg->set(msg->proc_id(), low_, high_, segment_size_, segments_per_thread_); } } // namespace <commit_msg>Refactoring<commit_after>/// /// @file S2_hard_mpi_LoadBalancer.cpp /// @brief The S2_hard_mpi_LoadBalancer evenly distributes the /// computation of the hard special leaves onto cluster nodes. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2_hard_mpi_LoadBalancer.hpp> #include <S2_hard_mpi_msg.hpp> #include <primecount-internal.hpp> #include <min_max.hpp> #include <stdint.h> #include <algorithm> using namespace std; namespace primecount { S2_hard_mpi_LoadBalancer::S2_hard_mpi_LoadBalancer(int64_t low, int64_t high, int64_t y, int64_t z, int slave_procs) : low_(low), high_(high), y_(y), z_(z), slave_procs_(slave_procs), max_finished_(0), segment_size_(isqrt(z)), segments_per_thread_(1), proc_interval_(0), start_time_(get_wtime()), seconds_(0) { } bool S2_hard_mpi_LoadBalancer::finished() const { return low_ > z_; } bool S2_hard_mpi_LoadBalancer::is_increase(double seconds, double percent) const { // avoid division by 0 percent = in_between(1, percent, 100); // calculate remaining time till finished double elapsed_time = get_wtime() - start_time_; double remaining_time = elapsed_time * (100 / percent) - elapsed_time; // for performance reasons all processes should // finish nearly at the same time double near_finish_time = elapsed_time / 100; double divisor = max(1.0, 100 / pow(5.0, 100 / percent)); double max_time = remaining_time / divisor; double is_increase = max3(0.1, max_time, near_finish_time); return seconds < is_increase; } void S2_hard_mpi_LoadBalancer::update(S2_hard_mpi_msg* msg, double percent) { if (msg->high() >= max_finished_) { max_finished_ = msg->high(); proc_interval_ = msg->high() - msg->low(); segment_size_ = msg->segment_size(); segments_per_thread_ = max(segments_per_thread_, msg->segments_per_thread()); seconds_ = msg->seconds(); } int64_t next_interval = proc_interval_; // balance load by increasing or decreasing the // next interval based on previous run-time if (is_increase(seconds_, percent)) next_interval *= 2; else next_interval = max(next_interval / 2, isqrt(z_)); low_ = high_ + 1; high_ = min(low_ + next_interval, z_); // udpate existing message with new work todo msg->set(msg->proc_id(), low_, high_, segment_size_, segments_per_thread_); } } // namespace <|endoftext|>
<commit_before>#include "GlyphContainer.hpp" #include <stdio.h> GlyphContainer::GlyphContainer(int size, sf::Vector2i layout, const sf::Texture& bg_text) : _background(bg_text) { _nglyphs = size; _glyphs = std::vector<Glyph>(); _layout = layout; } GlyphContainer::~GlyphContainer() {} void GlyphContainer::draw(sf::RenderTarget* target) { target->draw(_background); for (auto g : _glyphs) { g.draw(target); } } void GlyphContainer::update(float deltaTime) { // TODO OR NOT TODO } void GlyphContainer::setRenderTarget(sf::RenderTarget* t) { _window = t; for (auto g : _glyphs) { g.setRenderTarget(t); } } void GlyphContainer::setPosition(const sf::Vector2f& pos) { _background.setPosition(pos); _pos = pos; sf::Vector2f g_size; if(!empty()) g_size = _glyphs[0].getSize(); else return; for(unsigned int i = 0; i < _layout.x; i++) { for(unsigned int j = 0; j < _layout.y; j++) { if((i * _layout.y + j) > _glyphs.size()) return; sf::Vector2f n_pos = _pos + sf::Vector2f(i * g_size.x, j * g_size.y); _glyphs[i * _layout.y + j].setPosition(n_pos); } } } void GlyphContainer::setSize(const sf::Vector2f& size) { setSize(size.x, size.y); } void GlyphContainer::setSize(float width, float height) { float x_ratio = width / _background.getTexture()->getSize().x; float y_ratio = height / _background.getTexture()->getSize().y; _background.setScale(sf::Vector2f(x_ratio, y_ratio)); sf::Vector2f gsize = calculateGlyphSize(); for(auto g : _glyphs) { g.setSize(gsize); } // Recalculate positions setPosition(_pos); } Glyph GlyphContainer::top() { return _glyphs[_glyphs.size()]; } void GlyphContainer::pop() { _glyphs.erase(_glyphs.end()--); } void GlyphContainer::add(Glyph g) { printf("Lmao1\n"); if(_glyphs.size() == 0) { printf("Lmao2\n"); g.setSize(calculateGlyphSize()); printf("Lmao3\n"); } else { printf("Lmao4\n"); g.setSize(_glyphs[0].getSize()); printf("Lmao5\n"); } printf("Lmao6\n"); _glyphs.push_back(g); printf("Lmao\n"); // Recalculate position setPosition(_pos); } void GlyphContainer::add(GlyphID gid) { Glyph g = Glyph(gid); add(g); } bool GlyphContainer::empty() { return _glyphs.size() == 0; } Glyph GlyphContainer::get(int index) { return _glyphs[index]; } GlyphID GlyphContainer::getGlyphID() { if(!empty()) return _glyphs[0].getID(); else return glyph_none; } sf::Vector2f GlyphContainer::calculateGlyphSize() { //sheeeeet float width; float height; width = _background.getTexture()->getSize().x / _layout.x * _background.getScale().x; height = _background.getTexture()->getSize().y / _layout.y * _background.getScale().y; return sf::Vector2f(width, height); } <commit_msg>nomerges<commit_after>#include "GlyphContainer.hpp" #include <stdio.h> GlyphContainer::GlyphContainer(int size, sf::Vector2i layout, const sf::Texture& bg_text) : _background(bg_text) { _nglyphs = size; _glyphs = std::vector<Glyph>(); _layout = layout; } GlyphContainer::~GlyphContainer() {} void GlyphContainer::draw(sf::RenderTarget* target) { target->draw(_background); for (auto g : _glyphs) { g.draw(target); } } void GlyphContainer::update(float deltaTime) { // TODO OR NOT TODO } void GlyphContainer::setRenderTarget(sf::RenderTarget* t) { _window = t; for (auto g : _glyphs) { g.setRenderTarget(t); } } void GlyphContainer::setPosition(const sf::Vector2f& pos) { _background.setPosition(pos); _pos = pos; sf::Vector2f g_size; if(!empty()) g_size = _glyphs[0].getSize(); else return; for(unsigned int i = 0; i < _layout.x; i++) { for(unsigned int j = 0; j < _layout.y; j++) { if((i * _layout.y + j) > _glyphs.size()) return; sf::Vector2f n_pos = _pos + sf::Vector2f(i * g_size.x, j * g_size.y); _glyphs[i * _layout.y + j].setPosition(n_pos); } } } void GlyphContainer::setSize(const sf::Vector2f& size) { setSize(size.x, size.y); } void GlyphContainer::setSize(float width, float height) { float x_ratio = width / _background.getTexture()->getSize().x; float y_ratio = height / _background.getTexture()->getSize().y; _background.setScale(sf::Vector2f(x_ratio, y_ratio)); sf::Vector2f gsize = calculateGlyphSize(); for(auto g : _glyphs) { g.setSize(gsize); } // Recalculate positions setPosition(_pos); } Glyph GlyphContainer::top() { return _glyphs[_glyphs.size()]; } void GlyphContainer::pop() { _glyphs.erase(_glyphs.end()--); } void GlyphContainer::add(Glyph g) { if(_glyphs.size() == 0) { g.setSize(calculateGlyphSize()); } else { g.setSize(_glyphs[0].getSize()); } _glyphs.push_back(g); // Recalculate position setPosition(_pos); } void GlyphContainer::add(GlyphID gid) { Glyph g = Glyph(gid); add(g); } bool GlyphContainer::empty() { return _glyphs.size() == 0; } Glyph GlyphContainer::get(int index) { return _glyphs[index]; } GlyphID GlyphContainer::getGlyphID() { if(!empty()) return _glyphs[0].getID(); else return glyph_none; } sf::Vector2f GlyphContainer::calculateGlyphSize() { //sheeeeet float width; float height; width = _background.getTexture()->getSize().x / _layout.x * _background.getScale().x; height = _background.getTexture()->getSize().y / _layout.y * _background.getScale().y; return sf::Vector2f(width, height); } <|endoftext|>
<commit_before>#include "VCardParser.h" #include <assert.h> #include <QIODevice> #include <QByteArray> #include <QDebug> #include "Exceptions.h" #include "Contact.h" /** Provides the actual parsing implementation. */ class VCardParserImpl { public: /** Creates a new parser instance and binds it to the specified data source and destination contact book. */ VCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest): m_State(psIdle), m_Source(a_Source), m_Dest(a_Dest), m_CurrentLineNum(0) { } /** Parses the source data from m_Source into the bound destination contact book m_Dest. Throws an EException descendant on error. Note that m_Dest may still be filled with some contacts that parsed successfully. */ void parse() { // Parse line-by-line, unwrap the lines here: QByteArray acc; // Accumulator for the current line while (!m_Source.atEnd()) { QByteArray cur = m_Source.readLine(); if ( !cur.isEmpty() && ( (cur.at(0) == 0x20) || // Continuation by a SP (cur.at(0) == 0x09) || // Continuation by a HT !cur.contains(':') // Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4) ) ) { // This was a folded line, append it to the accumulator: cur.remove(0, 1); acc.append(cur); } else { // This is a (start of a) new line, process the accumulator and store the new line in it: if (!acc.isEmpty()) { processLine(acc); } std::swap(acc, cur); } } // Process the last line: if (!acc.isEmpty()) { processLine(acc); } } protected: /** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). */ enum State { psIdle, //< The parser has no current contact, it expects a new "BEGIN:VCARD" sentence psBeginVCard, //< The parser has just read the "BEGIN:VCARD" line, expects a "VERSION" sentence psContact, //< The parser is reading individual contact property sentence } m_State; /** The source data provider. */ QIODevice & m_Source; /** The contact book into which the data is to be written. */ ContactBookPtr m_Dest; /** The current contact being parsed. Only valid in the psContact state. */ ContactPtr m_CurrentContact; /** The number of the line currently being processed (for error reporting). */ int m_CurrentLineNum; /** Parses the given single (unfolded) line. */ void processLine(const QByteArray & a_Line) { m_CurrentLineNum += 1; if (a_Line.isEmpty() || (a_Line == "\n")) { return; } try { auto sentence = breakUpSentence(a_Line); switch (m_State) { case psIdle: processSentenceIdle(sentence); break; case psBeginVCard: processSentenceBeginVCard(sentence); break; case psContact: processSentenceContact(sentence); break; } } catch (const EParseError & exc) { qWarning() << QString::fromUtf8("Cannot parse VCARD, line %1: %2. The line contents: \"%3\"") .arg(m_CurrentLineNum) .arg(QString::fromStdString(exc.m_Message)) .arg(QString::fromUtf8(a_Line)); throw; } } /** Breaks the specified single (unfolded) line into the contact sentence representation. */ Contact::Sentence breakUpSentence(const QByteArray & a_Line) { Contact::Sentence res; // The state of the inner state-machine, parsing a single sentence. // Each sentence has a basic structure of "[group.]key[;param1;param2]=value" enum { ssBegin, //< The parser is reading the beginning of the sentence (group or key) ssKey, //< The parser is reading the key (the group was present) ssParamName, //< The parser is reading the param name ssParamValue, //< The parser is reading the param value ssParamValueDQuote, //< The parser is reading the param value and is inside a dquote ssParamValueEnd, //< The parser has just finished the DQuote of a param value } sentenceState = ssBegin; auto len = a_Line.length(); assert(len > 0); if (a_Line.at(len - 1) == '\n') { assert(len > 1); len -= 1; } int last = 0; QByteArray currentParamName, currentParamValue; for (auto i = 0; i < len; ++i) { auto ch = a_Line.at(i); switch (sentenceState) { case ssBegin: { if (ch == '.') { res.m_Group = a_Line.mid(0, i - 1); last = i + 1; sentenceState = ssKey; continue; } // fallthrough } // case ssBegin case ssKey: { if (ch == ';') { if (last == i) { throw EParseError(__FILE__, __LINE__, "An empty key is not allowed"); } res.m_Key = a_Line.mid(last, i - last).toLower(); last = i + 1; sentenceState = ssParamName; continue; } if (ch == ':') { if (last == i) { throw EParseError(__FILE__, __LINE__, "An empty key is not allowed"); } res.m_Key = a_Line.mid(last, i - last).toLower(); res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } if (ch == '.') { throw EParseError(__FILE__, __LINE__, "A group has already been parsed, cannot add another one."); } break; } // case ssKey case ssParamName: { if (ch == '=') { if (i == last) { throw EParseError(__FILE__, __LINE__, "A parameter with no name is not allowed"); } currentParamName = a_Line.mid(last, i - last).toLower(); last = i + 1; currentParamValue.clear(); sentenceState = ssParamValue; continue; } if (ch == ';') { // Value-less parameter with another parameter following ("TEL;CELL;OTHER:...") res.m_Params.emplace_back(a_Line.mid(last, i - last), QByteArray()); last = i + 1; currentParamValue.clear(); currentParamName.clear(); continue; } if (ch == ':') { // Value-less parameter ending the params ("TEL;CELL:...") res.m_Params.emplace_back(a_Line.mid(last, i - last), QByteArray()); last = i + 1; last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } break; } // case ssParamName case ssParamValue: { if (ch == '"') { if (i > last) { throw EParseError(__FILE__, __LINE__, "Param value double-quoting is wrong"); } last = i + 1; } if (ch == ',') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; continue; } if (ch == ':') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } break; } // case ssParamValue case ssParamValueDQuote: { if (ch == '"') { res.m_Params.emplace_back(currentParamName, std::move(currentParamValue)); last = i + 1; sentenceState = ssParamValueEnd; continue; } if (ch == '\\') { // Skip the escape continue; } else { currentParamValue.append(ch); } break; } // case ssParamValueDQuote case ssParamValueEnd: { if (ch == ',') { last = i + 1; currentParamValue.clear(); sentenceState = ssParamValue; } if (ch == ':') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } throw EParseError(__FILE__, __LINE__, "An extra character following a param value double-quote"); } // case ssParamValueEnd } } // for i - a_Line[] throw EParseError(__FILE__, __LINE__, "Incomplete sentence"); } /** Processes the given sentence in the psIdle parser state. */ void processSentenceIdle(const Contact::Sentence & a_Sentence) { // The only valid line in this context is the "BEGIN:VCARD" line. // Any other line will cause an error throw if ( !a_Sentence.m_Group.isEmpty() ) { throw EParseError(__FILE__, __LINE__, "Expected a BEGIN:VCARD sentence, got a different sentence"); } m_State = psBeginVCard; } /** Parses the given single sentence in the psBeginVCard parser state. */ void processSentenceBeginVCard(const Contact::Sentence & a_Sentence) { // The only valid sentence in this context is the "VERSION:X" line. if ( !a_Sentence.m_Group.isEmpty() || (a_Sentence.m_Key != "version") || !a_Sentence.m_Params.empty() ) { throw EParseError(__FILE__, __LINE__, "Expected a VERSION sentence, got a different sentence"); } if (a_Sentence.m_Value.toFloat() == 0) { throw EParseError(__FILE__, __LINE__, "The VERSION sentence has an invalid value."); } m_CurrentContact.reset(new Contact); m_State = psContact; } /** Parses the given single (unfolded) line in the psContact parser state. */ void processSentenceContact(const Contact::Sentence & a_Sentence) { // If the sentence is "END:VCARD", terminate the current contact: if ( a_Sentence.m_Group.isEmpty() && (a_Sentence.m_Key == "end") && a_Sentence.m_Params.empty() && (a_Sentence.m_Value.toLower() == "vcard") ) { if (m_CurrentContact != nullptr) { m_Dest->addContact(m_CurrentContact); } m_CurrentContact.reset(); m_State = psIdle; return; } // Add the sentence to the current contact: m_CurrentContact->addSentence(a_Sentence); } }; void VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest) { VCardParserImpl impl(a_Source, a_Dest); impl.parse(); } std::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value) { std::vector<std::vector<QByteArray>> res; res.push_back({}); auto * curComponent = &res.back(); curComponent->push_back({}); auto * curValue = &curComponent->back(); auto len = a_Value.length(); for (int i = 0; i < len; ++i) { auto ch = a_Value.at(i); switch (ch) { case ';': { // Start a new component: res.push_back({}); curComponent = &res.back(); curComponent->push_back({}); curValue = &curComponent->back(); break; } // case ';' case ',': { // Start a new value: curComponent->push_back({}); curValue = &curComponent->back(); break; } case '\\': { // Skip the escape char and push the next char directly into the current value: i = 1 + 1; curValue->append(a_Value.at(i)); break; } default: { curValue->append(ch); break; } } // switch (ch) } // for i - a_Value[] return res; } <commit_msg>VCardParser: Fixed param-value parsing, added encoding support.<commit_after>#include "VCardParser.h" #include <assert.h> #include <QIODevice> #include <QByteArray> #include <QDebug> #include "Exceptions.h" #include "Contact.h" /** Provides the actual parsing implementation. */ class VCardParserImpl { public: /** Creates a new parser instance and binds it to the specified data source and destination contact book. */ VCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest): m_State(psIdle), m_Source(a_Source), m_Dest(a_Dest), m_CurrentLineNum(0) { } /** Parses the source data from m_Source into the bound destination contact book m_Dest. Throws an EException descendant on error. Note that m_Dest may still be filled with some contacts that parsed successfully. */ void parse() { // Parse line-by-line, unwrap the lines here: QByteArray acc; // Accumulator for the current line while (!m_Source.atEnd()) { QByteArray cur = m_Source.readLine(); if ( !cur.isEmpty() && ( (cur.at(0) == 0x20) || // Continuation by a SP (cur.at(0) == 0x09) || // Continuation by a HT !cur.contains(':') // Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4) ) ) { // This was a folded line, append it to the accumulator: cur.remove(0, 1); acc.append(cur); } else { // This is a (start of a) new line, process the accumulator and store the new line in it: if (!acc.isEmpty()) { processLine(acc); } std::swap(acc, cur); } } // Process the last line: if (!acc.isEmpty()) { processLine(acc); } } protected: /** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). */ enum State { psIdle, //< The parser has no current contact, it expects a new "BEGIN:VCARD" sentence psBeginVCard, //< The parser has just read the "BEGIN:VCARD" line, expects a "VERSION" sentence psContact, //< The parser is reading individual contact property sentence } m_State; /** The source data provider. */ QIODevice & m_Source; /** The contact book into which the data is to be written. */ ContactBookPtr m_Dest; /** The current contact being parsed. Only valid in the psContact state. */ ContactPtr m_CurrentContact; /** The number of the line currently being processed (for error reporting). */ int m_CurrentLineNum; /** Parses the given single (unfolded) line. */ void processLine(const QByteArray & a_Line) { m_CurrentLineNum += 1; if (a_Line.isEmpty() || (a_Line == "\n")) { return; } try { auto sentence = breakUpSentence(a_Line); switch (m_State) { case psIdle: processSentenceIdle(sentence); break; case psBeginVCard: processSentenceBeginVCard(sentence); break; case psContact: processSentenceContact(sentence); break; } } catch (const EParseError & exc) { qWarning() << QString::fromUtf8("Cannot parse VCARD, line %1: %2. The line contents: \"%3\"") .arg(m_CurrentLineNum) .arg(QString::fromStdString(exc.m_Message)) .arg(QString::fromUtf8(a_Line)); throw; } } /** Breaks the specified single (unfolded) line into the contact sentence representation. */ Contact::Sentence breakUpSentence(const QByteArray & a_Line) { Contact::Sentence res; // The state of the inner state-machine, parsing a single sentence. // Each sentence has a basic structure of "[group.]key[;param1;param2]=value" enum { ssBegin, //< The parser is reading the beginning of the sentence (group or key) ssKey, //< The parser is reading the key (the group was present) ssParamName, //< The parser is reading the param name ssParamValue, //< The parser is reading the param value ssParamValueDQuote, //< The parser is reading the param value and is inside a dquote ssParamValueEnd, //< The parser has just finished the DQuote of a param value } sentenceState = ssBegin; auto len = a_Line.length(); assert(len > 0); if (a_Line.at(len - 1) == '\n') { assert(len > 1); len -= 1; } int last = 0; QByteArray currentParamName, currentParamValue; for (auto i = 0; i < len; ++i) { auto ch = a_Line.at(i); switch (sentenceState) { case ssBegin: { if (ch == '.') { res.m_Group = a_Line.mid(0, i - 1); last = i + 1; sentenceState = ssKey; continue; } // fallthrough } // case ssBegin case ssKey: { if (ch == ';') { if (last == i) { throw EParseError(__FILE__, __LINE__, "An empty key is not allowed"); } res.m_Key = a_Line.mid(last, i - last).toLower(); last = i + 1; sentenceState = ssParamName; continue; } if (ch == ':') { if (last == i) { throw EParseError(__FILE__, __LINE__, "An empty key is not allowed"); } res.m_Key = a_Line.mid(last, i - last).toLower(); res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } if (ch == '.') { throw EParseError(__FILE__, __LINE__, "A group has already been parsed, cannot add another one."); } break; } // case ssKey case ssParamName: { if (ch == '=') { if (i == last) { throw EParseError(__FILE__, __LINE__, "A parameter with no name is not allowed"); } currentParamName = a_Line.mid(last, i - last).toLower(); last = i + 1; currentParamValue.clear(); sentenceState = ssParamValue; continue; } if (ch == ';') { // Value-less parameter with another parameter following ("TEL;CELL;OTHER:...") res.m_Params.emplace_back(a_Line.mid(last, i - last), QByteArray()); last = i + 1; currentParamValue.clear(); currentParamName.clear(); continue; } if (ch == ':') { // Value-less parameter ending the params ("TEL;CELL:...") res.m_Params.emplace_back(a_Line.mid(last, i - last), QByteArray()); last = i + 1; last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } break; } // case ssParamName case ssParamValue: { if (ch == '"') { if (i > last) { throw EParseError(__FILE__, __LINE__, "Param value double-quoting is wrong"); } last = i + 1; sentenceState = ssParamValueDQuote; continue; } if (ch == ',') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; continue; } if (ch == ':') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } if (ch == ';') { res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last)); last = i + 1; sentenceState = ssParamName; currentParamName.clear(); continue; } break; } // case ssParamValue case ssParamValueDQuote: { if (ch == '"') { res.m_Params.emplace_back(currentParamName, std::move(currentParamValue)); last = i + 1; sentenceState = ssParamValueEnd; continue; } if (ch == '\\') { // Skip the escape continue; } else { currentParamValue.append(ch); } break; } // case ssParamValueDQuote case ssParamValueEnd: { if (ch == ':') { last = i + 1; res.m_Value = a_Line.mid(i + 1, len - i - 1); return res; } if (ch == ';') { last = i + 1; sentenceState = ssParamName; continue; } throw EParseError(__FILE__, __LINE__, "An invalid character following a param value double-quote"); } // case ssParamValueEnd } } // for i - a_Line[] throw EParseError(__FILE__, __LINE__, "Incomplete sentence"); } /** Processes the given sentence in the psIdle parser state. */ void processSentenceIdle(const Contact::Sentence & a_Sentence) { // The only valid line in this context is the "BEGIN:VCARD" line. // Any other line will cause an error throw if ( !a_Sentence.m_Group.isEmpty() ) { throw EParseError(__FILE__, __LINE__, "Expected a BEGIN:VCARD sentence, got a different sentence"); } m_State = psBeginVCard; } /** Parses the given single sentence in the psBeginVCard parser state. */ void processSentenceBeginVCard(const Contact::Sentence & a_Sentence) { // The only valid sentence in this context is the "VERSION:X" line. if ( !a_Sentence.m_Group.isEmpty() || (a_Sentence.m_Key != "version") || !a_Sentence.m_Params.empty() ) { throw EParseError(__FILE__, __LINE__, "Expected a VERSION sentence, got a different sentence"); } if (a_Sentence.m_Value.toFloat() == 0) { throw EParseError(__FILE__, __LINE__, "The VERSION sentence has an invalid value."); } m_CurrentContact.reset(new Contact); m_State = psContact; } /** Parses the given single (unfolded) line in the psContact parser state. May modify the sentence / trash it. */ void processSentenceContact(Contact::Sentence & a_Sentence) { // If the sentence is "END:VCARD", terminate the current contact: if ( a_Sentence.m_Group.isEmpty() && (a_Sentence.m_Key == "end") && a_Sentence.m_Params.empty() && (a_Sentence.m_Value.toLower() == "vcard") ) { if (m_CurrentContact != nullptr) { m_Dest->addContact(m_CurrentContact); } m_CurrentContact.reset(); m_State = psIdle; return; } // Decode any encoding on the sentence's value: std::vector<QByteArray> enc; for (const auto & p: a_Sentence.m_Params) { if (p.m_Name == "encoding") { enc = p.m_Values; } } decodeValueEncoding(a_Sentence, enc); // Add the sentence to the current contact: m_CurrentContact->addSentence(a_Sentence); } /** Decodes the sentence's value according to the specified encoding. a_EncodingSpec is the encoding to be decoded, represented as a VCard property values. */ void decodeValueEncoding(Contact::Sentence & a_Sentence, const std::vector<QByteArray> & a_EncodingSpec) { for (const auto & enc: a_EncodingSpec) { auto lcEnc = enc.toLower(); if ((lcEnc == "b") || (lcEnc == "base64")) { a_Sentence.m_Value = QByteArray::fromBase64(a_Sentence.m_Value); return; } if (lcEnc == "quoted-printable") { a_Sentence.m_Value = decodeQuotedPrintable(a_Sentence.m_Value); return; } } } /** Returns the data after performing a quoted-printable decoding on it. */ static QByteArray decodeQuotedPrintable(const QByteArray & a_Src) { QByteArray res; auto len = a_Src.length(); res.reserve(len / 3); for (int i = 0; i < len; ++i) { auto ch = a_Src.at(i); if (ch == '=') { if (i + 2 == len) { // There's only one char left in the input, cannot decode -> copy to output res.append(a_Src.mid(i)); return res; } auto hex = a_Src.mid(i + 1, 2); bool isOK; auto decodedCh = hex.toInt(&isOK, 16); if (isOK) { res.append(decodedCh); } else { res.append(a_Src.mid(i, 3)); } i += 2; } else { res.append(ch); } } return res; } }; void VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest) { VCardParserImpl impl(a_Source, a_Dest); impl.parse(); } std::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value) { std::vector<std::vector<QByteArray>> res; res.push_back({}); auto * curComponent = &res.back(); curComponent->push_back({}); auto * curValue = &curComponent->back(); auto len = a_Value.length(); for (int i = 0; i < len; ++i) { auto ch = a_Value.at(i); switch (ch) { case ';': { // Start a new component: res.push_back({}); curComponent = &res.back(); curComponent->push_back({}); curValue = &curComponent->back(); break; } // case ';' case ',': { // Start a new value: curComponent->push_back({}); curValue = &curComponent->back(); break; } case '\\': { // Skip the escape char and push the next char directly into the current value: i = 1 + 1; curValue->append(a_Value.at(i)); break; } default: { curValue->append(ch); break; } } // switch (ch) } // for i - a_Value[] return res; } <|endoftext|>
<commit_before>#ifndef CMDSTAN_WRITE_DATETIME_HPP #define CMDSTAN_WRITE_DATETIME_HPP #include <stan/callbacks/writer.hpp> #include <stan/version.hpp> #include <chrono> #include <iomanip> #include <string> namespace cmdstan { void write_datetime(stan::callbacks::writer &writer) { const std::time_t current_datetime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm* curr_tm = std::localtime(&current_datetime); std::stringstream current_datetime_msg; current_datetime_msg << "start_datetime = " << std::setfill('0') << (1900+curr_tm->tm_year) << "-" << std::setw(2) << (curr_tm->tm_mon+1) << "-" << std::setw(2) << curr_tm->tm_mday << " " << std::setw(2) << curr_tm->tm_hour << ":" << std::setw(2) << curr_tm->tm_min << ":" << std::setw(2) << curr_tm->tm_sec; writer(current_datetime_msg.str()); } } // namespace cmdstan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef CMDSTAN_WRITE_DATETIME_HPP #define CMDSTAN_WRITE_DATETIME_HPP #include <stan/callbacks/writer.hpp> #include <stan/version.hpp> #include <chrono> #include <iomanip> #include <string> namespace cmdstan { void write_datetime(stan::callbacks::writer& writer) { const std::time_t current_datetime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm* curr_tm = std::localtime(&current_datetime); std::stringstream current_datetime_msg; current_datetime_msg << "start_datetime = " << std::setfill('0') << (1900 + curr_tm->tm_year) << "-" << std::setw(2) << (curr_tm->tm_mon + 1) << "-" << std::setw(2) << curr_tm->tm_mday << " " << std::setw(2) << curr_tm->tm_hour << ":" << std::setw(2) << curr_tm->tm_min << ":" << std::setw(2) << curr_tm->tm_sec; writer(current_datetime_msg.str()); } } // namespace cmdstan #endif <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013-2014 winlin 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 SRS_CORE_HPP #define SRS_CORE_HPP /* #include <srs_core.hpp> */ // current release version #define VERSION_MAJOR 2 #define VERSION_MINOR 0 #define VERSION_REVISION 16 // server info. #define RTMP_SIG_SRS_KEY "SRS" #define RTMP_SIG_SRS_ROLE "origin/edge server" #define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)" #define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server" #define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT #define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin" #define RTMP_SIG_SRS_EMAIL "[email protected]" #define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)" #define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin" #define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjie.zhao" #define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt" #define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")" #define RTMP_SIG_SRS_RELEASE "https://github.com/winlinvip/simple-rtmp-server/tree/1.0release" #define RTMP_SIG_SRS_HTTP_SERVER "https://github.com/winlinvip/simple-rtmp-server/wiki/v1_CN_HTTPServer#feature" #define RTMP_SIG_SRS_VERSION __SRS_XSTR(VERSION_MAJOR)"."__SRS_XSTR(VERSION_MINOR)"."__SRS_XSTR(VERSION_REVISION) // internal macros, covert macro values to str, // see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define __SRS_XSTR(v) __SRS_STR(v) #define __SRS_STR(v) #v /** * the core provides the common defined macros, utilities, * user must include the srs_core.hpp before any header, or maybe * build failed. */ // for 32bit os, 2G big file limit for unistd io, // ie. read/write/lseek to use 64bits size for huge file. #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif // for int64_t print using PRId64 format. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <assert.h> #define srs_assert(expression) assert(expression) #include <stddef.h> #include <sys/types.h> // generated by configure. #include <srs_auto_headers.hpp> // free the p and set to NULL. // p must be a T*. #define srs_freep(p) \ if (p) { \ delete p; \ p = NULL; \ } \ (void)0 // sometimes, the freepa is useless, // it's recomments to free each elem explicit. // so we remove the srs_freepa utility. /** * disable copy constructor of class, * to avoid the memory leak or corrupt by copy instance. */ #define disable_default_copy(className)\ private:\ /** \ * disable the copy constructor and operator=, donot allow directly copy. \ */ \ className(const className&); \ className& operator= (const className&) #endif <commit_msg>for bug #194, refine code, to 2.0.17<commit_after>/* The MIT License (MIT) Copyright (c) 2013-2014 winlin 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 SRS_CORE_HPP #define SRS_CORE_HPP /* #include <srs_core.hpp> */ // current release version #define VERSION_MAJOR 2 #define VERSION_MINOR 0 #define VERSION_REVISION 17 // server info. #define RTMP_SIG_SRS_KEY "SRS" #define RTMP_SIG_SRS_ROLE "origin/edge server" #define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)" #define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server" #define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT #define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin" #define RTMP_SIG_SRS_EMAIL "[email protected]" #define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)" #define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin" #define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjie.zhao" #define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt" #define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")" #define RTMP_SIG_SRS_RELEASE "https://github.com/winlinvip/simple-rtmp-server/tree/1.0release" #define RTMP_SIG_SRS_HTTP_SERVER "https://github.com/winlinvip/simple-rtmp-server/wiki/v1_CN_HTTPServer#feature" #define RTMP_SIG_SRS_VERSION __SRS_XSTR(VERSION_MAJOR)"."__SRS_XSTR(VERSION_MINOR)"."__SRS_XSTR(VERSION_REVISION) // internal macros, covert macro values to str, // see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define __SRS_XSTR(v) __SRS_STR(v) #define __SRS_STR(v) #v /** * the core provides the common defined macros, utilities, * user must include the srs_core.hpp before any header, or maybe * build failed. */ // for 32bit os, 2G big file limit for unistd io, // ie. read/write/lseek to use 64bits size for huge file. #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif // for int64_t print using PRId64 format. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <assert.h> #define srs_assert(expression) assert(expression) #include <stddef.h> #include <sys/types.h> // generated by configure. #include <srs_auto_headers.hpp> // free the p and set to NULL. // p must be a T*. #define srs_freep(p) \ if (p) { \ delete p; \ p = NULL; \ } \ (void)0 // sometimes, the freepa is useless, // it's recomments to free each elem explicit. // so we remove the srs_freepa utility. /** * disable copy constructor of class, * to avoid the memory leak or corrupt by copy instance. */ #define disable_default_copy(className)\ private:\ /** \ * disable the copy constructor and operator=, donot allow directly copy. \ */ \ className(const className&); \ className& operator= (const className&) #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "profilehighlighter.h" #include <QtCore/QRegExp> #include <QtGui/QColor> #include <QtGui/QTextDocument> #include <QtGui/QTextEdit> using namespace Qt4ProjectManager::Internal; #define MAX_VARIABLES 50 const char *const variables[MAX_VARIABLES] = { "CONFIG", "DEFINES", "DEF_FILE", "DEPENDPATH", "DESTDIR", "DESTDIR_TARGET", "DISTFILES", "DLLDESTDIR", "FORMS", "HEADERS", "INCLUDEPATH", "LEXSOURCES", "LIBS", "MAKEFILE", "MOC_DIR", "OBJECTS", "OBJECTS_DIR", "OBJMOC", "OTHER_FILES", "PKGCONFIG", "POST_TARGETDEPS", "PRECOMPILED_HEADER", "PRE_TARGETDEPS", "QMAKE", "QMAKESPEC", "QT", "RCC_DIR", "RC_FILE", "REQUIRES", "RESOURCES", "RES_FILE", "SOURCES", "SRCMOC", "SUBDIRS", "TARGET", "TARGET_EXT", "TARGET_x", "TARGET_x.y.z", "TEMPLATE", "TRANSLATIONS", "UI_DIR", "UI_HEADERS_DIR", "UI_SOURCES_DIR", "VER_MAJ", "VER_MIN", "VER_PAT", "VERSION", "VPATH", "YACCSOURCES", 0 }; #define MAX_FUNCTIONS 22 const char *const functions[MAX_FUNCTIONS] = { "basename", "CONFIG", "contains", "count", "dirname", "error", "exists", "find", "for", "include", "infile", "isEmpty", "join", "member", "message", "prompt", "quote", "sprintf", "system", "unique", "warning", 0 }; struct KeywordHelper { inline KeywordHelper(const QString &word) : needle(word) {} const QString needle; }; static bool operator<(const KeywordHelper &helper, const char *kw) { return helper.needle < QLatin1String(kw); } static bool operator<(const char *kw, const KeywordHelper &helper) { return QLatin1String(kw) < helper.needle; } static bool isVariable(const QString &word) { const char *const *start = &variables[0]; const char *const *end = &variables[MAX_VARIABLES - 1]; const char *const *kw = qBinaryFind(start, end, KeywordHelper(word)); return *kw != 0; } static bool isFunction(const QString &word) { const char *const *start = &functions[0]; const char *const *end = &functions[MAX_FUNCTIONS - 1]; const char *const *kw = qBinaryFind(start, end, KeywordHelper(word)); return *kw != 0; } ProFileHighlighter::ProFileHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { } void ProFileHighlighter::highlightBlock(const QString &text) { if (text.isEmpty()) return; QString buf; bool inCommentMode = false; QTextCharFormat emptyFormat; int i = 0; for (;;) { const QChar c = text.at(i); if (inCommentMode) { setFormat(i, 1, m_formats[ProfileCommentFormat]); } else { if (c.isLetter() || c == '_' || c == '.') { buf += c; setFormat(i - buf.length()+1, buf.length(), emptyFormat); if (!buf.isEmpty() && isFunction(buf)) setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]); else if (!buf.isEmpty() && isVariable(buf)) setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]); } else if (c == '(') { if (!buf.isEmpty() && isFunction(buf)) setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]); buf.clear(); } else if (c == '#') { inCommentMode = true; setFormat(i, 1, m_formats[ProfileCommentFormat]); buf.clear(); } else { if (!buf.isEmpty() && isVariable(buf)) setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]); buf.clear(); } } i++; if (i >= text.length()) break; } } <commit_msg>Highlight CCFLAGS and INSTALLS and STATECHARTS in .pro files.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used 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. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "profilehighlighter.h" #include <QtCore/QRegExp> #include <QtGui/QColor> #include <QtGui/QTextDocument> #include <QtGui/QTextEdit> using namespace Qt4ProjectManager::Internal; #define MAX_VARIABLES 53 const char *const variables[MAX_VARIABLES] = { "CCFLAG", "CONFIG", "DEFINES", "DEF_FILE", "DEPENDPATH", "DESTDIR", "DESTDIR_TARGET", "DISTFILES", "DLLDESTDIR", "FORMS", "HEADERS", "INCLUDEPATH", "INSTALLS", "LEXSOURCES", "LIBS", "MAKEFILE", "MOC_DIR", "OBJECTS", "OBJECTS_DIR", "OBJMOC", "OTHER_FILES", "PKGCONFIG", "POST_TARGETDEPS", "PRECOMPILED_HEADER", "PRE_TARGETDEPS", "QMAKE", "QMAKESPEC", "QT", "RCC_DIR", "RC_FILE", "REQUIRES", "RESOURCES", "RES_FILE", "SOURCES", "SRCMOC", "STATECHARTS", "SUBDIRS", "TARGET", "TARGET_EXT", "TARGET_x", "TARGET_x.y.z", "TEMPLATE", "TRANSLATIONS", "UI_DIR", "UI_HEADERS_DIR", "UI_SOURCES_DIR", "VER_MAJ", "VER_MIN", "VER_PAT", "VERSION", "VPATH", "YACCSOURCES", 0 }; #define MAX_FUNCTIONS 22 const char *const functions[MAX_FUNCTIONS] = { "basename", "CONFIG", "contains", "count", "dirname", "error", "exists", "find", "for", "include", "infile", "isEmpty", "join", "member", "message", "prompt", "quote", "sprintf", "system", "unique", "warning", 0 }; struct KeywordHelper { inline KeywordHelper(const QString &word) : needle(word) {} const QString needle; }; static bool operator<(const KeywordHelper &helper, const char *kw) { return helper.needle < QLatin1String(kw); } static bool operator<(const char *kw, const KeywordHelper &helper) { return QLatin1String(kw) < helper.needle; } static bool isVariable(const QString &word) { const char *const *start = &variables[0]; const char *const *end = &variables[MAX_VARIABLES - 1]; const char *const *kw = qBinaryFind(start, end, KeywordHelper(word)); return *kw != 0; } static bool isFunction(const QString &word) { const char *const *start = &functions[0]; const char *const *end = &functions[MAX_FUNCTIONS - 1]; const char *const *kw = qBinaryFind(start, end, KeywordHelper(word)); return *kw != 0; } ProFileHighlighter::ProFileHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { } void ProFileHighlighter::highlightBlock(const QString &text) { if (text.isEmpty()) return; QString buf; bool inCommentMode = false; QTextCharFormat emptyFormat; int i = 0; for (;;) { const QChar c = text.at(i); if (inCommentMode) { setFormat(i, 1, m_formats[ProfileCommentFormat]); } else { if (c.isLetter() || c == '_' || c == '.') { buf += c; setFormat(i - buf.length()+1, buf.length(), emptyFormat); if (!buf.isEmpty() && isFunction(buf)) setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]); else if (!buf.isEmpty() && isVariable(buf)) setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]); } else if (c == '(') { if (!buf.isEmpty() && isFunction(buf)) setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]); buf.clear(); } else if (c == '#') { inCommentMode = true; setFormat(i, 1, m_formats[ProfileCommentFormat]); buf.clear(); } else { if (!buf.isEmpty() && isVariable(buf)) setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]); buf.clear(); } } i++; if (i >= text.length()) break; } } <|endoftext|>
<commit_before>/* algorithm.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for algorithm namespace */ #include <ctime> #include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <thread> #include "algorithm.hpp" #include "../individual/individual.hpp" #include "../problem/problem.hpp" #include "../random_generator/random_generator.hpp" namespace algorithm { using std::vector; using individual::Individual; using problem::Problem; using namespace random_generator; bool compare_fitness(const Individual & a, const Individual & b) { return (std::isnan(a.get_fitness())) ? false : a.get_fitness() < b.get_fitness(); } std::ofstream open_log(const std::time_t & time) { std::stringstream time_string; time_string << std::put_time(std::localtime(&time), "%y%m%d_%H%M%S"); std::ofstream log("logs/" + time_string.str(), std::ios_base::app); if (!log.is_open()) { std::cerr << "Log file logs/" << time_string.str() << " could not be opened!"; std::exit(EXIT_FAILURE); } return log; } void log_info(const std::time_t & time, const Individual & best, const vector<Individual> & population) { double total_fitness = std::accumulate(population.begin(), population.end(), 0., [](const double & a, const Individual & b)->double const {return a + b.get_fitness();}); int total_size = std::accumulate(population.begin(), population.end(), 0, [](const int & a, const Individual & b)->double const {return a + b.get_total();}); std::ofstream log = open_log(time); log << best.get_fitness() << "\t" << total_fitness / population.size() << "\t" << best.get_total() << "\t" << total_size / population.size() << "\n"; log.close(); } vector<Individual> new_population(const Problem & problem) { vector<Individual> population; for (int i = 0; i < problem.population_size; ++i) population.emplace_back(Individual(problem)); return population; } Individual selection(const Problem & problem, const vector<Individual> & population) { int_dist dis(0, problem.population_size - 1); // closed interval vector<Individual> contestants; // get contestants for (int i = 0; i < problem.tournament_size; ++i) contestants.emplace_back(population[dis(rg.engine)]); return *std::min_element(contestants.begin(), contestants.end(), compare_fitness); } vector<Individual> new_offspring(const Problem & problem, const vector<Individual> & population) { vector<Individual> offspring; while (offspring.size() != population.size()) { // select parents for children vector<Individual> parents; for (int i = 0; i < problem.crossover_size; ++i) parents.emplace_back(selection(problem, population)); // crossover with probability real_dist dis(0, 1); if (dis(rg.engine) < problem.crossover_chance) crossover(problem.internals_chance, parents[0], parents[1]); // process children for (Individual & child : parents) { // mutate children child.mutate(problem.mutate_chance, problem.constant_min, problem.constant_max); // update fitness and size child.evaluate(problem.values); // save children offspring.emplace_back(child); } } return offspring; } const individual::Individual genetic(const problem::Problem & problem) { // setup time and start log std::time_t time = std::time(nullptr); std::ofstream log = open_log(time); log << "# running a Genetic Program on " << std::ctime(&time) << "\n"; log.close(); // start timing algorithm std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); // create initial popuation vector<Individual> population = new_population(problem); Individual best; // run algorithm to termination for (int iteration = 0; iteration < problem.iterations; ++iteration) { // find Individual with lowest "fitness" AKA error from populaiton best = *std::min_element(population.begin(), population.end(), compare_fitness); std::thread log_thread([time, best, population] {log_info(time, best, population);}); // create replacement population vector<Individual> offspring = new_offspring(problem, population); // perform elitism int_dist dis(0, problem.population_size - 1); for (int i = 0; i < problem.elitism_size; ++i) offspring[dis(rg.engine)] = best; // replace current population with offspring population.swap(offspring); log_thread.join(); } // end timing algorithm end = std::chrono::system_clock::now(); // log duration std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::ofstream log_after = open_log(time); log_after << "# finished computation at " << std::ctime(&end_time) << "# elapsed time: " << elapsed_seconds.count() << "s\n"; log_after.close(); return best; } } <commit_msg>More logged info<commit_after>/* algorithm.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for algorithm namespace */ #include <ctime> #include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <thread> #include "algorithm.hpp" #include "../individual/individual.hpp" #include "../problem/problem.hpp" #include "../random_generator/random_generator.hpp" namespace algorithm { using std::vector; using individual::Individual; using problem::Problem; using namespace random_generator; bool compare_fitness(const Individual & a, const Individual & b) { return (std::isnan(a.get_fitness())) ? false : a.get_fitness() < b.get_fitness(); } std::ofstream open_log(const std::time_t & time) { std::stringstream time_string; time_string << std::put_time(std::localtime(&time), "%y%m%d_%H%M%S"); std::ofstream log("logs/" + time_string.str(), std::ios_base::app); if (!log.is_open()) { std::cerr << "Log file logs/" << time_string.str() << " could not be opened!"; std::exit(EXIT_FAILURE); } return log; } void log_info(const std::time_t & time, const Individual & best, const vector<Individual> & population) { double total_fitness = std::accumulate(population.begin(), population.end(), 0., [](const double & a, const Individual & b)->double const {return a + b.get_fitness();}); int total_size = std::accumulate(population.begin(), population.end(), 0, [](const int & a, const Individual & b)->double const {return a + b.get_total();}); std::ofstream log = open_log(time); log << best.get_fitness() << "\t" << total_fitness / population.size() << "\t" << best.get_total() << "\t" << total_size / population.size() << "\n"; log.close(); } vector<Individual> new_population(const Problem & problem) { vector<Individual> population; for (int i = 0; i < problem.population_size; ++i) population.emplace_back(Individual(problem)); return population; } Individual selection(const Problem & problem, const vector<Individual> & population) { int_dist dis(0, problem.population_size - 1); // closed interval vector<Individual> contestants; // get contestants for (int i = 0; i < problem.tournament_size; ++i) contestants.emplace_back(population[dis(rg.engine)]); return *std::min_element(contestants.begin(), contestants.end(), compare_fitness); } vector<Individual> new_offspring(const Problem & problem, const vector<Individual> & population) { vector<Individual> offspring; while (offspring.size() != population.size()) { // select parents for children vector<Individual> parents; for (int i = 0; i < problem.crossover_size; ++i) parents.emplace_back(selection(problem, population)); // crossover with probability real_dist dis(0, 1); if (dis(rg.engine) < problem.crossover_chance) crossover(problem.internals_chance, parents[0], parents[1]); // process children for (Individual & child : parents) { // mutate children child.mutate(problem.mutate_chance, problem.constant_min, problem.constant_max); // update fitness and size child.evaluate(problem.values); // save children offspring.emplace_back(child); } } return offspring; } const individual::Individual genetic(const problem::Problem & problem) { // setup time and start log std::time_t time = std::time(nullptr); std::ofstream log = open_log(time); log << "# running a Genetic Program @ " << std::ctime(&time) << "# initial depth: " << problem.max_depth << ", iterations: " << problem.iterations << ", population size: " << problem.population_size << ", tournament size: " << problem.tournament_size << "\n" << "# best fitness - average fitness - size of best - average size\n"; log.close(); // start timing algorithm std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); // create initial popuation vector<Individual> population = new_population(problem); Individual best; // run algorithm to termination for (int iteration = 0; iteration < problem.iterations; ++iteration) { // find Individual with lowest "fitness" AKA error from populaiton best = *std::min_element(population.begin(), population.end(), compare_fitness); std::thread log_thread([time, best, population] {log_info(time, best, population);}); // create replacement population vector<Individual> offspring = new_offspring(problem, population); // perform elitism int_dist dis(0, problem.population_size - 1); for (int i = 0; i < problem.elitism_size; ++i) offspring[dis(rg.engine)] = best; // replace current population with offspring population.swap(offspring); log_thread.join(); } // end timing algorithm end = std::chrono::system_clock::now(); // log duration std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::ofstream log_after = open_log(time); log_after << "# finished computation @ " << std::ctime(&end_time) << "# elapsed time: " << elapsed_seconds.count() << "s\n"; log_after.close(); return best; } } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <algorithm> #include <thread> #include <fnord-eventdb/TableReader.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-msg/MessageEncoder.h> namespace fnord { namespace eventdb { static uint64_t findHeadGen( const String& table_name, const String& replica_id, const String& db_path) { uint64_t head_gen = 0; auto gen_prefix = StringUtil::format("$0.$1.", table_name, replica_id); FileUtil::ls(db_path, [gen_prefix, &head_gen] (const String& file) -> bool { if (StringUtil::beginsWith(file, gen_prefix) && StringUtil::endsWith(file, ".idx")) { auto s = file.substr(gen_prefix.size()); auto gen = std::stoul(s.substr(0, s.size() - 4)); if (gen > head_gen) { head_gen = gen; } } return true; }); return head_gen; } RefPtr<TableReader> TableReader::open( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema) { return new TableReader( table_name, replica_id, db_path, schema, findHeadGen(table_name, replica_id, db_path)); } TableReader::TableReader( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema, uint64_t head_generation) : name_(table_name), replica_id_(replica_id), db_path_(db_path), schema_(schema), head_gen_(head_generation) {} const String& TableReader::name() const { return name_; } const String& TableReader::basePath() const { return db_path_; } const msg::MessageSchema& TableReader::schema() const { return schema_; } RefPtr<TableSnapshot> TableReader::getSnapshot() { std::unique_lock<std::mutex> lk(mutex_); auto g = head_gen_; lk.unlock(); auto maxg = g + 100; while (g < maxg && !FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g + 1))) ++g; if (!FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g ))) { g = findHeadGen(name_, replica_id_, db_path_); } while (FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g + 1))) ++g; if (g != head_gen_) { lk.lock(); head_gen_ = g; lk.unlock(); } RefPtr<TableGeneration> head(new TableGeneration); head->table_name = name_; head->generation = g; if (head_gen_ > 0) { auto file = FileUtil::read(StringUtil::format( "$0/$1.$2.$3.idx", db_path_, name_, replica_id_, g)); head->decode(file); } return new TableSnapshot( head, List<RefPtr<fnord::eventdb::TableArena>>{}); } size_t TableReader::fetchRecords( const String& replica_id, uint64_t start_sequence, size_t limit, Function<bool (const msg::MessageObject& record)> fn) { auto snap = getSnapshot(); for (const auto& c : snap->head->chunks) { auto cbegin = c.start_sequence; auto cend = cbegin + c.num_records; if (cbegin <= start_sequence && cend > start_sequence) { auto roff = start_sequence - cbegin; auto rlen = c.num_records - roff; if (limit != size_t(-1) && rlen > limit) { rlen = limit; } return fetchRecords(c, roff, rlen, fn); } } return 0; } size_t TableReader::fetchRecords( const TableChunkRef& chunk, size_t offset, size_t limit, Function<bool (const msg::MessageObject& record)> fn) { auto filename = StringUtil::format( "$0/$1.$2.$3.sst", db_path_, name_, chunk.replica_id, chunk.chunk_id); #ifndef FNORD_NOTRACE fnord::logTrace( "fnord.evdb", "Reading rows local=$0..$1 global=$2..$3 from table=$4 chunk=$5", offset, offset + limit, chunk.start_sequence + offset, chunk.start_sequence + offset + limit, name_, chunk.replica_id + "." + chunk.chunk_id); #endif sstable::SSTableReader reader(File::openFile(filename, File::O_READ)); if (!reader.isFinalized()) { RAISEF(kRuntimeError, "unfinished table chunk: $0", filename); } auto body_size = reader.bodySize(); if (body_size == 0) { fnord::logWarning("fnord.evdb", "empty table chunk: $0", filename); return 0; } size_t n = 0; auto cursor = reader.getCursor(); while (cursor->valid()) { auto buf = cursor->getDataBuffer(); msg::MessageObject record; msg::MessageDecoder::decode(buf, schema_, &record); fn(record); if (++n == limit) { break; } if (!cursor->next()) { break; } } return n; } } // namespace eventdb } // namespace fnord <commit_msg>fix off by one<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <algorithm> #include <thread> #include <fnord-eventdb/TableReader.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-msg/MessageEncoder.h> namespace fnord { namespace eventdb { static uint64_t findHeadGen( const String& table_name, const String& replica_id, const String& db_path) { uint64_t head_gen = 0; auto gen_prefix = StringUtil::format("$0.$1.", table_name, replica_id); FileUtil::ls(db_path, [gen_prefix, &head_gen] (const String& file) -> bool { if (StringUtil::beginsWith(file, gen_prefix) && StringUtil::endsWith(file, ".idx")) { auto s = file.substr(gen_prefix.size()); auto gen = std::stoul(s.substr(0, s.size() - 4)); if (gen > head_gen) { head_gen = gen; } } return true; }); return head_gen; } RefPtr<TableReader> TableReader::open( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema) { return new TableReader( table_name, replica_id, db_path, schema, findHeadGen(table_name, replica_id, db_path)); } TableReader::TableReader( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema, uint64_t head_generation) : name_(table_name), replica_id_(replica_id), db_path_(db_path), schema_(schema), head_gen_(head_generation) {} const String& TableReader::name() const { return name_; } const String& TableReader::basePath() const { return db_path_; } const msg::MessageSchema& TableReader::schema() const { return schema_; } RefPtr<TableSnapshot> TableReader::getSnapshot() { std::unique_lock<std::mutex> lk(mutex_); auto g = head_gen_; lk.unlock(); auto maxg = g + 100; while (g < maxg && !FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g))) ++g; if (!FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g ))) { g = findHeadGen(name_, replica_id_, db_path_); } while (FileUtil::exists( StringUtil::format( "$0$1.$2.$3.idx", db_path_, name_, replica_id_, g + 1))) ++g; if (g != head_gen_) { lk.lock(); head_gen_ = g; lk.unlock(); } RefPtr<TableGeneration> head(new TableGeneration); head->table_name = name_; head->generation = g; if (head_gen_ > 0) { auto file = FileUtil::read(StringUtil::format( "$0/$1.$2.$3.idx", db_path_, name_, replica_id_, g)); head->decode(file); } return new TableSnapshot( head, List<RefPtr<fnord::eventdb::TableArena>>{}); } size_t TableReader::fetchRecords( const String& replica_id, uint64_t start_sequence, size_t limit, Function<bool (const msg::MessageObject& record)> fn) { auto snap = getSnapshot(); for (const auto& c : snap->head->chunks) { auto cbegin = c.start_sequence; auto cend = cbegin + c.num_records; if (cbegin <= start_sequence && cend > start_sequence) { auto roff = start_sequence - cbegin; auto rlen = c.num_records - roff; if (limit != size_t(-1) && rlen > limit) { rlen = limit; } return fetchRecords(c, roff, rlen, fn); } } return 0; } size_t TableReader::fetchRecords( const TableChunkRef& chunk, size_t offset, size_t limit, Function<bool (const msg::MessageObject& record)> fn) { auto filename = StringUtil::format( "$0/$1.$2.$3.sst", db_path_, name_, chunk.replica_id, chunk.chunk_id); #ifndef FNORD_NOTRACE fnord::logTrace( "fnord.evdb", "Reading rows local=$0..$1 global=$2..$3 from table=$4 chunk=$5", offset, offset + limit, chunk.start_sequence + offset, chunk.start_sequence + offset + limit, name_, chunk.replica_id + "." + chunk.chunk_id); #endif sstable::SSTableReader reader(File::openFile(filename, File::O_READ)); if (!reader.isFinalized()) { RAISEF(kRuntimeError, "unfinished table chunk: $0", filename); } auto body_size = reader.bodySize(); if (body_size == 0) { fnord::logWarning("fnord.evdb", "empty table chunk: $0", filename); return 0; } size_t n = 0; auto cursor = reader.getCursor(); while (cursor->valid()) { auto buf = cursor->getDataBuffer(); msg::MessageObject record; msg::MessageDecoder::decode(buf, schema_, &record); fn(record); if (++n == limit) { break; } if (!cursor->next()) { break; } } return n; } } // namespace eventdb } // namespace fnord <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsSelectionFunction.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-01-28 15:42:13 $ * * 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 SD_SLIDESORTER_SELECTION_FUNCTION_HXX #define SD_SLIDESORTER_SELECTION_FUNCTION_HXX #include "controller/SlsSlideFunction.hxx" #ifndef _LIST_HXX #include <tools/list.hxx> #endif class SdSlideViewShell; class SdWindow; class SdSlideView; class SdDrawDocument; class Sound; namespace sd { namespace slidesorter { namespace model { class PageDescriptor; } } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; class SelectionFunction : public SlideFunction { public: TYPEINFO(); SelectionFunction ( SlideSorterController& rController, SfxRequest& rRequest); virtual ~SelectionFunction (void); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Paint(const Rectangle& rRect, SdWindow* pWin); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void ScrollStart(); virtual void ScrollEnd(); /// Forward to the clipboard manager. virtual void DoCut (void); /// Forward to the clipboard manager. virtual void DoCopy (void); /// Forward to the clipboard manager. virtual void DoPaste (void); /** is called when the current function should be aborted. <p> This is used when a function gets a KEY_ESCAPE but can also be called directly. @returns true if a active function was aborted */ virtual bool cancel(); protected: SlideSorterController& mrController; private: /// Set in MouseButtonDown this flag indicates that a page has been hit. bool mbPageHit; /// This flag indicates whether the selection rectangle is visible. bool mbRectangleSelection; /// The rectangle of the mouse drag selection. Rectangle maDragSelectionRectangle; bool mbDragSelection; /// Box of the insert marker in model coordinates. Rectangle maInsertionMarkerBox; Sound* mpSound; class ShowingEffectInfo; ShowingEffectInfo* mpShowingEffectInfo; model::PageDescriptor* mpRangeSelectionAnchor; /** We use this flag to filter out the cases where MouseMotion() is called with a pressed mouse button but without a prior MouseButtonDown() call. This is an indication that the mouse button was pressed over another control, e.g. the view tab bar, and that a re-layout of the controls moved the slide sorter under the mouse. */ bool mbProcessingMouseButtonDown; /** Show the effect of the specified page. */ void ShowEffect (model::PageDescriptor& rDescriptor); /** Return whether there is currently an effect being shown. */ bool IsShowingEffect (void) const; DECL_LINK( DragSlideHdl, Timer* ); void StartDrag (void); /** Set the selection to exactly the specified page and also set it as the current page. Furthermore, if the view on which this selection function is working is the main view then the view is switched to the regular editing view. @param rDescriptor This page descriptor represents the page which will (a) replace the current selection and (b) become the current page of the main view. */ void SetCurrentPageAndSwitchView (model::PageDescriptor& rDescriptor); /** Make the slide nOffset slides away of the current one the new current slide. When the new index is outside the range of valid page numbers it is clipped to that range. @param nOffset When nOffset is negative then go back. When nOffset if positive go forward. When it is zero then ignore the call. */ void GotoNextPage (int nOffset); void ProcessMouseEvent (sal_uInt32 nEventType, const MouseEvent& rEvent); // What follows are a couple of helper methods that are used by // ProcessMouseEvent(). /// Select the specified page and set the selection anchor. void SelectHitPage (model::PageDescriptor& rDescriptor); /// Deselect the specified page. void DeselectHitPage (model::PageDescriptor& rDescriptor); /// Deselect all pages. void DeselectAllPages (void); /** for a possibly following mouse motion by starting the drag timer that after a short time of pressed but un-moved mouse starts a drag operation. */ void PrepareMouseMotion (const Point& aMouseModelPosition); /** Set the current page of the main view to the one specified by the given descriptor. */ void SetCurrentPage (model::PageDescriptor& rDescriptor); /** Select all pages between and including the selection anchor and the specified page. */ void RangeSelect (model::PageDescriptor& rDescriptor); /** Start a rectangle selection at the given position. */ void StartRectangleSelection (const Point& aMouseModelPosition); /** Update the rectangle selection so that the given position becomes the new second point of the selection rectangle. */ void UpdateRectangleSelection (const Point& aMouseModelPosition); /** Select all pages that lie completly in the selection rectangle. */ void ProcessRectangleSelection (bool bToggleSelection); /** Create a substitution display of the currently selected pages and use the given position as the anchor point. */ void CreateSubstitution (const Point& rMouseModelPosition); /** Move the substitution display by the distance the mouse has travelled since the last call to this method or to CreateSubstitution(). The given point becomes the new anchor. */ void UpdateSubstitution (const Point& rMouseModelPosition); /** Move the substitution display of the currently selected pages. */ void MoveSubstitution (void); }; } } } // end of namespace ::sd::slidesorter::controller #endif <commit_msg>INTEGRATION: CWS impress37 (1.6.46); FILE MERGED 2005/03/09 12:55:57 af 1.6.46.1: #i44006# Code clean up.<commit_after>/************************************************************************* * * $RCSfile: SlsSelectionFunction.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2005-03-23 14:01:29 $ * * 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 SD_SLIDESORTER_SELECTION_FUNCTION_HXX #define SD_SLIDESORTER_SELECTION_FUNCTION_HXX #include "controller/SlsSlideFunction.hxx" #ifndef _LIST_HXX #include <tools/list.hxx> #endif #include <memory> class SdSlideViewShell; class SdWindow; class SdSlideView; class SdDrawDocument; class Sound; namespace sd { namespace slidesorter { namespace model { class PageDescriptor; } } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; class SelectionFunction : public SlideFunction { public: TYPEINFO(); SelectionFunction ( SlideSorterController& rController, SfxRequest& rRequest); virtual ~SelectionFunction (void); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Paint(const Rectangle& rRect, SdWindow* pWin); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void ScrollStart(); virtual void ScrollEnd(); /// Forward to the clipboard manager. virtual void DoCut (void); /// Forward to the clipboard manager. virtual void DoCopy (void); /// Forward to the clipboard manager. virtual void DoPaste (void); /** is called when the current function should be aborted. <p> This is used when a function gets a KEY_ESCAPE but can also be called directly. @returns true if a active function was aborted */ virtual bool cancel(); protected: SlideSorterController& mrController; private: class SubstitutionHandler; class EventDescriptor; class InsertionIndicatorHandler; /// Set in MouseButtonDown this flag indicates that a page has been hit. bool mbPageHit; /// The rectangle of the mouse drag selection. Rectangle maDragSelectionRectangle; bool mbDragSelection; /// Box of the insert marker in model coordinates. Rectangle maInsertionMarkerBox; /** We use this flag to filter out the cases where MouseMotion() is called with a pressed mouse button but without a prior MouseButtonDown() call. This is an indication that the mouse button was pressed over another control, e.g. the view tab bar, and that a re-layout of the controls moved the slide sorter under the mouse. */ bool mbProcessingMouseButtonDown; ::std::auto_ptr<SubstitutionHandler> mpSubstitutionHandler; ::std::auto_ptr<InsertionIndicatorHandler> mpInsertionIndicatorHandler; DECL_LINK( DragSlideHdl, Timer* ); void StartDrag (void); /** Set the selection to exactly the specified page and also set it as the current page. */ void SetCurrentPage (model::PageDescriptor& rDescriptor); /** When the view on which this selection function is working is the main view then the view is switched to the regular editing view. */ void SwitchView (model::PageDescriptor& rDescriptor); /** Make the slide nOffset slides away of the current one the new current slide. When the new index is outside the range of valid page numbers it is clipped to that range. @param nOffset When nOffset is negative then go back. When nOffset if positive go forward. When it is zero then ignore the call. */ void GotoNextPage (int nOffset); void ProcessMouseEvent (sal_uInt32 nEventType, const MouseEvent& rEvent); // What follows are a couple of helper methods that are used by // ProcessMouseEvent(). /// Select the specified page and set the selection anchor. void SelectHitPage (model::PageDescriptor& rDescriptor); /// Deselect the specified page. void DeselectHitPage (model::PageDescriptor& rDescriptor); /// Deselect all pages. void DeselectAllPages (void); /** for a possibly following mouse motion by starting the drag timer that after a short time of pressed but un-moved mouse starts a drag operation. */ void PrepareMouseMotion (const Point& aMouseModelPosition); /** Select all pages between and including the selection anchor and the specified page. */ void RangeSelect (model::PageDescriptor& rDescriptor); /** Start a rectangle selection at the given position. */ void StartRectangleSelection (const Point& aMouseModelPosition); /** Update the rectangle selection so that the given position becomes the new second point of the selection rectangle. */ void UpdateRectangleSelection (const Point& aMouseModelPosition); /** Select all pages that lie completly in the selection rectangle. */ void ProcessRectangleSelection (bool bToggleSelection); /** Hide and clear the insertion indiciator, substitution display and selection rectangle. */ void ClearOverlays (void); /** Compute a numerical code that describes a mouse event and that can be used for fast look up of the appropriate reaction. */ sal_uInt32 EncodeMouseEvent ( const EventDescriptor& rDescriptor, const MouseEvent& rEvent) const; void EventPreprocessing (const EventDescriptor& rEvent); bool EventProcessing (const EventDescriptor& rEvent); void EventPostprocessing (const EventDescriptor& rEvent); }; } } } // end of namespace ::sd::slidesorter::controller #endif <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, 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 Willow Garage, 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. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ #define PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ #include "pcl/features/principal_curvatures.h" ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computePointPrincipalCurvatures ( const pcl::PointCloud<PointNT> &normals, int p_idx, const std::vector<int> &indices, float &pcx, float &pcy, float &pcz, float &pc1, float &pc2) { EIGEN_ALIGN16 Eigen::Matrix3f I = Eigen::Matrix3f::Identity (); Eigen::Vector3f n_idx (normals.points[p_idx].normal[0], normals.points[p_idx].normal[1], normals.points[p_idx].normal[2]); EIGEN_ALIGN16 Eigen::Matrix3f M = I - n_idx * n_idx.transpose (); // projection matrix (into tangent plane) // Project normals into the tangent plane Eigen::Vector3f normal; projected_normals_.resize (indices.size ()); xyz_centroid_.setZero (); for (size_t idx = 0; idx < indices.size(); ++idx) { normal[0] = normals.points[indices[idx]].normal[0]; normal[1] = normals.points[indices[idx]].normal[1]; normal[2] = normals.points[indices[idx]].normal[2]; projected_normals_[idx] = M * normal; xyz_centroid_ += projected_normals_[idx]; } // Estimate the XYZ centroid xyz_centroid_ /= indices.size (); // Initialize to 0 covariance_matrix_.setZero (); double demean_xy, demean_xz, demean_yz; // For each point in the cloud for (size_t idx = 0; idx < indices.size (); ++idx) { demean_ = projected_normals_[idx] - xyz_centroid_; demean_xy = demean_[0] * demean_[1]; demean_xz = demean_[0] * demean_[2]; demean_yz = demean_[1] * demean_[2]; covariance_matrix_(0, 0) += demean_[0] * demean_[0]; covariance_matrix_(0, 1) += demean_xy; covariance_matrix_(0, 2) += demean_xz; covariance_matrix_(1, 0) += demean_xy; covariance_matrix_(1, 1) += demean_[1] * demean_[1]; covariance_matrix_(1, 2) += demean_yz; covariance_matrix_(2, 0) += demean_xz; covariance_matrix_(2, 1) += demean_yz; covariance_matrix_(2, 2) += demean_[2] * demean_[2]; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix_); //eigenvalues_ = ei_symm.eigenvalues (); //eigenvectors_ = ei_symm.eigenvectors (); pcl::eigen33 (covariance_matrix_, eigenvectors_, eigenvalues_); pcx = eigenvectors_ (0, 2); pcy = eigenvectors_ (1, 2); pcz = eigenvectors_ (2, 2); pc1 = eigenvalues_ (2); //pc2 = eigenvalues_ (1); Here is an error, min eval has zero index. Fixed in r2635. pc2 = eigenvalues_ (0); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists); // Estimate the principal curvatures at each patch computePointPrincipalCurvatures (*normals_, (*indices_)[idx], nn_indices, output.points[idx].principal_curvature[0], output.points[idx].principal_curvature[1], output.points[idx].principal_curvature[2], output.points[idx].pc1, output.points[idx].pc2); } } #define PCL_INSTANTIATE_PrincipalCurvaturesEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PrincipalCurvaturesEstimation<T,NT,OutT>; #endif // PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ <commit_msg>issue #364, reverted commit r2635. First eigen value evaluates to 0, that's why middle is taken.<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, 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 Willow Garage, 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. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ #define PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ #include "pcl/features/principal_curvatures.h" ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computePointPrincipalCurvatures ( const pcl::PointCloud<PointNT> &normals, int p_idx, const std::vector<int> &indices, float &pcx, float &pcy, float &pcz, float &pc1, float &pc2) { EIGEN_ALIGN16 Eigen::Matrix3f I = Eigen::Matrix3f::Identity (); Eigen::Vector3f n_idx (normals.points[p_idx].normal[0], normals.points[p_idx].normal[1], normals.points[p_idx].normal[2]); EIGEN_ALIGN16 Eigen::Matrix3f M = I - n_idx * n_idx.transpose (); // projection matrix (into tangent plane) // Project normals into the tangent plane Eigen::Vector3f normal; projected_normals_.resize (indices.size ()); xyz_centroid_.setZero (); for (size_t idx = 0; idx < indices.size(); ++idx) { normal[0] = normals.points[indices[idx]].normal[0]; normal[1] = normals.points[indices[idx]].normal[1]; normal[2] = normals.points[indices[idx]].normal[2]; projected_normals_[idx] = M * normal; xyz_centroid_ += projected_normals_[idx]; } // Estimate the XYZ centroid xyz_centroid_ /= indices.size (); // Initialize to 0 covariance_matrix_.setZero (); double demean_xy, demean_xz, demean_yz; // For each point in the cloud for (size_t idx = 0; idx < indices.size (); ++idx) { demean_ = projected_normals_[idx] - xyz_centroid_; demean_xy = demean_[0] * demean_[1]; demean_xz = demean_[0] * demean_[2]; demean_yz = demean_[1] * demean_[2]; covariance_matrix_(0, 0) += demean_[0] * demean_[0]; covariance_matrix_(0, 1) += demean_xy; covariance_matrix_(0, 2) += demean_xz; covariance_matrix_(1, 0) += demean_xy; covariance_matrix_(1, 1) += demean_[1] * demean_[1]; covariance_matrix_(1, 2) += demean_yz; covariance_matrix_(2, 0) += demean_xz; covariance_matrix_(2, 1) += demean_yz; covariance_matrix_(2, 2) += demean_[2] * demean_[2]; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix_); //eigenvalues_ = ei_symm.eigenvalues (); //eigenvectors_ = ei_symm.eigenvectors (); pcl::eigen33 (covariance_matrix_, eigenvectors_, eigenvalues_); pcx = eigenvectors_ (0, 2); pcy = eigenvectors_ (1, 2); pcz = eigenvectors_ (2, 2); pc1 = eigenvalues_ (2); pc2 = eigenvalues_ (1); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists); // Estimate the principal curvatures at each patch computePointPrincipalCurvatures (*normals_, (*indices_)[idx], nn_indices, output.points[idx].principal_curvature[0], output.points[idx].principal_curvature[1], output.points[idx].principal_curvature[2], output.points[idx].pc1, output.points[idx].pc2); } } #define PCL_INSTANTIATE_PrincipalCurvaturesEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PrincipalCurvaturesEstimation<T,NT,OutT>; #endif // PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_ <|endoftext|>
<commit_before>#include "minishift.h" #include "glcdfont.h" Minishift::Minishift(int data_pin, int clock_pin, int latch_pin) { this->data_pin = data_pin; this->clock_pin = clock_pin; this->latch_pin = latch_pin; this->latch_state = HIGH; pinMode(data_pin, OUTPUT); pinMode(clock_pin, OUTPUT); digitalWrite(latch_pin, HIGH); pinMode(latch_pin, OUTPUT); } void Minishift::startTransaction() { if(this->latch_state != LOW) { this->latch_state = LOW; digitalWrite(this->latch_pin, this->latch_state); } } void Minishift::writeColumns(const uint8_t *buf, int len) { this->writeColumns(buf, len, -1); } void Minishift::writeColumns(const uint8_t *buf, int len, int ms) { for(int i = 0; i < len; i++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, buf[i]); if(ms != -1) { this->update(); delay(ms); } } } void Minishift::writeString(const char *str) { this->writeString(str, -1); } void Minishift::writeString(const char *str, int ms) { this->writeString(str, ms, 0); } void Minishift::writeString(const char *str, int ms, int trailing) { for(const char *c = str; *c != '\0'; c++) { for(int col = 0; col < 5; col++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, pgm_read_byte(font + (*c * 5) + col)); this->update(); if(ms != -1) { delay(ms); } } for(int col = 0; col < trailing; col++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, 0); this->update(); if(ms != -1) { delay(ms); } } } } void Minishift::update() { if(this->latch_state != HIGH) { this->latch_state = HIGH; digitalWrite(this->latch_pin, this->latch_state); } } <commit_msg>Update minishift.cpp<commit_after>#include "minishift.h" #include "glcdfont.h" Minishift::Minishift(int data_pin, int clock_pin, int latch_pin) { this->data_pin = data_pin; this->clock_pin = clock_pin; this->latch_pin = latch_pin; this->latch_state = HIGH; pinMode(data_pin, OUTPUT); pinMode(clock_pin, OUTPUT); digitalWrite(latch_pin, HIGH); pinMode(latch_pin, OUTPUT); } void Minishift::startTransaction() { if(this->latch_state != LOW) { this->latch_state = LOW; digitalWrite(this->latch_pin, this->latch_state); } } void Minishift::writeColumns(const uint8_t *buf, int len) { this->writeColumns(buf, len, -1); } void Minishift::writeColumns(const uint8_t *buf, int len, int ms) { for(int i = 0; i < len; i++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, buf[i]); this->update(); if(ms != -1) { delay(ms); } } } void Minishift::writeString(const char *str) { this->writeString(str, -1); } void Minishift::writeString(const char *str, int ms) { this->writeString(str, ms, 0); } void Minishift::writeString(const char *str, int ms, int trailing) { for(const char *c = str; *c != '\0'; c++) { for(int col = 0; col < 5; col++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, pgm_read_byte(font + (*c * 5) + col)); this->update(); if(ms != -1) { delay(ms); } } for(int col = 0; col < trailing; col++) { this->startTransaction(); shiftOut(this->data_pin, this->clock_pin, LSBFIRST, 0); this->update(); if(ms != -1) { delay(ms); } } } } void Minishift::update() { if(this->latch_state != HIGH) { this->latch_state = HIGH; digitalWrite(this->latch_pin, this->latch_state); } } <|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include "../include/spica.h" using namespace spica; int main(int argc, char** argv) { std::cout << "*** spica: Subsurface scattering (SPPM) ***" << std::endl; const int width = argc >= 2 ? atoi(argv[1]) : 320; const int height = argc >= 3 ? atoi(argv[2]) : 240; const int samplePerPixel = argc >= 4 ? atoi(argv[3]) : 32; const int numPhotons = argc >= 5 ? atoi(argv[4]) : 1000000; std::cout << " width: " << width << std::endl; std::cout << " height: " << height << std::endl; std::cout << " sample/px: " << samplePerPixel << std::endl; std::cout << " photons: " << numPhotons << std::endl << std::endl; Scene scene; Camera camera; // cornellBoxDragon(&scene, &camera, width, height); kittenBox(&scene, &camera, width, height); BSSRDF bssrdf = DiffusionBSSRDF::factory(1.0e-4, 10.0, 1.3); SubsurfaceSPPMRenderer renderer; Timer timer; timer.start(); renderer.render(scene, camera, bssrdf, samplePerPixel, numPhotons, QUASI_MONTE_CARLO); printf("Time: %f sec\n", timer.stop()); } <commit_msg>Minor bug fix.<commit_after>#include <cstdio> #include <iostream> #include "../include/spica.h" using namespace spica; int main(int argc, char** argv) { std::cout << "*** spica: Subsurface scattering (SPPM) ***" << std::endl; const int width = argc >= 2 ? atoi(argv[1]) : 320; const int height = argc >= 3 ? atoi(argv[2]) : 240; const int samplePerPixel = argc >= 4 ? atoi(argv[3]) : 32; const int numPhotons = argc >= 5 ? atoi(argv[4]) : 1000000; std::cout << " width: " << width << std::endl; std::cout << " height: " << height << std::endl; std::cout << " sample/px: " << samplePerPixel << std::endl; std::cout << " photons: " << numPhotons << std::endl << std::endl; Scene scene; Camera camera; // cornellBoxDragon(&scene, &camera, width, height); kittenBox(&scene, &camera, width, height); BSSRDF bssrdf = DipoleBSSRDF::factory(1.0e-4, 10.0, 1.3); SubsurfaceSPPMRenderer renderer; Timer timer; timer.start(); renderer.render(scene, camera, bssrdf, samplePerPixel, numPhotons, QUASI_MONTE_CARLO); printf("Time: %f sec\n", timer.stop()); } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Ruben Dörfel <[email protected]>; * @version dev * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <vector> #include <math.h> #include <fiff/fiff.h> #include <fiff/fiff_info.h> #include <fiff/fiff_dig_point_set.h> #include <fiff/fiff_cov.h> #include <inverse/hpiFit/hpifit.h> #include <inverse/hpiFit/hpifitdata.h> #include <utils/ioutils.h> #include <utils/generics/applicationlogger.h> #include <fwd/fwd_coil_set.h> //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QFile> #include <QCommandLineParser> #include <QDebug> #include <QGenericMatrix> #include <QQuaternion> #include <QElapsedTimer> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace INVERSELIB; using namespace FIFFLIB; using namespace Eigen; //============================================================================================================= // Member functions //============================================================================================================= //========================================================================================================= /** * Store results from dev_Head_t as quaternions in position matrix. The postion matrix is consisten with the MaxFilter output * * @param[in] time The corresponding time in the measurement for the fit. * @param[in] pFiffInfo The FiffInfo file from the measurement. * @param[in] position The matrix to store the results * @param[in] vGoF The vector that stores the goodness of fit. * * ToDo: get correct GoF; vGof that is passed to fitHPI does not represent the actual GoF * */ void writePos(const float time, QSharedPointer<FiffInfo> pFiffInfo, MatrixXd& position, const QVector<double>& vGoF) { // Write quaternions and time in position matrix. Format is the same like MaxFilter's .pos files. QMatrix3x3 rot; for(int ir = 0; ir < 3; ir++) { for(int ic = 0; ic < 3; ic++) { rot(ir,ic) = pFiffInfo->dev_head_t.trans(ir,ic); } } // double error = std::accumulate(vGoF.begin(), vGoF.end(), .0) / vGoF.size(); QQuaternion quatHPI = QQuaternion::fromRotationMatrix(rot); //qDebug() << "quatHPI.x() " << "quatHPI.y() " << "quatHPI.y() " << "trans x " << "trans y " << "trans z " << std::endl; //qDebug() << quatHPI.x() << quatHPI.y() << quatHPI.z() << info->dev_head_t.trans(0,3) << info->dev_head_t.trans(1,3) << info->dev_head_t.trans(2,3) << std::endl; position.conservativeResize(position.rows()+1, 10); position(position.rows()-1,0) = time; position(position.rows()-1,1) = quatHPI.x(); position(position.rows()-1,2) = quatHPI.y(); position(position.rows()-1,3) = quatHPI.z(); position(position.rows()-1,4) = pFiffInfo->dev_head_t.trans(0,3); position(position.rows()-1,5) = pFiffInfo->dev_head_t.trans(1,3); position(position.rows()-1,6) = pFiffInfo->dev_head_t.trans(2,3); position(position.rows()-1,7) = 0; position(position.rows()-1,8) = 0; position(position.rows()-1,9) = 0; } //========================================================================================================= /** * Compare new head position with current head position and update dev_head_t if big displacement occured * * @param[in] devHeadTrans The device to head transformation matrix to compare to. * @param[in] devHeadTransNew The device to head transformation matrix to be compared. * @param[in] treshRot The threshold for big head rotation in degree * @param[in] treshTrans The threshold for big head movement in m * * @param[out] state The status that shows if devHead is updated or not * */ bool compareResults(FiffCoordTrans& devHeadT, const FiffCoordTrans& devHeadTNew,const float& treshRot,const float& treshTrans, MatrixXd& result) { QMatrix3x3 rot; QMatrix3x3 rotNew; for(int ir = 0; ir < 3; ir++) { for(int ic = 0; ic < 3; ic++) { rot(ir,ic) = devHeadT.trans(ir,ic); rotNew(ir,ic) = devHeadTNew.trans(ir,ic); } } VectorXf trans = devHeadT.trans.col(3); VectorXf transNew = devHeadTNew.trans.col(3); QQuaternion quat = QQuaternion::fromRotationMatrix(rot); QQuaternion quatNew = QQuaternion::fromRotationMatrix(rotNew); // Compare Rotation QQuaternion quatCompare; float angle; QVector3D axis; // get rotation between both transformations by multiplying with the inverted quaternion quatCompare = quat*quatNew.inverted(); quatCompare.getAxisAndAngle(&axis,&angle); qInfo() << "Displacement angle [degree]: " << angle; // Compare translation float move = (trans-transNew).norm(); qInfo() << "Displacement Move [mm]: " << move*1000; // write results for debug purpose - quaternions are quatCompare result.conservativeResize(result.rows()+1, 10); result.conservativeResize(result.rows()+1, 10); result(result.rows()-1,0) = 0; result(result.rows()-1,1) = quatCompare.x(); result(result.rows()-1,2) = quatCompare.y(); result(result.rows()-1,3) = quatCompare.z(); result(result.rows()-1,4) = (trans-transNew).x(); result(result.rows()-1,5) = (trans-transNew).y(); result(result.rows()-1,6) = (trans-transNew).z(); result(result.rows()-1,7) = angle; result(result.rows()-1,8) = move; result(result.rows()-1,9) = 0; return false; } //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter); QElapsedTimer timer; QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("hpiFit Example"); parser.addHelpOption(); qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin."; QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif"); parser.addOption(inputOption); parser.process(a); // Init data loading and writing QFile t_fileIn(parser.value(inputOption)); FiffRawData raw(t_fileIn); QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info)); FiffCoordTrans devHeadTrans = pFiffInfo->dev_head_t; // Set up the reading parameters RowVectorXi picks = pFiffInfo->pick_types(true, false, false); MatrixXd matData; MatrixXd times; fiff_int_t from; fiff_int_t to; fiff_int_t first = raw.first_samp; fiff_int_t last = raw.last_samp; float dT_sec = 0.1; // time between hpi fits float quantum_sec = 0.2f; // read and write in 200 ms junks fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq); // // create time vector that specifies when to fit // int N = ceil((last-first)/quantum); // RowVectorXf time = RowVectorXf::LinSpaced(N, 0, N-1) * dT_sec; // To fit at specific times outcommend the following block // // Read Quaternion File MatrixXd pos; qInfo() << "Specify the path to your position file (.txt)"; UTILSLIB::IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt"); RowVectorXd time = pos.col(0); MatrixXd position; // Position matrix to save quaternions etc. MatrixXd result; float threshRot = 10; // in degree float threshTrans = 5/1000; // in m // setup informations for HPI fit (VectorView) QVector<int> vFreqs {166,154,161,158}; QVector<double> vGof; FiffDigPointSet fittedPointSet; // Use SSP + SGM + calibration MatrixXd matProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size()); //Do a copy here because we are going to change the activity flags of the SSP's FiffInfo infoTemp = *(pFiffInfo.data()); //Turn on all SSP for(int i = 0; i < infoTemp.projs.size(); ++i) { infoTemp.projs[i].active = true; } //Create the projector for all SSP's on infoTemp.make_projector(matProjectors); //set columns of matrix to zero depending on bad channels indexes for(qint32 j = 0; j < infoTemp.bads.size(); ++j) { matProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero(); } // if debugging files are necessary set bDoDebug = true; QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug"; bool bDoDebug = false; // read and fit for(int i = 0; i < time.size(); i++) { from = first + time(i)*pFiffInfo->sfreq; to = from + quantum; if (to > last) { to = last; qWarning() << "Block size < quantum " << quantum; } // Reading if(!raw.read_raw_segment(matData, times, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; qInfo() << "HPI-Fit..."; timer.start(); HPIFit::fitHPI(matData, matProjectors, pFiffInfo->dev_head_t, vFreqs, vGof, fittedPointSet, pFiffInfo, bDoDebug, sHPIResourceDir); qInfo() << "The HPI-Fit took" << timer.elapsed() << "milliseconds"; qInfo() << "[done]"; writePos(time(i),pFiffInfo,position,vGof); if(compareResults(devHeadTrans,pFiffInfo->dev_head_t,threshRot,threshTrans,result)){ qInfo() << "Big head displacement: dev_head_t has been updated"; } } UTILSLIB::IOUtils::write_eigen_matrix(position, QCoreApplication::applicationDirPath() + "/MNE-sample-data/position.txt"); UTILSLIB::IOUtils::write_eigen_matrix(result, QCoreApplication::applicationDirPath() + "/MNE-sample-data/result.txt"); } <commit_msg>TEMP: change filepaths for evaluation<commit_after>//============================================================================================================= /** * @file main.cpp * @author Ruben Dörfel <[email protected]>; * @version dev * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <vector> #include <math.h> #include <fiff/fiff.h> #include <fiff/fiff_info.h> #include <fiff/fiff_dig_point_set.h> #include <fiff/fiff_cov.h> #include <inverse/hpiFit/hpifit.h> #include <inverse/hpiFit/hpifitdata.h> #include <utils/ioutils.h> #include <utils/generics/applicationlogger.h> #include <fwd/fwd_coil_set.h> //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QFile> #include <QCommandLineParser> #include <QDebug> #include <QGenericMatrix> #include <QQuaternion> #include <QElapsedTimer> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace INVERSELIB; using namespace FIFFLIB; using namespace Eigen; //============================================================================================================= // Member functions //============================================================================================================= //========================================================================================================= /** * Store results from dev_Head_t as quaternions in position matrix. The postion matrix is consisten with the MaxFilter output * * @param[in] time The corresponding time in the measurement for the fit. * @param[in] pFiffInfo The FiffInfo file from the measurement. * @param[in] position The matrix to store the results * @param[in] vGoF The vector that stores the goodness of fit. * * ToDo: get correct GoF; vGof that is passed to fitHPI does not represent the actual GoF * */ void writePos(const float time, QSharedPointer<FiffInfo> pFiffInfo, MatrixXd& position, const QVector<double>& vGoF) { // Write quaternions and time in position matrix. Format is the same like MaxFilter's .pos files. QMatrix3x3 rot; for(int ir = 0; ir < 3; ir++) { for(int ic = 0; ic < 3; ic++) { rot(ir,ic) = pFiffInfo->dev_head_t.trans(ir,ic); } } // double error = std::accumulate(vGoF.begin(), vGoF.end(), .0) / vGoF.size(); QQuaternion quatHPI = QQuaternion::fromRotationMatrix(rot); //qDebug() << "quatHPI.x() " << "quatHPI.y() " << "quatHPI.y() " << "trans x " << "trans y " << "trans z " << std::endl; //qDebug() << quatHPI.x() << quatHPI.y() << quatHPI.z() << info->dev_head_t.trans(0,3) << info->dev_head_t.trans(1,3) << info->dev_head_t.trans(2,3) << std::endl; position.conservativeResize(position.rows()+1, 10); position(position.rows()-1,0) = time; position(position.rows()-1,1) = quatHPI.x(); position(position.rows()-1,2) = quatHPI.y(); position(position.rows()-1,3) = quatHPI.z(); position(position.rows()-1,4) = pFiffInfo->dev_head_t.trans(0,3); position(position.rows()-1,5) = pFiffInfo->dev_head_t.trans(1,3); position(position.rows()-1,6) = pFiffInfo->dev_head_t.trans(2,3); position(position.rows()-1,7) = 0; position(position.rows()-1,8) = 0; position(position.rows()-1,9) = 0; } //========================================================================================================= /** * Compare new head position with current head position and update dev_head_t if big displacement occured * * @param[in] devHeadTrans The device to head transformation matrix to compare to. * @param[in] devHeadTransNew The device to head transformation matrix to be compared. * @param[in] treshRot The threshold for big head rotation in degree * @param[in] treshTrans The threshold for big head movement in m * * @param[out] state The status that shows if devHead is updated or not * */ bool compareResults(FiffCoordTrans& devHeadT, const FiffCoordTrans& devHeadTNew,const float& treshRot,const float& treshTrans, MatrixXd& result) { QMatrix3x3 rot; QMatrix3x3 rotNew; for(int ir = 0; ir < 3; ir++) { for(int ic = 0; ic < 3; ic++) { rot(ir,ic) = devHeadT.trans(ir,ic); rotNew(ir,ic) = devHeadTNew.trans(ir,ic); } } VectorXf trans = devHeadT.trans.col(3); VectorXf transNew = devHeadTNew.trans.col(3); QQuaternion quat = QQuaternion::fromRotationMatrix(rot); QQuaternion quatNew = QQuaternion::fromRotationMatrix(rotNew); // Compare Rotation QQuaternion quatCompare; float angle; QVector3D axis; // get rotation between both transformations by multiplying with the inverted quaternion quatCompare = quat*quatNew.inverted(); quatCompare.getAxisAndAngle(&axis,&angle); qInfo() << "Displacement angle [degree]: " << angle; // Compare translation float move = (trans-transNew).norm(); qInfo() << "Displacement Move [mm]: " << move*1000; // write results for debug purpose - quaternions are quatCompare result.conservativeResize(result.rows()+1, 10); result.conservativeResize(result.rows()+1, 10); result(result.rows()-1,0) = 0; result(result.rows()-1,1) = quatCompare.x(); result(result.rows()-1,2) = quatCompare.y(); result(result.rows()-1,3) = quatCompare.z(); result(result.rows()-1,4) = (trans-transNew).x(); result(result.rows()-1,5) = (trans-transNew).y(); result(result.rows()-1,6) = (trans-transNew).z(); result(result.rows()-1,7) = angle; result(result.rows()-1,8) = move; result(result.rows()-1,9) = 0; return false; } //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(UTILSLIB::ApplicationLogger::customLogWriter); QElapsedTimer timer; QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("hpiFit Example"); parser.addHelpOption(); qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin."; QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/raw/sim_move_y_chpi_raw.fif"); parser.addOption(inputOption); parser.process(a); // Init data loading and writing QFile t_fileIn(parser.value(inputOption)); FiffRawData raw(t_fileIn); QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info)); FiffCoordTrans devHeadTrans = pFiffInfo->dev_head_t; // Set up the reading parameters RowVectorXi picks = pFiffInfo->pick_types(true, false, false); MatrixXd matData; MatrixXd times; fiff_int_t from; fiff_int_t to; fiff_int_t first = raw.first_samp; fiff_int_t last = raw.last_samp; float dT_sec = 0.1; // time between hpi fits float quantum_sec = 0.2f; // read and write in 200 ms junks fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq); // // create time vector that specifies when to fit // int N = ceil((last-first)/quantum); // RowVectorXf time = RowVectorXf::LinSpaced(N, 0, N-1) * dT_sec; // To fit at specific times outcommend the following block // // Read Quaternion File MatrixXd pos; qInfo() << "Specify the path to your position file (.txt)"; UTILSLIB::IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/pos/sim_move_y_chpi_pos.txt"); RowVectorXd time = pos.col(0); MatrixXd position; // Position matrix to save quaternions etc. MatrixXd result; float threshRot = 10; // in degree float threshTrans = 5/1000; // in m // setup informations for HPI fit (VectorView) QVector<int> vFreqs {166,154,161,158}; QVector<double> vGof; FiffDigPointSet fittedPointSet; // Use SSP + SGM + calibration MatrixXd matProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size()); //Do a copy here because we are going to change the activity flags of the SSP's FiffInfo infoTemp = *(pFiffInfo.data()); //Turn on all SSP for(int i = 0; i < infoTemp.projs.size(); ++i) { infoTemp.projs[i].active = true; } //Create the projector for all SSP's on infoTemp.make_projector(matProjectors); //set columns of matrix to zero depending on bad channels indexes for(qint32 j = 0; j < infoTemp.bads.size(); ++j) { matProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero(); } // if debugging files are necessary set bDoDebug = true; QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug"; bool bDoDebug = false; // read and fit for(int i = 0; i < time.size(); i++) { from = first + time(i)*pFiffInfo->sfreq; to = from + quantum; if (to > last) { to = last; qWarning() << "Block size < quantum " << quantum; } // Reading if(!raw.read_raw_segment(matData, times, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; qInfo() << "HPI-Fit..."; timer.start(); HPIFit::fitHPI(matData, matProjectors, pFiffInfo->dev_head_t, vFreqs, vGof, fittedPointSet, pFiffInfo, bDoDebug, sHPIResourceDir); qInfo() << "The HPI-Fit took" << timer.elapsed() << "milliseconds"; qInfo() << "[done]"; writePos(time(i),pFiffInfo,position,vGof); if(compareResults(devHeadTrans,pFiffInfo->dev_head_t,threshRot,threshTrans,result)){ qInfo() << "Big head displacement: dev_head_t has been updated"; } } UTILSLIB::IOUtils::write_eigen_matrix(position, QCoreApplication::applicationDirPath() + "/MNE-sample-data/position.txt"); UTILSLIB::IOUtils::write_eigen_matrix(result, QCoreApplication::applicationDirPath() + "/MNE-sample-data/result.txt"); } <|endoftext|>
<commit_before>// Tests of Linux-specific functionality #ifdef __linux__ #include <sys/types.h> #include <sys/timerfd.h> #include <sys/signalfd.h> #include <poll.h> #include <signal.h> #include "capsicum.h" #include "syscalls.h" #include "capsicum-test.h" TEST(Linux, TimerFD) { int fd = timerfd_create(CLOCK_MONOTONIC, 0); int cap_fd_ro = cap_new(fd, CAP_READ); int cap_fd_wo = cap_new(fd, CAP_WRITE); int cap_fd_rw = cap_new(fd, CAP_READ|CAP_WRITE); int cap_fd_all = cap_new(fd, CAP_READ|CAP_WRITE|CAP_POLL_EVENT); struct itimerspec old_ispec; struct itimerspec ispec; ispec.it_interval.tv_sec = 0; ispec.it_interval.tv_nsec = 0; ispec.it_value.tv_sec = 0; ispec.it_value.tv_nsec = 100000000; // 100ms EXPECT_NOTCAPABLE(timerfd_settime(cap_fd_ro, 0, &ispec, NULL)); EXPECT_NOTCAPABLE(timerfd_settime(cap_fd_wo, 0, &ispec, &old_ispec)); EXPECT_OK(timerfd_settime(cap_fd_wo, 0, &ispec, NULL)); EXPECT_OK(timerfd_settime(cap_fd_rw, 0, &ispec, NULL)); EXPECT_OK(timerfd_settime(cap_fd_all, 0, &ispec, NULL)); EXPECT_NOTCAPABLE(timerfd_gettime(cap_fd_wo, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_ro, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_rw, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_all, &old_ispec)); // To be able to poll() for the timer pop, still need CAP_POLL_EVENT. struct pollfd poll_fd; for (int ii = 0; ii < 3; ii++) { poll_fd.revents = 0; poll_fd.events = POLLIN; switch (ii) { case 0: poll_fd.fd = cap_fd_ro; break; case 1: poll_fd.fd = cap_fd_wo; break; case 2: poll_fd.fd = cap_fd_rw; break; } // Poll immediately returns with POLLNVAL EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_EQ(0, (poll_fd.revents & POLLIN)); EXPECT_NE(0, (poll_fd.revents & POLLNVAL)); } poll_fd.fd = cap_fd_all; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_NE(0, (poll_fd.revents & POLLIN)); EXPECT_EQ(0, (poll_fd.revents & POLLNVAL)); EXPECT_OK(timerfd_gettime(cap_fd_all, &old_ispec)); EXPECT_EQ(0, old_ispec.it_value.tv_sec); EXPECT_EQ(0, old_ispec.it_value.tv_nsec); EXPECT_EQ(0, old_ispec.it_interval.tv_sec); EXPECT_EQ(0, old_ispec.it_interval.tv_nsec); close(cap_fd_all); close(cap_fd_rw); close(cap_fd_wo); close(cap_fd_ro); close(fd); } FORK_TEST(Linux, SignalFD) { pid_t me = getpid(); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGUSR1); // Block signals before registering against a new signal FD. EXPECT_OK(sigprocmask(SIG_BLOCK, &mask, NULL)); int fd = signalfd(-1, &mask, 0); EXPECT_OK(fd); // Various capability variants. int cap_fd_none = cap_new(fd, CAP_WRITE|CAP_SEEK); int cap_fd_read = cap_new(fd, CAP_READ|CAP_SEEK); int cap_fd_sig = cap_new(fd, CAP_FSIGNAL); int cap_fd_sig_read = cap_new(fd, CAP_FSIGNAL|CAP_READ|CAP_SEEK); int cap_fd_all = cap_new(fd, CAP_FSIGNAL|CAP_READ|CAP_SEEK|CAP_POLL_EVENT); struct signalfd_siginfo fdsi; // Need CAP_READ to read the signal information kill(me, SIGUSR1); EXPECT_NOTCAPABLE(read(cap_fd_none, &fdsi, sizeof(struct signalfd_siginfo))); EXPECT_NOTCAPABLE(read(cap_fd_sig, &fdsi, sizeof(struct signalfd_siginfo))); int len = read(cap_fd_read, &fdsi, sizeof(struct signalfd_siginfo)); EXPECT_OK(len); EXPECT_EQ(sizeof(struct signalfd_siginfo), (size_t)len); EXPECT_EQ(SIGUSR1, (int)fdsi.ssi_signo); // Need CAP_FSIGNAL to modify the signal mask. sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); EXPECT_OK(sigprocmask(SIG_BLOCK, &mask, NULL)); EXPECT_NOTCAPABLE(signalfd(cap_fd_none, &mask, 0)); EXPECT_NOTCAPABLE(signalfd(cap_fd_read, &mask, 0)); EXPECT_EQ(cap_fd_sig, signalfd(cap_fd_sig, &mask, 0)); // Need CAP_POLL_EVENT to get notification of a signal in poll(2). kill(me, SIGUSR2); struct pollfd poll_fd; poll_fd.revents = 0; poll_fd.events = POLLIN; poll_fd.fd = cap_fd_sig_read; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_EQ(0, (poll_fd.revents & POLLIN)); EXPECT_NE(0, (poll_fd.revents & POLLNVAL)); poll_fd.fd = cap_fd_all; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_NE(0, (poll_fd.revents & POLLIN)); EXPECT_EQ(0, (poll_fd.revents & POLLNVAL)); } #else void noop() {} #endif <commit_msg>Add (Linux-specific) simple eventfd test<commit_after>// Tests of Linux-specific functionality #ifdef __linux__ #include <sys/types.h> #include <sys/timerfd.h> #include <sys/signalfd.h> #include <sys/eventfd.h> #include <poll.h> #include <signal.h> #include "capsicum.h" #include "syscalls.h" #include "capsicum-test.h" TEST(Linux, TimerFD) { int fd = timerfd_create(CLOCK_MONOTONIC, 0); int cap_fd_ro = cap_new(fd, CAP_READ); int cap_fd_wo = cap_new(fd, CAP_WRITE); int cap_fd_rw = cap_new(fd, CAP_READ|CAP_WRITE); int cap_fd_all = cap_new(fd, CAP_READ|CAP_WRITE|CAP_POLL_EVENT); struct itimerspec old_ispec; struct itimerspec ispec; ispec.it_interval.tv_sec = 0; ispec.it_interval.tv_nsec = 0; ispec.it_value.tv_sec = 0; ispec.it_value.tv_nsec = 100000000; // 100ms EXPECT_NOTCAPABLE(timerfd_settime(cap_fd_ro, 0, &ispec, NULL)); EXPECT_NOTCAPABLE(timerfd_settime(cap_fd_wo, 0, &ispec, &old_ispec)); EXPECT_OK(timerfd_settime(cap_fd_wo, 0, &ispec, NULL)); EXPECT_OK(timerfd_settime(cap_fd_rw, 0, &ispec, NULL)); EXPECT_OK(timerfd_settime(cap_fd_all, 0, &ispec, NULL)); EXPECT_NOTCAPABLE(timerfd_gettime(cap_fd_wo, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_ro, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_rw, &old_ispec)); EXPECT_OK(timerfd_gettime(cap_fd_all, &old_ispec)); // To be able to poll() for the timer pop, still need CAP_POLL_EVENT. struct pollfd poll_fd; for (int ii = 0; ii < 3; ii++) { poll_fd.revents = 0; poll_fd.events = POLLIN; switch (ii) { case 0: poll_fd.fd = cap_fd_ro; break; case 1: poll_fd.fd = cap_fd_wo; break; case 2: poll_fd.fd = cap_fd_rw; break; } // Poll immediately returns with POLLNVAL EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_EQ(0, (poll_fd.revents & POLLIN)); EXPECT_NE(0, (poll_fd.revents & POLLNVAL)); } poll_fd.fd = cap_fd_all; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_NE(0, (poll_fd.revents & POLLIN)); EXPECT_EQ(0, (poll_fd.revents & POLLNVAL)); EXPECT_OK(timerfd_gettime(cap_fd_all, &old_ispec)); EXPECT_EQ(0, old_ispec.it_value.tv_sec); EXPECT_EQ(0, old_ispec.it_value.tv_nsec); EXPECT_EQ(0, old_ispec.it_interval.tv_sec); EXPECT_EQ(0, old_ispec.it_interval.tv_nsec); close(cap_fd_all); close(cap_fd_rw); close(cap_fd_wo); close(cap_fd_ro); close(fd); } FORK_TEST(Linux, SignalFD) { pid_t me = getpid(); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGUSR1); // Block signals before registering against a new signal FD. EXPECT_OK(sigprocmask(SIG_BLOCK, &mask, NULL)); int fd = signalfd(-1, &mask, 0); EXPECT_OK(fd); // Various capability variants. int cap_fd_none = cap_new(fd, CAP_WRITE|CAP_SEEK); int cap_fd_read = cap_new(fd, CAP_READ|CAP_SEEK); int cap_fd_sig = cap_new(fd, CAP_FSIGNAL); int cap_fd_sig_read = cap_new(fd, CAP_FSIGNAL|CAP_READ|CAP_SEEK); int cap_fd_all = cap_new(fd, CAP_FSIGNAL|CAP_READ|CAP_SEEK|CAP_POLL_EVENT); struct signalfd_siginfo fdsi; // Need CAP_READ to read the signal information kill(me, SIGUSR1); EXPECT_NOTCAPABLE(read(cap_fd_none, &fdsi, sizeof(struct signalfd_siginfo))); EXPECT_NOTCAPABLE(read(cap_fd_sig, &fdsi, sizeof(struct signalfd_siginfo))); int len = read(cap_fd_read, &fdsi, sizeof(struct signalfd_siginfo)); EXPECT_OK(len); EXPECT_EQ(sizeof(struct signalfd_siginfo), (size_t)len); EXPECT_EQ(SIGUSR1, (int)fdsi.ssi_signo); // Need CAP_FSIGNAL to modify the signal mask. sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); EXPECT_OK(sigprocmask(SIG_BLOCK, &mask, NULL)); EXPECT_NOTCAPABLE(signalfd(cap_fd_none, &mask, 0)); EXPECT_NOTCAPABLE(signalfd(cap_fd_read, &mask, 0)); EXPECT_EQ(cap_fd_sig, signalfd(cap_fd_sig, &mask, 0)); // Need CAP_POLL_EVENT to get notification of a signal in poll(2). kill(me, SIGUSR2); struct pollfd poll_fd; poll_fd.revents = 0; poll_fd.events = POLLIN; poll_fd.fd = cap_fd_sig_read; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_EQ(0, (poll_fd.revents & POLLIN)); EXPECT_NE(0, (poll_fd.revents & POLLNVAL)); poll_fd.fd = cap_fd_all; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_NE(0, (poll_fd.revents & POLLIN)); EXPECT_EQ(0, (poll_fd.revents & POLLNVAL)); } TEST(Linux, EventFD) { int fd = eventfd(0, 0); EXPECT_OK(fd); int cap_ro = cap_new(fd, CAP_READ|CAP_SEEK); int cap_wo = cap_new(fd, CAP_WRITE|CAP_SEEK); int cap_rw = cap_new(fd, CAP_READ|CAP_WRITE|CAP_SEEK); int cap_all = cap_new(fd, CAP_READ|CAP_WRITE|CAP_SEEK|CAP_POLL_EVENT); pid_t child = fork(); if (child == 0) { // Child: write counter to eventfd uint64_t u = 42; EXPECT_NOTCAPABLE(write(cap_ro, &u, sizeof(u))); EXPECT_OK(write(cap_wo, &u, sizeof(u))); exit(HasFailure()); } sleep(1); // Allow child to write struct pollfd poll_fd; poll_fd.revents = 0; poll_fd.events = POLLIN; poll_fd.fd = cap_rw; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_EQ(0, (poll_fd.revents & POLLIN)); EXPECT_NE(0, (poll_fd.revents & POLLNVAL)); poll_fd.fd = cap_all; EXPECT_OK(poll(&poll_fd, 1, 400)); EXPECT_NE(0, (poll_fd.revents & POLLIN)); EXPECT_EQ(0, (poll_fd.revents & POLLNVAL)); uint64_t u; EXPECT_NOTCAPABLE(read(cap_wo, &u, sizeof(u))); EXPECT_OK(read(cap_ro, &u, sizeof(u))); EXPECT_EQ(42, (int)u); // Wait for the child. int status; EXPECT_EQ(child, waitpid(child, &status, 0)); int rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1; EXPECT_EQ(0, rc); close(cap_all); close(cap_rw); close(cap_wo); close(cap_ro); close(fd); } #else void noop() {} #endif <|endoftext|>
<commit_before>// Copyright (c) 2017 Jackal Engine, MIT License. #pragma once #include "Core/Platform/JTypes.hpp" #include "Core/Platform/Platform.hpp" #include "Core/Structure/JString.hpp" #include <string> #include <type_traits> // TODO(): Figure out a better way than to include unecessary headers // just for windows. #if JACKAL_PLATFORM == JACKAL_WINDOWS #include <locale> #include <codecvt> #endif namespace jackal { class JStringUtils { public: // TODO(): Remove heap allocation from these functions! static void UTF8To16(const uint8 *input, uint16 *output); static void UTF16To8(const uint16 *input, uint8 *output); static void UTF16To32(const uint16 *input, uint32 *output); static void UTF32To16(const uint32 *input, uint16 *output); // Get the string size of the tchar. static size_t GetStringSize(const tchar *src); static tchar *AllocateStringSize(size_t size); static void StringCopy(tchar *dest, const tchar *src); template<typename Type> static JString ToString(Type n) { //static_assert<std::is_same<decltype(Type), tchar>::value, "No need to convert tchar"); JString str = TO_JSTRING(n); return str; } #if JACKAL_PLATFORM == JACKAL_WINDOWS template<> static JString ToString(char *n) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::wstring wide = converter.from_bytes(n); return wide; } #endif }; } // jackal <commit_msg>Another fix for linux char to JString conversion<commit_after>// Copyright (c) 2017 Jackal Engine, MIT License. #pragma once #include "Core/Platform/JTypes.hpp" #include "Core/Platform/Platform.hpp" #include "Core/Structure/JString.hpp" #include <string> #include <type_traits> // TODO(): Figure out a better way than to include unecessary headers // just for windows. #if JACKAL_PLATFORM == JACKAL_WINDOWS #include <locale> #include <codecvt> #endif namespace jackal { class JStringUtils { public: // TODO(): Remove heap allocation from these functions! static void UTF8To16(const uint8 *input, uint16 *output); static void UTF16To8(const uint16 *input, uint8 *output); static void UTF16To32(const uint16 *input, uint32 *output); static void UTF32To16(const uint32 *input, uint16 *output); // Get the string size of the tchar. static size_t GetStringSize(const tchar *src); static tchar *AllocateStringSize(size_t size); static void StringCopy(tchar *dest, const tchar *src); template<typename Type> static JString ToString(Type n) { //static_assert<std::is_same<decltype(Type), tchar>::value, "No need to convert tchar"); JString str = TO_JSTRING(n); return str; } #if JACKAL_PLATFORM == JACKAL_WINDOWS template<> static JString ToString(char *n) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::wstring wide = converter.from_bytes(n); return wide; } #else template<> static JString ToString(char* n) { return std::string(n); } #endif }; } // jackal <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of the Qt Build Suite ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used 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. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. ** Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** **************************************************************************/ #include <QtCore/QCoreApplication> #include <QtCore/QProcess> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtCore/QStringList> #include <QtCore/QDebug> #include <QtCore/QTextStream> #include <QtCore/QSettings> #include <tools/platform.h> using namespace qbs; static QString searchPath(const QString &path, const QString &me) { //TODO: use native seperator foreach (const QString &ppath, path.split(":")) { if (QFileInfo(ppath + "/" + me).exists()) { return QDir::cleanPath(ppath + "/" + me); } } return QString(); } static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForStarted(); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } static int specific_probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms, QString cc, bool printComfortingMessage = false) { QTextStream qstdout(stdout); QString toolchainType; if(cc.contains("clang")) toolchainType = "clang"; else if (cc.contains("gcc")) toolchainType = "gcc"; QString path = QString::fromLocal8Bit(qgetenv("PATH")); QString cxx = QString::fromLocal8Bit(qgetenv("CXX")); QString ld = QString::fromLocal8Bit(qgetenv("LD")); QString cflags = QString::fromLocal8Bit(qgetenv("CFLAGS")); QString cxxflags = QString::fromLocal8Bit(qgetenv("CXXFLAGS")); QString ldflags = QString::fromLocal8Bit(qgetenv("LDFLAGS")); QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE")); QString arch = QString::fromLocal8Bit(qgetenv("ARCH")); QString pathToGcc; QString architecture; QString endianness; QString name; QString sysroot; QString uname = qsystem("uname", QStringList() << "-m").simplified(); if (arch.isEmpty()) arch = uname; #ifdef Q_OS_MAC // HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS. if (arch == "i386") arch = "i686"; #endif if (ld.isEmpty()) ld = "ld"; if (cxx.isEmpty()) { if (toolchainType == "gcc") cxx = "g++"; else if(toolchainType == "clang") cxx = "clang++"; } if(!cross.isEmpty() && !cc.startsWith("/")) { pathToGcc = searchPath(path, cross + cc); if (QFileInfo(pathToGcc).exists()) { if (!cc.contains(cross)) cc.prepend(cross); if (!cxx.contains(cross)) cxx.prepend(cross); if (!ld.contains(cross)) ld.prepend(cross); } } if (cc.startsWith("/")) pathToGcc = cc; else pathToGcc = searchPath(path, cc); if (!QFileInfo(pathToGcc).exists()) { fprintf(stderr, "Cannot find %s.", qPrintable(cc)); if (printComfortingMessage) fprintf(stderr, " But that's not a problem. I've already found other platforms.\n"); else fprintf(stderr, "\n"); return 1; } Platform::Ptr s; foreach (Platform::Ptr p, platforms.values()) { QString path = p->settings.value(Platform::internalKey() + "/completeccpath").toString(); if (path == pathToGcc) { name = p->name; s = p; name = s->name; break; } } QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified(); QStringList compilerTripletl = compilerTriplet.split('-'); if (compilerTripletl.count() < 2 || !(compilerTripletl.at(0).contains(QRegExp(".86")) || compilerTripletl.at(0).contains("arm") ) ) { qDebug("detected %s , but i don't understand it's architecture: %s", qPrintable(pathToGcc), qPrintable(compilerTriplet)); return 12; } architecture = compilerTripletl.at(0); if (architecture.contains("arm")) { endianness = "big-endian"; } else { endianness = "little-endian"; } QStringList pathToGccL = pathToGcc.split('/'); QString compilerName = pathToGccL.takeLast().replace(cc, cxx); if (cflags.contains("--sysroot")) { QStringList flagl = cflags.split(' '); bool nextitis = false; foreach (const QString &flag, flagl) { if (nextitis) { sysroot = flag; break; } if (flag == "--sysroot") { nextitis = true; } } } qstdout << "==> " << (s?"reconfiguring " + name :"detected") << " " << pathToGcc << "\n" << " triplet: " << compilerTriplet << "\n" << " arch: " << architecture << "\n" << " bin: " << pathToGccL.join("/") << "\n" << " cc: " << cc << "\n" ; if (!cxx.isEmpty()) qstdout << " cxx: " << cxx << "\n"; if (!ld.isEmpty()) qstdout << " ld: " << ld << "\n"; if (!sysroot.isEmpty()) qstdout << " sysroot: " << sysroot << "\n"; if (!cflags.isEmpty()) qstdout << " CFLAGS: " << cflags << "\n"; if (!cxxflags.isEmpty()) qstdout << " CXXFLAGS: " << cxxflags << "\n"; if (!ldflags.isEmpty()) qstdout << " CXXFLAGS: " << ldflags << "\n"; qstdout << flush; if (!s) { if (name.isEmpty()) name = toolchainType; s = Platform::Ptr(new Platform(name, settingsPath + "/" + name)); } // fixme should be cpp.toolchain // also there is no toolchain:clang s->settings.setValue("toolchain", "gcc"); s->settings.setValue(Platform::internalKey() + "/completeccpath", pathToGcc); s->settings.setValue(Platform::internalKey() + "/target-triplet", compilerTriplet); s->settings.setValue("architecture", architecture); s->settings.setValue("endianness", endianness); #if defined(Q_OS_MAC) s->settings.setValue("targetOS", "mac"); #elif defined(Q_OS_LINUX) s->settings.setValue("targetOS", "linux"); #else s->settings.setValue("targetOS", "unknown"); //fixme #endif if (compilerName.contains('-')) { QStringList nl = compilerName.split('-'); s->settings.setValue("cpp/compilerName", nl.takeLast()); s->settings.setValue("cpp/toolchainPrefix", nl.join("-") + '-'); } else { s->settings.setValue("cpp/compilerName", compilerName); } s->settings.setValue("cpp/toolchainInstallPath", pathToGccL.join("/")); if (!cross.isEmpty()) s->settings.setValue("environment/CROSS_COMPILE", cross); if (!cflags.isEmpty()) s->settings.setValue("environment/CFLAGS", cflags); if (!cxxflags.isEmpty()) s->settings.setValue("environment/CXXFLAGS", cxxflags); if (!ldflags.isEmpty()) s->settings.setValue("environment/LDFLAGS", ldflags); platforms.insert(s->name, s); return 0; } #ifdef Q_OS_WIN static void msvcProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { QTextStream qstdout(stdout); QString vcInstallDir = QDir::fromNativeSeparators(QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"))); if (vcInstallDir.endsWith('/')) vcInstallDir.chop(1); if (vcInstallDir.isEmpty()) return; QString winSDKPath = QDir::fromNativeSeparators(QString::fromLocal8Bit(qgetenv("WindowsSdkDir"))); if (winSDKPath.endsWith('/')) winSDKPath.chop(1); QString clOutput = qsystem(vcInstallDir + "/bin/cl.exe"); if (clOutput.isEmpty()) return; QRegExp rex("C/C\\+\\+ Optimizing Compiler Version ((\\d|\\.)+) for ((x|\\d)+)"); int idx = rex.indexIn(clOutput); if (idx < 0) return; QStringList clVersion = rex.cap(1).split("."); if (clVersion.isEmpty()) return; QString clArch = rex.cap(3); QString msvcVersion = "msvc"; switch (clVersion.first().toInt()) { case 14: msvcVersion += "2005"; break; case 15: msvcVersion += "2008"; break; case 16: msvcVersion += "2010"; break; default: return; } QString vsInstallDir = vcInstallDir; idx = vsInstallDir.lastIndexOf("/"); if (idx < 0) return; vsInstallDir.truncate(idx); Platform::Ptr platform = platforms.value(msvcVersion); if (!platform) { platform = Platform::Ptr(new Platform(msvcVersion, settingsPath + "/" + msvcVersion)); platforms.insert(platform->name, platform); } platform->settings.setValue("targetOS", "windows"); platform->settings.setValue("cpp/toolchainInstallPath", vsInstallDir); platform->settings.setValue("toolchain", "msvc"); platform->settings.setValue("cpp/windowsSDKPath", winSDKPath); qstdout << "Detected platform " << msvcVersion << " for " << clArch << ".\n"; qstdout << "When building projects, the architecture can be chosen by passing\narchitecture:x86 or architecture:x86_64 to qbs.\n"; } static void mingwProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { QString mingwPath; QString mingwBinPath; QString gccPath; QByteArray envPath = qgetenv("PATH"); foreach (const QByteArray &dir, envPath.split(';')) { QFileInfo fi(dir + "/gcc.exe"); if (fi.exists()) { mingwPath = QFileInfo(dir + "/..").canonicalFilePath(); gccPath = fi.absoluteFilePath(); mingwBinPath = fi.absolutePath(); break; } } if (gccPath.isEmpty()) return; QProcess process; process.start(gccPath, QStringList() << "-dumpmachine"); if (!process.waitForStarted()) { fprintf(stderr, "Could not start \"gcc -dumpmachine\".\n"); return; } process.waitForFinished(-1); QByteArray gccMachineName = process.readAll().trimmed(); if (gccMachineName != "mingw32" && gccMachineName != "mingw64") { fprintf(stderr, "Detected gcc platform '%s' is not supported.\n", gccMachineName.data()); return; } Platform::Ptr platform = platforms.value(gccMachineName); printf("Platform '%s' detected in '%s'.", gccMachineName.data(), qPrintable(QDir::toNativeSeparators(mingwPath))); if (!platform) { platform = Platform::Ptr(new Platform(gccMachineName, settingsPath + "/" + gccMachineName)); platforms.insert(platform->name, platform); } platform->settings.setValue("targetOS", "windows"); platform->settings.setValue("cpp/toolchainInstallPath", QDir::toNativeSeparators(mingwBinPath)); platform->settings.setValue("toolchain", "mingw"); } #endif int probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { #ifdef Q_OS_WIN msvcProbe(settingsPath, platforms); mingwProbe(settingsPath, platforms); #else QString cc = QString::fromLocal8Bit(qgetenv("CC")); if (cc.isEmpty()) { bool somethingFound = false; if (specific_probe(settingsPath, platforms, "gcc") == 0) somethingFound = true; specific_probe(settingsPath, platforms, "clang", somethingFound); } else { specific_probe(settingsPath, platforms, cc); } #endif if (platforms.isEmpty()) fprintf(stderr, "Could not detect any platforms.\n"); return 0; } <commit_msg>fix detection of localized MSVC versions<commit_after>/************************************************************************** ** ** This file is part of the Qt Build Suite ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used 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. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. ** Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** **************************************************************************/ #include <QtCore/QCoreApplication> #include <QtCore/QProcess> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtCore/QStringList> #include <QtCore/QDebug> #include <QtCore/QTextStream> #include <QtCore/QSettings> #include <tools/platform.h> using namespace qbs; static QString searchPath(const QString &path, const QString &me) { //TODO: use native seperator foreach (const QString &ppath, path.split(":")) { if (QFileInfo(ppath + "/" + me).exists()) { return QDir::cleanPath(ppath + "/" + me); } } return QString(); } static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForStarted(); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } static int specific_probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms, QString cc, bool printComfortingMessage = false) { QTextStream qstdout(stdout); QString toolchainType; if(cc.contains("clang")) toolchainType = "clang"; else if (cc.contains("gcc")) toolchainType = "gcc"; QString path = QString::fromLocal8Bit(qgetenv("PATH")); QString cxx = QString::fromLocal8Bit(qgetenv("CXX")); QString ld = QString::fromLocal8Bit(qgetenv("LD")); QString cflags = QString::fromLocal8Bit(qgetenv("CFLAGS")); QString cxxflags = QString::fromLocal8Bit(qgetenv("CXXFLAGS")); QString ldflags = QString::fromLocal8Bit(qgetenv("LDFLAGS")); QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE")); QString arch = QString::fromLocal8Bit(qgetenv("ARCH")); QString pathToGcc; QString architecture; QString endianness; QString name; QString sysroot; QString uname = qsystem("uname", QStringList() << "-m").simplified(); if (arch.isEmpty()) arch = uname; #ifdef Q_OS_MAC // HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS. if (arch == "i386") arch = "i686"; #endif if (ld.isEmpty()) ld = "ld"; if (cxx.isEmpty()) { if (toolchainType == "gcc") cxx = "g++"; else if(toolchainType == "clang") cxx = "clang++"; } if(!cross.isEmpty() && !cc.startsWith("/")) { pathToGcc = searchPath(path, cross + cc); if (QFileInfo(pathToGcc).exists()) { if (!cc.contains(cross)) cc.prepend(cross); if (!cxx.contains(cross)) cxx.prepend(cross); if (!ld.contains(cross)) ld.prepend(cross); } } if (cc.startsWith("/")) pathToGcc = cc; else pathToGcc = searchPath(path, cc); if (!QFileInfo(pathToGcc).exists()) { fprintf(stderr, "Cannot find %s.", qPrintable(cc)); if (printComfortingMessage) fprintf(stderr, " But that's not a problem. I've already found other platforms.\n"); else fprintf(stderr, "\n"); return 1; } Platform::Ptr s; foreach (Platform::Ptr p, platforms.values()) { QString path = p->settings.value(Platform::internalKey() + "/completeccpath").toString(); if (path == pathToGcc) { name = p->name; s = p; name = s->name; break; } } QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified(); QStringList compilerTripletl = compilerTriplet.split('-'); if (compilerTripletl.count() < 2 || !(compilerTripletl.at(0).contains(QRegExp(".86")) || compilerTripletl.at(0).contains("arm") ) ) { qDebug("detected %s , but i don't understand it's architecture: %s", qPrintable(pathToGcc), qPrintable(compilerTriplet)); return 12; } architecture = compilerTripletl.at(0); if (architecture.contains("arm")) { endianness = "big-endian"; } else { endianness = "little-endian"; } QStringList pathToGccL = pathToGcc.split('/'); QString compilerName = pathToGccL.takeLast().replace(cc, cxx); if (cflags.contains("--sysroot")) { QStringList flagl = cflags.split(' '); bool nextitis = false; foreach (const QString &flag, flagl) { if (nextitis) { sysroot = flag; break; } if (flag == "--sysroot") { nextitis = true; } } } qstdout << "==> " << (s?"reconfiguring " + name :"detected") << " " << pathToGcc << "\n" << " triplet: " << compilerTriplet << "\n" << " arch: " << architecture << "\n" << " bin: " << pathToGccL.join("/") << "\n" << " cc: " << cc << "\n" ; if (!cxx.isEmpty()) qstdout << " cxx: " << cxx << "\n"; if (!ld.isEmpty()) qstdout << " ld: " << ld << "\n"; if (!sysroot.isEmpty()) qstdout << " sysroot: " << sysroot << "\n"; if (!cflags.isEmpty()) qstdout << " CFLAGS: " << cflags << "\n"; if (!cxxflags.isEmpty()) qstdout << " CXXFLAGS: " << cxxflags << "\n"; if (!ldflags.isEmpty()) qstdout << " CXXFLAGS: " << ldflags << "\n"; qstdout << flush; if (!s) { if (name.isEmpty()) name = toolchainType; s = Platform::Ptr(new Platform(name, settingsPath + "/" + name)); } // fixme should be cpp.toolchain // also there is no toolchain:clang s->settings.setValue("toolchain", "gcc"); s->settings.setValue(Platform::internalKey() + "/completeccpath", pathToGcc); s->settings.setValue(Platform::internalKey() + "/target-triplet", compilerTriplet); s->settings.setValue("architecture", architecture); s->settings.setValue("endianness", endianness); #if defined(Q_OS_MAC) s->settings.setValue("targetOS", "mac"); #elif defined(Q_OS_LINUX) s->settings.setValue("targetOS", "linux"); #else s->settings.setValue("targetOS", "unknown"); //fixme #endif if (compilerName.contains('-')) { QStringList nl = compilerName.split('-'); s->settings.setValue("cpp/compilerName", nl.takeLast()); s->settings.setValue("cpp/toolchainPrefix", nl.join("-") + '-'); } else { s->settings.setValue("cpp/compilerName", compilerName); } s->settings.setValue("cpp/toolchainInstallPath", pathToGccL.join("/")); if (!cross.isEmpty()) s->settings.setValue("environment/CROSS_COMPILE", cross); if (!cflags.isEmpty()) s->settings.setValue("environment/CFLAGS", cflags); if (!cxxflags.isEmpty()) s->settings.setValue("environment/CXXFLAGS", cxxflags); if (!ldflags.isEmpty()) s->settings.setValue("environment/LDFLAGS", ldflags); platforms.insert(s->name, s); return 0; } #ifdef Q_OS_WIN static void msvcProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { QTextStream qstdout(stdout); QString vcInstallDir = QDir::fromNativeSeparators(QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"))); if (vcInstallDir.endsWith('/')) vcInstallDir.chop(1); if (vcInstallDir.isEmpty()) return; QString winSDKPath = QDir::fromNativeSeparators(QString::fromLocal8Bit(qgetenv("WindowsSdkDir"))); if (winSDKPath.endsWith('/')) winSDKPath.chop(1); QString clOutput = qsystem(vcInstallDir + "/bin/cl.exe"); if (clOutput.isEmpty()) return; QRegExp rex("C/C\\+\\+ .+ Version ((?:\\d|\\.)+) \\w+ ((?:x|\\d)+)"); int idx = rex.indexIn(clOutput); if (idx < 0) return; QStringList clVersion = rex.cap(1).split("."); if (clVersion.isEmpty()) return; QString clArch = rex.cap(2); QString msvcVersion = "msvc"; switch (clVersion.first().toInt()) { case 14: msvcVersion += "2005"; break; case 15: msvcVersion += "2008"; break; case 16: msvcVersion += "2010"; break; default: return; } QString vsInstallDir = vcInstallDir; idx = vsInstallDir.lastIndexOf("/"); if (idx < 0) return; vsInstallDir.truncate(idx); Platform::Ptr platform = platforms.value(msvcVersion); if (!platform) { platform = Platform::Ptr(new Platform(msvcVersion, settingsPath + "/" + msvcVersion)); platforms.insert(platform->name, platform); } platform->settings.setValue("targetOS", "windows"); platform->settings.setValue("cpp/toolchainInstallPath", vsInstallDir); platform->settings.setValue("toolchain", "msvc"); platform->settings.setValue("cpp/windowsSDKPath", winSDKPath); qstdout << "Detected platform " << msvcVersion << " for " << clArch << ".\n"; qstdout << "When building projects, the architecture can be chosen by passing\narchitecture:x86 or architecture:x86_64 to qbs.\n"; } static void mingwProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { QString mingwPath; QString mingwBinPath; QString gccPath; QByteArray envPath = qgetenv("PATH"); foreach (const QByteArray &dir, envPath.split(';')) { QFileInfo fi(dir + "/gcc.exe"); if (fi.exists()) { mingwPath = QFileInfo(dir + "/..").canonicalFilePath(); gccPath = fi.absoluteFilePath(); mingwBinPath = fi.absolutePath(); break; } } if (gccPath.isEmpty()) return; QProcess process; process.start(gccPath, QStringList() << "-dumpmachine"); if (!process.waitForStarted()) { fprintf(stderr, "Could not start \"gcc -dumpmachine\".\n"); return; } process.waitForFinished(-1); QByteArray gccMachineName = process.readAll().trimmed(); if (gccMachineName != "mingw32" && gccMachineName != "mingw64") { fprintf(stderr, "Detected gcc platform '%s' is not supported.\n", gccMachineName.data()); return; } Platform::Ptr platform = platforms.value(gccMachineName); printf("Platform '%s' detected in '%s'.", gccMachineName.data(), qPrintable(QDir::toNativeSeparators(mingwPath))); if (!platform) { platform = Platform::Ptr(new Platform(gccMachineName, settingsPath + "/" + gccMachineName)); platforms.insert(platform->name, platform); } platform->settings.setValue("targetOS", "windows"); platform->settings.setValue("cpp/toolchainInstallPath", QDir::toNativeSeparators(mingwBinPath)); platform->settings.setValue("toolchain", "mingw"); } #endif int probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms) { #ifdef Q_OS_WIN msvcProbe(settingsPath, platforms); mingwProbe(settingsPath, platforms); #else QString cc = QString::fromLocal8Bit(qgetenv("CC")); if (cc.isEmpty()) { bool somethingFound = false; if (specific_probe(settingsPath, platforms, "gcc") == 0) somethingFound = true; specific_probe(settingsPath, platforms, "clang", somethingFound); } else { specific_probe(settingsPath, platforms, cc); } #endif if (platforms.isEmpty()) fprintf(stderr, "Could not detect any platforms.\n"); return 0; } <|endoftext|>
<commit_before>#include "core/narukami.h" #include "core/geometry.h" #include "core/transform.h" #include "core/mesh.h" #include "core/imageio.h" using namespace narukami; int main(){ Point3f vertices[4]={Point3f(0,1,1),Point3f(0,0,1),Point3f(1,0,1),Point3f(1,1,1)}; Point2f uvs[4] = {Point2f(0,1),Point2f(0,0),Point2f(1,0),Point2f(1,1)}; uint32_t indices[6]={0,1,3,1,2,3}; auto transform = translate(Vector3f(0,0,0)); auto transform2 = translate(Vector3f(0,0,0)); auto triangles=create_mesh_triangles(&transform,&transform2,2,indices,4,vertices,nullptr,uvs); auto soa_triangles=cast2SoA(triangles,0,2); std::cout<<soa_triangles[0]; std::vector<uint8_t> image; float data[128*128*3]; for (int i = 0; i<128*128; ++i) { narukami::Point2f uv; float t; narukami::SoARay ray(narukami::Point3f((i/128.0f)/128.0f,(i%128)/128.0f,0),narukami::Vector3f(0,0,1)); int index; bool b =intersect(ray,soa_triangles[0],&t,&uv,&index); // std::cout<<index; // for(int j=0;j<soa_triangles.size();++j){ // b=(b||intersect(ray,soa_triangles[j],&t,&uv,&index)); // if(b){ // break; // } // } uv=triangles[index]->sample_uv(uv); data[i*3] = uv[0]; data[i*3+1] = uv[1]; data[i*3+2] = 0; } narukami::write_image_to_file("mesh.png",data,128,128); //unsigned error = lodepng::encode(, image, 128, 128); }<commit_msg>change to use sampler<commit_after>#include "core/narukami.h" #include "core/geometry.h" #include "core/transform.h" #include "core/mesh.h" #include "core/imageio.h" #include "core/sampler.h" using namespace narukami; int main() { Sampler sampler(16); Point3f vertices[4] = {Point3f(0, 1, 1), Point3f(0, 0, 1), Point3f(1, 0, 1), Point3f(1, 1, 1)}; Point2f uvs[4] = {Point2f(0, 1), Point2f(0, 0), Point2f(1, 0), Point2f(1, 1)}; uint32_t indices[6] = {0, 1, 3, 1, 2, 3}; auto transform = translate(Vector3f(0, 0, 0)); auto transform2 = translate(Vector3f(0, 0, 0)); auto triangles = create_mesh_triangles(&transform, &transform2, 2, indices, 4, vertices, nullptr, uvs); auto soa_triangles = cast2SoA(triangles, 0, 2); std::cout << soa_triangles[0]; std::vector<uint8_t> image; float data[128 * 128 * 3]; for (int y = 0; y < 128; ++y) { for (int x = 0; x < 128; ++x) { data[(y*128+x)* 3] = 0; data[(y*128+x)* 3 + 1] = 0; sampler.start_pixel(Point2i(0, 0)); do { auto sample = sampler.get_2D(); SoARay ray(Point3f((x+sample.x)/128.0f, (y+sample.y)/128.0f, 0), Vector3f(0, 0, 1)); Point2f uv; float t; int index; bool b = intersect(ray, soa_triangles[0], &t, &uv, &index); if (b) { uv = triangles[index]->sample_uv(uv); data[(y*128+x)* 3] += uv[0]; data[(y*128+x)* 3 + 1] += uv[1]; } else { std::cout << "miss " << ray.o << std::endl; } } while (sampler.start_next_sample()); data[(y*128+x)* 3] /= 16; data[(y*128+x)* 3 + 1] /= 16; data[(y*128+x)* 3 + 2] = 0; } } narukami::write_image_to_file("mesh.png", data, 128, 128); //unsigned error = lodepng::encode(, image, 128, 128); }<|endoftext|>
<commit_before>#include "ManipulationConstraint.h" #include "PointContactRelation.h" using namespace action_authoring; using namespace affordance; using namespace boost; ManipulationConstraint:: ManipulationConstraint(AffConstPtr affordance, ManipulatorStateConstPtr manipulator, RelationStatePtr relationState ) : _affordance(affordance), _manipulator(manipulator), _relationState(relationState) { _timeLowerBound = 0.0; _timeUpperBound = 0.0; } ManipulationConstraint:: ManipulationConstraint(AffConstPtr affordance, ManipulatorStateConstPtr manipulator, RelationStatePtr relationState, double timeLowerBound, double timeUpperBound ) : _affordance(affordance), _manipulator(manipulator), _relationState(relationState) { _timeLowerBound = timeLowerBound; _timeUpperBound = timeUpperBound; } drc::contact_goal_t ManipulationConstraint::toLCM() { printf("creating LCM message\n"); drc::contact_goal_t msg; msg.utime = 0.0; //TODO change contact type based on affordance msg.contact_type = 0; msg.object_1_name = _manipulator->getName(); msg.object_1_contact_grp = _manipulator->getContactGroupName(); //TODO remove hardcodes here! msg.contact_type = msg.ON_GROUND_PLANE; msg.ground_plane_pt_radius = .25; msg.lower_bound_completion_time = _timeLowerBound; msg.upper_bound_completion_time = _timeUpperBound; if (_relationState->getRelationType() == RelationState::POINT_CONTACT) { Eigen::Vector3f v = (boost::static_pointer_cast<PointContactRelation>(_relationState))->getPoint2(); drc::vector_3d_t pt; pt.x = v.x(); pt.y = v.y(); pt.z = v.z(); msg.ground_plane_pt = pt; } return msg; } <commit_msg>ManipulationConstraint uses new ManipulationState getLinkName() method for serialization<commit_after>#include "ManipulationConstraint.h" #include "PointContactRelation.h" using namespace action_authoring; using namespace affordance; using namespace boost; ManipulationConstraint:: ManipulationConstraint(AffConstPtr affordance, ManipulatorStateConstPtr manipulator, RelationStatePtr relationState ) : _affordance(affordance), _manipulator(manipulator), _relationState(relationState) { _timeLowerBound = 0.0; _timeUpperBound = 0.0; } ManipulationConstraint:: ManipulationConstraint(AffConstPtr affordance, ManipulatorStateConstPtr manipulator, RelationStatePtr relationState, double timeLowerBound, double timeUpperBound ) : _affordance(affordance), _manipulator(manipulator), _relationState(relationState) { _timeLowerBound = timeLowerBound; _timeUpperBound = timeUpperBound; } drc::contact_goal_t ManipulationConstraint::toLCM() { printf("creating LCM message\n"); drc::contact_goal_t msg; msg.utime = 0.0; //TODO change contact type based on affordance msg.contact_type = 0; printf("flag0\n"); msg.object_1_name = _manipulator->getLinkName(); printf("flag0.5\n"); msg.object_1_contact_grp = _manipulator->getContactGroupName(); //TODO remove hardcodes here! msg.contact_type = msg.ON_GROUND_PLANE; msg.ground_plane_pt_radius = .25; msg.lower_bound_completion_time = _timeLowerBound; msg.upper_bound_completion_time = _timeUpperBound; if (_relationState->getRelationType() == RelationState::POINT_CONTACT) { printf("flag1\n"); Eigen::Vector3f v = (boost::static_pointer_cast<PointContactRelation>(_relationState))->getPoint2(); printf("flag2\n"); drc::vector_3d_t pt; pt.x = v.x(); pt.y = v.y(); pt.z = v.z(); msg.ground_plane_pt = pt; } return msg; } <|endoftext|>