text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. */ #ifndef MAKE_UNIQUE_H__ #define MAKE_UNIQUE_H__ #include <cstdlib> #include <memory> #include <type_traits> namespace osrm { // Taken from http://msdn.microsoft.com/en-us/library/dn439780.asp // Note, that the snippet is broken there and needed minor massaging // make_unique<T> template <class T, class... Types> std::unique_ptr<T> make_unique(Types &&... Args) { return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...))); } // make_unique<T[]> template <class T> std::unique_ptr<T> make_unique(std::size_t Size) { return (std::unique_ptr<T>(new T[Size]())); } // make_unique<T[N]> disallowed template <class T, class... Types> typename std::enable_if<std::extent<T>::value != 0, void>::type make_unique(Types &&...) = delete; } #endif <commit_msg>fix typo<commit_after>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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. */ #ifndef MAKE_UNIQUE_H__ #define MAKE_UNIQUE_H__ #include <cstdlib> #include <memory> #include <type_traits> namespace osrm { // Taken from http://msdn.microsoft.com/en-us/library/dn439780.asp // Note, that the snippet was broken there and needed minor massaging // make_unique<T> template <class T, class... Types> std::unique_ptr<T> make_unique(Types &&... Args) { return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...))); } // make_unique<T[]> template <class T> std::unique_ptr<T> make_unique(std::size_t Size) { return (std::unique_ptr<T>(new T[Size]())); } // make_unique<T[N]> disallowed template <class T, class... Types> typename std::enable_if<std::extent<T>::value != 0, void>::type make_unique(Types &&...) = delete; } #endif <|endoftext|>
<commit_before>//============================================================================= // ■ VMGS/Scene/scene.cpp //============================================================================= #include "../VMGS.hpp" namespace VM76 { namespace SceneManager { Scene* context = NULL; } void Scene::key_callback(int key, int scancode, int action, int mods) {} void Scene::update() {} Scene::~Scene() {} bool SceneManager::render_debug_info = true; void SceneManager::load_scene(Scene* c) { context = c; } void SceneManager::update_scene() { if (context) context->update(); } void SceneManager::render_scene() { if (context) context->render(); // Render FPS if (render_debug_info) { VMSC::disable_depth_test(); char fps[40]; sprintf(fps, "FPS: %d, %f.4ms", VMDE->fps, VMDE->frame_time); trex->instanceRenderText( fps, gui_2d_projection, glm::mat4(1.0), glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.94, 0.0)), 0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE ); VMSC::enable_depth_test(); } } void SceneManager::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_F3 && action == GLFW_PRESS) { render_debug_info = !render_debug_info; return; } if (context) context->key_callback(key, scancode, action, mods); } } <commit_msg>Add Ctrl-Break functionality<commit_after>//============================================================================= // ■ VMGS/Scene/scene.cpp //============================================================================= #include "../VMGS.hpp" namespace VM76 { namespace SceneManager { Scene* context = NULL; } void Scene::key_callback(int key, int scancode, int action, int mods) {} void Scene::update() {} Scene::~Scene() {} bool SceneManager::render_debug_info = true; void SceneManager::load_scene(Scene* c) { context = c; } void SceneManager::update_scene() { if (context) context->update(); } void SceneManager::render_scene() { if (context) context->render(); // Render FPS if (render_debug_info) { VMSC::disable_depth_test(); char fps[40]; sprintf(fps, "FPS: %d, %f.4ms", VMDE->fps, VMDE->frame_time); trex->instanceRenderText( fps, gui_2d_projection, glm::mat4(1.0), glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.94, 0.0)), 0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE ); VMSC::enable_depth_test(); } } void SceneManager::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_PAUSE && action == GLFW_PRESS && (mods & GLFW_MOD_CONTROL)) { abort(); } if (key == GLFW_KEY_F3 && action == GLFW_PRESS) { render_debug_info = !render_debug_info; return; } if (context) context->key_callback(key, scancode, action, mods); } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <cstdlib> #include <benejson/pull.hh> #include "posix.hh" void OutputValue(BNJ::PullParser& parser){ const bnj_val& val = parser.GetValue(); if(val.key_length){ char key[512]; BNJ::GetKey(key, 1024, parser); fprintf(stdout, "key: '%s'\n", key); } switch(bnj_val_type(&val)){ case BNJ_NUMERIC: if(val.exp_val){ double f; BNJ::Get(f, parser); fprintf(stdout, "double: %g\n", f); } else{ if(val.type & BNJ_VFLAG_NEGATIVE_SIGNIFICAND){ int v; BNJ::Get(v, parser); fprintf(stdout, "integer: %d\n", v); } else{ unsigned v; BNJ::Get(v, parser); fprintf(stdout, "unsigned: %d\n", v); } } break; case BNJ_SPECIAL: switch(val.significand_val){ case BNJ_SPC_FALSE: fprintf(stdout, "bool: false\n"); break; case BNJ_SPC_TRUE: fprintf(stdout, "bool: true\n"); break; case BNJ_SPC_NULL: fprintf(stdout, "null\n"); break; case BNJ_SPC_NAN: fprintf(stdout, "float: NaN\n"); break; case BNJ_SPC_INFINITY: { char c = (val.type & BNJ_VFLAG_NEGATIVE_SIGNIFICAND) ? '-' : ' '; fprintf(stdout, "float: %cInfinity\n", c); } break; default: break; } break; case BNJ_ARR_BEGIN: break; case BNJ_OBJ_BEGIN: break; case BNJ_STRING: { /* Can read the length of the string fragment before consuming unsigned outlen = bnj_strlen8(&parser.GetValue()); unsigned outlen = bnj_strlen16(&parser.GetValue()); unsigned outlen = bnj_strlen32&parser.GetValue()); */ unsigned len; char buffer[1024]; /* Consume/Write loop */ fprintf(stdout, "string: '"); while((len = parser.ChunkRead8(buffer, 1024))) fwrite(buffer, 1, len, stdout); fprintf(stdout, "'\n"); } break; default: break; } } int main(int argc, const char* argv[]){ if(argc < 3){ fprintf(stderr, "Usage: %s buffer_size stack_depth\n", argv[0]); return 1; } /* Read arguments. */ char* endptr; unsigned buffsize = strtol(argv[1], &endptr, 10); unsigned depth = strtol(argv[2], &endptr, 10); /* Read json from std input. */ FD_Reader reader(0); uint32_t *pstack = new uint32_t[depth]; BNJ::PullParser parser(depth, pstack); /* Initialize parsing session. buffer is I/O scratch space. */ uint8_t *buffer = new uint8_t[buffsize]; parser.Begin(buffer, buffsize, &reader); int ret = 0; try{ /* Begin a tree walk. */ bool running = true; while(running){ switch(parser.Pull()){ /* Stop when there is no more data. */ case BNJ::PullParser::ST_NO_DATA: running = false; break; /* Parser pulled a datum. */ case BNJ::PullParser::ST_DATUM: OutputValue(parser); break; case BNJ::PullParser::ST_MAP: fprintf(stdout, "map open '{'\n"); break; case BNJ::PullParser::ST_LIST: fprintf(stdout, "array open '['\n"); break; case BNJ::PullParser::ST_ASCEND_MAP: fprintf(stdout, "map close '}'\n"); break; case BNJ::PullParser::ST_ASCEND_LIST: fprintf(stdout, "array close ']'\n"); break; default: break; } } } catch(const std::exception& e){ fprintf(stderr, "Runtime Error: %s\n", e.what()); ret = 1; } delete [] buffer; delete [] pstack; return ret; } <commit_msg>Print out keys for maps/lists now<commit_after>#include <cstdio> #include <cstring> #include <cstdlib> #include <benejson/pull.hh> #include "posix.hh" void OutputValue(BNJ::PullParser& parser){ const bnj_val& val = parser.GetValue(); switch(bnj_val_type(&val)){ case BNJ_NUMERIC: if(val.exp_val){ double f; BNJ::Get(f, parser); fprintf(stdout, "double: %g\n", f); } else{ if(val.type & BNJ_VFLAG_NEGATIVE_SIGNIFICAND){ int v; BNJ::Get(v, parser); fprintf(stdout, "integer: %d\n", v); } else{ unsigned v; BNJ::Get(v, parser); fprintf(stdout, "unsigned: %d\n", v); } } break; case BNJ_SPECIAL: switch(val.significand_val){ case BNJ_SPC_FALSE: fprintf(stdout, "bool: false\n"); break; case BNJ_SPC_TRUE: fprintf(stdout, "bool: true\n"); break; case BNJ_SPC_NULL: fprintf(stdout, "null\n"); break; case BNJ_SPC_NAN: fprintf(stdout, "float: NaN\n"); break; case BNJ_SPC_INFINITY: { char c = (val.type & BNJ_VFLAG_NEGATIVE_SIGNIFICAND) ? '-' : ' '; fprintf(stdout, "float: %cInfinity\n", c); } break; default: break; } break; case BNJ_ARR_BEGIN: break; case BNJ_OBJ_BEGIN: break; case BNJ_STRING: { /* Can read the length of the string fragment before consuming unsigned outlen = bnj_strlen8(&parser.GetValue()); unsigned outlen = bnj_strlen16(&parser.GetValue()); unsigned outlen = bnj_strlen32&parser.GetValue()); */ unsigned len; char buffer[1024]; /* Consume/Write loop */ fprintf(stdout, "string: '"); while((len = parser.ChunkRead8(buffer, 1024))) fwrite(buffer, 1, len, stdout); fprintf(stdout, "'\n"); } break; default: break; } } int main(int argc, const char* argv[]){ if(argc < 3){ fprintf(stderr, "Usage: %s buffer_size stack_depth\n", argv[0]); return 1; } /* Read arguments. */ char* endptr; unsigned buffsize = strtol(argv[1], &endptr, 10); unsigned depth = strtol(argv[2], &endptr, 10); /* Read json from std input. */ FD_Reader reader(0); uint32_t *pstack = new uint32_t[depth]; BNJ::PullParser parser(depth, pstack); /* Initialize parsing session. buffer is I/O scratch space. */ uint8_t *buffer = new uint8_t[buffsize]; parser.Begin(buffer, buffsize, &reader); int ret = 0; try{ /* Begin a tree walk. */ bool running = true; while(running){ unsigned ret = parser.Pull(); if(parser.ValidValue()){ const bnj_val& val = parser.GetValue(); if(val.key_length){ char key[512]; BNJ::GetKey(key, 1024, parser); fprintf(stdout, "key: '%s'\n", key); } } switch(ret){ /* Stop when there is no more data. */ case BNJ::PullParser::ST_NO_DATA: running = false; break; /* Parser pulled a datum. */ case BNJ::PullParser::ST_DATUM: OutputValue(parser); break; case BNJ::PullParser::ST_MAP: fprintf(stdout, "map open '{'\n"); break; case BNJ::PullParser::ST_LIST: fprintf(stdout, "array open '['\n"); break; case BNJ::PullParser::ST_ASCEND_MAP: fprintf(stdout, "map close '}'\n"); break; case BNJ::PullParser::ST_ASCEND_LIST: fprintf(stdout, "array close ']'\n"); break; default: break; } } } catch(const std::exception& e){ fprintf(stderr, "Runtime Error: %s\n", e.what()); ret = 1; } delete [] buffer; delete [] pstack; return ret; } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/client/computation_builder.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" namespace xla { namespace { class ConditionalOpTest : public ClientLibraryTestBase { protected: Computation CreateR0F32ConstantComputation(float value) { ComputationBuilder builder(client_, "Constant"); builder.Parameter(0, empty_tuple_, "tuple"); builder.ConstantR0<float>(value); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32IdentityComputation() { ComputationBuilder builder(client_, "Identity"); builder.Parameter(0, r0f32_, "x"); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32CeilComputation() { ComputationBuilder builder(client_, "Ceil"); auto param = builder.Parameter(0, r0f32_, "param"); builder.Ceil(param); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32FloorComputation() { ComputationBuilder builder(client_, "Ceil"); auto param = builder.Parameter(0, r0f32_, "param"); builder.Floor(param); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateAddTupleComputation(const string& computation_name, const Shape& tuple_shape) { ComputationBuilder builder(client_, computation_name); auto tuple = builder.Parameter(0, tuple_shape, "tuple"); auto x = builder.GetTupleElement(tuple, 0); auto y = builder.GetTupleElement(tuple, 1); builder.Add(x, y); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateAddR0Computation() { return CreateAddTupleComputation("AddR0", tuple_2_r0f32_); } Computation CreateAddR1Computation() { return CreateAddTupleComputation("AddR1", tuple_2_r1s2f32_); } Computation CreateSubTupleComputation(const string& computation_name, const Shape& tuple_shape) { ComputationBuilder builder(client_, computation_name); auto tuple = builder.Parameter(0, tuple_shape, "tuple"); auto x = builder.GetTupleElement(tuple, 0); auto y = builder.GetTupleElement(tuple, 1); builder.Sub(x, y); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateSubR0Computation() { return CreateSubTupleComputation("SubR0", tuple_2_r0f32_); } Computation CreateSubR1Computation() { return CreateSubTupleComputation("SubR1", tuple_2_r1s2f32_); } Shape r0f32_ = ShapeUtil::MakeShape(F32, {}); Shape tuple_2_r0f32_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); Shape tuple_2_r1s2f32_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {2}), ShapeUtil::MakeShape(F32, {2})}); Shape empty_tuple_ = ShapeUtil::MakeTupleShape({}); ErrorSpec error_spec_{0.001}; }; // Test true and false computations that do not take any parameters. XLA_TEST_F(ConditionalOpTest, Parameters0) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operands = builder.Tuple({}); auto true_computation = CreateR0F32ConstantComputation(56.0f); auto false_computation = CreateR0F32ConstantComputation(12.0f); auto result = builder.Conditional(pred, operands, true_computation, operands, false_computation); ComputeAndCompareR0<float>(&builder, 56.0f, {}, error_spec_); } // Test true and false computations that take in 1 parameter. XLA_TEST_F(ConditionalOpTest, Parameters1) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto identity = CreateR0F32IdentityComputation(); auto result = builder.Conditional(pred, operand1, identity, operand2, identity); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test true and false computations that take in 2 parameters and predicate is // true. XLA_TEST_F(ConditionalOpTest, Parameters2TrueBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR0Computation(), operands, CreateSubR0Computation()); ComputeAndCompareR0<float>(&builder, 68.0f, {}, error_spec_); } // Test true and false computations that take in 2 parameters and predicate is // false. XLA_TEST_F(ConditionalOpTest, Parameters2FalseBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR0Computation(), operands, CreateSubR0Computation()); ComputeAndCompareR0<float>(&builder, 44.0f, {}, error_spec_); } // Test true and false computations that take in 2 array parameters and // predicate is true. XLA_TEST_F(ConditionalOpTest, Parameters2ArrayTrueBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR1<float>({24.0f, 56.0f}); auto operand2 = builder.ConstantR1<float>({10.0f, 11.0f}); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR1Computation()); ComputeAndCompareR1<float>(&builder, {34.0f, 67.0f}, {}, error_spec_); } // Test true and false computations that take in 2 array parameters and // predicate is false. XLA_TEST_F(ConditionalOpTest, Parameters2ArrayFalseBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR1<float>({24.0f, 56.0f}); auto operand2 = builder.ConstantR1<float>({10.0f, 11.0f}); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR1Computation()); ComputeAndCompareR1<float>(&builder, {14.0f, 45.0f}, {}, error_spec_); } // Test the case where one conditional is nested within another. XLA_TEST_F(ConditionalOpTest, NestedConditionals) { Shape r0bool = ShapeUtil::MakeShape(PRED, {}); Shape tuple_shape = ShapeUtil::MakeTupleShape({r0bool, r0f32_, r0f32_}); ComputationBuilder inner_builder(client_, TestName() + ".inner_conditional"); auto param0 = inner_builder.Parameter(0, tuple_shape, "param0"); auto pred_cond = inner_builder.GetTupleElement(param0, 0); auto true_operand = inner_builder.GetTupleElement(param0, 1); auto false_operand = inner_builder.GetTupleElement(param0, 2); inner_builder.Conditional(pred_cond, true_operand, CreateR0F32CeilComputation(), false_operand, CreateR0F32FloorComputation()); auto inner_builder_result = inner_builder.Build(); ComputationBuilder builder(client_, TestName()); auto pred1 = builder.ConstantR0<bool>(true); auto pred2 = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(1.1f); auto operand2 = builder.ConstantR0<float>(12.2f); auto operand3 = builder.ConstantR0<float>(43.3f); auto tuple_operand = builder.Tuple({pred2, operand1, operand2}); builder.Conditional(pred1, tuple_operand, inner_builder_result.ConsumeValueOrDie(), operand3, CreateR0F32IdentityComputation()); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test a mismatch in the shape of the true operand and true computation. XLA_TEST_F(ConditionalOpTest, ShapeMismatch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR0Computation()); auto result = builder.Build(); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().error_message(), ::testing::HasSubstr("true_operand must match the shape of the " "only parameter of true_computation")); } } // namespace } // namespace xla <commit_msg>[XLA] Adding more tests for conditional.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/client/computation_builder.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" namespace xla { namespace { class ConditionalOpTest : public ClientLibraryTestBase { protected: Computation CreateR0F32ConstantComputation(float value) { ComputationBuilder builder(client_, "Constant"); builder.Parameter(0, empty_tuple_, "tuple"); builder.ConstantR0<float>(value); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32IdentityComputation() { ComputationBuilder builder(client_, "Identity"); builder.Parameter(0, r0f32_, "x"); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32CeilComputation() { ComputationBuilder builder(client_, "Ceil"); auto param = builder.Parameter(0, r0f32_, "param"); builder.Ceil(param); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateR0F32FloorComputation() { ComputationBuilder builder(client_, "Ceil"); auto param = builder.Parameter(0, r0f32_, "param"); builder.Floor(param); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateAddTupleComputation(const string& computation_name, const Shape& tuple_shape) { ComputationBuilder builder(client_, computation_name); auto tuple = builder.Parameter(0, tuple_shape, "tuple"); auto x = builder.GetTupleElement(tuple, 0); auto y = builder.GetTupleElement(tuple, 1); builder.Add(x, y); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateAddR0Computation() { return CreateAddTupleComputation("AddR0", tuple_2_r0f32_); } Computation CreateAddR1Computation() { return CreateAddTupleComputation("AddR1", tuple_2_r1s2f32_); } Computation CreateSubTupleComputation(const string& computation_name, const Shape& tuple_shape) { ComputationBuilder builder(client_, computation_name); auto tuple = builder.Parameter(0, tuple_shape, "tuple"); auto x = builder.GetTupleElement(tuple, 0); auto y = builder.GetTupleElement(tuple, 1); builder.Sub(x, y); auto build_status = builder.Build(); EXPECT_IS_OK(build_status.status()); return build_status.ConsumeValueOrDie(); } Computation CreateSubR0Computation() { return CreateSubTupleComputation("SubR0", tuple_2_r0f32_); } Computation CreateSubR1Computation() { return CreateSubTupleComputation("SubR1", tuple_2_r1s2f32_); } Shape r0f32_ = ShapeUtil::MakeShape(F32, {}); Shape tuple_2_r0f32_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); Shape tuple_2_r1s2f32_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {2}), ShapeUtil::MakeShape(F32, {2})}); Shape empty_tuple_ = ShapeUtil::MakeTupleShape({}); ErrorSpec error_spec_{0.001}; }; // Test true and false computations that do not take any parameters. XLA_TEST_F(ConditionalOpTest, Parameters0) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operands = builder.Tuple({}); auto true_computation = CreateR0F32ConstantComputation(56.0f); auto false_computation = CreateR0F32ConstantComputation(12.0f); auto result = builder.Conditional(pred, operands, true_computation, operands, false_computation); ComputeAndCompareR0<float>(&builder, 56.0f, {}, error_spec_); } // Test true and false computations that take in 1 parameter. XLA_TEST_F(ConditionalOpTest, Parameters1) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto identity = CreateR0F32IdentityComputation(); auto result = builder.Conditional(pred, operand1, identity, operand2, identity); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test conditional with two different computations in the true and false cases // that take in different arguments. XLA_TEST_F(ConditionalOpTest, DiffComputationsDiffArgs) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.4f); auto operand2 = builder.ConstantR0<float>(12.6f); auto result = builder.Conditional(pred, operand1, CreateR0F32CeilComputation(), operand2, CreateR0F32FloorComputation()); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test conditional with two different computations in the true and false cases // that take in the same arguments. XLA_TEST_F(ConditionalOpTest, DiffComputationsSameArg) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand = builder.ConstantR0<float>(12.6f); auto result = builder.Conditional(pred, operand, CreateR0F32CeilComputation(), operand, CreateR0F32FloorComputation()); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test conditional with the same computation in the true and false cases but // take in different arguments. XLA_TEST_F(ConditionalOpTest, SameComputationDiffArgs) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.4f); auto operand2 = builder.ConstantR0<float>(12.6f); auto floor = CreateR0F32FloorComputation(); auto result = builder.Conditional(pred, operand1, floor, operand2, floor); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test conditional with the same computation in the true and false cases that // take in the same arguments. XLA_TEST_F(ConditionalOpTest, SameComputationSameArg) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand = builder.ConstantR0<float>(12.6f); auto floor = CreateR0F32FloorComputation(); auto result = builder.Conditional(pred, operand, floor, operand, floor); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test conditional with different instances of the same computation in the true // and false cases. XLA_TEST_F(ConditionalOpTest, SameComputationDiffInstances) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.4f); auto operand2 = builder.ConstantR0<float>(12.6f); auto result = builder.Conditional(pred, operand1, CreateR0F32FloorComputation(), operand2, CreateR0F32FloorComputation()); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test the case when a call invokes a computation that contains a conditional. XLA_TEST_F(ConditionalOpTest, ConditionalWithCall) { Shape r0bool = ShapeUtil::MakeShape(PRED, {}); ComputationBuilder inner_builder(client_, TestName() + ".inner_conditional"); auto pred_cond = inner_builder.Parameter(0, r0bool, "param0"); auto true_operand = inner_builder.Parameter(1, r0f32_, "param1"); auto false_operand = inner_builder.Parameter(2, r0f32_, "param2"); inner_builder.Conditional(pred_cond, true_operand, CreateR0F32CeilComputation(), false_operand, CreateR0F32FloorComputation()); auto inner_builder_result = inner_builder.Build(); ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.4f); auto operand2 = builder.ConstantR0<float>(12.6f); builder.Call(inner_builder_result.ConsumeValueOrDie(), {pred, operand1, operand2}); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test true and false computations that take in 2 parameters and predicate is // true. XLA_TEST_F(ConditionalOpTest, Parameters2TrueBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR0Computation(), operands, CreateSubR0Computation()); ComputeAndCompareR0<float>(&builder, 68.0f, {}, error_spec_); } // Test true and false computations that take in 2 parameters and predicate is // false. XLA_TEST_F(ConditionalOpTest, Parameters2FalseBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR0Computation(), operands, CreateSubR0Computation()); ComputeAndCompareR0<float>(&builder, 44.0f, {}, error_spec_); } // Test true and false computations that take in 2 array parameters and // predicate is true. XLA_TEST_F(ConditionalOpTest, Parameters2ArrayTrueBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR1<float>({24.0f, 56.0f}); auto operand2 = builder.ConstantR1<float>({10.0f, 11.0f}); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR1Computation()); ComputeAndCompareR1<float>(&builder, {34.0f, 67.0f}, {}, error_spec_); } // Test true and false computations that take in 2 array parameters and // predicate is false. XLA_TEST_F(ConditionalOpTest, Parameters2ArrayFalseBranch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR1<float>({24.0f, 56.0f}); auto operand2 = builder.ConstantR1<float>({10.0f, 11.0f}); auto operands = builder.Tuple({operand1, operand2}); auto result = builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR1Computation()); ComputeAndCompareR1<float>(&builder, {14.0f, 45.0f}, {}, error_spec_); } // Test the case where one conditional is nested within another. XLA_TEST_F(ConditionalOpTest, NestedConditionals) { Shape r0bool = ShapeUtil::MakeShape(PRED, {}); Shape tuple_shape = ShapeUtil::MakeTupleShape({r0bool, r0f32_, r0f32_}); ComputationBuilder inner_builder(client_, TestName() + ".inner_conditional"); auto param0 = inner_builder.Parameter(0, tuple_shape, "param0"); auto pred_cond = inner_builder.GetTupleElement(param0, 0); auto true_operand = inner_builder.GetTupleElement(param0, 1); auto false_operand = inner_builder.GetTupleElement(param0, 2); inner_builder.Conditional(pred_cond, true_operand, CreateR0F32CeilComputation(), false_operand, CreateR0F32FloorComputation()); auto inner_builder_result = inner_builder.Build(); ComputationBuilder builder(client_, TestName()); auto pred1 = builder.ConstantR0<bool>(true); auto pred2 = builder.ConstantR0<bool>(false); auto operand1 = builder.ConstantR0<float>(1.1f); auto operand2 = builder.ConstantR0<float>(12.2f); auto operand3 = builder.ConstantR0<float>(43.3f); auto tuple_operand = builder.Tuple({pred2, operand1, operand2}); builder.Conditional(pred1, tuple_operand, inner_builder_result.ConsumeValueOrDie(), operand3, CreateR0F32IdentityComputation()); ComputeAndCompareR0<float>(&builder, 12.0f, {}, error_spec_); } // Test a mismatch in the shape of the true operand and true computation. XLA_TEST_F(ConditionalOpTest, ShapeMismatch) { ComputationBuilder builder(client_, TestName()); auto pred = builder.ConstantR0<bool>(true); auto operand1 = builder.ConstantR0<float>(56.0f); auto operand2 = builder.ConstantR0<float>(12.0f); auto operands = builder.Tuple({operand1, operand2}); builder.Conditional(pred, operands, CreateAddR1Computation(), operands, CreateSubR0Computation()); auto result = builder.Build(); EXPECT_FALSE(result.ok()); EXPECT_THAT(result.status().error_message(), ::testing::HasSubstr("true_operand must match the shape of the " "only parameter of true_computation")); } } // namespace } // namespace xla <|endoftext|>
<commit_before><commit_msg>Fix: The invariant mass histograms are empty<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/setup/daemon_controller.h" #include <unistd.h> #include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/environment.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/md5.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/process/process_handle.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/threading/thread.h" #include "base/values.h" #include "net/base/net_util.h" #include "remoting/host/host_config.h" #include "remoting/host/json_host_config.h" #include "remoting/host/usage_stats_consent.h" namespace remoting { namespace { const char kDaemonScript[] = "/opt/google/chrome-remote-desktop/chrome-remote-desktop"; // Timeout for running daemon script. const int64 kDaemonTimeoutMs = 5000; // Timeout for commands that require password prompt - 5 minutes. const int64 kSudoTimeoutSeconds = 5 * 60; std::string GetMd5(const std::string& value) { base::MD5Context ctx; base::MD5Init(&ctx); base::MD5Update(&ctx, value); base::MD5Digest digest; base::MD5Final(&digest, &ctx); return StringToLowerASCII(base::HexEncode(digest.a, sizeof(digest.a))); } class DaemonControllerLinux : public remoting::DaemonController { public: DaemonControllerLinux(); virtual State GetState() OVERRIDE; virtual void GetConfig(const GetConfigCallback& callback) OVERRIDE; virtual void SetConfigAndStart( scoped_ptr<base::DictionaryValue> config, bool consent, const CompletionCallback& done) OVERRIDE; virtual void UpdateConfig(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) OVERRIDE; virtual void Stop(const CompletionCallback& done_callback) OVERRIDE; virtual void SetWindow(void* window_handle) OVERRIDE; virtual void GetVersion(const GetVersionCallback& done_callback) OVERRIDE; virtual void GetUsageStatsConsent( const GetUsageStatsConsentCallback& done) OVERRIDE; private: base::FilePath GetConfigPath(); void DoGetConfig(const GetConfigCallback& callback); void DoSetConfigAndStart(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done); void DoUpdateConfig(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback); void DoStop(const CompletionCallback& done_callback); void DoGetVersion(const GetVersionCallback& done_callback); base::Thread file_io_thread_; DISALLOW_COPY_AND_ASSIGN(DaemonControllerLinux); }; DaemonControllerLinux::DaemonControllerLinux() : file_io_thread_("DaemonControllerFileIO") { file_io_thread_.Start(); } static bool GetScriptPath(base::FilePath* result) { base::FilePath candidate_exe(kDaemonScript); if (access(candidate_exe.value().c_str(), X_OK) == 0) { *result = candidate_exe; return true; } return false; } static bool RunHostScriptWithTimeout( const std::vector<std::string>& args, base::TimeDelta timeout, int* exit_code) { DCHECK(exit_code); // As long as we're relying on running an external binary from the // PATH, don't do it as root. if (getuid() == 0) { return false; } base::FilePath script_path; if (!GetScriptPath(&script_path)) { return false; } CommandLine command_line(script_path); for (unsigned int i = 0; i < args.size(); ++i) { command_line.AppendArg(args[i]); } base::ProcessHandle process_handle; // Redirect the child's stdout to the parent's stderr. In the case where this // parent process is a Native Messaging host, its stdout is used to send // messages to the web-app. base::FileHandleMappingVector fds_to_remap; fds_to_remap.push_back(std::pair<int, int>(STDERR_FILENO, STDOUT_FILENO)); base::LaunchOptions options; options.fds_to_remap = &fds_to_remap; if (!base::LaunchProcess(command_line, options, &process_handle)) { return false; } if (!base::WaitForExitCodeWithTimeout(process_handle, exit_code, timeout)) { base::KillProcess(process_handle, 0, false); return false; } return true; } static bool RunHostScript(const std::vector<std::string>& args, int* exit_code) { return RunHostScriptWithTimeout( args, base::TimeDelta::FromMilliseconds(kDaemonTimeoutMs), exit_code); } remoting::DaemonController::State DaemonControllerLinux::GetState() { std::vector<std::string> args; args.push_back("--check-running"); int exit_code = 0; if (!RunHostScript(args, &exit_code)) { // TODO(jamiewalch): When we have a good story for installing, return // NOT_INSTALLED rather than NOT_IMPLEMENTED (the former suppresses // the relevant UI in the web-app). return remoting::DaemonController::STATE_NOT_IMPLEMENTED; } if (exit_code == 0) { return remoting::DaemonController::STATE_STARTED; } else { return remoting::DaemonController::STATE_STOPPED; } } void DaemonControllerLinux::GetConfig(const GetConfigCallback& callback) { // base::Unretained() is safe because we control lifetime of the thread. file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoGetConfig, base::Unretained(this), callback)); } void DaemonControllerLinux::GetUsageStatsConsent( const GetUsageStatsConsentCallback& done) { // Crash dump collection is not implemented on Linux yet. // http://crbug.com/130678. done.Run(false, false, false); } void DaemonControllerLinux::SetConfigAndStart( scoped_ptr<base::DictionaryValue> config, bool /* consent */, const CompletionCallback& done) { // base::Unretained() is safe because we control lifetime of the thread. file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoSetConfigAndStart, base::Unretained(this), base::Passed(&config), done)); } void DaemonControllerLinux::UpdateConfig( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoUpdateConfig, base::Unretained(this), base::Passed(&config), done_callback)); } void DaemonControllerLinux::Stop(const CompletionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoStop, base::Unretained(this), done_callback)); } void DaemonControllerLinux::SetWindow(void* window_handle) { // noop } void DaemonControllerLinux::GetVersion( const GetVersionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoGetVersion, base::Unretained(this), done_callback)); } base::FilePath DaemonControllerLinux::GetConfigPath() { std::string filename = "host#" + GetMd5(net::GetHostName()) + ".json"; return file_util::GetHomeDir(). Append(".config/chrome-remote-desktop").Append(filename); } void DaemonControllerLinux::DoGetConfig(const GetConfigCallback& callback) { scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue()); if (GetState() != remoting::DaemonController::STATE_NOT_IMPLEMENTED) { JsonHostConfig config(GetConfigPath()); if (config.Read()) { std::string value; if (config.GetString(kHostIdConfigPath, &value)) { result->SetString(kHostIdConfigPath, value); } if (config.GetString(kXmppLoginConfigPath, &value)) { result->SetString(kXmppLoginConfigPath, value); } } else { result.reset(); // Return NULL in case of error. } } callback.Run(result.Pass()); } void DaemonControllerLinux::DoSetConfigAndStart( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { // Add the user to chrome-remote-desktop group first. std::vector<std::string> args; args.push_back("--add-user"); int exit_code; if (!RunHostScriptWithTimeout( args, base::TimeDelta::FromSeconds(kSudoTimeoutSeconds), &exit_code) || exit_code != 0) { LOG(ERROR) << "Failed to add user to chrome-remote-desktop group."; done_callback.Run(RESULT_FAILED); return; } // Ensure the configuration directory exists. base::FilePath config_dir = GetConfigPath().DirName(); if (!base::DirectoryExists(config_dir) && !file_util::CreateDirectory(config_dir)) { LOG(ERROR) << "Failed to create config directory " << config_dir.value(); done_callback.Run(RESULT_FAILED); return; } // Write config. JsonHostConfig config_file(GetConfigPath()); if (!config_file.CopyFrom(config.get()) || !config_file.Save()) { LOG(ERROR) << "Failed to update config file."; done_callback.Run(RESULT_FAILED); return; } // Finally start the host. args.clear(); args.push_back("--start"); AsyncResult result; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoUpdateConfig( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { JsonHostConfig config_file(GetConfigPath()); if (!config_file.Read() || !config_file.CopyFrom(config.get()) || !config_file.Save()) { LOG(ERROR) << "Failed to update config file."; done_callback.Run(RESULT_FAILED); return; } std::vector<std::string> args; args.push_back("--reload"); AsyncResult result; int exit_code; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoStop(const CompletionCallback& done_callback) { std::vector<std::string> args; args.push_back("--stop"); int exit_code = 0; AsyncResult result; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoGetVersion( const GetVersionCallback& done_callback) { base::FilePath script_path; if (!GetScriptPath(&script_path)) { done_callback.Run(std::string()); return; } CommandLine command_line(script_path); command_line.AppendArg("--host-version"); std::string version; int exit_code = 0; int result = base::GetAppOutputWithExitCode(command_line, &version, &exit_code); if (!result || exit_code != 0) { LOG(ERROR) << "Failed to run \"" << command_line.GetCommandLineString() << "\". Exit code: " << exit_code; done_callback.Run(std::string()); return; } TrimWhitespaceASCII(version, TRIM_ALL, &version); if (!ContainsOnlyChars(version, "0123456789.")) { LOG(ERROR) << "Received invalid host version number: " << version; done_callback.Run(std::string()); return; } done_callback.Run(version); } } // namespace scoped_ptr<DaemonController> remoting::DaemonController::Create() { return scoped_ptr<DaemonController>(new DaemonControllerLinux()); } } // namespace remoting <commit_msg>Increase DaemonControllerLinux timeout for starting host service<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/setup/daemon_controller.h" #include <unistd.h> #include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/environment.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/md5.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/process/process_handle.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/threading/thread.h" #include "base/values.h" #include "net/base/net_util.h" #include "remoting/host/host_config.h" #include "remoting/host/json_host_config.h" #include "remoting/host/usage_stats_consent.h" namespace remoting { namespace { const char kDaemonScript[] = "/opt/google/chrome-remote-desktop/chrome-remote-desktop"; // Timeout for running daemon script. The script itself sets a timeout when // waiting for the host to come online, so the setting here should be at least // as long. const int64 kDaemonTimeoutMs = 60000; // Timeout for commands that require password prompt - 5 minutes. const int64 kSudoTimeoutSeconds = 5 * 60; std::string GetMd5(const std::string& value) { base::MD5Context ctx; base::MD5Init(&ctx); base::MD5Update(&ctx, value); base::MD5Digest digest; base::MD5Final(&digest, &ctx); return StringToLowerASCII(base::HexEncode(digest.a, sizeof(digest.a))); } class DaemonControllerLinux : public remoting::DaemonController { public: DaemonControllerLinux(); virtual State GetState() OVERRIDE; virtual void GetConfig(const GetConfigCallback& callback) OVERRIDE; virtual void SetConfigAndStart( scoped_ptr<base::DictionaryValue> config, bool consent, const CompletionCallback& done) OVERRIDE; virtual void UpdateConfig(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) OVERRIDE; virtual void Stop(const CompletionCallback& done_callback) OVERRIDE; virtual void SetWindow(void* window_handle) OVERRIDE; virtual void GetVersion(const GetVersionCallback& done_callback) OVERRIDE; virtual void GetUsageStatsConsent( const GetUsageStatsConsentCallback& done) OVERRIDE; private: base::FilePath GetConfigPath(); void DoGetConfig(const GetConfigCallback& callback); void DoSetConfigAndStart(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done); void DoUpdateConfig(scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback); void DoStop(const CompletionCallback& done_callback); void DoGetVersion(const GetVersionCallback& done_callback); base::Thread file_io_thread_; DISALLOW_COPY_AND_ASSIGN(DaemonControllerLinux); }; DaemonControllerLinux::DaemonControllerLinux() : file_io_thread_("DaemonControllerFileIO") { file_io_thread_.Start(); } static bool GetScriptPath(base::FilePath* result) { base::FilePath candidate_exe(kDaemonScript); if (access(candidate_exe.value().c_str(), X_OK) == 0) { *result = candidate_exe; return true; } return false; } static bool RunHostScriptWithTimeout( const std::vector<std::string>& args, base::TimeDelta timeout, int* exit_code) { DCHECK(exit_code); // As long as we're relying on running an external binary from the // PATH, don't do it as root. if (getuid() == 0) { return false; } base::FilePath script_path; if (!GetScriptPath(&script_path)) { return false; } CommandLine command_line(script_path); for (unsigned int i = 0; i < args.size(); ++i) { command_line.AppendArg(args[i]); } base::ProcessHandle process_handle; // Redirect the child's stdout to the parent's stderr. In the case where this // parent process is a Native Messaging host, its stdout is used to send // messages to the web-app. base::FileHandleMappingVector fds_to_remap; fds_to_remap.push_back(std::pair<int, int>(STDERR_FILENO, STDOUT_FILENO)); base::LaunchOptions options; options.fds_to_remap = &fds_to_remap; if (!base::LaunchProcess(command_line, options, &process_handle)) { return false; } if (!base::WaitForExitCodeWithTimeout(process_handle, exit_code, timeout)) { base::KillProcess(process_handle, 0, false); return false; } return true; } static bool RunHostScript(const std::vector<std::string>& args, int* exit_code) { return RunHostScriptWithTimeout( args, base::TimeDelta::FromMilliseconds(kDaemonTimeoutMs), exit_code); } remoting::DaemonController::State DaemonControllerLinux::GetState() { std::vector<std::string> args; args.push_back("--check-running"); int exit_code = 0; if (!RunHostScript(args, &exit_code)) { // TODO(jamiewalch): When we have a good story for installing, return // NOT_INSTALLED rather than NOT_IMPLEMENTED (the former suppresses // the relevant UI in the web-app). return remoting::DaemonController::STATE_NOT_IMPLEMENTED; } if (exit_code == 0) { return remoting::DaemonController::STATE_STARTED; } else { return remoting::DaemonController::STATE_STOPPED; } } void DaemonControllerLinux::GetConfig(const GetConfigCallback& callback) { // base::Unretained() is safe because we control lifetime of the thread. file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoGetConfig, base::Unretained(this), callback)); } void DaemonControllerLinux::GetUsageStatsConsent( const GetUsageStatsConsentCallback& done) { // Crash dump collection is not implemented on Linux yet. // http://crbug.com/130678. done.Run(false, false, false); } void DaemonControllerLinux::SetConfigAndStart( scoped_ptr<base::DictionaryValue> config, bool /* consent */, const CompletionCallback& done) { // base::Unretained() is safe because we control lifetime of the thread. file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoSetConfigAndStart, base::Unretained(this), base::Passed(&config), done)); } void DaemonControllerLinux::UpdateConfig( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoUpdateConfig, base::Unretained(this), base::Passed(&config), done_callback)); } void DaemonControllerLinux::Stop(const CompletionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoStop, base::Unretained(this), done_callback)); } void DaemonControllerLinux::SetWindow(void* window_handle) { // noop } void DaemonControllerLinux::GetVersion( const GetVersionCallback& done_callback) { file_io_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &DaemonControllerLinux::DoGetVersion, base::Unretained(this), done_callback)); } base::FilePath DaemonControllerLinux::GetConfigPath() { std::string filename = "host#" + GetMd5(net::GetHostName()) + ".json"; return file_util::GetHomeDir(). Append(".config/chrome-remote-desktop").Append(filename); } void DaemonControllerLinux::DoGetConfig(const GetConfigCallback& callback) { scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue()); if (GetState() != remoting::DaemonController::STATE_NOT_IMPLEMENTED) { JsonHostConfig config(GetConfigPath()); if (config.Read()) { std::string value; if (config.GetString(kHostIdConfigPath, &value)) { result->SetString(kHostIdConfigPath, value); } if (config.GetString(kXmppLoginConfigPath, &value)) { result->SetString(kXmppLoginConfigPath, value); } } else { result.reset(); // Return NULL in case of error. } } callback.Run(result.Pass()); } void DaemonControllerLinux::DoSetConfigAndStart( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { // Add the user to chrome-remote-desktop group first. std::vector<std::string> args; args.push_back("--add-user"); int exit_code; if (!RunHostScriptWithTimeout( args, base::TimeDelta::FromSeconds(kSudoTimeoutSeconds), &exit_code) || exit_code != 0) { LOG(ERROR) << "Failed to add user to chrome-remote-desktop group."; done_callback.Run(RESULT_FAILED); return; } // Ensure the configuration directory exists. base::FilePath config_dir = GetConfigPath().DirName(); if (!base::DirectoryExists(config_dir) && !file_util::CreateDirectory(config_dir)) { LOG(ERROR) << "Failed to create config directory " << config_dir.value(); done_callback.Run(RESULT_FAILED); return; } // Write config. JsonHostConfig config_file(GetConfigPath()); if (!config_file.CopyFrom(config.get()) || !config_file.Save()) { LOG(ERROR) << "Failed to update config file."; done_callback.Run(RESULT_FAILED); return; } // Finally start the host. args.clear(); args.push_back("--start"); AsyncResult result; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoUpdateConfig( scoped_ptr<base::DictionaryValue> config, const CompletionCallback& done_callback) { JsonHostConfig config_file(GetConfigPath()); if (!config_file.Read() || !config_file.CopyFrom(config.get()) || !config_file.Save()) { LOG(ERROR) << "Failed to update config file."; done_callback.Run(RESULT_FAILED); return; } std::vector<std::string> args; args.push_back("--reload"); AsyncResult result; int exit_code; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoStop(const CompletionCallback& done_callback) { std::vector<std::string> args; args.push_back("--stop"); int exit_code = 0; AsyncResult result; if (RunHostScript(args, &exit_code)) { result = (exit_code == 0) ? RESULT_OK : RESULT_FAILED; } else { result = RESULT_FAILED; } done_callback.Run(result); } void DaemonControllerLinux::DoGetVersion( const GetVersionCallback& done_callback) { base::FilePath script_path; if (!GetScriptPath(&script_path)) { done_callback.Run(std::string()); return; } CommandLine command_line(script_path); command_line.AppendArg("--host-version"); std::string version; int exit_code = 0; int result = base::GetAppOutputWithExitCode(command_line, &version, &exit_code); if (!result || exit_code != 0) { LOG(ERROR) << "Failed to run \"" << command_line.GetCommandLineString() << "\". Exit code: " << exit_code; done_callback.Run(std::string()); return; } TrimWhitespaceASCII(version, TRIM_ALL, &version); if (!ContainsOnlyChars(version, "0123456789.")) { LOG(ERROR) << "Received invalid host version number: " << version; done_callback.Run(std::string()); return; } done_callback.Run(version); } } // namespace scoped_ptr<DaemonController> remoting::DaemonController::Create() { return scoped_ptr<DaemonController>(new DaemonControllerLinux()); } } // namespace remoting <|endoftext|>
<commit_before>#ifndef __STAN__IO__MCMC__WRITER__HPP #define __STAN__IO__MCMC__WRITER__HPP #include <ostream> #include <iomanip> #include <vector> #include <string> #include <stan/mcmc/sample.hpp> #include <stan/mcmc/base_mcmc.hpp> #include <stan/model/prob_grad.hpp> namespace stan { namespace io { template <class M> class mcmc_writer { public: mcmc_writer(std::ostream* sample_stream, std::ostream* diagnostic_stream): _sample_stream(sample_stream), _diagnostic_stream(diagnostic_stream) {} void print_sample_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_sample_stream) return; std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); model.constrained_param_names(names); (*_sample_stream) << names.at(0); for (int i = 1; i < names.size(); ++i) { (*_sample_stream) << "," << names.at(i); } (*_sample_stream) << std::endl; } void print_sample_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_sample_stream) return; std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); std::vector<double> model_values; model.write_array_params(const_cast<std::vector<double>&>(sample.cont_params()), const_cast<std::vector<int>&>(sample.disc_params()), model_values); values.insert(values.end(), model_values.begin(), model_values.end()); (*_sample_stream) << values.at(0); for (int i = 1; i < values.size(); ++i) { (*_sample_stream) << "," << values.at(i); } (*_sample_stream) << std::endl; } void print_adapt_finish(stan::mcmc::base_mcmc& sampler, std::ostream* stream) { if(!stream) return; *stream << "# Adaptation terminated" << std::endl; sampler.write_sampler_state(stream); } void print_adapt_finish(stan::mcmc::base_mcmc& sampler) { print_adapt_finish(sampler, _sample_stream); print_adapt_finish(sampler, _diagnostic_stream); } void print_diagnostic_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_diagnostic_stream) return; std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); std::vector<std::string> model_names; model.unconstrained_param_names(model_names, false, false); sampler.get_sampler_diagnostic_names(model_names, names); (*_diagnostic_stream) << names.at(0); for (int i = 1; i < names.size(); ++i) { (*_diagnostic_stream) << "," << names.at(i); } (*_diagnostic_stream) << std::endl; } void print_diagnostic_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler) { if(!_diagnostic_stream) return; std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); sampler.get_sampler_diagnostics(values); (*_diagnostic_stream) << values.at(0); for (int i = 1; i < values.size(); ++i) { (*_diagnostic_stream) << "," << values.at(i); } (*_diagnostic_stream) << std::endl; } void print_timing(double warmDeltaT, double sampleDeltaT, std::ostream* stream) { if(!stream) return; std::string prefix("Elapsed Time: "); *stream << std::endl << prefix << warmDeltaT << " seconds (Warm Up)" << std::endl << std::string(prefix.size(), ' ') << sampleDeltaT << " seconds (Sampling)" << std::endl << std::string(prefix.size(), ' ') << warmDeltaT + sampleDeltaT << " seconds (Total)" << std::endl << std::endl; } void print_timing(double warmDeltaT, double sampleDeltaT) { print_timing(warmDeltaT, sampleDeltaT, _sample_stream); print_timing(warmDeltaT, sampleDeltaT, _diagnostic_stream); print_timing(warmDeltaT, sampleDeltaT, &std::cout); } private: std::ostream* _sample_stream; std::ostream* _diagnostic_stream; }; } //io } // stan #endif<commit_msg>Don't include transformed/generated parameter names in header<commit_after>#ifndef __STAN__IO__MCMC__WRITER__HPP #define __STAN__IO__MCMC__WRITER__HPP #include <ostream> #include <iomanip> #include <vector> #include <string> #include <stan/mcmc/sample.hpp> #include <stan/mcmc/base_mcmc.hpp> #include <stan/model/prob_grad.hpp> namespace stan { namespace io { template <class M> class mcmc_writer { public: mcmc_writer(std::ostream* sample_stream, std::ostream* diagnostic_stream): _sample_stream(sample_stream), _diagnostic_stream(diagnostic_stream) {} void print_sample_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_sample_stream) return; std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); model.constrained_param_names(names, false, false); (*_sample_stream) << names.at(0); for (int i = 1; i < names.size(); ++i) { (*_sample_stream) << "," << names.at(i); } (*_sample_stream) << std::endl; } void print_sample_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_sample_stream) return; std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); std::vector<double> model_values; model.write_array_params(const_cast<std::vector<double>&>(sample.cont_params()), const_cast<std::vector<int>&>(sample.disc_params()), model_values); values.insert(values.end(), model_values.begin(), model_values.end()); (*_sample_stream) << values.at(0); for (int i = 1; i < values.size(); ++i) { (*_sample_stream) << "," << values.at(i); } (*_sample_stream) << std::endl; } void print_adapt_finish(stan::mcmc::base_mcmc& sampler, std::ostream* stream) { if(!stream) return; *stream << "# Adaptation terminated" << std::endl; sampler.write_sampler_state(stream); } void print_adapt_finish(stan::mcmc::base_mcmc& sampler) { print_adapt_finish(sampler, _sample_stream); print_adapt_finish(sampler, _diagnostic_stream); } void print_diagnostic_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, M& model) { if(!_diagnostic_stream) return; std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); std::vector<std::string> model_names; model.unconstrained_param_names(model_names, false, false); sampler.get_sampler_diagnostic_names(model_names, names); (*_diagnostic_stream) << names.at(0); for (int i = 1; i < names.size(); ++i) { (*_diagnostic_stream) << "," << names.at(i); } (*_diagnostic_stream) << std::endl; } void print_diagnostic_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler) { if(!_diagnostic_stream) return; std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); sampler.get_sampler_diagnostics(values); (*_diagnostic_stream) << values.at(0); for (int i = 1; i < values.size(); ++i) { (*_diagnostic_stream) << "," << values.at(i); } (*_diagnostic_stream) << std::endl; } void print_timing(double warmDeltaT, double sampleDeltaT, std::ostream* stream) { if(!stream) return; std::string prefix("Elapsed Time: "); *stream << std::endl << prefix << warmDeltaT << " seconds (Warm Up)" << std::endl << std::string(prefix.size(), ' ') << sampleDeltaT << " seconds (Sampling)" << std::endl << std::string(prefix.size(), ' ') << warmDeltaT + sampleDeltaT << " seconds (Total)" << std::endl << std::endl; } void print_timing(double warmDeltaT, double sampleDeltaT) { print_timing(warmDeltaT, sampleDeltaT, _sample_stream); print_timing(warmDeltaT, sampleDeltaT, _diagnostic_stream); print_timing(warmDeltaT, sampleDeltaT, &std::cout); } private: std::ostream* _sample_stream; std::ostream* _diagnostic_stream; }; } //io } // stan #endif<|endoftext|>
<commit_before><commit_msg>loplugin:literaltoboolconversion<commit_after><|endoftext|>
<commit_before>/* * Number Theory Functions * (C) 1999-2011 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/internal/bit_ops.h> #include <algorithm> namespace Botan { namespace { /* * Miller-Rabin Primality Tester */ class MillerRabin_Test { public: bool is_witness(const BigInt& nonce); MillerRabin_Test(const BigInt& num); private: BigInt n, r, n_minus_1; size_t s; Fixed_Exponent_Power_Mod pow_mod; Modular_Reducer reducer; }; /* * Miller-Rabin Test, as described in Handbook of Applied Cryptography * section 4.24 */ bool MillerRabin_Test::is_witness(const BigInt& a) { if(a < 2 || a >= n_minus_1) throw Invalid_Argument("Bad size for nonce in Miller-Rabin test"); BigInt y = pow_mod(a); if(y == 1 || y == n_minus_1) return false; for(size_t i = 1; i != s; ++i) { y = reducer.square(y); if(y == 1) // found a non-trivial square root return true; if(y == n_minus_1) // -1, trivial square root, so give up return false; } if(y != n_minus_1) // fails Fermat test return true; return false; } /* * Miller-Rabin Constructor */ MillerRabin_Test::MillerRabin_Test(const BigInt& num) { if(num.is_even() || num < 3) throw Invalid_Argument("MillerRabin_Test: Invalid number for testing"); n = num; n_minus_1 = n - 1; s = low_zero_bits(n_minus_1); r = n_minus_1 >> s; pow_mod = Fixed_Exponent_Power_Mod(r, n); reducer = Modular_Reducer(n); } /* * Miller-Rabin Iterations */ size_t miller_rabin_test_iterations(size_t bits, size_t level) { struct mapping { size_t bits; size_t verify_iter; size_t check_iter; }; const mapping tests[] = { { 50, 55, 25 }, { 100, 38, 22 }, { 160, 32, 18 }, { 163, 31, 17 }, { 168, 30, 16 }, { 177, 29, 16 }, { 181, 28, 15 }, { 185, 27, 15 }, { 190, 26, 15 }, { 195, 25, 14 }, { 201, 24, 14 }, { 208, 23, 14 }, { 215, 22, 13 }, { 222, 21, 13 }, { 231, 20, 13 }, { 241, 19, 12 }, { 252, 18, 12 }, { 264, 17, 12 }, { 278, 16, 11 }, { 294, 15, 10 }, { 313, 14, 9 }, { 334, 13, 8 }, { 360, 12, 8 }, { 392, 11, 7 }, { 430, 10, 7 }, { 479, 9, 6 }, { 542, 8, 6 }, { 626, 7, 5 }, { 746, 6, 4 }, { 926, 5, 3 }, { 1232, 4, 2 }, { 1853, 3, 2 }, { 0, 0, 0 } }; for(size_t i = 0; tests[i].bits; ++i) { if(bits <= tests[i].bits) { if(level >= 2) return tests[i].verify_iter; else if(level == 1) return tests[i].check_iter; else if(level == 0) return std::max<size_t>(tests[i].check_iter / 4, 1); } } return level > 0 ? 2 : 1; // for large inputs } } /* * Return the number of 0 bits at the end of n */ size_t low_zero_bits(const BigInt& n) { size_t low_zero = 0; if(n.is_positive() && n.is_nonzero()) { for(size_t i = 0; i != n.size(); ++i) { word x = n[i]; if(x) { low_zero += ctz(x); break; } else low_zero += BOTAN_MP_WORD_BITS; } } return low_zero; } /* * Calculate the GCD */ BigInt gcd(const BigInt& a, const BigInt& b) { if(a.is_zero() || b.is_zero()) return 0; if(a == 1 || b == 1) return 1; BigInt x = a, y = b; x.set_sign(BigInt::Positive); y.set_sign(BigInt::Positive); size_t shift = std::min(low_zero_bits(x), low_zero_bits(y)); x >>= shift; y >>= shift; while(x.is_nonzero()) { x >>= low_zero_bits(x); y >>= low_zero_bits(y); if(x >= y) { x -= y; x >>= 1; } else { y -= x; y >>= 1; } } return (y << shift); } /* * Calculate the LCM */ BigInt lcm(const BigInt& a, const BigInt& b) { return ((a * b) / gcd(a, b)); } namespace { /* * If the modulus is odd, then we can avoid computing A and C. This is * a critical path algorithm in some instances and an odd modulus is * the common case for crypto, so worth special casing. See note 14.64 * in Handbook of Applied Cryptography for more details. */ BigInt inverse_mod_odd_modulus(const BigInt& n, const BigInt& mod) { BigInt u = mod, v = n; BigInt B = 0, D = 1; while(u.is_nonzero()) { const size_t u_zero_bits = low_zero_bits(u); u >>= u_zero_bits; for(size_t i = 0; i != u_zero_bits; ++i) { if(B.is_odd()) { B -= mod; } B >>= 1; } const size_t v_zero_bits = low_zero_bits(v); v >>= v_zero_bits; for(size_t i = 0; i != v_zero_bits; ++i) { if(D.is_odd()) { D -= mod; } D >>= 1; } if(u >= v) { u -= v; B -= D; } else { v -= u; D -= B; } } if(v != 1) return 0; // no modular inverse while(D.is_negative()) D += mod; while(D >= mod) D -= mod; return D; } } /* * Find the Modular Inverse */ BigInt inverse_mod(const BigInt& n, const BigInt& mod) { if(mod.is_zero()) throw BigInt::DivideByZero(); if(mod.is_negative() || n.is_negative()) throw Invalid_Argument("inverse_mod: arguments must be non-negative"); if(n.is_zero() || (n.is_even() && mod.is_even())) return 0; // fast fail checks if(mod.is_odd()) return inverse_mod_odd_modulus(n, mod); BigInt u = mod, v = n; BigInt A = 1, B = 0, C = 0, D = 1; while(u.is_nonzero()) { const size_t u_zero_bits = low_zero_bits(u); u >>= u_zero_bits; for(size_t i = 0; i != u_zero_bits; ++i) { if(A.is_odd() || B.is_odd()) { A += n; B -= mod; } A >>= 1; B >>= 1; } const size_t v_zero_bits = low_zero_bits(v); v >>= v_zero_bits; for(size_t i = 0; i != v_zero_bits; ++i) { if(C.is_odd() || D.is_odd()) { C += n; D -= mod; } C >>= 1; D >>= 1; } if(u >= v) { u -= v; A -= C; B -= D; } else { v -= u; C -= A; D -= B; } } if(v != 1) return 0; // no modular inverse while(D.is_negative()) D += mod; while(D >= mod) D -= mod; return D; } /* * Modular Exponentiation */ BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod) { Power_Mod pow_mod(mod); /* * Calling set_base before set_exponent means we end up using a * minimal window. This makes sense given that here we know that any * precomputation is wasted. */ pow_mod.set_base(base); pow_mod.set_exponent(exp); return pow_mod.execute(); } /* * Test for primaility using Miller-Rabin */ bool primality_test(const BigInt& n, RandomNumberGenerator& rng, size_t level) { const size_t PREF_NONCE_BITS = 64; if(n == 2) return true; if(n <= 1 || n.is_even()) return false; // Fast path testing for small numbers (<= 65521) if(n <= PRIMES[PRIME_TABLE_SIZE-1]) { const word num = n.word_at(0); for(size_t i = 0; PRIMES[i]; ++i) { if(num == PRIMES[i]) return true; if(num < PRIMES[i]) return false; } return false; } if(level > 2) level = 2; const size_t NONCE_BITS = std::min(n.bits() - 2, PREF_NONCE_BITS); MillerRabin_Test mr(n); const size_t tests = miller_rabin_test_iterations(n.bits(), level); BigInt nonce; for(size_t i = 0; i != tests; ++i) { while(nonce < 2 || nonce >= (n-1)) nonce.randomize(rng, NONCE_BITS); if(mr.is_witness(nonce)) return false; } return true; } } <commit_msg>Increase default Miller-Rabin nonce to 192 bits<commit_after>/* * Number Theory Functions * (C) 1999-2011 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/internal/bit_ops.h> #include <algorithm> namespace Botan { namespace { /* * Miller-Rabin Primality Tester */ class MillerRabin_Test { public: bool is_witness(const BigInt& nonce); MillerRabin_Test(const BigInt& num); private: BigInt n, r, n_minus_1; size_t s; Fixed_Exponent_Power_Mod pow_mod; Modular_Reducer reducer; }; /* * Miller-Rabin Test, as described in Handbook of Applied Cryptography * section 4.24 */ bool MillerRabin_Test::is_witness(const BigInt& a) { if(a < 2 || a >= n_minus_1) throw Invalid_Argument("Bad size for nonce in Miller-Rabin test"); BigInt y = pow_mod(a); if(y == 1 || y == n_minus_1) return false; for(size_t i = 1; i != s; ++i) { y = reducer.square(y); if(y == 1) // found a non-trivial square root return true; if(y == n_minus_1) // -1, trivial square root, so give up return false; } if(y != n_minus_1) // fails Fermat test return true; return false; } /* * Miller-Rabin Constructor */ MillerRabin_Test::MillerRabin_Test(const BigInt& num) { if(num.is_even() || num < 3) throw Invalid_Argument("MillerRabin_Test: Invalid number for testing"); n = num; n_minus_1 = n - 1; s = low_zero_bits(n_minus_1); r = n_minus_1 >> s; pow_mod = Fixed_Exponent_Power_Mod(r, n); reducer = Modular_Reducer(n); } /* * Miller-Rabin Iterations */ size_t miller_rabin_test_iterations(size_t bits, size_t level) { struct mapping { size_t bits; size_t verify_iter; size_t check_iter; }; const mapping tests[] = { { 50, 55, 25 }, { 100, 38, 22 }, { 160, 32, 18 }, { 163, 31, 17 }, { 168, 30, 16 }, { 177, 29, 16 }, { 181, 28, 15 }, { 185, 27, 15 }, { 190, 26, 15 }, { 195, 25, 14 }, { 201, 24, 14 }, { 208, 23, 14 }, { 215, 22, 13 }, { 222, 21, 13 }, { 231, 20, 13 }, { 241, 19, 12 }, { 252, 18, 12 }, { 264, 17, 12 }, { 278, 16, 11 }, { 294, 15, 10 }, { 313, 14, 9 }, { 334, 13, 8 }, { 360, 12, 8 }, { 392, 11, 7 }, { 430, 10, 7 }, { 479, 9, 6 }, { 542, 8, 6 }, { 626, 7, 5 }, { 746, 6, 4 }, { 926, 5, 3 }, { 1232, 4, 2 }, { 1853, 3, 2 }, { 0, 0, 0 } }; for(size_t i = 0; tests[i].bits; ++i) { if(bits <= tests[i].bits) { if(level >= 2) return tests[i].verify_iter; else if(level == 1) return tests[i].check_iter; else if(level == 0) return std::max<size_t>(tests[i].check_iter / 4, 1); } } return level > 0 ? 2 : 1; // for large inputs } } /* * Return the number of 0 bits at the end of n */ size_t low_zero_bits(const BigInt& n) { size_t low_zero = 0; if(n.is_positive() && n.is_nonzero()) { for(size_t i = 0; i != n.size(); ++i) { word x = n[i]; if(x) { low_zero += ctz(x); break; } else low_zero += BOTAN_MP_WORD_BITS; } } return low_zero; } /* * Calculate the GCD */ BigInt gcd(const BigInt& a, const BigInt& b) { if(a.is_zero() || b.is_zero()) return 0; if(a == 1 || b == 1) return 1; BigInt x = a, y = b; x.set_sign(BigInt::Positive); y.set_sign(BigInt::Positive); size_t shift = std::min(low_zero_bits(x), low_zero_bits(y)); x >>= shift; y >>= shift; while(x.is_nonzero()) { x >>= low_zero_bits(x); y >>= low_zero_bits(y); if(x >= y) { x -= y; x >>= 1; } else { y -= x; y >>= 1; } } return (y << shift); } /* * Calculate the LCM */ BigInt lcm(const BigInt& a, const BigInt& b) { return ((a * b) / gcd(a, b)); } namespace { /* * If the modulus is odd, then we can avoid computing A and C. This is * a critical path algorithm in some instances and an odd modulus is * the common case for crypto, so worth special casing. See note 14.64 * in Handbook of Applied Cryptography for more details. */ BigInt inverse_mod_odd_modulus(const BigInt& n, const BigInt& mod) { BigInt u = mod, v = n; BigInt B = 0, D = 1; while(u.is_nonzero()) { const size_t u_zero_bits = low_zero_bits(u); u >>= u_zero_bits; for(size_t i = 0; i != u_zero_bits; ++i) { if(B.is_odd()) { B -= mod; } B >>= 1; } const size_t v_zero_bits = low_zero_bits(v); v >>= v_zero_bits; for(size_t i = 0; i != v_zero_bits; ++i) { if(D.is_odd()) { D -= mod; } D >>= 1; } if(u >= v) { u -= v; B -= D; } else { v -= u; D -= B; } } if(v != 1) return 0; // no modular inverse while(D.is_negative()) D += mod; while(D >= mod) D -= mod; return D; } } /* * Find the Modular Inverse */ BigInt inverse_mod(const BigInt& n, const BigInt& mod) { if(mod.is_zero()) throw BigInt::DivideByZero(); if(mod.is_negative() || n.is_negative()) throw Invalid_Argument("inverse_mod: arguments must be non-negative"); if(n.is_zero() || (n.is_even() && mod.is_even())) return 0; // fast fail checks if(mod.is_odd()) return inverse_mod_odd_modulus(n, mod); BigInt u = mod, v = n; BigInt A = 1, B = 0, C = 0, D = 1; while(u.is_nonzero()) { const size_t u_zero_bits = low_zero_bits(u); u >>= u_zero_bits; for(size_t i = 0; i != u_zero_bits; ++i) { if(A.is_odd() || B.is_odd()) { A += n; B -= mod; } A >>= 1; B >>= 1; } const size_t v_zero_bits = low_zero_bits(v); v >>= v_zero_bits; for(size_t i = 0; i != v_zero_bits; ++i) { if(C.is_odd() || D.is_odd()) { C += n; D -= mod; } C >>= 1; D >>= 1; } if(u >= v) { u -= v; A -= C; B -= D; } else { v -= u; C -= A; D -= B; } } if(v != 1) return 0; // no modular inverse while(D.is_negative()) D += mod; while(D >= mod) D -= mod; return D; } /* * Modular Exponentiation */ BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod) { Power_Mod pow_mod(mod); /* * Calling set_base before set_exponent means we end up using a * minimal window. This makes sense given that here we know that any * precomputation is wasted. */ pow_mod.set_base(base); pow_mod.set_exponent(exp); return pow_mod.execute(); } /* * Test for primaility using Miller-Rabin */ bool primality_test(const BigInt& n, RandomNumberGenerator& rng, size_t level) { if(n == 2) return true; if(n <= 1 || n.is_even()) return false; // Fast path testing for small numbers (<= 65521) if(n <= PRIMES[PRIME_TABLE_SIZE-1]) { const word num = n.word_at(0); for(size_t i = 0; PRIMES[i]; ++i) { if(num == PRIMES[i]) return true; if(num < PRIMES[i]) return false; } return false; } if(level > 2) level = 2; const size_t PREF_NONCE_BITS = 192; const size_t NONCE_BITS = std::min(n.bits() - 2, PREF_NONCE_BITS); MillerRabin_Test mr(n); const size_t tests = miller_rabin_test_iterations(n.bits(), level); BigInt nonce; for(size_t i = 0; i != tests; ++i) { while(nonce < 2 || nonce >= (n-1)) nonce.randomize(rng, NONCE_BITS); if(mr.is_witness(nonce)) return false; } return true; } } <|endoftext|>
<commit_before>// // Copyright Silvin Lubecki 2010 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include "Test.h" #include "openclam/cl.hpp" #include <math.h> #include <CL/cl.h> namespace { void *srcA, *srcB, *dst; void* Golden; cl_context cxGPUContext; cl_command_queue cqCommandQue; cl_device_id* cdDevices; cl_program cpProgram; cl_kernel ckKernel; cl_mem cmDevSrcA; cl_mem cmDevSrcB; cl_mem cmDevDst; size_t szGlobalWorkSize; size_t szLocalWorkSize; size_t szParmDataBytes; size_t szKernelLength; cl_int ciErr1, ciErr2; char* cPathAndName = NULL; char* cSourceCL = NULL; int iNumElements = 11444777; KERNEL( const char * addKernel, void VectorAdd( GLOBAL const float* a, GLOBAL const float* b, GLOBAL float* c, int iNumElements ) { const int iGID = get_global_id( 0 ); if( iGID >= iNumElements ) return; c[ iGID ] = a[ iGID ] + b[ iGID ]; } ); size_t shrRoundUp( int group_size, int global_size ) { int r = global_size % group_size; if( r == 0 ) return global_size; return global_size + group_size - r; } void shrFillArray( float* pfData, int iSize ) { int i; const float fScale = 1.0f / (float)RAND_MAX; for( i = 0; i < iSize; ++i ) pfData[i] = fScale * rand(); } int shrDiffArray( const float* pfResult1, const float* pfResult2, int iNumElements ) { int iErrorCount = 0, i; for( i = 0; i < iNumElements; i++ ) if( fabs( pfResult2[ i ] - pfResult1[ i ] ) > 1e-5 ) iErrorCount++; return iErrorCount; } // "Golden" Host processing vector addition function for comparison purposes // ********************************************************************* void VectorAddHost( const float* pfData1, const float* pfData2, float* pfResult, int iNumElements ) { int i; for ( i = 0; i < iNumElements; i++ ) pfResult[ i ] = pfData1[ i ] + pfData2[ i ]; } } BOOST_AUTO_TEST_CASE( test3 ) { // set and log Global and Local work size dimensions szLocalWorkSize = 256; szGlobalWorkSize = shrRoundUp( (int)szLocalWorkSize, iNumElements ); // rounded up to the nearest multiple of the LocalWorkSize // Allocate and initialize host arrays srcA = (void *)malloc( sizeof( cl_float ) * szGlobalWorkSize ); srcB = (void *)malloc( sizeof( cl_float ) * szGlobalWorkSize ); dst = (void *)malloc( sizeof(cl_float ) * szGlobalWorkSize ); Golden = (void *)malloc( sizeof(cl_float) * iNumElements ); shrFillArray( (float*)srcA, iNumElements ); shrFillArray( (float*)srcB, iNumElements ); // Create the OpenCL context on a GPU device cxGPUContext = clCreateContextFromType( 0, CL_DEVICE_TYPE_GPU, NULL, NULL, &ciErr1 ); // Get the list of GPU devices associated with context ciErr1 = clGetContextInfo( cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes ); cdDevices = ( cl_device_id* )malloc( szParmDataBytes ); ciErr1 |= clGetContextInfo( cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL ); // Create a command-queue cqCommandQue = clCreateCommandQueue( cxGPUContext, cdDevices[ 0 ], 0, &ciErr1 ); // Allocate the OpenCL buffer memory objects for source and result on the device GMEM cmDevSrcA = clCreateBuffer( cxGPUContext, CL_MEM_READ_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr1 ); cmDevSrcB = clCreateBuffer( cxGPUContext, CL_MEM_READ_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr2 ); ciErr1 |= ciErr2; cmDevDst = clCreateBuffer( cxGPUContext, CL_MEM_WRITE_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr2 ); ciErr1 |= ciErr2; // Create the program szKernelLength = strlen( addKernel ); cpProgram = clCreateProgramWithSource( cxGPUContext, 1, (const char **)&addKernel, &szKernelLength, &ciErr1 ); // Build the program ciErr1 = clBuildProgram( cpProgram, 0, NULL, NULL, NULL, NULL ); // Create the kernel ckKernel = clCreateKernel( cpProgram, "VectorAdd", &ciErr1 ); // Set the Argument values ciErr1 = clSetKernelArg( ckKernel, 0, sizeof(cl_mem), (void*)&cmDevSrcA ); ciErr1 |= clSetKernelArg( ckKernel, 1, sizeof(cl_mem), (void*)&cmDevSrcB ); ciErr1 |= clSetKernelArg( ckKernel, 2, sizeof(cl_mem), (void*)&cmDevDst ); ciErr1 |= clSetKernelArg( ckKernel, 3, sizeof(cl_int), (void*)&iNumElements ); // -------------------------------------------------------- // Start Core sequence... copy input data to GPU, compute, copy results back // Asynchronous write of data to GPU device ciErr1 = clEnqueueWriteBuffer( cqCommandQue, cmDevSrcA, CL_FALSE, 0, sizeof(cl_float) * szGlobalWorkSize, srcA, 0, NULL, NULL ); ciErr1 |= clEnqueueWriteBuffer( cqCommandQue, cmDevSrcB, CL_FALSE, 0, sizeof(cl_float) * szGlobalWorkSize, srcB, 0, NULL, NULL ); // Launch kernel ciErr1 = clEnqueueNDRangeKernel( cqCommandQue, ckKernel, 1, NULL, &szGlobalWorkSize, &szLocalWorkSize, 0, NULL, NULL ); // Synchronous/blocking read of results, and check accumulated errors ciErr1 = clEnqueueReadBuffer( cqCommandQue, cmDevDst, CL_TRUE, 0, sizeof(cl_float) * szGlobalWorkSize, dst, 0, NULL, NULL ); //-------------------------------------------------------- // Compute and compare results for golden-host and report errors and pass/fail VectorAddHost( (const float*)srcA, (const float*)srcB, (float*)Golden, iNumElements ); BOOST_CHECK_EQUAL( 0, shrDiffArray(( const float*)dst, (const float*)Golden, iNumElements ) ); free( srcA ); free( srcB ); free( dst ); free( Golden ); free( cdDevices ); } <commit_msg>clean up<commit_after>// // Copyright Silvin Lubecki 2010 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include "Test.h" #include "openclam/cl.hpp" #include <CL/cl.h> namespace { void *srcA, *srcB, *dst; void* Golden; cl_context cxGPUContext; cl_command_queue cqCommandQue; cl_device_id* cdDevices; cl_program cpProgram; cl_kernel ckKernel; cl_mem cmDevSrcA; cl_mem cmDevSrcB; cl_mem cmDevDst; size_t szGlobalWorkSize; size_t szLocalWorkSize; size_t szParmDataBytes; size_t szKernelLength; cl_int ciErr1, ciErr2; char* cPathAndName = NULL; char* cSourceCL = NULL; int iNumElements = 11444777; KERNEL( const char * addKernel, void VectorAdd( GLOBAL const float* a, GLOBAL const float* b, GLOBAL float* c, int iNumElements ) { const int iGID = get_global_id( 0 ); if( iGID >= iNumElements ) return; c[ iGID ] = a[ iGID ] + b[ iGID ]; } ); size_t shrRoundUp( int group_size, int global_size ) { int r = global_size % group_size; if( r == 0 ) return global_size; return global_size + group_size - r; } void shrFillArray( float* pfData, int iSize ) { int i; const float fScale = 1.0f / (float)RAND_MAX; for( i = 0; i < iSize; ++i ) pfData[i] = fScale * rand(); } int shrDiffArray( const float* pfResult1, const float* pfResult2, int iNumElements ) { int iErrorCount = 0, i; for( i = 0; i < iNumElements; i++ ) if( std::abs( pfResult2[ i ] - pfResult1[ i ] ) > 1e-5 ) iErrorCount++; return iErrorCount; } // "Golden" Host processing vector addition function for comparison purposes // ********************************************************************* void VectorAddHost( const float* pfData1, const float* pfData2, float* pfResult, int iNumElements ) { int i; for ( i = 0; i < iNumElements; i++ ) pfResult[ i ] = pfData1[ i ] + pfData2[ i ]; } } BOOST_AUTO_TEST_CASE( test3 ) { // set and log Global and Local work size dimensions szLocalWorkSize = 256; szGlobalWorkSize = shrRoundUp( (int)szLocalWorkSize, iNumElements ); // rounded up to the nearest multiple of the LocalWorkSize // Allocate and initialize host arrays srcA = (void *)malloc( sizeof( cl_float ) * szGlobalWorkSize ); srcB = (void *)malloc( sizeof( cl_float ) * szGlobalWorkSize ); dst = (void *)malloc( sizeof(cl_float ) * szGlobalWorkSize ); Golden = (void *)malloc( sizeof(cl_float) * iNumElements ); shrFillArray( (float*)srcA, iNumElements ); shrFillArray( (float*)srcB, iNumElements ); // Create the OpenCL context on a GPU device cxGPUContext = clCreateContextFromType( 0, CL_DEVICE_TYPE_GPU, NULL, NULL, &ciErr1 ); // Get the list of GPU devices associated with context ciErr1 = clGetContextInfo( cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes ); cdDevices = ( cl_device_id* )malloc( szParmDataBytes ); ciErr1 |= clGetContextInfo( cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL ); // Create a command-queue cqCommandQue = clCreateCommandQueue( cxGPUContext, cdDevices[ 0 ], 0, &ciErr1 ); // Allocate the OpenCL buffer memory objects for source and result on the device GMEM cmDevSrcA = clCreateBuffer( cxGPUContext, CL_MEM_READ_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr1 ); cmDevSrcB = clCreateBuffer( cxGPUContext, CL_MEM_READ_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr2 ); ciErr1 |= ciErr2; cmDevDst = clCreateBuffer( cxGPUContext, CL_MEM_WRITE_ONLY, sizeof(cl_float) * szGlobalWorkSize, NULL, &ciErr2 ); ciErr1 |= ciErr2; // Create the program szKernelLength = strlen( addKernel ); cpProgram = clCreateProgramWithSource( cxGPUContext, 1, (const char **)&addKernel, &szKernelLength, &ciErr1 ); // Build the program ciErr1 = clBuildProgram( cpProgram, 0, NULL, NULL, NULL, NULL ); // Create the kernel ckKernel = clCreateKernel( cpProgram, "VectorAdd", &ciErr1 ); // Set the Argument values ciErr1 = clSetKernelArg( ckKernel, 0, sizeof(cl_mem), (void*)&cmDevSrcA ); ciErr1 |= clSetKernelArg( ckKernel, 1, sizeof(cl_mem), (void*)&cmDevSrcB ); ciErr1 |= clSetKernelArg( ckKernel, 2, sizeof(cl_mem), (void*)&cmDevDst ); ciErr1 |= clSetKernelArg( ckKernel, 3, sizeof(cl_int), (void*)&iNumElements ); // -------------------------------------------------------- // Start Core sequence... copy input data to GPU, compute, copy results back // Asynchronous write of data to GPU device ciErr1 = clEnqueueWriteBuffer( cqCommandQue, cmDevSrcA, CL_FALSE, 0, sizeof(cl_float) * szGlobalWorkSize, srcA, 0, NULL, NULL ); ciErr1 |= clEnqueueWriteBuffer( cqCommandQue, cmDevSrcB, CL_FALSE, 0, sizeof(cl_float) * szGlobalWorkSize, srcB, 0, NULL, NULL ); // Launch kernel ciErr1 = clEnqueueNDRangeKernel( cqCommandQue, ckKernel, 1, NULL, &szGlobalWorkSize, &szLocalWorkSize, 0, NULL, NULL ); // Synchronous/blocking read of results, and check accumulated errors ciErr1 = clEnqueueReadBuffer( cqCommandQue, cmDevDst, CL_TRUE, 0, sizeof(cl_float) * szGlobalWorkSize, dst, 0, NULL, NULL ); //-------------------------------------------------------- // Compute and compare results for golden-host and report errors and pass/fail VectorAddHost( (const float*)srcA, (const float*)srcB, (float*)Golden, iNumElements ); BOOST_CHECK_EQUAL( 0, shrDiffArray(( const float*)dst, (const float*)Golden, iNumElements ) ); free( srcA ); free( srcB ); free( dst ); free( Golden ); free( cdDevices ); } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <iostream> typedef std::vector<std::string> nomi_squadre_t; typedef std::vector<unsigned int> punti_giornata_t; typedef std::vector<punti_giornata_t> punti_giornate_t; int trova_indice_squadra(nomi_squadre_t nomi_squadre, std::string nome_squadra) { for (unsigned int i = 0; i < nomi_squadre.size(); i++) { if (nomi_squadre[i] == nome_squadra) { return i; } } return -1; } int trova_punti_squadra(unsigned int indice_squadra, punti_giornate_t punti_giornate) { unsigned int punti = 0; unsigned int i; for (i = 0; i < punti_giornate.size(); i++) { punti += punti_giornate[i][indice_squadra]; } return punti; } std::vector<unsigned int> trova_punti_squadre(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { std::vector<unsigned int> punti_squadre; punti_squadre.resize(nomi_squadre.size(), 0); for (unsigned int i = 0; i < nomi_squadre.size(); i++) { punti_squadre[i] = trova_punti_squadra(i, punti_giornate); } return punti_squadre; } std::vector<unsigned int> trova_vincitori_giornata(unsigned int giornata, punti_giornate_t punti_giornate) { unsigned int i; std::vector<unsigned int> vincitori; for (i = 0; i < punti_giornate[giornata - 1].size(); i++) { if (punti_giornate[giornata - 1][i] == 3) { vincitori.push_back(i); } } return vincitori; } unsigned int trova_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int i, indice_vincitore, punti_vincitore = 0; std::vector<unsigned int> punti_squadre = trova_punti_squadre(nomi_squadre, punti_giornate); for (i = 0; i < punti_squadre.size(); i++) { if (punti_squadre[i] > punti_vincitore) { punti_vincitore = punti_squadre[i]; indice_vincitore = i; } } return indice_vincitore; } void inizializzazione(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate) { unsigned int numero_giornate, numero_squadre; unsigned int i; std::cout << "Inserisci il numero di giornate: "; std::cin >> numero_giornate; std::cout << "Inserisci il numero di squadre: "; std::cin >> numero_squadre; nomi_squadre.resize(numero_squadre); punti_giornate.resize(numero_giornate); for (i = 0; i < punti_giornate.size(); i++) { punti_giornate[i].resize(numero_squadre); } } void caricamento(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate) { unsigned int i, j; for (i = 0; i < nomi_squadre.size(); i++) { std::cout << "Inserisci il nome della squadra " << i + 1 << ": "; std::cin >> nomi_squadre[i]; } std::cout << std::endl; for (i = 0; i < punti_giornate.size(); i++) { for (j = 0; j < nomi_squadre.size(); j++) { do { std::cout << "Inserisci punti " << nomi_squadre[j] << " (giornata " << i + 1 << "): "; std::cin >> punti_giornate[i][j]; } while (punti_giornate[i][j] != 0 && punti_giornate[i][j] != 1 && punti_giornate[i][j] != 3); } std::cout << std::endl; } } void mostra_vincitori_giornata(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int i; unsigned int giornata; std::vector<unsigned int> vincitori; do { std::cout << "Di quale giornata vuoi sapere i vincitori? "; std::cin >> giornata; } while (giornata < 1 || giornata > punti_giornate.size()); std::cout << std::endl; vincitori = trova_vincitori_giornata(giornata, punti_giornate); for (i = 0; i < vincitori.size(); i++) { std::cout << "La squadra " << nomi_squadre[vincitori[i]] << " ha vinto la giornata " << giornata << "." << std::endl; } } void mostra_punti_squadra(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { std::string nome_squadra; int indice_squadra; unsigned int punti; do { std::cout << "Di quale squadra vuoi conoscere i punti? "; std::cin >> nome_squadra; indice_squadra = trova_indice_squadra(nomi_squadre, nome_squadra); } while (indice_squadra == -1); std::cout << std::endl; punti = trova_punti_squadra(indice_squadra, punti_giornate); std::cout << "La squadra " << nome_squadra << " ha totalizzato " << punti << " punti." << std::endl; } void mostra_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int indice_vincitore; indice_vincitore = trova_vincitore_campionato(nomi_squadre, punti_giornate); std::cout << "La squadra che ha vinto il campionato è " << nomi_squadre[indice_vincitore] << "." << std::endl; } int main() { nomi_squadre_t nomi_squadre; punti_giornate_t punti_giornate; unsigned int scelta; inizializzazione(nomi_squadre, punti_giornate); std::cout << std::endl; caricamento(nomi_squadre, punti_giornate); do { std::cout << "1. Vincitori giornata" << std::endl; std::cout << "2. Punti squadra" << std::endl; std::cout << "3. Vincitore campionato" << std::endl; std::cout << "0. Uscita" << std::endl; std::cout << std::endl; std::cout << "Inserisci un'opzione: "; std::cin >> scelta; if (scelta != 0) { std::cout << std::endl; } switch (scelta) { case 1: mostra_vincitori_giornata(nomi_squadre, punti_giornate); break; case 2: mostra_punti_squadra(nomi_squadre, punti_giornate); break; case 3: mostra_vincitore_campionato(nomi_squadre, punti_giornate); break; case 0: break; default: std::cout << "Scelta non valida." << std::endl; } if (scelta != 0) { std::cout << std::endl; } } while (scelta != 0); return 0; } <commit_msg>Extract some request methods<commit_after>#include <string> #include <vector> #include <iostream> typedef std::vector<std::string> nomi_squadre_t; typedef std::vector<unsigned int> punti_giornata_t; typedef std::vector<punti_giornata_t> punti_giornate_t; int trova_indice_squadra(nomi_squadre_t nomi_squadre, std::string nome_squadra) { for (unsigned int i = 0; i < nomi_squadre.size(); i++) { if (nomi_squadre[i] == nome_squadra) { return i; } } return -1; } int trova_punti_squadra(unsigned int indice_squadra, punti_giornate_t punti_giornate) { unsigned int punti = 0; unsigned int i; for (i = 0; i < punti_giornate.size(); i++) { punti += punti_giornate[i][indice_squadra]; } return punti; } std::vector<unsigned int> trova_punti_squadre(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { std::vector<unsigned int> punti_squadre; punti_squadre.resize(nomi_squadre.size(), 0); for (unsigned int i = 0; i < nomi_squadre.size(); i++) { punti_squadre[i] = trova_punti_squadra(i, punti_giornate); } return punti_squadre; } std::vector<unsigned int> trova_vincitori_giornata(unsigned int giornata, punti_giornate_t punti_giornate) { unsigned int i; std::vector<unsigned int> vincitori; for (i = 0; i < punti_giornate[giornata - 1].size(); i++) { if (punti_giornate[giornata - 1][i] == 3) { vincitori.push_back(i); } } return vincitori; } unsigned int trova_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int i, indice_vincitore, punti_vincitore = 0; std::vector<unsigned int> punti_squadre = trova_punti_squadre(nomi_squadre, punti_giornate); for (i = 0; i < punti_squadre.size(); i++) { if (punti_squadre[i] > punti_vincitore) { punti_vincitore = punti_squadre[i]; indice_vincitore = i; } } return indice_vincitore; } unsigned int chiedi_giornata(punti_giornate_t punti_giornate) { unsigned int giornata; do { std::cout << "Di quale giornata vuoi sapere i vincitori? "; std::cin >> giornata; } while (giornata < 1 || giornata > punti_giornate.size()); return giornata; } unsigned int chiedi_squadra(nomi_squadre_t nomi_squadre) { int indice_squadra; std::string nome_squadra; do { std::cout << "Di quale squadra vuoi conoscere i punti? "; std::cin >> nome_squadra; indice_squadra = trova_indice_squadra(nomi_squadre, nome_squadra); } while (indice_squadra == -1); return indice_squadra; } void inizializzazione(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate) { unsigned int numero_giornate, numero_squadre; unsigned int i; std::cout << "Inserisci il numero di giornate: "; std::cin >> numero_giornate; std::cout << "Inserisci il numero di squadre: "; std::cin >> numero_squadre; nomi_squadre.resize(numero_squadre); punti_giornate.resize(numero_giornate); for (i = 0; i < punti_giornate.size(); i++) { punti_giornate[i].resize(numero_squadre); } } void caricamento(nomi_squadre_t& nomi_squadre, punti_giornate_t& punti_giornate) { unsigned int i, j; for (i = 0; i < nomi_squadre.size(); i++) { std::cout << "Inserisci il nome della squadra " << i + 1 << ": "; std::cin >> nomi_squadre[i]; } std::cout << std::endl; for (i = 0; i < punti_giornate.size(); i++) { for (j = 0; j < nomi_squadre.size(); j++) { do { std::cout << "Inserisci punti " << nomi_squadre[j] << " (giornata " << i + 1 << "): "; std::cin >> punti_giornate[i][j]; } while (punti_giornate[i][j] != 0 && punti_giornate[i][j] != 1 && punti_giornate[i][j] != 3); } std::cout << std::endl; } } void mostra_vincitori_giornata(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int i; unsigned int giornata; std::vector<unsigned int> vincitori; giornata = chiedi_giornata(punti_giornate); std::cout << std::endl; vincitori = trova_vincitori_giornata(giornata, punti_giornate); for (i = 0; i < vincitori.size(); i++) { std::cout << "La squadra " << nomi_squadre[vincitori[i]] << " ha vinto la giornata " << giornata << "." << std::endl; } } void mostra_punti_squadra(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { int indice_squadra; unsigned int punti; indice_squadra = chiedi_squadra(nomi_squadre); std::cout << std::endl; punti = trova_punti_squadra(indice_squadra, punti_giornate); std::cout << "La squadra " << nomi_squadre[indice_squadra] << " ha totalizzato " << punti << " punti." << std::endl; } void mostra_vincitore_campionato(nomi_squadre_t nomi_squadre, punti_giornate_t punti_giornate) { unsigned int indice_vincitore; indice_vincitore = trova_vincitore_campionato(nomi_squadre, punti_giornate); std::cout << "La squadra che ha vinto il campionato è " << nomi_squadre[indice_vincitore] << "." << std::endl; } int main() { nomi_squadre_t nomi_squadre; punti_giornate_t punti_giornate; unsigned int scelta; inizializzazione(nomi_squadre, punti_giornate); std::cout << std::endl; caricamento(nomi_squadre, punti_giornate); do { std::cout << "1. Vincitori giornata" << std::endl; std::cout << "2. Punti squadra" << std::endl; std::cout << "3. Vincitore campionato" << std::endl; std::cout << "0. Uscita" << std::endl; std::cout << std::endl; std::cout << "Inserisci un'opzione: "; std::cin >> scelta; if (scelta != 0) { std::cout << std::endl; } switch (scelta) { case 1: mostra_vincitori_giornata(nomi_squadre, punti_giornate); break; case 2: mostra_punti_squadra(nomi_squadre, punti_giornate); break; case 3: mostra_vincitore_campionato(nomi_squadre, punti_giornate); break; case 0: break; default: std::cout << "Scelta non valida." << std::endl; } if (scelta != 0) { std::cout << std::endl; } } while (scelta != 0); return 0; } <|endoftext|>
<commit_before><commit_msg>valgrind: memset the window command data structure. |timestamp| is aligned on a 16 byte boundary leaving 4 bytes of uninitialized data in the middle of the struct. We write this data to disk, which is a possible security risk.<commit_after><|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/reference/pooling.h" // These are headers from the ARM CMSIS-NN library. #include "arm_nnfunctions.h" // NOLINT #include "scratch_buffer.h" // NOLINT #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace micro { namespace pooling { namespace { constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; struct OpData { TfLitePaddingValues padding; }; TfLiteStatus CalculateOpData(const TfLiteContext* context, const TfLitePoolParams* params, const TfLiteTensor* input, const TfLiteTensor* output, OpData* data) { // input: batch, height, width, channel int height = SizeOfDimension(input, 1); int width = SizeOfDimension(input, 2); int out_height, out_width; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, /*dilation_rate_height=*/1, /*dilation_rate_width=*/1, height, width, params->filter_height, params->filter_width, params->padding, &out_height, &out_width); return kTfLiteOk; } void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } TfLiteStatus AverageEvalInt8(TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); TFLITE_DCHECK_LE(activation_min, activation_max); #if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL) RuntimeShape input_shape = GetTensorShape(input); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); RuntimeShape output_shape = GetTensorShape(output); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int depth = MatchingDim(input_shape, 3, output_shape, 3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int stride_height = params->stride_height; const int stride_width = params->stride_width; const int filter_height = params->filter_height; const int filter_width = params->filter_width; const int padding_height = data->padding.height; const int padding_width = data->padding.width; int16_t* scratch_buffer = nullptr; int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth); TF_LITE_ENSURE_OK( context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size)); TF_LITE_ENSURE_EQ( context, arm_avgpool_s8(input_height, input_width, output_height, output_width, stride_height, stride_width, filter_height, filter_width, padding_height, padding_width, activation_min, activation_max, depth, GetTensorData<int8_t>(input), scratch_buffer, GetTensorData<int8_t>(output)), ARM_MATH_SUCCESS); #else PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_integer_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<int8_t>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); #endif return kTfLiteOk; } void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; // Todo: make 'input' const once CMSIS-reuse is fixed TfLiteTensor* input = &context->tensors[flatbuffers::EndianScalar( node->inputs->data[kInputTensor])]; TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); // Inputs and outputs share the same type, guarenteed by the converter. switch (input->type) { case kTfLiteFloat32: AverageEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: AverageEvalUint8(context, node, params, &data, input, output); break; case kTfLiteInt8: return AverageEvalInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Input type %s is not currently supported", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); switch (input->type) { case kTfLiteFloat32: MaxEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace pooling TfLiteRegistration* Register_AVERAGE_POOL_2D() { static TfLiteRegistration r = { pooling::Init, pooling::Free, pooling::Prepare, pooling::AverageEval, }; return &r; } TfLiteRegistration* Register_MAX_POOL_2D() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare, pooling::MaxEval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite <commit_msg>Micro: Fix compile error for Arm Mbed OS.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/reference/pooling.h" // These are headers from the ARM CMSIS-NN library. #include "arm_nnfunctions.h" // NOLINT #include "scratch_buffer.h" // NOLINT #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace micro { namespace pooling { namespace { constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; struct OpData { TfLitePaddingValues padding; }; TfLiteStatus CalculateOpData(const TfLiteContext* context, const TfLitePoolParams* params, const TfLiteTensor* input, const TfLiteTensor* output, OpData* data) { // input: batch, height, width, channel int height = SizeOfDimension(input, 1); int width = SizeOfDimension(input, 2); int out_height, out_width; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, /*dilation_rate_height=*/1, /*dilation_rate_width=*/1, height, width, params->filter_height, params->filter_width, params->padding, &out_height, &out_width); return kTfLiteOk; } void AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void AverageEvalUint8(TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } TfLiteStatus AverageEvalInt8(TfLiteContext* context, const TfLiteNode* node, const TfLitePoolParams* params, const OpData* data, TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); TFLITE_DCHECK_LE(activation_min, activation_max); #if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL) RuntimeShape input_shape = GetTensorShape(input); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); RuntimeShape output_shape = GetTensorShape(output); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int depth = MatchingDim(input_shape, 3, output_shape, 3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int stride_height = params->stride_height; const int stride_width = params->stride_width; const int filter_height = params->filter_height; const int filter_width = params->filter_width; const int padding_height = data->padding.height; const int padding_width = data->padding.width; int16_t* scratch_buffer = nullptr; int32_t buffer_size = arm_avgpool_s8_get_buffer_size(output_width, depth); TF_LITE_ENSURE_OK( context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size)); TF_LITE_ENSURE_EQ( context, arm_avgpool_s8(input_height, input_width, output_height, output_width, stride_height, stride_width, filter_height, filter_width, padding_height, padding_width, activation_min, activation_max, depth, GetTensorData<int8_t>(input), scratch_buffer, GetTensorData<int8_t>(output)), ARM_MATH_SUCCESS); #else PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_integer_ops::AveragePool( op_params, GetTensorShape(input), GetTensorData<int8_t>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); #endif return kTfLiteOk; } void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.float_activation_min = activation_min; op_params.float_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); } void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min, activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); tflite::PoolParams op_params; op_params.stride_height = params->stride_height; op_params.stride_width = params->stride_width; op_params.filter_height = params->filter_height; op_params.filter_width = params->filter_width; op_params.padding_values.height = data->padding.height; op_params.padding_values.width = data->padding.width; op_params.quantized_activation_min = activation_min; op_params.quantized_activation_max = activation_max; reference_ops::MaxPool(op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; // Todo: make 'input' const once CMSIS-reuse is fixed TfLiteTensor* input = &context->tensors[flatbuffers::EndianScalar( node->inputs->data[kInputTensor])]; TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); // Inputs and outputs share the same type, guarenteed by the converter. switch (input->type) { case kTfLiteFloat32: AverageEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: AverageEvalUint8(context, node, params, &data, input, output); break; case kTfLiteInt8: return AverageEvalInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Input type %s is not currently supported", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData data; const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data)); switch (input->type) { case kTfLiteFloat32: MaxEvalFloat(context, node, params, &data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8(context, node, params, &data, input, output); break; default: context->ReportError(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace pooling TfLiteRegistration* Register_AVERAGE_POOL_2D() { static TfLiteRegistration r = { pooling::Init, pooling::Free, pooling::Prepare, pooling::AverageEval, }; return &r; } TfLiteRegistration* Register_MAX_POOL_2D() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare, pooling::MaxEval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite <|endoftext|>
<commit_before>// infoware - C++ System information Library // // Written in 2016 by nabijaczleweli <[email protected]> and ThePhD <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifndef _WIN32 #ifdef INFOWARE_USE_X11 #include "infoware/system.hpp" #include <X11/Xlib.h> #include <cstdlib> std::vector<iware::system::display_t> iware::system::displays() { std::vector<iware::system::display_t> ret; if(const auto display_name = std::getenv("DISPLAY")) if(const auto display = XOpenDisplay(display_name)) for(int i = 0; i < ScreenCount(display); ++i) { const unsigned int width = DisplayWidth(display, i); // 25.4 millimeters per inch ret.emplace_back(iware::system::display_t{width, DisplayHeight(display, i), static_cast<unsigned int>(25.4 * DisplayWidthMM(display, i) / width), DefaultDepth(display, i)}); } return ret; } #endif #endif <commit_msg>Fixes for narrowing conversions.<commit_after>// infoware - C++ System information Library // // Written in 2016 by nabijaczleweli <[email protected]> and ThePhD <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifndef _WIN32 #ifdef INFOWARE_USE_X11 #include "infoware/system.hpp" #include <X11/Xlib.h> #include <cstdlib> std::vector<iware::system::display_t> iware::system::displays() { std::vector<iware::system::display_t> ret; if(const auto display_name = std::getenv("DISPLAY")) if(const auto display = XOpenDisplay(display_name)) for(int i = 0; i < ScreenCount(display); ++i) { const unsigned int width = DisplayWidth(display, i); // 25.4 millimeters per inch ret.emplace_back(iware::system::display_t{ width, static_cast<std::uint32_t>(DisplayHeight(display, i)), static_cast<std::uint32_t>(25.4 * DisplayWidthMM(display, i) / width), static_cast<std::uint32_t>(DefaultDepth(display, i)) }); } return ret; } #endif #endif <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qimage.h> #include <qlabel.h> #include <qlayout.h> #include <qtooltip.h> #include <dcopclient.h> #include <dcopref.h> #include <kapplication.h> #include <kdebug.h> #include <kglobal.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <klocale.h> #include <kurllabel.h> #include "summarywidget.h" SummaryWidget::SummaryWidget( QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), DCOPObject( "WeatherSummaryWidget" ), mProc( 0 ) { mLayout = new QVBoxLayout( this ); mLayout->setAlignment( Qt::AlignTop ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kweather", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "Weather Information" ) ); mLayout->addWidget( header ); QString error; QCString appID; bool serviceAvailable = true; if ( !kapp->dcopClient()->isApplicationRegistered( "KWeatherService" ) ) { if ( KApplication::startServiceByDesktopName( "kweatherservice", QStringList(), &error, &appID ) ) { QLabel *label = new QLabel( i18n( "No weather dcop service available;\nyou need KWeather to use this plugin." ), this ); mLayout->addWidget( label, Qt::AlignHCenter ); serviceAvailable = false; } } if ( serviceAvailable ) { connectDCOPSignal( 0, 0, "fileUpdate(QString)", "refresh(QString)", false ); connectDCOPSignal( 0, 0, "stationRemoved(QString)", "stationRemoved(QString)", false ); DCOPRef dcopCall( "KWeatherService", "WeatherService" ); DCOPReply reply = dcopCall.call( "listStations()", true ); if ( reply.isValid() ) { mStations = reply; connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) ); mTimer.start( 0 ); } else { kdDebug(5602) << "ERROR: dcop reply not valid..." << endl; } } } void SummaryWidget::updateView() { mLayouts.setAutoDelete( true ); mLayouts.clear(); mLayouts.setAutoDelete( false ); mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); if ( mStations.count() == 0 ) { kdDebug(5602) << "No weather stations defined..." << endl; return; } QValueList<WeatherData> dataList = mWeatherMap.values(); qHeapSort( dataList ); QValueList<WeatherData>::Iterator it; for ( it = dataList.begin(); it != dataList.end(); ++it ) { QString cover; for ( uint i = 0; i < (*it).cover().count(); ++i ) cover += QString( "- %1\n" ).arg( (*it).cover()[ i ] ); QImage img; img = (*it).icon(); QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 ); mLayout->addStretch( 10 ); mLayouts.append( layout ); KURLLabel* urlLabel = new KURLLabel(this); urlLabel->installEventFilter(this); urlLabel->setURL((*it).stationID()); urlLabel->setPixmap( img.smoothScale( 32, 32 ) ); urlLabel->setMaximumSize(urlLabel->sizeHint()); urlLabel->setAlignment(/* AlignRight |*/ AlignTop ); layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 ); mLabels.append( urlLabel ); connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ), this, SLOT(slotShowReport(const QString& ))); QLabel* label = new QLabel( this ); label->setText( QString( "%1 (%2)" ).arg( (*it).name() ).arg( (*it).temperature() ) ); QFont font = label->font(); font.setBold( true ); label->setFont( font ); label->setAlignment( AlignLeft ); layout->addMultiCellWidget( label, 0, 0, 1, 2 ); mLabels.append( label ); QString labelText; labelText = QString( "<b>%1:</b> %2<br>" "<b>%3:</b> %4" ) .arg( i18n( "Wind Speed" ) ) .arg( (*it).windSpeed() ) .arg( i18n( "Rel. Humidity" ) ) .arg( (*it).relativeHumidity() ); QToolTip::add( label, labelText.replace( " ", "&nbsp;" ) ); label = new QLabel( cover, this ); label->setAlignment( AlignLeft ); layout->addMultiCellWidget( label, 1, 1, 1, 2 ); mLabels.append( label ); } for ( QLabel *label = mLabels.first(); label; label = mLabels.next() ) label->show(); mLayout->addStretch( 1 ); } void SummaryWidget::timeout() { mTimer.stop(); DCOPRef dcopCall( "KWeatherService", "WeatherService" ); dcopCall.send( "updateAll()" ); mTimer.start( 15 * 60000 ); } void SummaryWidget::refresh( QString station ) { DCOPRef dcopCall( "KWeatherService", "WeatherService" ); mWeatherMap[ station ].setIcon( dcopCall.call( "currentIcon(QString)", station, true ) ); mWeatherMap[ station ].setName( dcopCall.call( "stationName(QString)", station, true ) ); mWeatherMap[ station ].setCover( dcopCall.call( "cover(QString)", station, true ) ); mWeatherMap[ station ].setTemperature( dcopCall.call( "temperature(QString)", station, true ) ); mWeatherMap[ station ].setWindSpeed( dcopCall.call( "wind(QString)", station, true ) ); mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( "relativeHumidity(QString)", station, true ) ); mWeatherMap[ station ].setStationID(station); updateView(); } void SummaryWidget::stationRemoved( QString station ) { mWeatherMap.remove( station ); updateView(); } QStringList SummaryWidget::configModules() const { return QStringList( "kcmweatherservice.desktop" ); } void SummaryWidget::slotShowReport(const QString &stationID) { mProc = new KProcess; QApplication::connect(mProc, SIGNAL(processExited(KProcess *)), this, SLOT(slotReportFinished(KProcess* ))); *mProc << "kweatherreport"; *mProc << stationID; if ( !mProc->start() ) { delete mProc; mProc=0; } } void SummaryWidget::slotReportFinished(KProcess* /*proc*/){ delete mProc; mProc = 0; } #include "summarywidget.moc" <commit_msg>Don't add extra space on every view update. That fixes #85031.<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qimage.h> #include <qlabel.h> #include <qlayout.h> #include <qtooltip.h> #include <dcopclient.h> #include <dcopref.h> #include <kapplication.h> #include <kdebug.h> #include <kglobal.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <klocale.h> #include <kurllabel.h> #include "summarywidget.h" SummaryWidget::SummaryWidget( QWidget *parent, const char *name ) : Kontact::Summary( parent, name ), DCOPObject( "WeatherSummaryWidget" ), mProc( 0 ) { mLayout = new QVBoxLayout( this ); mLayout->setAlignment( Qt::AlignTop ); QPixmap icon = KGlobal::iconLoader()->loadIcon( "kweather", KIcon::Desktop, KIcon::SizeMedium ); QWidget *header = createHeader( this, icon, i18n( "Weather Information" ) ); mLayout->addWidget( header ); QString error; QCString appID; bool serviceAvailable = true; if ( !kapp->dcopClient()->isApplicationRegistered( "KWeatherService" ) ) { if ( KApplication::startServiceByDesktopName( "kweatherservice", QStringList(), &error, &appID ) ) { QLabel *label = new QLabel( i18n( "No weather dcop service available;\nyou need KWeather to use this plugin." ), this ); mLayout->addWidget( label, Qt::AlignHCenter ); serviceAvailable = false; } } if ( serviceAvailable ) { connectDCOPSignal( 0, 0, "fileUpdate(QString)", "refresh(QString)", false ); connectDCOPSignal( 0, 0, "stationRemoved(QString)", "stationRemoved(QString)", false ); DCOPRef dcopCall( "KWeatherService", "WeatherService" ); DCOPReply reply = dcopCall.call( "listStations()", true ); if ( reply.isValid() ) { mStations = reply; connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) ); mTimer.start( 0 ); } else { kdDebug(5602) << "ERROR: dcop reply not valid..." << endl; } } } void SummaryWidget::updateView() { mLayouts.setAutoDelete( true ); mLayouts.clear(); mLayouts.setAutoDelete( false ); mLabels.setAutoDelete( true ); mLabels.clear(); mLabels.setAutoDelete( false ); if ( mStations.count() == 0 ) { kdDebug(5602) << "No weather stations defined..." << endl; return; } QValueList<WeatherData> dataList = mWeatherMap.values(); qHeapSort( dataList ); QValueList<WeatherData>::Iterator it; for ( it = dataList.begin(); it != dataList.end(); ++it ) { QString cover; for ( uint i = 0; i < (*it).cover().count(); ++i ) cover += QString( "- %1\n" ).arg( (*it).cover()[ i ] ); QImage img; img = (*it).icon(); QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 ); mLayouts.append( layout ); KURLLabel* urlLabel = new KURLLabel(this); urlLabel->installEventFilter(this); urlLabel->setURL((*it).stationID()); urlLabel->setPixmap( img.smoothScale( 32, 32 ) ); urlLabel->setMaximumSize(urlLabel->sizeHint()); urlLabel->setAlignment(/* AlignRight |*/ AlignTop ); layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 ); mLabels.append( urlLabel ); connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ), this, SLOT(slotShowReport(const QString& ))); QLabel* label = new QLabel( this ); label->setText( QString( "%1 (%2)" ).arg( (*it).name() ).arg( (*it).temperature() ) ); QFont font = label->font(); font.setBold( true ); label->setFont( font ); label->setAlignment( AlignLeft ); layout->addMultiCellWidget( label, 0, 0, 1, 2 ); mLabels.append( label ); QString labelText; labelText = QString( "<b>%1:</b> %2<br>" "<b>%3:</b> %4" ) .arg( i18n( "Wind Speed" ) ) .arg( (*it).windSpeed() ) .arg( i18n( "Rel. Humidity" ) ) .arg( (*it).relativeHumidity() ); QToolTip::add( label, labelText.replace( " ", "&nbsp;" ) ); label = new QLabel( cover, this ); label->setAlignment( AlignLeft ); layout->addMultiCellWidget( label, 1, 1, 1, 2 ); mLabels.append( label ); } for ( QLabel *label = mLabels.first(); label; label = mLabels.next() ) label->show(); mLayout->addStretch( 1 ); } void SummaryWidget::timeout() { mTimer.stop(); DCOPRef dcopCall( "KWeatherService", "WeatherService" ); dcopCall.send( "updateAll()" ); mTimer.start( 15 * 60000 ); } void SummaryWidget::refresh( QString station ) { DCOPRef dcopCall( "KWeatherService", "WeatherService" ); mWeatherMap[ station ].setIcon( dcopCall.call( "currentIcon(QString)", station, true ) ); mWeatherMap[ station ].setName( dcopCall.call( "stationName(QString)", station, true ) ); mWeatherMap[ station ].setCover( dcopCall.call( "cover(QString)", station, true ) ); mWeatherMap[ station ].setTemperature( dcopCall.call( "temperature(QString)", station, true ) ); mWeatherMap[ station ].setWindSpeed( dcopCall.call( "wind(QString)", station, true ) ); mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( "relativeHumidity(QString)", station, true ) ); mWeatherMap[ station ].setStationID(station); updateView(); } void SummaryWidget::stationRemoved( QString station ) { mWeatherMap.remove( station ); updateView(); } QStringList SummaryWidget::configModules() const { return QStringList( "kcmweatherservice.desktop" ); } void SummaryWidget::slotShowReport(const QString &stationID) { mProc = new KProcess; QApplication::connect(mProc, SIGNAL(processExited(KProcess *)), this, SLOT(slotReportFinished(KProcess* ))); *mProc << "kweatherreport"; *mProc << stationID; if ( !mProc->start() ) { delete mProc; mProc=0; } } void SummaryWidget::slotReportFinished(KProcess* /*proc*/){ delete mProc; mProc = 0; } #include "summarywidget.moc" <|endoftext|>
<commit_before>/* * TCPServer.cpp * * Created on: Apr 4, 2016 * Author: james */ #include "tcp/TCPDeviceServer.h" #include <netinet/in.h> #include <stddef.h> #include <sys/socket.h> #include <unistd.h> #include <cstdint> #include <iostream> #include <utility> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "device/socket/tcp/TCPClient.h" #include "device/socket/tcp/TCPClientProxy.h" #include "Debug.h" #include "tcp/TCPConnParams.h" #include "tcp/SSLConfig.h" #include "util/write.h" TCPDeviceServer::TCPDeviceServer(Beetle &beetle, SSLConfig sslConfig, int port) : beetle(beetle), sslConfig(sslConfig) { running = true; sockfd = -1; t = std::thread(&TCPDeviceServer::serverDaemon, this, port); } TCPDeviceServer::~TCPDeviceServer() { running = false; shutdown(sockfd, SHUT_RDWR); t.join(); } void TCPDeviceServer::serverDaemon(int port) { if (debug) pdebug("tcp serverDaemon started on port: " + std::to_string(port)); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { throw ServerException("error creating socket"); } struct sockaddr_in server_addr = {0}; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { throw ServerException("error on bind"); } listen(sockfd, 5); while (running) { struct sockaddr_in client_addr; socklen_t clilen = sizeof(client_addr); int clifd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen); if (clifd < 0) { if (!running) { break; } pwarn("error on accept"); continue; } SSL *ssl = SSL_new(sslConfig.getCtx()); SSL_set_fd(ssl, clifd); if (SSL_accept(ssl) <= 0) { pwarn("error on ssl accept"); ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); continue; } startTcpDeviceHelper(ssl, clifd, client_addr); } close(sockfd); if (debug) pdebug("tcp serverDaemon exited"); } void TCPDeviceServer::startTcpDeviceHelper(SSL *ssl, int clifd, struct sockaddr_in cliaddr) { uint32_t clientParamsLen; if (SSL_read(ssl, &clientParamsLen, sizeof(uint32_t)) != sizeof(uint32_t)) { if (debug) { pdebug("could not read tcp connection client parameters length"); } ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); return; } /* * Read params from the client. */ clientParamsLen = ntohl(clientParamsLen); if (debug) { pdebug("expecting " + std::to_string(clientParamsLen) + " bytes of parameters"); } std::map<std::string, std::string> clientParams; if (!readParamsHelper(ssl, clientParamsLen, clientParams)) { pwarn("unable to read parameters"); close(clifd); return; } if (debug) { for (auto &kv : clientParams) { pdebug("parsed param (" + kv.first + "," + kv.second + ")"); } pdebug("done reading tcp connection parameters"); } /* * Send params to the client. */ std::stringstream ss; ss << TCP_PARAM_GATEWAY << " " << beetle.name; std::string serverParams = ss.str(); uint32_t serverParamsLen = htonl(serverParams.length()); if (SSL_write_all(ssl, (uint8_t *)&serverParamsLen, sizeof(serverParamsLen)) == false) { ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); if (debug) pdebug("could not write server params length"); } if (SSL_write_all(ssl, (uint8_t *)serverParams.c_str(), serverParams.length()) == false) { ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); if (debug) pdebug("could not write server params"); } /* * Instantiate the virtual device around the client socket. */ VirtualDevice *device = NULL; try { /* * Takes over the clifd */ if (clientParams.find(TCP_PARAM_GATEWAY) == clientParams.end()) { device = new TCPClient(beetle, ssl, clifd, clientParams[TCP_PARAM_CLIENT], cliaddr); } else { // name of the client gateway std::string client = clientParams[TCP_PARAM_GATEWAY]; // device that the client is requesting device_t deviceId = std::stol(clientParams[TCP_PARAM_DEVICE]); device = new TCPClientProxy(beetle, ssl, clifd, client, cliaddr, deviceId); } if (clientParams[TCP_PARAM_SERVER] == "true") { device->start(); } else { device->startNd(); } beetle.addDevice(device); pdebug("connected to " + device->getName()); if (debug) { pdebug(device->getName() + " has handle range [0," + std::to_string(device->getHighestHandle()) + "]"); } } catch (std::exception& e) { std::cout << "caught exception: " << e.what() << std::endl; if (device) { beetle.removeDevice(device->getId()); } } } <commit_msg>Change import.<commit_after>/* * TCPServer.cpp * * Created on: Apr 4, 2016 * Author: james */ #include "tcp/TCPDeviceServer.h" #include <netinet/in.h> #include <stddef.h> #include <sys/socket.h> #include <unistd.h> #include <cstdint> #include <iostream> #include <utility> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "device/socket/tcp/TCPClient.h" #include "device/socket/tcp/TCPClientProxy.h" #include "Debug.h" #include "tcp/TCPConnParams.h" #include "util/write.h" TCPDeviceServer::TCPDeviceServer(Beetle &beetle, SSLConfig sslConfig, int port) : beetle(beetle), sslConfig(sslConfig) { running = true; sockfd = -1; t = std::thread(&TCPDeviceServer::serverDaemon, this, port); } TCPDeviceServer::~TCPDeviceServer() { running = false; shutdown(sockfd, SHUT_RDWR); t.join(); } void TCPDeviceServer::serverDaemon(int port) { if (debug) pdebug("tcp serverDaemon started on port: " + std::to_string(port)); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { throw ServerException("error creating socket"); } struct sockaddr_in server_addr = {0}; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { throw ServerException("error on bind"); } listen(sockfd, 5); while (running) { struct sockaddr_in client_addr; socklen_t clilen = sizeof(client_addr); int clifd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen); if (clifd < 0) { if (!running) { break; } pwarn("error on accept"); continue; } SSL *ssl = SSL_new(sslConfig.getCtx()); SSL_set_fd(ssl, clifd); if (SSL_accept(ssl) <= 0) { pwarn("error on ssl accept"); ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); continue; } startTcpDeviceHelper(ssl, clifd, client_addr); } close(sockfd); if (debug) pdebug("tcp serverDaemon exited"); } void TCPDeviceServer::startTcpDeviceHelper(SSL *ssl, int clifd, struct sockaddr_in cliaddr) { uint32_t clientParamsLen; if (SSL_read(ssl, &clientParamsLen, sizeof(uint32_t)) != sizeof(uint32_t)) { if (debug) { pdebug("could not read tcp connection client parameters length"); } ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); return; } /* * Read params from the client. */ clientParamsLen = ntohl(clientParamsLen); if (debug) { pdebug("expecting " + std::to_string(clientParamsLen) + " bytes of parameters"); } std::map<std::string, std::string> clientParams; if (!readParamsHelper(ssl, clientParamsLen, clientParams)) { pwarn("unable to read parameters"); close(clifd); return; } if (debug) { for (auto &kv : clientParams) { pdebug("parsed param (" + kv.first + "," + kv.second + ")"); } pdebug("done reading tcp connection parameters"); } /* * Send params to the client. */ std::stringstream ss; ss << TCP_PARAM_GATEWAY << " " << beetle.name; std::string serverParams = ss.str(); uint32_t serverParamsLen = htonl(serverParams.length()); if (SSL_write_all(ssl, (uint8_t *)&serverParamsLen, sizeof(serverParamsLen)) == false) { ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); if (debug) pdebug("could not write server params length"); } if (SSL_write_all(ssl, (uint8_t *)serverParams.c_str(), serverParams.length()) == false) { ERR_print_errors_fp(stderr); SSL_shutdown(ssl); SSL_free(ssl); close(clifd); if (debug) pdebug("could not write server params"); } /* * Instantiate the virtual device around the client socket. */ VirtualDevice *device = NULL; try { /* * Takes over the clifd */ if (clientParams.find(TCP_PARAM_GATEWAY) == clientParams.end()) { device = new TCPClient(beetle, ssl, clifd, clientParams[TCP_PARAM_CLIENT], cliaddr); } else { // name of the client gateway std::string client = clientParams[TCP_PARAM_GATEWAY]; // device that the client is requesting device_t deviceId = std::stol(clientParams[TCP_PARAM_DEVICE]); device = new TCPClientProxy(beetle, ssl, clifd, client, cliaddr, deviceId); } if (clientParams[TCP_PARAM_SERVER] == "true") { device->start(); } else { device->startNd(); } beetle.addDevice(device); pdebug("connected to " + device->getName()); if (debug) { pdebug(device->getName() + " has handle range [0," + std::to_string(device->getHighestHandle()) + "]"); } } catch (std::exception& e) { std::cout << "caught exception: " << e.what() << std::endl; if (device) { beetle.removeDevice(device->getId()); } } } <|endoftext|>
<commit_before><commit_msg>Match up array delete to array allocate.<commit_after><|endoftext|>
<commit_before>/* Kopete View Item Delegate Copyright (c) 2007 by Matt Rogers <[email protected]> Kopete (c) 2002-2007 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteitemdelegate.h" #include "kopeteitembase.h" #include <QPainter> #include <QStyleOptionViewItem> #include <QModelIndex> #include <QAbstractItemView> #include <QItemDelegate> #include "kopetemetacontact.h" #include "kopeteappearancesettings.h" KopeteItemDelegate::KopeteItemDelegate( QAbstractItemView* parent ) : QItemDelegate( parent ) { } KopeteItemDelegate::~KopeteItemDelegate() { } QSize KopeteItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(45, 20); } void KopeteItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { //pull in contact settings: idleContactColor, greyIdleMetaContacts //pull in contact list settings: contactListDisplayMode QStyleOptionViewItem opt = option; if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::MetaContact ) { //check the idle state of the metacontact and apply the appropriate //color QVariant v = index.data( Kopete::Items::IdleTimeRole ); if ( Kopete::AppearanceSettings::self()->greyIdleMetaContacts() && v.toInt() > 0 ) { QColor idleColor( Kopete::AppearanceSettings::self()->idleContactColor() ); opt.palette.setColor( QPalette::Text, idleColor ); } } if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::Group ) { QColor gc( Kopete::AppearanceSettings::self()->groupNameColor() ); opt.palette.setColor( QPalette::Text, gc ); } QItemDelegate::paint( painter, opt, index ); } <commit_msg>Use the QItemDelegate size hint instead of our own custom hint for now<commit_after>/* Kopete View Item Delegate Copyright (c) 2007 by Matt Rogers <[email protected]> Kopete (c) 2002-2007 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteitemdelegate.h" #include "kopeteitembase.h" #include <QPainter> #include <QStyleOptionViewItem> #include <QModelIndex> #include <QAbstractItemView> #include <QItemDelegate> #include "kopetemetacontact.h" #include "kopeteappearancesettings.h" KopeteItemDelegate::KopeteItemDelegate( QAbstractItemView* parent ) : QItemDelegate( parent ) { } KopeteItemDelegate::~KopeteItemDelegate() { } QSize KopeteItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QItemDelegate::sizeHint( option, index ); } void KopeteItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { //pull in contact settings: idleContactColor, greyIdleMetaContacts //pull in contact list settings: contactListDisplayMode QStyleOptionViewItem opt = option; if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::MetaContact ) { //check the idle state of the metacontact and apply the appropriate //color QVariant v = index.data( Kopete::Items::IdleTimeRole ); if ( Kopete::AppearanceSettings::self()->greyIdleMetaContacts() && v.toInt() > 0 ) { QColor idleColor( Kopete::AppearanceSettings::self()->idleContactColor() ); opt.palette.setColor( QPalette::Text, idleColor ); } } if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::Group ) { QColor gc( Kopete::AppearanceSettings::self()->groupNameColor() ); opt.palette.setColor( QPalette::Text, gc ); } QItemDelegate::paint( painter, opt, index ); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2015, Julien Bernard * * 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 "Assets.h" #include <cassert> #include <boost/filesystem.hpp> #include "Log.h" namespace fs = boost::filesystem; namespace game { void AssetManager::addSearchDir(std::string path) { Log::info(Log::RESOURCES, "Added a new search directory: %s\n", path.c_str()); m_searchdirs.emplace_back(std::move(path)); } std::string AssetManager::getAbsolutePath(const std::string& relative_path) { fs::path file(relative_path); if (file.is_absolute()) { return relative_path; } for (fs::path base : m_searchdirs) { fs::path absolute_path = base / file; if (fs::is_regular_file(absolute_path)) { Log::info(Log::RESOURCES, "Found a resource file: %s\n", absolute_path.string().c_str()); return absolute_path.string(); } } Log::error(Log::RESOURCES, "Could not find the following file: %s\n", relative_path.c_str()); return std::string(); } } <commit_msg>add some log for absolute filenames<commit_after>/* * Copyright (c) 2014-2015, Julien Bernard * * 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 "Assets.h" #include <cassert> #include <boost/filesystem.hpp> #include "Log.h" namespace fs = boost::filesystem; namespace game { void AssetManager::addSearchDir(std::string path) { Log::info(Log::RESOURCES, "Added a new search directory: %s\n", path.c_str()); m_searchdirs.emplace_back(std::move(path)); } std::string AssetManager::getAbsolutePath(const std::string& relative_path) { fs::path file(relative_path); if (file.is_absolute()) { assert(fs::is_regular_file(file)); Log::info(Log::RESOURCES, "Found a resource file: %s\n", relative_path.c_str()); return relative_path; } for (fs::path base : m_searchdirs) { fs::path absolute_path = base / file; if (fs::is_regular_file(absolute_path)) { Log::info(Log::RESOURCES, "Found a resource file: %s\n", absolute_path.string().c_str()); return absolute_path.string(); } } Log::error(Log::RESOURCES, "Could not find the following file: %s\n", relative_path.c_str()); return std::string(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dsbrowserDnD.cxx,v $ * * $Revision: 1.64 $ * * last change: $Author: hr $ $Date: 2004-08-02 15:33:59 $ * * 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 EXPRESS 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 _SBA_UNODATBR_HXX_ #include "unodatbr.hxx" #endif #ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_ #include <com/sun/star/sdb/CommandType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _DBU_BRW_HRC_ #include "dbu_brw.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef DBAUI_DBEXCHANGE_HXX #include "dbexchange.hxx" #endif #ifndef DBAUI_ENUMTYPES_HXX #include "QEnumTypes.hxx" #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _SVX_DATACCESSDESCRIPTOR_HXX_ #include <svx/dataaccessdescriptor.hxx> #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif // ......................................................................... namespace dbaui { // ......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::form; using namespace ::com::sun::star::io; using namespace ::com::sun::star::i18n; using namespace ::com::sun::star::task; using namespace ::com::sun::star::datatransfer; using namespace ::dbtools; using namespace ::svx; // ----------------------------------------------------------------------------- TransferableHelper* SbaTableQueryBrowser::implCopyObject( SvLBoxEntry* _pApplyTo, sal_Int32 _nCommandType, sal_Bool _bAllowConnection ) { try { ::osl::MutexGuard aGuard(m_aEntryMutex); ::rtl::OUString aName = GetEntryText( _pApplyTo ); ::rtl::OUString aDSName = GetEntryText( m_pTreeView->getListBox()->GetRootLevelParent( _pApplyTo ) ); ODataClipboard* pData = NULL; Reference<XConnection> xConnection; // supports the service sdb::connection if ( CommandType::QUERY != _nCommandType ) { if (_bAllowConnection && !ensureConnection(_pApplyTo, xConnection)) return NULL; pData = new ODataClipboard(aDSName, _nCommandType, aName, xConnection, getNumberFormatter(), getORB()); } else pData = new ODataClipboard(aDSName, _nCommandType, aName, getNumberFormatter(), getORB()); // the owner ship goes to ODataClipboards return pData; } catch(SQLException& e) { showError(SQLExceptionInfo(e)); } catch(Exception&) { DBG_ERROR("SbaTableQueryBrowser::implCopyObject: caught a generic exception!"); } return NULL; } // ----------------------------------------------------------------------------- sal_Int8 SbaTableQueryBrowser::queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors ) { return DND_ACTION_NONE; } // ----------------------------------------------------------------------------- sal_Int8 SbaTableQueryBrowser::executeDrop( const ExecuteDropEvent& _rEvt ) { return DND_ACTION_NONE; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::requestDrag( sal_Int8 _nAction, const Point& _rPosPixel ) { // get the affected list entry // ensure that the entry which the user clicked at is selected SvLBoxEntry* pHitEntry = m_pTreeView->getListBox()->GetEntry( _rPosPixel ); if (!pHitEntry) // no drag of no entry was hit .... return sal_False; // it must be a query/table EntryType eEntryType = getEntryType( pHitEntry ); if (!isObject(eEntryType)) return DND_ACTION_NONE; TransferableHelper* pTransfer = implCopyObject( pHitEntry, (etTable == eEntryType || etView == eEntryType) ? CommandType::TABLE : CommandType::QUERY); Reference< XTransferable> xEnsureDelete = pTransfer; if (pTransfer) pTransfer->StartDrag( m_pTreeView->getListBox(), DND_ACTION_COPY ); return NULL != pTransfer; } // ----------------------------------------------------------------------------- IMPL_LINK(SbaTableQueryBrowser, OnCopyEntry, SvLBoxEntry*, _pEntry) { if( isEntryCopyAllowed(_pEntry) ) copyEntry(_pEntry); return 0; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryCutAllowed(SvLBoxEntry* _pEntry) const { // at the momoent this isn't allowed return sal_False; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryCopyAllowed(SvLBoxEntry* _pEntry) const { EntryType eType = getEntryType(_pEntry); return (eType == etTable || eType == etQuery || eType == etView); } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryPasteAllowed(SvLBoxEntry* _pEntry) const { return sal_False; } // ----------------------------------------------------------------------------- void SbaTableQueryBrowser::copyEntry(SvLBoxEntry* _pEntry) { TransferableHelper* pTransfer = NULL; Reference< XTransferable> aEnsureDelete; EntryType eType = getEntryType(_pEntry); pTransfer = implCopyObject( _pEntry, eType == etQuery ? CommandType::QUERY : CommandType::TABLE); aEnsureDelete = pTransfer; if (pTransfer) pTransfer->CopyToClipboard(getView()); } // ----------------------------------------------------------------------------- // ......................................................................... } // namespace dbaui // ......................................................................... <commit_msg>INTEGRATION: CWS ooo20040704 (1.63.12); FILE MERGED 2004/07/02 13:42:26 cmc 1.63.12.2: #i30891# revert header and namespace change 2004/06/30 15:32:02 cmc 1.63.12.1: #i30801# allow using system stl if possible<commit_after>/************************************************************************* * * $RCSfile: dsbrowserDnD.cxx,v $ * * $Revision: 1.65 $ * * last change: $Author: rt $ $Date: 2004-09-08 16:28:51 $ * * 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 EXPRESS 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 _SBA_UNODATBR_HXX_ #include "unodatbr.hxx" #endif #ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_ #include <com/sun/star/sdb/CommandType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _DBU_BRW_HRC_ #include "dbu_brw.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef DBAUI_DBEXCHANGE_HXX #include "dbexchange.hxx" #endif #ifndef DBAUI_ENUMTYPES_HXX #include "QEnumTypes.hxx" #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _SVX_DATACCESSDESCRIPTOR_HXX_ #include <svx/dataaccessdescriptor.hxx> #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif #include <functional> // ......................................................................... namespace dbaui { // ......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::form; using namespace ::com::sun::star::io; using namespace ::com::sun::star::i18n; using namespace ::com::sun::star::task; using namespace ::com::sun::star::datatransfer; using namespace ::dbtools; using namespace ::svx; // ----------------------------------------------------------------------------- TransferableHelper* SbaTableQueryBrowser::implCopyObject( SvLBoxEntry* _pApplyTo, sal_Int32 _nCommandType, sal_Bool _bAllowConnection ) { try { ::osl::MutexGuard aGuard(m_aEntryMutex); ::rtl::OUString aName = GetEntryText( _pApplyTo ); ::rtl::OUString aDSName = GetEntryText( m_pTreeView->getListBox()->GetRootLevelParent( _pApplyTo ) ); ODataClipboard* pData = NULL; Reference<XConnection> xConnection; // supports the service sdb::connection if ( CommandType::QUERY != _nCommandType ) { if (_bAllowConnection && !ensureConnection(_pApplyTo, xConnection)) return NULL; pData = new ODataClipboard(aDSName, _nCommandType, aName, xConnection, getNumberFormatter(), getORB()); } else pData = new ODataClipboard(aDSName, _nCommandType, aName, getNumberFormatter(), getORB()); // the owner ship goes to ODataClipboards return pData; } catch(SQLException& e) { showError(SQLExceptionInfo(e)); } catch(Exception&) { DBG_ERROR("SbaTableQueryBrowser::implCopyObject: caught a generic exception!"); } return NULL; } // ----------------------------------------------------------------------------- sal_Int8 SbaTableQueryBrowser::queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors ) { return DND_ACTION_NONE; } // ----------------------------------------------------------------------------- sal_Int8 SbaTableQueryBrowser::executeDrop( const ExecuteDropEvent& _rEvt ) { return DND_ACTION_NONE; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::requestDrag( sal_Int8 _nAction, const Point& _rPosPixel ) { // get the affected list entry // ensure that the entry which the user clicked at is selected SvLBoxEntry* pHitEntry = m_pTreeView->getListBox()->GetEntry( _rPosPixel ); if (!pHitEntry) // no drag of no entry was hit .... return sal_False; // it must be a query/table EntryType eEntryType = getEntryType( pHitEntry ); if (!isObject(eEntryType)) return DND_ACTION_NONE; TransferableHelper* pTransfer = implCopyObject( pHitEntry, (etTable == eEntryType || etView == eEntryType) ? CommandType::TABLE : CommandType::QUERY); Reference< XTransferable> xEnsureDelete = pTransfer; if (pTransfer) pTransfer->StartDrag( m_pTreeView->getListBox(), DND_ACTION_COPY ); return NULL != pTransfer; } // ----------------------------------------------------------------------------- IMPL_LINK(SbaTableQueryBrowser, OnCopyEntry, SvLBoxEntry*, _pEntry) { if( isEntryCopyAllowed(_pEntry) ) copyEntry(_pEntry); return 0; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryCutAllowed(SvLBoxEntry* _pEntry) const { // at the momoent this isn't allowed return sal_False; } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryCopyAllowed(SvLBoxEntry* _pEntry) const { EntryType eType = getEntryType(_pEntry); return (eType == etTable || eType == etQuery || eType == etView); } // ----------------------------------------------------------------------------- sal_Bool SbaTableQueryBrowser::isEntryPasteAllowed(SvLBoxEntry* _pEntry) const { return sal_False; } // ----------------------------------------------------------------------------- void SbaTableQueryBrowser::copyEntry(SvLBoxEntry* _pEntry) { TransferableHelper* pTransfer = NULL; Reference< XTransferable> aEnsureDelete; EntryType eType = getEntryType(_pEntry); pTransfer = implCopyObject( _pEntry, eType == etQuery ? CommandType::QUERY : CommandType::TABLE); aEnsureDelete = pTransfer; if (pTransfer) pTransfer->CopyToClipboard(getView()); } // ----------------------------------------------------------------------------- // ......................................................................... } // namespace dbaui // ......................................................................... <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "LimitBox.hxx" #include "dbu_qry.hrc" #include "moduledbu.hxx" #define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString() #define ALL_INT -1 namespace global{ /// Default values sal_Int64 aDefLimitAry[] = { 5, 10, 20, 50 }; } namespace dbaui { LimitBox::LimitBox( Window* pParent, WinBits nStyle ) : NumericBox( pParent, nStyle ) { SetShowTrailingZeros( sal_False ); SetDecimalDigits( 0 ); SetMin( -1 ); ///Use the maximum value of Int32 SetMax( 2147483647 ); LoadDefaultLimits(); Size aSize( GetSizePixel().Width(), CalcWindowSizePixel(GetEntryCount() + 1) ); SetSizePixel(aSize); } LimitBox::~LimitBox() { } OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const { if( nValue == ALL_INT ) return ALL_STRING; else return NumericBox::CreateFieldText( nValue ); } void LimitBox::Reformat() { if( GetText() == ALL_STRING ) { SetValue( ALL_INT ); } ///Reformat only when text is not All else { ///Not allow user to type in -1 if( GetText() == "-1" ) { Undo(); } else NumericBox::Reformat(); } } void LimitBox::ReformatAll() { ///First entry is All, which do not need numeric reformat if ( GetEntryCount() > 0 ) { RemoveEntry( 0 ); NumericBox::ReformatAll(); InsertEntry( ALL_STRING, 0); } else { NumericBox::ReformatAll(); } } Size LimitBox::GetOptimalSize() const { return CalcSize(10,1); } ///Initialize entries void LimitBox::LoadDefaultLimits() { SetValue( ALL_INT ); InsertEntry( ALL_STRING ); const unsigned nSize = sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]); for( unsigned nIndex = 0; nIndex< nSize; ++nIndex) { InsertValue( global::aDefLimitAry[nIndex] ); } } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeLimitBox( Window *pParent ) { LimitBox* pBox = new LimitBox( pParent, WB_DROPDOWN | WB_VSCROLL ); return pBox; } } ///dbaui namespace /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fdo#61794 Set maximum of LimitBox to SAL_MAX_INT64<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "LimitBox.hxx" #include "dbu_qry.hrc" #include "moduledbu.hxx" #define ALL_STRING ModuleRes(STR_QUERY_LIMIT_ALL).toString() #define ALL_INT -1 namespace global{ /// Default values sal_Int64 aDefLimitAry[] = { 5, 10, 20, 50 }; } namespace dbaui { LimitBox::LimitBox( Window* pParent, WinBits nStyle ) : NumericBox( pParent, nStyle ) { SetShowTrailingZeros( sal_False ); SetDecimalDigits( 0 ); SetMin( -1 ); SetMax( SAL_MAX_INT64 ); LoadDefaultLimits(); Size aSize( GetSizePixel().Width(), CalcWindowSizePixel(GetEntryCount() + 1) ); SetSizePixel(aSize); } LimitBox::~LimitBox() { } OUString LimitBox::CreateFieldText( sal_Int64 nValue ) const { if( nValue == ALL_INT ) return ALL_STRING; else return NumericBox::CreateFieldText( nValue ); } void LimitBox::Reformat() { if( GetText() == ALL_STRING ) { SetValue( ALL_INT ); } ///Reformat only when text is not All else { ///Not allow user to type in -1 if( GetText() == "-1" ) { Undo(); } else NumericBox::Reformat(); } } void LimitBox::ReformatAll() { ///First entry is All, which do not need numeric reformat if ( GetEntryCount() > 0 ) { RemoveEntry( 0 ); NumericBox::ReformatAll(); InsertEntry( ALL_STRING, 0); } else { NumericBox::ReformatAll(); } } Size LimitBox::GetOptimalSize() const { return CalcSize(10,1); } ///Initialize entries void LimitBox::LoadDefaultLimits() { SetValue( ALL_INT ); InsertEntry( ALL_STRING ); const unsigned nSize = sizeof(global::aDefLimitAry)/sizeof(global::aDefLimitAry[0]); for( unsigned nIndex = 0; nIndex< nSize; ++nIndex) { InsertValue( global::aDefLimitAry[nIndex] ); } } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeLimitBox( Window *pParent ) { LimitBox* pBox = new LimitBox( pParent, WB_DROPDOWN | WB_VSCROLL ); return pBox; } } ///dbaui namespace /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "test/test_pivx.h" #include "util.h" #include "validation.h" #include <vector> #include <boost/test/unit_test.hpp> #define SKIPLIST_LENGTH 300000 BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(skiplist_test) { std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH); for (int i=0; i<SKIPLIST_LENGTH; i++) { vIndex[i].nHeight = i; vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1]; vIndex[i].BuildSkip(); } for (int i=0; i<SKIPLIST_LENGTH; i++) { if (i > 0) { BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]); BOOST_CHECK(vIndex[i].pskip->nHeight < i); } else { BOOST_CHECK(vIndex[i].pskip == NULL); } } for (int i=0; i < 1000; i++) { int from = InsecureRandRange(SKIPLIST_LENGTH - 1); int to = InsecureRandRange(from + 1); BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]); BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]); BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]); } } BOOST_AUTO_TEST_CASE(getlocator_test) { // Build a main chain 100000 blocks long. std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = i; // Set the hash equal to the height, so we can quickly check the distances. vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); BOOST_CHECK_EQUAL((int)vBlocksMain[i].GetBlockHash().GetLow64(), vBlocksMain[i].nHeight); BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1); } // Build a branch that splits off at block 49999, 50000 blocks long. std::vector<uint256> vHashSide(50000); std::vector<CBlockIndex> vBlocksSide(50000); for (unsigned int i=0; i<vBlocksSide.size(); i++) { vHashSide[i] = i + 50000 + (uint256(1) << 128); // Add 1<<128 to the hashes, so GetLow64() still returns the height. vBlocksSide[i].nHeight = i + 50000; vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[49999]; vBlocksSide[i].phashBlock = &vHashSide[i]; vBlocksSide[i].BuildSkip(); BOOST_CHECK_EQUAL((int)vBlocksSide[i].GetBlockHash().GetLow64(), vBlocksSide[i].nHeight); BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Test 100 random starting points for locators. for (int n=0; n<100; n++) { int r = InsecureRandRange(150000); CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000]; CBlockLocator locator = chain.GetLocator(tip); // The first result must be the block itself, the last one must be genesis. BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash()); BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash()); // Entries 1 through 11 (inclusive) go back one step each. for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(locator.vHave[i].GetLow64(), tip->nHeight - i); } // The further ones (excluding the last one) go back with exponential steps. unsigned int dist = 2; for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(locator.vHave[i - 1].GetLow64() - locator.vHave[i].GetLow64(), dist); dist *= 2; } } } BOOST_AUTO_TEST_CASE(findearliestatleast_test) { std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); if (i < 10) { vBlocksMain[i].nTime = i; vBlocksMain[i].nTimeMax = i; } else { // randomly choose something in the range [MTP, MTP*2] int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast(); int r = InsecureRandRange(medianTimePast); vBlocksMain[i].nTime = r + medianTimePast; vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax); } } // Check that we set nTimeMax up correctly. unsigned int curTimeMax = 0; for (unsigned int i=0; i<vBlocksMain.size(); ++i) { curTimeMax = std::max(curTimeMax, vBlocksMain[i].nTime); BOOST_CHECK(curTimeMax == vBlocksMain[i].nTimeMax); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Verify that FindEarliestAtLeast is correct. for (unsigned int i=0; i<10000; ++i) { // Pick a random element in vBlocksMain. int r = InsecureRandRange(vBlocksMain.size()); int64_t test_time = vBlocksMain[r].nTime; CBlockIndex *ret = chain.FindEarliestAtLeast(test_time); BOOST_CHECK(ret->nTimeMax >= test_time); BOOST_CHECK((ret->pprev==NULL) || ret->pprev->nTimeMax < test_time); BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>[Trivial] NULL --> nullptr in skiplist_tests<commit_after>// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "test/test_pivx.h" #include "util.h" #include "validation.h" #include <vector> #include <boost/test/unit_test.hpp> #define SKIPLIST_LENGTH 300000 BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(skiplist_test) { std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH); for (int i=0; i<SKIPLIST_LENGTH; i++) { vIndex[i].nHeight = i; vIndex[i].pprev = (i == 0) ? nullptr : &vIndex[i - 1]; vIndex[i].BuildSkip(); } for (int i=0; i<SKIPLIST_LENGTH; i++) { if (i > 0) { BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]); BOOST_CHECK(vIndex[i].pskip->nHeight < i); } else { BOOST_CHECK(vIndex[i].pskip == nullptr); } } for (int i=0; i < 1000; i++) { int from = InsecureRandRange(SKIPLIST_LENGTH - 1); int to = InsecureRandRange(from + 1); BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]); BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]); BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]); } } BOOST_AUTO_TEST_CASE(getlocator_test) { // Build a main chain 100000 blocks long. std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = i; // Set the hash equal to the height, so we can quickly check the distances. vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); BOOST_CHECK_EQUAL((int)vBlocksMain[i].GetBlockHash().GetLow64(), vBlocksMain[i].nHeight); BOOST_CHECK(vBlocksMain[i].pprev == nullptr || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1); } // Build a branch that splits off at block 49999, 50000 blocks long. std::vector<uint256> vHashSide(50000); std::vector<CBlockIndex> vBlocksSide(50000); for (unsigned int i=0; i<vBlocksSide.size(); i++) { vHashSide[i] = i + 50000 + (uint256(1) << 128); // Add 1<<128 to the hashes, so GetLow64() still returns the height. vBlocksSide[i].nHeight = i + 50000; vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[49999]; vBlocksSide[i].phashBlock = &vHashSide[i]; vBlocksSide[i].BuildSkip(); BOOST_CHECK_EQUAL((int)vBlocksSide[i].GetBlockHash().GetLow64(), vBlocksSide[i].nHeight); BOOST_CHECK(vBlocksSide[i].pprev == nullptr || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Test 100 random starting points for locators. for (int n=0; n<100; n++) { int r = InsecureRandRange(150000); CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000]; CBlockLocator locator = chain.GetLocator(tip); // The first result must be the block itself, the last one must be genesis. BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash()); BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash()); // Entries 1 through 11 (inclusive) go back one step each. for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(locator.vHave[i].GetLow64(), tip->nHeight - i); } // The further ones (excluding the last one) go back with exponential steps. unsigned int dist = 2; for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) { BOOST_CHECK_EQUAL(locator.vHave[i - 1].GetLow64() - locator.vHave[i].GetLow64(), dist); dist *= 2; } } } BOOST_AUTO_TEST_CASE(findearliestatleast_test) { std::vector<uint256> vHashMain(100000); std::vector<CBlockIndex> vBlocksMain(100000); for (unsigned int i=0; i<vBlocksMain.size(); i++) { vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height vBlocksMain[i].nHeight = i; vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr; vBlocksMain[i].phashBlock = &vHashMain[i]; vBlocksMain[i].BuildSkip(); if (i < 10) { vBlocksMain[i].nTime = i; vBlocksMain[i].nTimeMax = i; } else { // randomly choose something in the range [MTP, MTP*2] int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast(); int r = InsecureRandRange(medianTimePast); vBlocksMain[i].nTime = r + medianTimePast; vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax); } } // Check that we set nTimeMax up correctly. unsigned int curTimeMax = 0; for (unsigned int i=0; i<vBlocksMain.size(); ++i) { curTimeMax = std::max(curTimeMax, vBlocksMain[i].nTime); BOOST_CHECK(curTimeMax == vBlocksMain[i].nTimeMax); } // Build a CChain for the main branch. CChain chain; chain.SetTip(&vBlocksMain.back()); // Verify that FindEarliestAtLeast is correct. for (unsigned int i=0; i<10000; ++i) { // Pick a random element in vBlocksMain. int r = InsecureRandRange(vBlocksMain.size()); int64_t test_time = vBlocksMain[r].nTime; CBlockIndex *ret = chain.FindEarliestAtLeast(test_time); BOOST_CHECK(ret->nTimeMax >= test_time); BOOST_CHECK((ret->pprev==nullptr) || ret->pprev->nTimeMax < test_time); BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <QObject> #include <QVector> #include <QString> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlField> #include <QSqlError> #include <QUrlQuery> #include "kernel.h" #include "ilwisdata.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "commandhandler.h" #include "mastercatalog.h" //---------------------------------- Ilwis::CommandHandler *Ilwis::CommandHandler::_commandHandler= 0; using namespace Ilwis; //----------------------------------- void ExecutionContext::clear() { _silent = false; _threaded = true; _results.clear(); } ExecutionContext::ExecutionContext(bool threaded) : _silent(false), _threaded(threaded){ } void ExecutionContext::addOutput(SymbolTable &tbl, const QVariant &var, const QString &nme, quint64 tp, const Resource& res) { QString name = nme == sUNDEF ? SymbolTable::newAnonym() : nme; tbl.addSymbol(name,_scope, tp, var); _results.push_back(name); if ( name.indexOf(INTERNAL_PREFIX) == -1 && res.isValid()) { mastercatalog()->addItems({res}); } } Ilwis::CommandHandler* Ilwis::commandhandler() { if (Ilwis::CommandHandler::_commandHandler == 0) { Ilwis::CommandHandler::_commandHandler = new Ilwis::CommandHandler(kernel()->parent()); //Ilwis::CommandHandler::_context->init(); } return Ilwis::CommandHandler::_commandHandler; } //------------------------------------------------------- CommandHandler::CommandHandler(QObject *parent) : QObject(parent) { } CommandHandler::~CommandHandler(){ _commands.clear(); } bool CommandHandler::execute(const QString& command, ExecutionContext *ctx) { SymbolTable tbl; OperationExpression expr(command, tbl); quint64 id = findOperationId(expr); if ( id != i64UNDEF) { QScopedPointer<OperationImplementation> oper(create( expr)); if ( !oper.isNull() && oper->isValid()) { return oper->execute(ctx, tbl); } } return false; } bool CommandHandler::execute(const QString &command, ExecutionContext *ctx, SymbolTable &symTable) { OperationExpression expr(command, symTable); quint64 id = findOperationId(expr); if ( id != i64UNDEF) { QScopedPointer<OperationImplementation> oper(create( expr)); if ( !oper.isNull() && oper->isValid()) { return oper->execute(ctx, symTable); } } return false; } OperationImplementation *CommandHandler::create(const OperationExpression &expr) { quint64 id = findOperationId(expr); auto iter = _commands.find(id); if ( iter != _commands.end()) { OperationImplementation *oper = ((*iter).second(id, expr)); return oper; } return 0; } void CommandHandler::addOperation(quint64 id, CreateOperation op) { if ( id != i64UNDEF) { _commands[id] = op; } } quint64 CommandHandler::findOperationId(const OperationExpression& expr) const { QSqlQuery db(kernel()->database()); QSqlQuery db2(kernel()->database()); QString query = QString("select * from mastercatalog where resource like '%1%' ").arg(expr.metaUrl().toString()); if (db.exec(query)) { while ( db.next()){ quint64 itemid = db.value("itemid").toLongLong(); query = QString("select * from catalogitemproperties where itemid=%1").arg(itemid); if (db2.exec(query)) { std::map<QString, QString> values; while ( db2.next()){ QSqlRecord rec = db2.record(); values[rec.value("propertyname").toString()] = rec.value("propertyvalue").toString(); } QString parmcount = values["inparameters"]; if ( !expr.matchesParameterCount(parmcount)) continue; bool found = true; for(int i=0; i < expr.parameterCount(); ++i) { QString key = QString("pin_%1_type").arg(i+1); IlwisTypes tpExpr = expr.parm(i).valuetype(); auto iter = values.find(key); if ( iter == values.end()){ found = false; break; } IlwisTypes tpMeta = (*iter).second.toULongLong(); if ( (tpMeta & tpExpr) == 0 && tpExpr != i64UNDEF) { found = false; break; } } if ( found) return itemid; } } } ERROR2(ERR_NO_INITIALIZED_2,"metadata",expr.name()); return i64UNDEF; } <commit_msg>improved the handling for methods with unbounded number of parameters<commit_after>#include <QObject> #include <QVector> #include <QString> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlField> #include <QSqlError> #include <QUrlQuery> #include "kernel.h" #include "ilwisdata.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "commandhandler.h" #include "mastercatalog.h" //---------------------------------- Ilwis::CommandHandler *Ilwis::CommandHandler::_commandHandler= 0; using namespace Ilwis; //----------------------------------- void ExecutionContext::clear() { _silent = false; _threaded = true; _results.clear(); } ExecutionContext::ExecutionContext(bool threaded) : _silent(false), _threaded(threaded){ } void ExecutionContext::addOutput(SymbolTable &tbl, const QVariant &var, const QString &nme, quint64 tp, const Resource& res) { QString name = nme == sUNDEF ? SymbolTable::newAnonym() : nme; tbl.addSymbol(name,_scope, tp, var); _results.push_back(name); if ( name.indexOf(INTERNAL_PREFIX) == -1 && res.isValid()) { mastercatalog()->addItems({res}); } } Ilwis::CommandHandler* Ilwis::commandhandler() { if (Ilwis::CommandHandler::_commandHandler == 0) { Ilwis::CommandHandler::_commandHandler = new Ilwis::CommandHandler(kernel()->parent()); //Ilwis::CommandHandler::_context->init(); } return Ilwis::CommandHandler::_commandHandler; } //------------------------------------------------------- CommandHandler::CommandHandler(QObject *parent) : QObject(parent) { } CommandHandler::~CommandHandler(){ _commands.clear(); } bool CommandHandler::execute(const QString& command, ExecutionContext *ctx) { SymbolTable tbl; OperationExpression expr(command, tbl); quint64 id = findOperationId(expr); if ( id != i64UNDEF) { QScopedPointer<OperationImplementation> oper(create( expr)); if ( !oper.isNull() && oper->isValid()) { return oper->execute(ctx, tbl); } } return false; } bool CommandHandler::execute(const QString &command, ExecutionContext *ctx, SymbolTable &symTable) { OperationExpression expr(command, symTable); quint64 id = findOperationId(expr); if ( id != i64UNDEF) { QScopedPointer<OperationImplementation> oper(create( expr)); if ( !oper.isNull() && oper->isValid()) { return oper->execute(ctx, symTable); } } return false; } OperationImplementation *CommandHandler::create(const OperationExpression &expr) { quint64 id = findOperationId(expr); auto iter = _commands.find(id); if ( iter != _commands.end()) { OperationImplementation *oper = ((*iter).second(id, expr)); return oper; } return 0; } void CommandHandler::addOperation(quint64 id, CreateOperation op) { if ( id != i64UNDEF) { _commands[id] = op; } } quint64 CommandHandler::findOperationId(const OperationExpression& expr) const { QSqlQuery db(kernel()->database()); QSqlQuery db2(kernel()->database()); QString query = QString("select * from mastercatalog where resource like '%1%' ").arg(expr.metaUrl().toString()); if (db.exec(query)) { while ( db.next()){ quint64 itemid = db.value("itemid").toLongLong(); query = QString("select * from catalogitemproperties where itemid=%1").arg(itemid); if (db2.exec(query)) { std::map<QString, QString> values; while ( db2.next()){ QSqlRecord rec = db2.record(); values[rec.value("propertyname").toString()] = rec.value("propertyvalue").toString(); } QString parmcount = values["inparameters"]; if ( !expr.matchesParameterCount(parmcount)) continue; bool found = true; long index; if ( (index = parmcount.indexOf('+')) != -1) { index = parmcount.left(index).toUInt(); } else index = 10000; for(long i=0; i < expr.parameterCount(); ++i) { int n = min(i+1, index); QString key = QString("pin_%1_type").arg(n); IlwisTypes tpExpr = expr.parm(i).valuetype(); auto iter = values.find(key); if ( iter == values.end()){ found = false; break; } IlwisTypes tpMeta = (*iter).second.toULongLong(); if ( (tpMeta & tpExpr) == 0 && tpExpr != i64UNDEF) { found = false; break; } } if ( found) return itemid; } } } ERROR2(ERR_NO_INITIALIZED_2,"metadata",expr.name()); return i64UNDEF; } <|endoftext|>
<commit_before>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ // // MhdWrapper.cpp // opendatacon // // Created by Alan Murray on 14/09/2014. // // #include <iostream> #include <opendatacon/util.h> #include "MhdWrapper.h" const int POSTBUFFERSIZE = 512; const char EMPTY_PAGE[] = "<html><head><title>File not found</title></head><body>File not found</body></html>"; const std::unordered_map<std::string, const std::string> MimeTypeMap { { "json", "application/json" }, { "js", "text/javascript" }, { "html", "text/html"}, { "jpg", "image/jpeg"}, { "css", "text/css"}, { "txt", "text/plain"}, { "svg", "image/svg+xml"}, { "default", "application/octet-stream"} }; const std::string& GetMimeType(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\."); if (last == std::string::npos) return MimeTypeMap.at("default"); const std::string pExt = rUrl.substr(last+1); if(MimeTypeMap.count(pExt) != 0) { return MimeTypeMap.at(pExt); } return MimeTypeMap.at("default"); } static ssize_t file_reader(void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *)cls; (void)fseek(file, pos, SEEK_SET); return fread(buf, 1, max, file); } static void file_free_callback(void *cls) { FILE *file = (FILE *)cls; fclose(file); } const std::string GetPath(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\"); if (last == std::string::npos) return ""; return rUrl.substr(0,last); } const std::string GetFile(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\"); if (last == std::string::npos) return rUrl; return rUrl.substr(last+1); } int ReturnFile(struct MHD_Connection *connection, const std::string& url) { struct stat buf; FILE *file; struct MHD_Response *response; int ret; if ((0 == stat(url.c_str(), &buf)) && (S_ISREG(buf.st_mode))) fopen_s(&file, url.c_str(), "rb"); else file = nullptr; if (file == nullptr) { if (auto log = odc::spdlog_get("WebUI")) log->error("WebUI : Failed to open file {}", url); response = MHD_create_response_from_buffer(strlen(EMPTY_PAGE), (void *)EMPTY_PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response(response); } else { response = MHD_create_response_from_callback(buf.st_size, 32 * 1024, /* 32k PAGE_NOT_FOUND size */ &file_reader, file, &file_free_callback); if (response == nullptr) { fclose(file); return MHD_NO; } MHD_add_response_header(response, "Content-Type", GetMimeType(url).c_str()); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); } return ret; } int ReturnJSON(struct MHD_Connection *connection, const std::string& json_str) { struct MHD_Response *response; int ret; /* MHD_RESPMEM_MUST_FREE MHD_RESPMEM_MUST_COPY */ response = MHD_create_response_from_buffer(json_str.size(), (void *)json_str.c_str(), MHD_RESPMEM_MUST_COPY); MHD_add_response_header (response, "Content-Type", MimeTypeMap.at("json").c_str()); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret; } /* * adapted from MHD_http_unescape */ std::string post_unescape(const char *val) { std::string result; const char *rpos = val; //char *wpos = val; char *end; char buf3[3]; while ('\0' != *rpos) { switch (*rpos) { case '+': { result += ' '; //*wpos = ' '; //wpos++; rpos++; break; } case '%': { if ( ('\0' == rpos[1]) || ('\0' == rpos[2]) ) { //*wpos = '\0'; //return wpos - val; return result; } buf3[0] = rpos[1]; buf3[1] = rpos[2]; buf3[2] = '\0'; auto num = strtoul (buf3, &end, 16); if ('\0' == *end) { //*wpos = (char)((unsigned char) num); //wpos++; result += (char)((unsigned char) num); rpos += 3; break; } /* intentional fall through! */ } default: { //*wpos = *rpos; //wpos++; result += *rpos; rpos++; } } } //*wpos = '\0'; /* add 0-terminator */ //return wpos - val; /* = strlen(val) */ return result; } static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, //MHD_POSTDATA_KIND const char *key, // POST KEY const char *filename, const char *content_type, const char *transfer_encoding, const char *data, // POST VALUE uint64_t off, size_t size // POST VALUE LENGTH ) { struct connection_info_struct* con_info = (connection_info_struct*) coninfo_cls; if (kind == MHD_POSTDATA_KIND) { con_info->PostValues[post_unescape(key)] = post_unescape(data); return MHD_YES; } return MHD_NO; } void request_completed(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = (connection_info_struct*)*con_cls; if (nullptr == con_info) return; if (nullptr != con_info->postprocessor) MHD_destroy_post_processor(con_info->postprocessor); con_info->postprocessor = nullptr; free(con_info); *con_cls = nullptr; } int CreateNewRequest(void *cls, struct MHD_Connection *connection, const std::string& url, const std::string& method, const std::string& version, const std::string& upload_data, size_t& upload_data_size, void **con_cls) { struct connection_info_struct *con_info; con_info = new connection_info_struct; if (nullptr == con_info) return MHD_NO; *con_cls = (void*)con_info; if (method == MHD_HTTP_METHOD_GET) return MHD_YES; if (method == "POST") { auto length = atoi(MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Content-Length")); if (length == 0) return MHD_YES; con_info->postprocessor = MHD_create_post_processor(connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (nullptr != con_info->postprocessor) return MHD_YES; } // unexpected method or couldn't create post processor free(con_info); *con_cls = nullptr; return MHD_NO; } <commit_msg>match new with delete (not free)<commit_after>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ // // MhdWrapper.cpp // opendatacon // // Created by Alan Murray on 14/09/2014. // // #include <iostream> #include <opendatacon/util.h> #include "MhdWrapper.h" const int POSTBUFFERSIZE = 512; const char EMPTY_PAGE[] = "<html><head><title>File not found</title></head><body>File not found</body></html>"; const std::unordered_map<std::string, const std::string> MimeTypeMap { { "json", "application/json" }, { "js", "text/javascript" }, { "html", "text/html"}, { "jpg", "image/jpeg"}, { "css", "text/css"}, { "txt", "text/plain"}, { "svg", "image/svg+xml"}, { "default", "application/octet-stream"} }; const std::string& GetMimeType(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\."); if (last == std::string::npos) return MimeTypeMap.at("default"); const std::string pExt = rUrl.substr(last+1); if(MimeTypeMap.count(pExt) != 0) { return MimeTypeMap.at(pExt); } return MimeTypeMap.at("default"); } static ssize_t file_reader(void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *)cls; (void)fseek(file, pos, SEEK_SET); return fread(buf, 1, max, file); } static void file_free_callback(void *cls) { FILE *file = (FILE *)cls; fclose(file); } const std::string GetPath(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\"); if (last == std::string::npos) return ""; return rUrl.substr(0,last); } const std::string GetFile(const std::string& rUrl) { auto last = rUrl.find_last_of("/\\"); if (last == std::string::npos) return rUrl; return rUrl.substr(last+1); } int ReturnFile(struct MHD_Connection *connection, const std::string& url) { struct stat buf; FILE *file; struct MHD_Response *response; int ret; if ((0 == stat(url.c_str(), &buf)) && (S_ISREG(buf.st_mode))) fopen_s(&file, url.c_str(), "rb"); else file = nullptr; if (file == nullptr) { if (auto log = odc::spdlog_get("WebUI")) log->error("WebUI : Failed to open file {}", url); response = MHD_create_response_from_buffer(strlen(EMPTY_PAGE), (void *)EMPTY_PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response(response); } else { response = MHD_create_response_from_callback(buf.st_size, 32 * 1024, /* 32k PAGE_NOT_FOUND size */ &file_reader, file, &file_free_callback); if (response == nullptr) { fclose(file); return MHD_NO; } MHD_add_response_header(response, "Content-Type", GetMimeType(url).c_str()); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); } return ret; } int ReturnJSON(struct MHD_Connection *connection, const std::string& json_str) { struct MHD_Response *response; int ret; /* MHD_RESPMEM_MUST_FREE MHD_RESPMEM_MUST_COPY */ response = MHD_create_response_from_buffer(json_str.size(), (void *)json_str.c_str(), MHD_RESPMEM_MUST_COPY); MHD_add_response_header (response, "Content-Type", MimeTypeMap.at("json").c_str()); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret; } /* * adapted from MHD_http_unescape */ std::string post_unescape(const char *val) { std::string result; const char *rpos = val; //char *wpos = val; char *end; char buf3[3]; while ('\0' != *rpos) { switch (*rpos) { case '+': { result += ' '; //*wpos = ' '; //wpos++; rpos++; break; } case '%': { if ( ('\0' == rpos[1]) || ('\0' == rpos[2]) ) { //*wpos = '\0'; //return wpos - val; return result; } buf3[0] = rpos[1]; buf3[1] = rpos[2]; buf3[2] = '\0'; auto num = strtoul (buf3, &end, 16); if ('\0' == *end) { //*wpos = (char)((unsigned char) num); //wpos++; result += (char)((unsigned char) num); rpos += 3; break; } /* intentional fall through! */ } default: { //*wpos = *rpos; //wpos++; result += *rpos; rpos++; } } } //*wpos = '\0'; /* add 0-terminator */ //return wpos - val; /* = strlen(val) */ return result; } static int iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, //MHD_POSTDATA_KIND const char *key, // POST KEY const char *filename, const char *content_type, const char *transfer_encoding, const char *data, // POST VALUE uint64_t off, size_t size // POST VALUE LENGTH ) { struct connection_info_struct* con_info = (connection_info_struct*) coninfo_cls; if (kind == MHD_POSTDATA_KIND) { con_info->PostValues[post_unescape(key)] = post_unescape(data); return MHD_YES; } return MHD_NO; } void request_completed(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = (connection_info_struct*)*con_cls; if (nullptr == con_info) return; if (nullptr != con_info->postprocessor) MHD_destroy_post_processor(con_info->postprocessor); con_info->postprocessor = nullptr; free(con_info); *con_cls = nullptr; } int CreateNewRequest(void *cls, struct MHD_Connection *connection, const std::string& url, const std::string& method, const std::string& version, const std::string& upload_data, size_t& upload_data_size, void **con_cls) { struct connection_info_struct *con_info; con_info = new connection_info_struct; if (nullptr == con_info) return MHD_NO; *con_cls = (void*)con_info; if (method == MHD_HTTP_METHOD_GET) return MHD_YES; if (method == "POST") { auto length = atoi(MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Content-Length")); if (length == 0) return MHD_YES; con_info->postprocessor = MHD_create_post_processor(connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (nullptr != con_info->postprocessor) return MHD_YES; } // unexpected method or couldn't create post processor delete con_info; *con_cls = nullptr; return MHD_NO; } <|endoftext|>
<commit_before>//---------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include "RecipeFileParser.h" #include <stdio.h> #include <stdlib.h> #include <locale.h> //-------- // Forward declarations //-------- static void parseCmdLineArgs( int argc, char ** argv, const char *& recipeFilename, const char *& scope); static void usage(); int main(int argc, char ** argv) { RecipeFileParser * parser; const char * recipeFilename; const char * scope; StringVector recipeScopes; StringVector steps; StringVector ingredients; const char * name; int i; int len; int i2; int len2; setlocale(LC_ALL, ""); parseCmdLineArgs(argc, argv, recipeFilename, scope); //-------- // Parse and error-check a file containing recipes. //-------- try { parser = new RecipeFileParser(); parser->parse(recipeFilename, scope); } catch(const RecipeFileParserException & ex) { fprintf(stderr, "%s\n", ex.c_str()); delete parser; return 1; } //-------- // Print information about the recipes. //-------- parser->listRecipeScopes(recipeScopes); len = recipeScopes.length(); printf("There are %d recipes\n", len); for (i = 0; i < len; i++) { name = parser->getRecipeName(recipeScopes[i]); parser->getRecipeIngredients(recipeScopes[i], ingredients); parser->getRecipeSteps(recipeScopes[i], steps); printf("\nRecipe \"%s\":\n", name); len2 = ingredients.length(); printf("\tThis recipe has %d ingredients:\n", len2); for (i2 = 0; i2 < len2; i2++) { printf("\t\t\"%s\"\n", ingredients[i2]); } len2 = steps.length(); printf("\tThis recipe has %d steps:\n", len2); for (i2 = 0; i2 < len2; i2++) { printf("\t\t\"%s\"\n", steps[i2]); } } delete parser; return 0; } static void parseCmdLineArgs( int argc, char ** argv, const char *& recipeFilename, const char *& scope) { int i; recipeFilename = ""; scope = ""; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { usage(); } else if (strcmp(argv[i], "-recipes") == 0) { if (i == argc-1) { usage(); } recipeFilename = argv[i+1]; i++; } else if (strcmp(argv[i], "-scope") == 0) { if (i == argc-1) { usage(); } scope = argv[i+1]; i++; } else { fprintf(stderr, "Unrecognised option '%s'\n\n", argv[i]); usage(); } } if (strcmp(recipeFilename, "") == 0) { usage(); } } static void usage() { fprintf(stderr, "\n" "usage: demo <options> -recipes <source>\n" "\n" "The <options> can be:\n" " -h Print this usage statement\n" " -scope scope within recipes file\n" "A <source> can be one of the following:\n" " file.cfg A file\n" " file#file.cfg A file\n" " exec#<command> Output from executing the specified command\n\n"); exit(1); } <commit_msg>Initialize variable.<commit_after>//---------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include "RecipeFileParser.h" #include <stdio.h> #include <stdlib.h> #include <locale.h> //-------- // Forward declarations //-------- static void parseCmdLineArgs( int argc, char ** argv, const char *& recipeFilename, const char *& scope); static void usage(); int main(int argc, char ** argv) { RecipeFileParser * parser = nullptr; const char * recipeFilename; const char * scope; StringVector recipeScopes; StringVector steps; StringVector ingredients; const char * name; int i; int len; int i2; int len2; setlocale(LC_ALL, ""); parseCmdLineArgs(argc, argv, recipeFilename, scope); //-------- // Parse and error-check a file containing recipes. //-------- try { parser = new RecipeFileParser(); parser->parse(recipeFilename, scope); } catch(const RecipeFileParserException & ex) { fprintf(stderr, "%s\n", ex.c_str()); delete parser; return 1; } //-------- // Print information about the recipes. //-------- parser->listRecipeScopes(recipeScopes); len = recipeScopes.length(); printf("There are %d recipes\n", len); for (i = 0; i < len; i++) { name = parser->getRecipeName(recipeScopes[i]); parser->getRecipeIngredients(recipeScopes[i], ingredients); parser->getRecipeSteps(recipeScopes[i], steps); printf("\nRecipe \"%s\":\n", name); len2 = ingredients.length(); printf("\tThis recipe has %d ingredients:\n", len2); for (i2 = 0; i2 < len2; i2++) { printf("\t\t\"%s\"\n", ingredients[i2]); } len2 = steps.length(); printf("\tThis recipe has %d steps:\n", len2); for (i2 = 0; i2 < len2; i2++) { printf("\t\t\"%s\"\n", steps[i2]); } } delete parser; return 0; } static void parseCmdLineArgs( int argc, char ** argv, const char *& recipeFilename, const char *& scope) { int i; recipeFilename = ""; scope = ""; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { usage(); } else if (strcmp(argv[i], "-recipes") == 0) { if (i == argc-1) { usage(); } recipeFilename = argv[i+1]; i++; } else if (strcmp(argv[i], "-scope") == 0) { if (i == argc-1) { usage(); } scope = argv[i+1]; i++; } else { fprintf(stderr, "Unrecognised option '%s'\n\n", argv[i]); usage(); } } if (strcmp(recipeFilename, "") == 0) { usage(); } } static void usage() { fprintf(stderr, "\n" "usage: demo <options> -recipes <source>\n" "\n" "The <options> can be:\n" " -h Print this usage statement\n" " -scope scope within recipes file\n" "A <source> can be one of the following:\n" " file.cfg A file\n" " file#file.cfg A file\n" " exec#<command> Output from executing the specified command\n\n"); exit(1); } <|endoftext|>
<commit_before>#include "..\include\SequentialGreedy.h" #include <iostream> // Greedily color one vertex uint16_t SequentialGreedy::colorVertexGreedy(uint64_t vertex, std::vector<uint64_t> &neighbors, ColorMap &colors) { uint16_t color = 0; bool lowest_found = false; while (!lowest_found) { lowest_found = true; for (uint64_t id : neighbors) { auto search = colors.find(id); if (search == colors.end()) continue; if (color == search->second) { lowest_found = false; color++; break; }; } } return color; } // Greedily color all vertices. int SequentialGreedy::color(AdjacencyList adjacencyList, std::set<Vertex> sortedVertices, bool ascending) { static std::unordered_map<uint64_t, uint16_t> colors = std::unordered_map<uint64_t, uint16_t>(); uint16_t highestColor = 0; // Ascending order if (ascending) { for (auto vertex = sortedVertices.begin(); vertex != sortedVertices.end(); ++vertex) { uint16_t color = colorVertexGreedy( vertex->id, adjacencyList.getNeighbors(vertex->id), colors ); colors.insert(std::make_pair(vertex->id, color)); if (color > highestColor) highestColor = color; } } // Descending order else { for (auto vertex = sortedVertices.rbegin(); vertex != sortedVertices.rend(); ++vertex) { uint16_t color = colorVertexGreedy( vertex->id, adjacencyList.getNeighbors(vertex->id), colors ); colors.insert(std::make_pair(vertex->id, color)); if (color > highestColor) highestColor = color; } } return highestColor + 1; } <commit_msg>Speed coloring individual vertices<commit_after>#include "..\include\SequentialGreedy.h" #include <iostream> // Greedily color one vertex uint16_t SequentialGreedy::colorVertexGreedy(uint64_t vertex, std::vector<uint64_t> &neighbors, ColorMap &colors) { std::set<uint16_t> neighborColors = std::set<uint16_t>(); for (uint64_t neighbor : neighbors) { auto search = colors.find(neighbor); if (search == colors.end()) continue; neighborColors.insert(search->second); } uint16_t last = 0; for (uint16_t color : neighborColors) { if (color == last) last += 1; else break; } return last; } // Greedily color all vertices. int SequentialGreedy::color(AdjacencyList adjacencyList, std::set<Vertex> sortedVertices, bool ascending) { static std::unordered_map<uint64_t, uint16_t> colors = std::unordered_map<uint64_t, uint16_t>(); uint16_t highestColor = 0; // Ascending order if (ascending) { for (auto vertex = sortedVertices.begin(); vertex != sortedVertices.end(); ++vertex) { uint16_t color = colorVertexGreedy( vertex->id, adjacencyList.getNeighbors(vertex->id), colors ); colors.insert(std::make_pair(vertex->id, color)); if (color > highestColor) highestColor = color; } } // Descending order else { for (auto vertex = sortedVertices.rbegin(); vertex != sortedVertices.rend(); ++vertex) { uint16_t color = colorVertexGreedy( vertex->id, adjacencyList.getNeighbors(vertex->id), colors ); colors.insert(std::make_pair(vertex->id, color)); if (color > highestColor) highestColor = color; } } return highestColor + 1; } <|endoftext|>
<commit_before>/* * $Id: BitVector.cpp,v 1.3 2006/09/18 06:20:15 nathanst Exp $ * * This file is part of HOG. * * HOG 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 2 of the License, or * (at your option) any later version. * * HOG 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 HOG; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cstdlib> #include <cstdio> #include "BitVector.h" #include "MMapUtil.h" #include <sys/mman.h> BitVector::BitVector(uint64_t _size) { true_size = _size; size = (_size>>storageBitsPower)+1; storage = new storageElement[size]; for (int x = 0; x < size; x++) storage[x] = 0; memmap = false; } BitVector::BitVector(uint64_t entries, const char *file, bool zero) { // make sure we allocate even space for 32 bit entries while (0 != entries%storageBits) { entries++; } uint8_t *mem = GetMMAP(file, entries/8, fd, zero); // number of bytes needed storage = (storageElement*)mem; size = (entries>>storageBitsPower)+1; true_size = entries; memmap = true; } BitVector::~BitVector() { if (!memmap) { delete [] storage; } else { printf("Closing mmap\n"); // close memmap CloseMMap((uint8_t*)storage, true_size/8, fd); } } void BitVector::Save(const char *file) { FILE *f = fopen(file, "w+"); if (f == 0) { printf("File write error\n"); exit(0); } fwrite(&true_size, sizeof(true_size), 1, f); fwrite(storage, sizeof(storageElement), size, f); fclose(f); } void BitVector::Load(const char *file) { if (memmap) { printf("BitVector is memmapped; not loading\n"); return; } delete [] storage; FILE *f = fopen(file, "r"); if (f == 0) { printf("File write error\n"); exit(0); } //fread(&size, sizeof(size), 1, f); fread(&true_size, sizeof(true_size), 1, f); printf("Loading %llu entries\n", true_size); // allocate storage size = (true_size>>storageBitsPower)+1; storage = new storageElement[size]; // for (int x = 0; x < size; x++) // storage[x] = 0; // TODO: fread(storage, sizeof(storageElement), size, f); fclose(f); } void BitVector::clear() { for (int x = 0; x < size; x++) storage[x] = 0; } //BitVector *BitVector::Clone() //{ // BitVector *bv = new BitVector(true_size); // bv->Merge(this); // return bv; //} void BitVector::Set(uint64_t index, bool value) { if ((index>>storageBitsPower) > size) { printf("SET %llu OUT OF RANGE\n", index); exit(0); } if (value) storage[index>>storageBitsPower] = storage[index>>storageBitsPower]|(1<<(index&storageMask)); else storage[index>>storageBitsPower] = storage[index>>storageBitsPower]&(~(1<<(index&storageMask))); } //void BitVector::Merge(BitVector *bv) //{ // if (bv == 0) return; // if (bv->size != size) { // printf("Error; can't merge vectors of different sizes (%d/%d)\n", bv->true_size, true_size); // return; // } // for (int x = 0; x < size; x++) storage[x] |= bv->storage[x]; //} bool BitVector::Equals(BitVector *bv) { if (bv->size != size) return false; for (int x = 0; x < size; x++) if (storage[x] != bv->storage[x]) return false; return true; } int BitVector::GetNumSetBits() { int sum = 0; for (int x = 0; x < size; x++) { storageElement iter = storage[x]; while (iter) { if (iter&1) sum++; iter = iter>>1; } } return sum; } <commit_msg>better error messages<commit_after>/* * $Id: BitVector.cpp,v 1.3 2006/09/18 06:20:15 nathanst Exp $ * * This file is part of HOG. * * HOG 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 2 of the License, or * (at your option) any later version. * * HOG 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 HOG; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cstdlib> #include <cstdio> #include "BitVector.h" #include "MMapUtil.h" #include <sys/mman.h> BitVector::BitVector(uint64_t _size) { true_size = _size; size = (_size>>storageBitsPower)+1; storage = new storageElement[size]; for (int x = 0; x < size; x++) storage[x] = 0; memmap = false; } BitVector::BitVector(uint64_t entries, const char *file, bool zero) { // make sure we allocate even space for 32 bit entries while (0 != entries%storageBits) { entries++; } uint8_t *mem = GetMMAP(file, entries/8, fd, zero); // number of bytes needed storage = (storageElement*)mem; size = (entries>>storageBitsPower)+1; true_size = entries; memmap = true; } BitVector::~BitVector() { if (!memmap) { delete [] storage; } else { printf("Closing mmap\n"); // close memmap CloseMMap((uint8_t*)storage, true_size/8, fd); } } void BitVector::Save(const char *file) { FILE *f = fopen(file, "w+"); if (f == 0) { printf("File write error (%s)\n", file); exit(0); } fwrite(&true_size, sizeof(true_size), 1, f); fwrite(storage, sizeof(storageElement), size, f); fclose(f); } void BitVector::Load(const char *file) { if (memmap) { printf("BitVector is memmapped; not loading\n"); return; } delete [] storage; FILE *f = fopen(file, "r"); if (f == 0) { printf("File read error (%s)\n", file); exit(0); } //fread(&size, sizeof(size), 1, f); fread(&true_size, sizeof(true_size), 1, f); printf("Loading %llu entries\n", true_size); // allocate storage size = (true_size>>storageBitsPower)+1; storage = new storageElement[size]; // for (int x = 0; x < size; x++) // storage[x] = 0; // TODO: fread(storage, sizeof(storageElement), size, f); fclose(f); } void BitVector::clear() { for (int x = 0; x < size; x++) storage[x] = 0; } //BitVector *BitVector::Clone() //{ // BitVector *bv = new BitVector(true_size); // bv->Merge(this); // return bv; //} void BitVector::Set(uint64_t index, bool value) { if ((index>>storageBitsPower) > size) { printf("SET %llu OUT OF RANGE\n", index); exit(0); } if (value) storage[index>>storageBitsPower] = storage[index>>storageBitsPower]|(1<<(index&storageMask)); else storage[index>>storageBitsPower] = storage[index>>storageBitsPower]&(~(1<<(index&storageMask))); } //void BitVector::Merge(BitVector *bv) //{ // if (bv == 0) return; // if (bv->size != size) { // printf("Error; can't merge vectors of different sizes (%d/%d)\n", bv->true_size, true_size); // return; // } // for (int x = 0; x < size; x++) storage[x] |= bv->storage[x]; //} bool BitVector::Equals(BitVector *bv) { if (bv->size != size) return false; for (int x = 0; x < size; x++) if (storage[x] != bv->storage[x]) return false; return true; } int BitVector::GetNumSetBits() { int sum = 0; for (int x = 0; x < size; x++) { storageElement iter = storage[x]; while (iter) { if (iter&1) sum++; iter = iter>>1; } } return sum; } <|endoftext|>
<commit_before>/* * Copyright 2016 Nu-book Inc. * Copyright 2019 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "GTIN.h" #include <cctype> #include <chrono> #include <clocale> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> using namespace ZXing; using namespace TextUtfEncoding; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-norotate] [-format <FORMAT[,...]>] [-pngout <png out path>] [-ispure] [-1] <png image path>...\n" << " -fast Skip some lines/pixels during detection (faster)\n" << " -norotate Don't try rotated image during detection (faster)\n" << " -noscale Don't try downscaled images during detection (faster)\n" << " -format Only detect given format(s) (faster)\n" << " -ispure Assume the image contains only a 'pure'/perfect code (faster)\n" << " -1 Print only file name, text and status on one line per file/barcode\n" << " -escape Escape non-graphical characters in angle brackets (implicit for -1 option, which always escapes)\n" << " -binary Write (only) the binary content of the symbol(s) to stdout\n" << " -pngout Write a copy of the input image with barcodes outlined by a green line\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints& hints, bool& oneLine, bool& angleEscape, bool& binaryOutput, std::vector<std::string>& filePaths, std::string& outPath) { for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints.setTryHarder(false); } else if (strcmp(argv[i], "-norotate") == 0) { hints.setTryRotate(false); } else if (strcmp(argv[i], "-noscale") == 0) { hints.setDownscaleThreshold(0); } else if (strcmp(argv[i], "-ispure") == 0) { hints.setIsPure(true); hints.setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints.setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else if (strcmp(argv[i], "-1") == 0) { oneLine = true; } else if (strcmp(argv[i], "-escape") == 0) { angleEscape = true; } else if (strcmp(argv[i], "-binary") == 0) { binaryOutput = true; } else if (strcmp(argv[i], "-pngout") == 0) { if (++i == argc) return false; outPath = argv[i]; } else { filePaths.push_back(argv[i]); } } return !filePaths.empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } void drawLine(const ImageView& iv, PointI a, PointI b) { int steps = maxAbsComponent(b - a); PointF dir = bresenhamDirection(PointF(b - a)); int R = RedIndex(iv.format()), G = GreenIndex(iv.format()), B = BlueIndex(iv.format()); for (int i = 0; i < steps; ++i) { auto p = PointI(centered(a + i * dir)); auto* dst = const_cast<uint8_t*>(iv.data(p.x, p.y)); dst[R] = dst[B] = 0; dst[G] = 0xff; } } void drawRect(const ImageView& image, const Position& pos) { for (int i = 0; i < 4; ++i) drawLine(image, pos[i], pos[(i + 1) % 4]); } int main(int argc, char* argv[]) { DecodeHints hints; std::vector<std::string> filePaths; std::string outPath; bool oneLine = false; bool angleEscape = false; bool binaryOutput = false; int ret = 0; if (!ParseOptions(argc, argv, hints, oneLine, angleEscape, binaryOutput, filePaths, outPath)) { PrintUsage(argv[0]); return -1; } hints.setEanAddOnSymbol(EanAddOnSymbol::Read); if (oneLine) angleEscape = true; if (angleEscape) std::setlocale(LC_CTYPE, "en_US.UTF-8"); // Needed so `std::iswgraph()` in `ToUtf8(angleEscape)` does not 'swallow' all printable non-ascii utf8 chars for (const auto& filePath : filePaths) { int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 3), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } ImageView image{buffer.get(), width, height, ImageFormat::RGB}; auto results = ReadBarcodes(image, hints); // if we did not find anything, insert a dummy to produce some output for each file if (results.empty()) results.emplace_back(DecodeStatus::NotFound); for (auto&& result : results) { if (!outPath.empty()) drawRect(image, result.position()); ret |= static_cast<int>(result.status()); if (binaryOutput) { std::cout.write(reinterpret_cast<const char*>(result.binary().data()), result.binary().size()); continue; } if (oneLine) { std::cout << filePath << " " << ToString(result.format()); if (result.isValid()) std::cout << " \"" << ToUtf8(result.text(), angleEscape) << "\""; else if (result.format() != BarcodeFormat::None) std::cout << " " << ToString(result.status()); std::cout << "\n"; continue; } if (filePaths.size() > 1 || results.size() > 1) { static bool firstFile = true; if (!firstFile) std::cout << "\n"; if (filePaths.size() > 1) std::cout << "File: " << filePath << "\n"; firstFile = false; } std::cout << "Text: \"" << ToUtf8(result.text(), angleEscape) << "\"\n" << "Binary: \"" << ToHex(result.binary()) << "\"\n" << "ECI-Proto: \"" << result.utf8Protocol() << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Identifier: " << result.symbologyIdentifier() << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << result.orientation() << " deg\n" << "IsMirrored: " << (result.isMirrored() ? "true" : "false") << "\n" << "Error: " << ToString(result.status()) << "\n"; auto printOptional = [](const char* key, const std::string& v) { if (!v.empty()) std::cout << key << v << "\n"; }; printOptional("EC Level: ", ToUtf8(result.ecLevel())); printOptional("App-Ind.: ", result.applicationIndicator()); if (result.lineCount()) std::cout << "Lines: " << result.lineCount() << "\n"; if ((BarcodeFormat::EAN13 | BarcodeFormat::EAN8 | BarcodeFormat::UPCA | BarcodeFormat::UPCE) .testFlag(result.format())) { printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format())); printOptional("Add-On: ", GTIN::EanAddOn(result)); printOptional("Price: ", GTIN::Price(GTIN::EanAddOn(result))); printOptional("Issue #: ", GTIN::IssueNr(GTIN::EanAddOn(result))); } else if (result.format() == BarcodeFormat::ITF && result.text().length() == 14) { printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format())); } if (result.isPartOfSequence()) std::cout << "Structured Append: symbol " << result.sequenceIndex() + 1 << " of " << result.sequenceSize() << " (parity/id: '" << result.sequenceId() << "')\n"; if (result.readerInit()) std::cout << "Reader Initialisation/Programming\n"; } if (Size(filePaths) == 1 && !outPath.empty()) stbi_write_png(outPath.c_str(), image.width(), image.height(), 3, image.data(0, 0), image.rowStride()); } return ret; } <commit_msg>example: use std::ios::boolalpha<commit_after>/* * Copyright 2016 Nu-book Inc. * Copyright 2019 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "GTIN.h" #include <cctype> #include <chrono> #include <clocale> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> using namespace ZXing; using namespace TextUtfEncoding; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-norotate] [-format <FORMAT[,...]>] [-pngout <png out path>] [-ispure] [-1] <png image path>...\n" << " -fast Skip some lines/pixels during detection (faster)\n" << " -norotate Don't try rotated image during detection (faster)\n" << " -noscale Don't try downscaled images during detection (faster)\n" << " -format Only detect given format(s) (faster)\n" << " -ispure Assume the image contains only a 'pure'/perfect code (faster)\n" << " -1 Print only file name, text and status on one line per file/barcode\n" << " -escape Escape non-graphical characters in angle brackets (implicit for -1 option, which always escapes)\n" << " -binary Write (only) the binary content of the symbol(s) to stdout\n" << " -pngout Write a copy of the input image with barcodes outlined by a green line\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints& hints, bool& oneLine, bool& angleEscape, bool& binaryOutput, std::vector<std::string>& filePaths, std::string& outPath) { for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints.setTryHarder(false); } else if (strcmp(argv[i], "-norotate") == 0) { hints.setTryRotate(false); } else if (strcmp(argv[i], "-noscale") == 0) { hints.setDownscaleThreshold(0); } else if (strcmp(argv[i], "-ispure") == 0) { hints.setIsPure(true); hints.setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints.setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else if (strcmp(argv[i], "-1") == 0) { oneLine = true; } else if (strcmp(argv[i], "-escape") == 0) { angleEscape = true; } else if (strcmp(argv[i], "-binary") == 0) { binaryOutput = true; } else if (strcmp(argv[i], "-pngout") == 0) { if (++i == argc) return false; outPath = argv[i]; } else { filePaths.push_back(argv[i]); } } return !filePaths.empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } void drawLine(const ImageView& iv, PointI a, PointI b) { int steps = maxAbsComponent(b - a); PointF dir = bresenhamDirection(PointF(b - a)); int R = RedIndex(iv.format()), G = GreenIndex(iv.format()), B = BlueIndex(iv.format()); for (int i = 0; i < steps; ++i) { auto p = PointI(centered(a + i * dir)); auto* dst = const_cast<uint8_t*>(iv.data(p.x, p.y)); dst[R] = dst[B] = 0; dst[G] = 0xff; } } void drawRect(const ImageView& image, const Position& pos) { for (int i = 0; i < 4; ++i) drawLine(image, pos[i], pos[(i + 1) % 4]); } int main(int argc, char* argv[]) { DecodeHints hints; std::vector<std::string> filePaths; std::string outPath; bool oneLine = false; bool angleEscape = false; bool binaryOutput = false; int ret = 0; if (!ParseOptions(argc, argv, hints, oneLine, angleEscape, binaryOutput, filePaths, outPath)) { PrintUsage(argv[0]); return -1; } hints.setEanAddOnSymbol(EanAddOnSymbol::Read); if (oneLine) angleEscape = true; if (angleEscape) std::setlocale(LC_CTYPE, "en_US.UTF-8"); // Needed so `std::iswgraph()` in `ToUtf8(angleEscape)` does not 'swallow' all printable non-ascii utf8 chars std::cout.setf(std::ios::boolalpha); for (const auto& filePath : filePaths) { int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 3), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } ImageView image{buffer.get(), width, height, ImageFormat::RGB}; auto results = ReadBarcodes(image, hints); // if we did not find anything, insert a dummy to produce some output for each file if (results.empty()) results.emplace_back(DecodeStatus::NotFound); for (auto&& result : results) { if (!outPath.empty()) drawRect(image, result.position()); ret |= static_cast<int>(result.status()); if (binaryOutput) { std::cout.write(reinterpret_cast<const char*>(result.binary().data()), result.binary().size()); continue; } if (oneLine) { std::cout << filePath << " " << ToString(result.format()); if (result.isValid()) std::cout << " \"" << ToUtf8(result.text(), angleEscape) << "\""; else if (result.format() != BarcodeFormat::None) std::cout << " " << ToString(result.status()); std::cout << "\n"; continue; } if (filePaths.size() > 1 || results.size() > 1) { static bool firstFile = true; if (!firstFile) std::cout << "\n"; if (filePaths.size() > 1) std::cout << "File: " << filePath << "\n"; firstFile = false; } std::cout << "Text: \"" << ToUtf8(result.text(), angleEscape) << "\"\n" << "Binary: \"" << ToHex(result.binary()) << "\"\n" << "ECI-Proto: \"" << result.utf8Protocol() << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Identifier: " << result.symbologyIdentifier() << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << result.orientation() << " deg\n" << "IsMirrored: " << result.isMirrored() << "\n" << "Error: " << ToString(result.status()) << "\n"; auto printOptional = [](const char* key, const std::string& v) { if (!v.empty()) std::cout << key << v << "\n"; }; printOptional("EC Level: ", ToUtf8(result.ecLevel())); printOptional("App-Ind.: ", result.applicationIndicator()); if (result.lineCount()) std::cout << "Lines: " << result.lineCount() << "\n"; if ((BarcodeFormat::EAN13 | BarcodeFormat::EAN8 | BarcodeFormat::UPCA | BarcodeFormat::UPCE) .testFlag(result.format())) { printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format())); printOptional("Add-On: ", GTIN::EanAddOn(result)); printOptional("Price: ", GTIN::Price(GTIN::EanAddOn(result))); printOptional("Issue #: ", GTIN::IssueNr(GTIN::EanAddOn(result))); } else if (result.format() == BarcodeFormat::ITF && result.text().length() == 14) { printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format())); } if (result.isPartOfSequence()) std::cout << "Structured Append: symbol " << result.sequenceIndex() + 1 << " of " << result.sequenceSize() << " (parity/id: '" << result.sequenceId() << "')\n"; if (result.readerInit()) std::cout << "Reader Initialisation/Programming\n"; } if (Size(filePaths) == 1 && !outPath.empty()) stbi_write_png(outPath.c_str(), image.width(), image.height(), 3, image.data(0, 0), image.rowStride()); } return ret; } <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NdbOut.hpp> #include <NdbApi.hpp> #include <NdbSleep.h> #include <NDBT.hpp> #include <HugoTransactions.hpp> #include <getarg.h> int main(int argc, const char** argv){ ndb_init(); int _help = 0; const char* db = 0; struct getargs args[] = { { "database", 'd', arg_string, &db, "Database", "" }, { "usage", '?', arg_flag, &_help, "Print help", "" } }; int num_args = sizeof(args) / sizeof(args[0]); int optind = 0, i; char desc[] = "<tabname>+ \nThis program listen to events on specified tables\n"; if(getarg(args, num_args, argc, argv, &optind) || argv[optind] == NULL || _help) { arg_printusage(args, num_args, argv[0], desc); return NDBT_ProgramExit(NDBT_WRONGARGS); } // Connect to Ndb Ndb_cluster_connection con; if(con.connect(12, 5, 1) != 0) { return NDBT_ProgramExit(NDBT_FAILED); } Ndb MyNdb( &con, db ? db : "TEST_DB" ); if(MyNdb.init() != 0){ ERR(MyNdb.getNdbError()); return NDBT_ProgramExit(NDBT_FAILED); } // Connect to Ndb and wait for it to become ready while(MyNdb.waitUntilReady() != 0) ndbout << "Waiting for ndb to become ready..." << endl; int result = 0; Uint64 last_gci= 0, cnt= 0; NdbDictionary::Dictionary *myDict = MyNdb.getDictionary(); Vector<NdbDictionary::Event*> events; Vector<NdbEventOperation*> event_ops; for(i= optind; i<argc; i++) { const NdbDictionary::Table* table= myDict->getTable(argv[i]); if(!table) { ndbout_c("Could not find table: %s, skipping", argv[i]); continue; } BaseString name; name.appfmt("EV-%s", argv[i]); NdbDictionary::Event *myEvent= new NdbDictionary::Event(name.c_str()); myEvent->setTable(table->getName()); myEvent->addTableEvent(NdbDictionary::Event::TE_ALL); for(int a = 0; a < table->getNoOfColumns(); a++){ myEvent->addEventColumn(a); } if (myDict->createEvent(* myEvent)) { if(myDict->getNdbError().classification == NdbError::SchemaObjectExists) { g_info << "Event creation failed event exists\n"; if (myDict->dropEvent(name.c_str())) { g_err << "Failed to drop event: " << myDict->getNdbError() << endl; result = 1; goto end; } // try again if (myDict->createEvent(* myEvent)) { g_err << "Failed to create event: " << myDict->getNdbError() << endl; result = 1; goto end; } } else { g_err << "Failed to create event: " << myDict->getNdbError() << endl; result = 1; goto end; } } events.push_back(myEvent); NdbEventOperation* pOp = MyNdb.createEventOperation(name.c_str()); if ( pOp == NULL ) { g_err << "Event operation creation failed" << endl; result = 1; goto end; } for (int a = 0; a < table->getNoOfColumns(); a++) { pOp->getValue(table->getColumn(a)->getName()); pOp->getPreValue(table->getColumn(a)->getName()); } event_ops.push_back(pOp); } for(i= 0; i<(int)event_ops.size(); i++) { if (event_ops[i]->execute()) { g_err << "operation execution failed: " << event_ops[i]->getNdbError() << endl; result = 1; goto end; } } while(true) { while(MyNdb.pollEvents(100) == 0); NdbEventOperation* pOp; while((pOp= MyNdb.nextEvent()) != 0) { if(pOp->getGCI() != last_gci) { if(cnt) ndbout_c("GCI: %lld events: %lld", last_gci, cnt); cnt= 1; last_gci= pOp->getGCI(); } else { cnt++; } } } end: return NDBT_ProgramExit(NDBT_OK); } template class Vector<NdbDictionary::Event*>; template class Vector<NdbEventOperation*>; <commit_msg>updated ndb listen_event to print more info, and to give immediate respose<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NdbOut.hpp> #include <NdbApi.hpp> #include <NdbSleep.h> #include <NDBT.hpp> #include <HugoTransactions.hpp> #include <getarg.h> int main(int argc, const char** argv){ ndb_init(); int _help = 0; const char* db = 0; struct getargs args[] = { { "database", 'd', arg_string, &db, "Database", "" }, { "usage", '?', arg_flag, &_help, "Print help", "" } }; int num_args = sizeof(args) / sizeof(args[0]); int optind = 0, i; char desc[] = "<tabname>+ \nThis program listen to events on specified tables\n"; if(getarg(args, num_args, argc, argv, &optind) || argv[optind] == NULL || _help) { arg_printusage(args, num_args, argv[0], desc); return NDBT_ProgramExit(NDBT_WRONGARGS); } // Connect to Ndb Ndb_cluster_connection con; if(con.connect(12, 5, 1) != 0) { return NDBT_ProgramExit(NDBT_FAILED); } Ndb MyNdb( &con, db ? db : "TEST_DB" ); if(MyNdb.init() != 0){ ERR(MyNdb.getNdbError()); return NDBT_ProgramExit(NDBT_FAILED); } // Connect to Ndb and wait for it to become ready while(MyNdb.waitUntilReady() != 0) ndbout << "Waiting for ndb to become ready..." << endl; int result = 0; NdbDictionary::Dictionary *myDict = MyNdb.getDictionary(); Vector<NdbDictionary::Event*> events; Vector<NdbEventOperation*> event_ops; for(i= optind; i<argc; i++) { const NdbDictionary::Table* table= myDict->getTable(argv[i]); if(!table) { ndbout_c("Could not find table: %s, skipping", argv[i]); continue; } BaseString name; name.appfmt("EV-%s", argv[i]); NdbDictionary::Event *myEvent= new NdbDictionary::Event(name.c_str()); myEvent->setTable(table->getName()); myEvent->addTableEvent(NdbDictionary::Event::TE_ALL); for(int a = 0; a < table->getNoOfColumns(); a++){ myEvent->addEventColumn(a); } if (myDict->createEvent(* myEvent)) { if(myDict->getNdbError().classification == NdbError::SchemaObjectExists) { g_info << "Event creation failed event exists. Removing...\n"; if (myDict->dropEvent(name.c_str())) { g_err << "Failed to drop event: " << myDict->getNdbError() << endl; result = 1; goto end; } // try again if (myDict->createEvent(* myEvent)) { g_err << "Failed to create event: " << myDict->getNdbError() << endl; result = 1; goto end; } } else { g_err << "Failed to create event: " << myDict->getNdbError() << endl; result = 1; goto end; } } events.push_back(myEvent); NdbEventOperation* pOp = MyNdb.createEventOperation(name.c_str()); if ( pOp == NULL ) { g_err << "Event operation creation failed" << endl; result = 1; goto end; } for (int a = 0; a < table->getNoOfColumns(); a++) { pOp->getValue(table->getColumn(a)->getName()); pOp->getPreValue(table->getColumn(a)->getName()); } event_ops.push_back(pOp); } for(i= 0; i<(int)event_ops.size(); i++) { if (event_ops[i]->execute()) { g_err << "operation execution failed: " << event_ops[i]->getNdbError() << endl; result = 1; goto end; } } while(true) { while(MyNdb.pollEvents(100) == 0); NdbEventOperation* pOp= MyNdb.nextEvent(); while(pOp) { Uint64 gci= pOp->getGCI(); Uint64 cnt_i= 0, cnt_u= 0, cnt_d= 0; do { switch(pOp->getEventType()) { case NdbDictionary::Event::TE_INSERT: cnt_i++; break; case NdbDictionary::Event::TE_DELETE: cnt_d++; break; case NdbDictionary::Event::TE_UPDATE: cnt_u++; break; default: /* We should REALLY never get here. */ ndbout_c("Error: unknown event type"); abort(); } } while ((pOp= MyNdb.nextEvent()) && gci == pOp->getGCI()); ndbout_c("GCI: %lld events: %lld(I) %lld(U) %lld(D)", gci, cnt_i, cnt_u, cnt_d); } } end: return NDBT_ProgramExit(NDBT_OK); } template class Vector<NdbDictionary::Event*>; template class Vector<NdbEventOperation*>; <|endoftext|>
<commit_before>#include "ToCNFAIG.h" namespace BEEV { // Can it only add in the new variables somehow?? void addVariables(BBNodeManagerAIG& mgr, Cnf_Dat_t*& cnfData , ToSATBase::ASTNodeToSATVar& nodeToVar) { BBNodeManagerAIG::SymbolToBBNode::const_iterator it; // Each symbol maps to a vector of CNF variables. for (it = mgr.symbolToBBNode.begin(); it != mgr.symbolToBBNode.end(); it++) { const ASTNode& n = it->first; const vector<BBNodeAIG> &b = it->second; const int width = (n.GetType() == BOOLEAN_TYPE) ? 1 : n.GetValueWidth(); // INT_MAX for parts of symbols that didn't get encoded. vector<unsigned> v(width, ~((unsigned) 0)); for (unsigned i = 0; i < b.size(); i++) { if (!b[i].IsNull()) { Aig_Obj_t * pObj; pObj = (Aig_Obj_t*) Vec_PtrEntry(mgr.aigMgr->vPis, b[i].symbol_index); v[i] = cnfData->pVarNums[pObj->Id]; } } nodeToVar.insert(make_pair(n, v)); } } // When we need abstraction refinement. void ToCNFAIG::toCNF_renter(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, BBNodeManagerAIG& mgr) { assert(priorCnfData != NULL); Aig_ObjCreatePo(mgr.aigMgr, top.n); // A new PO. cnfData = Cnf_DeriveSimple_Additional(mgr.aigMgr, priorCnfData); Cnf_DataFree(priorCnfData); priorCnfData = cnfData; addVariables( mgr, cnfData , nodeToVar); } void ToCNFAIG::toCNF(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, bool needAbsRef, BBNodeManagerAIG& mgr) { assert(cnfData == NULL); Aig_ObjCreatePo(mgr.aigMgr, top.n); if (!needAbsRef) { Aig_ManCleanup( mgr.aigMgr); // remove nodes not connected to the PO. } Aig_ManCheck( mgr.aigMgr); // check that AIG looks ok. assert(Aig_ManPoNum(mgr.aigMgr) == 1); // UseZeroes gives assertion errors. // Rewriting is sometimes very slow. Can it be configured to be faster? // What about refactoring??? int nodeCount = mgr.aigMgr->nObjs[AIG_OBJ_AND]; if (uf.stats_flag) cerr << "Nodes before AIG rewrite:" << nodeCount << endl; if (!needAbsRef && uf.isSet("aig_rewrite","0")) { Dar_LibStart(); Aig_Man_t * pTemp; Dar_RwrPar_t Pars, *pPars = &Pars; Dar_ManDefaultRwrParams(pPars); // Assertion errors occur with this enabled. // pPars->fUseZeros = 1; // For mul63bit.smt2 with iterations =3 & nCutsMax = 8 // CNF generation was taking 139 seconds, solving 10 seconds. // With nCutsMax =2, CNF generation takes 16 seconds, solving 10 seconds. // The rewriting doesn't remove as many nodes of course.. int iterations = 3; for (int i = 0; i < iterations; i++) { mgr.aigMgr = Aig_ManDup(pTemp = mgr.aigMgr, 0); Aig_ManStop(pTemp); Dar_ManRewrite(mgr.aigMgr, pPars); mgr.aigMgr = Aig_ManDup(pTemp = mgr.aigMgr, 0); Aig_ManStop(pTemp); if (uf.stats_flag) cerr << "After rewrite [" << i << "] nodes:" << mgr.aigMgr->nObjs[AIG_OBJ_AND] << endl; if (nodeCount == mgr.aigMgr->nObjs[AIG_OBJ_AND]) break; } } if (!needAbsRef && mgr.aigMgr->nObjs[AIG_OBJ_AND] < 2000000 && !uf.isSet("simple-cnf","0")) { cnfData = Cnf_Derive(mgr.aigMgr, 0); } else { cnfData = Cnf_DeriveSimple(mgr.aigMgr, 0); } BBNodeManagerAIG::SymbolToBBNode::const_iterator it; assert(nodeToVar.size() == 0); //todo. cf. with addvariables above... // Each symbol maps to a vector of CNF variables. for (it = mgr.symbolToBBNode.begin(); it != mgr.symbolToBBNode.end(); it++) { const ASTNode& n = it->first; const vector<BBNodeAIG> &b = it->second; assert(nodeToVar.find(n) == nodeToVar.end()); const int width = (n.GetType() == BOOLEAN_TYPE) ? 1 : n.GetValueWidth(); // INT_MAX for parts of symbols that didn't get encoded. vector<unsigned> v(width, ~((unsigned) 0)); for (unsigned i = 0; i < b.size(); i++) { if (!b[i].IsNull()) { Aig_Obj_t * pObj; pObj = (Aig_Obj_t*) Vec_PtrEntry(mgr.aigMgr->vPis, b[i].symbol_index); v[i] = cnfData->pVarNums[pObj->Id]; } } nodeToVar.insert(make_pair(n, v)); } assert(cnfData != NULL); } }; <commit_msg>No longer default to the simple CNF generator for big AIGs, i.e >=2Million nodes. We used to do this because of a bug(?) now fixed in ABC.<commit_after>#include "ToCNFAIG.h" namespace BEEV { // Can it only add in the new variables somehow?? void addVariables(BBNodeManagerAIG& mgr, Cnf_Dat_t*& cnfData , ToSATBase::ASTNodeToSATVar& nodeToVar) { BBNodeManagerAIG::SymbolToBBNode::const_iterator it; // Each symbol maps to a vector of CNF variables. for (it = mgr.symbolToBBNode.begin(); it != mgr.symbolToBBNode.end(); it++) { const ASTNode& n = it->first; const vector<BBNodeAIG> &b = it->second; const int width = (n.GetType() == BOOLEAN_TYPE) ? 1 : n.GetValueWidth(); // INT_MAX for parts of symbols that didn't get encoded. vector<unsigned> v(width, ~((unsigned) 0)); for (unsigned i = 0; i < b.size(); i++) { if (!b[i].IsNull()) { Aig_Obj_t * pObj; pObj = (Aig_Obj_t*) Vec_PtrEntry(mgr.aigMgr->vPis, b[i].symbol_index); v[i] = cnfData->pVarNums[pObj->Id]; } } nodeToVar.insert(make_pair(n, v)); } } // When we need abstraction refinement. void ToCNFAIG::toCNF_renter(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, BBNodeManagerAIG& mgr) { assert(priorCnfData != NULL); Aig_ObjCreatePo(mgr.aigMgr, top.n); // A new PO. cnfData = Cnf_DeriveSimple_Additional(mgr.aigMgr, priorCnfData); Cnf_DataFree(priorCnfData); priorCnfData = cnfData; addVariables( mgr, cnfData , nodeToVar); } void ToCNFAIG::toCNF(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, bool needAbsRef, BBNodeManagerAIG& mgr) { assert(cnfData == NULL); Aig_ObjCreatePo(mgr.aigMgr, top.n); if (!needAbsRef) { Aig_ManCleanup( mgr.aigMgr); // remove nodes not connected to the PO. } Aig_ManCheck( mgr.aigMgr); // check that AIG looks ok. assert(Aig_ManPoNum(mgr.aigMgr) == 1); // UseZeroes gives assertion errors. // Rewriting is sometimes very slow. Can it be configured to be faster? // What about refactoring??? int nodeCount = mgr.aigMgr->nObjs[AIG_OBJ_AND]; if (uf.stats_flag) cerr << "Nodes before AIG rewrite:" << nodeCount << endl; if (!needAbsRef && uf.isSet("aig_rewrite","0")) { Dar_LibStart(); Aig_Man_t * pTemp; Dar_RwrPar_t Pars, *pPars = &Pars; Dar_ManDefaultRwrParams(pPars); // Assertion errors occur with this enabled. // pPars->fUseZeros = 1; // For mul63bit.smt2 with iterations =3 & nCutsMax = 8 // CNF generation was taking 139 seconds, solving 10 seconds. // With nCutsMax =2, CNF generation takes 16 seconds, solving 10 seconds. // The rewriting doesn't remove as many nodes of course.. int iterations = 3; for (int i = 0; i < iterations; i++) { mgr.aigMgr = Aig_ManDup(pTemp = mgr.aigMgr, 0); Aig_ManStop(pTemp); Dar_ManRewrite(mgr.aigMgr, pPars); mgr.aigMgr = Aig_ManDup(pTemp = mgr.aigMgr, 0); Aig_ManStop(pTemp); if (uf.stats_flag) cerr << "After rewrite [" << i << "] nodes:" << mgr.aigMgr->nObjs[AIG_OBJ_AND] << endl; if (nodeCount == mgr.aigMgr->nObjs[AIG_OBJ_AND]) break; } } if (!needAbsRef && !uf.isSet("simple-cnf","0")) { cnfData = Cnf_Derive(mgr.aigMgr, 0); if (uf.stats_flag) cerr << "advanced CNF" << endl; } else { cnfData = Cnf_DeriveSimple(mgr.aigMgr, 0); if (uf.stats_flag) cerr << "simple CNF" << endl; } BBNodeManagerAIG::SymbolToBBNode::const_iterator it; assert(nodeToVar.size() == 0); //todo. cf. with addvariables above... // Each symbol maps to a vector of CNF variables. for (it = mgr.symbolToBBNode.begin(); it != mgr.symbolToBBNode.end(); it++) { const ASTNode& n = it->first; const vector<BBNodeAIG> &b = it->second; assert(nodeToVar.find(n) == nodeToVar.end()); const int width = (n.GetType() == BOOLEAN_TYPE) ? 1 : n.GetValueWidth(); // INT_MAX for parts of symbols that didn't get encoded. vector<unsigned> v(width, ~((unsigned) 0)); for (unsigned i = 0; i < b.size(); i++) { if (!b[i].IsNull()) { Aig_Obj_t * pObj; pObj = (Aig_Obj_t*) Vec_PtrEntry(mgr.aigMgr->vPis, b[i].symbol_index); v[i] = cnfData->pVarNums[pObj->Id]; } } nodeToVar.insert(make_pair(n, v)); } assert(cnfData != NULL); } }; <|endoftext|>
<commit_before>/** * Copyright 2013 Da Zheng * * This file is part of SA-GraphLib. * * SA-GraphLib 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. * * SA-GraphLib 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 SA-GraphLib. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <google/profiler.h> #include <vector> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" class bfs_vertex: public compute_directed_vertex { enum { VISITED, }; atomic_flags<int> flags; public: bfs_vertex() { } bfs_vertex(vertex_id_t id, const vertex_index *index): compute_directed_vertex(id, index) { } bool has_visited() const { return flags.test_flag(VISITED); } bool set_visited(bool visited) { if (visited) return flags.set_flag(VISITED); else return flags.clear_flag(VISITED); } void run(vertex_program &prog) { if (!has_visited()) { directed_vertex_request req(get_id(), edge_type::OUT_EDGE); request_partial_vertices(&req, 1); } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &prog, const vertex_message &msg) { } }; void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex) { assert(!has_visited()); set_visited(true); int num_dests = vertex.get_num_edges(OUT_EDGE); if (num_dests == 0) return; // We need to add the neighbors of the vertex to the queue of // the next level. #ifdef USE_ARRAY stack_array<vertex_id_t, 1024> neighs(num_dests); vertex.read_edges(OUT_EDGE, neighs.data(), num_dests); prog.activate_vertices(neighs.data(), num_dests); #else edge_seq_iterator it = vertex.get_neigh_seq_it(OUT_EDGE, 0, num_dests); prog.activate_vertices(it); #endif } void int_handler(int sig_num) { if (!graph_conf.get_prof_file().empty()) ProfilerStop(); exit(0); } void print_usage() { fprintf(stderr, "bfs [options] conf_file graph_file index_file start_vertex\n"); fprintf(stderr, "-c confs: add more configurations to the system\n"); fprintf(stderr, "-p: preload the graph\n"); graph_conf.print_help(); params.print_help(); } int main(int argc, char *argv[]) { int opt; std::string confs; int num_opts = 0; bool preload = false; while ((opt = getopt(argc, argv, "c:p")) != -1) { num_opts++; switch (opt) { case 'c': confs = optarg; num_opts++; break; case 'p': preload = true; break; default: print_usage(); } } argv += 1 + num_opts; argc -= 1 + num_opts; if (argc < 4) { print_usage(); exit(-1); } std::string conf_file = argv[0]; std::string graph_file = argv[1]; std::string index_file = argv[2]; vertex_id_t start_vertex = atoi(argv[3]); config_map configs(conf_file); configs.add_options(confs); graph_conf.init(configs); graph_conf.print(); signal(SIGINT, int_handler); init_io_system(configs); graph_index *index = NUMA_graph_index<bfs_vertex>::create(index_file, graph_conf.get_num_threads(), params.get_num_nodes()); graph_engine *graph = graph_engine::create(graph_conf.get_num_threads(), params.get_num_nodes(), graph_file, index); if (preload) graph->preload_graph(); printf("BFS starts\n"); printf("prof_file: %s\n", graph_conf.get_prof_file().c_str()); if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); struct timeval start, end; gettimeofday(&start, NULL); graph->start(&start_vertex, 1); graph->wait4complete(); gettimeofday(&end, NULL); NUMA_graph_index<bfs_vertex>::const_iterator it = ((NUMA_graph_index<bfs_vertex> *) index)->begin(); NUMA_graph_index<bfs_vertex>::const_iterator end_it = ((NUMA_graph_index<bfs_vertex> *) index)->end(); int num_visited = 0; for (; it != end_it; ++it) { const bfs_vertex &v = (const bfs_vertex &) *it; if (v.has_visited()) num_visited++; } if (!graph_conf.get_prof_file().empty()) ProfilerStop(); if (graph_conf.get_print_io_stat()) print_io_thread_stat(); graph_engine::destroy(graph); destroy_io_system(); printf("BFS from vertex %ld visits %d vertices. It takes %f seconds\n", (unsigned long) start_vertex, num_visited, time_diff(start, end)); } <commit_msg>[Graph]: allow to choose traversed edges in BFS.<commit_after>/** * Copyright 2013 Da Zheng * * This file is part of SA-GraphLib. * * SA-GraphLib 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. * * SA-GraphLib 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 SA-GraphLib. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <google/profiler.h> #include <vector> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" edge_type traverse_edge = edge_type::OUT_EDGE; class bfs_vertex: public compute_directed_vertex { enum { VISITED, }; atomic_flags<int> flags; public: bfs_vertex() { } bfs_vertex(vertex_id_t id, const vertex_index *index): compute_directed_vertex(id, index) { } bool has_visited() const { return flags.test_flag(VISITED); } bool set_visited(bool visited) { if (visited) return flags.set_flag(VISITED); else return flags.clear_flag(VISITED); } void run(vertex_program &prog) { if (!has_visited()) { directed_vertex_request req(get_id(), traverse_edge); request_partial_vertices(&req, 1); } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &prog, const vertex_message &msg) { } }; void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex) { assert(!has_visited()); set_visited(true); int num_dests = vertex.get_num_edges(traverse_edge); if (num_dests == 0) return; // We need to add the neighbors of the vertex to the queue of // the next level. #ifdef USE_ARRAY stack_array<vertex_id_t, 1024> neighs(num_dests); vertex.read_edges(traverse_edge, neighs.data(), num_dests); prog.activate_vertices(neighs.data(), num_dests); #else edge_seq_iterator it = vertex.get_neigh_seq_it(traverse_edge, 0, num_dests); prog.activate_vertices(it); #endif } void int_handler(int sig_num) { if (!graph_conf.get_prof_file().empty()) ProfilerStop(); exit(0); } void print_usage() { fprintf(stderr, "bfs [options] conf_file graph_file index_file start_vertex\n"); fprintf(stderr, "-c confs: add more configurations to the system\n"); fprintf(stderr, "-p: preload the graph\n"); fprintf(stderr, "-b: traverse with both in-edges and out-edges\n"); graph_conf.print_help(); params.print_help(); } int main(int argc, char *argv[]) { int opt; std::string confs; int num_opts = 0; bool preload = false; while ((opt = getopt(argc, argv, "c:pb")) != -1) { num_opts++; switch (opt) { case 'c': confs = optarg; num_opts++; break; case 'p': preload = true; break; case 'b': traverse_edge = edge_type::BOTH_EDGES; break; default: print_usage(); } } argv += 1 + num_opts; argc -= 1 + num_opts; if (argc < 4) { print_usage(); exit(-1); } std::string conf_file = argv[0]; std::string graph_file = argv[1]; std::string index_file = argv[2]; vertex_id_t start_vertex = atoi(argv[3]); config_map configs(conf_file); configs.add_options(confs); graph_conf.init(configs); graph_conf.print(); signal(SIGINT, int_handler); init_io_system(configs); graph_index *index = NUMA_graph_index<bfs_vertex>::create(index_file, graph_conf.get_num_threads(), params.get_num_nodes()); graph_engine *graph = graph_engine::create(graph_conf.get_num_threads(), params.get_num_nodes(), graph_file, index); if (preload) graph->preload_graph(); printf("BFS starts\n"); printf("prof_file: %s\n", graph_conf.get_prof_file().c_str()); if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); struct timeval start, end; gettimeofday(&start, NULL); graph->start(&start_vertex, 1); graph->wait4complete(); gettimeofday(&end, NULL); NUMA_graph_index<bfs_vertex>::const_iterator it = ((NUMA_graph_index<bfs_vertex> *) index)->begin(); NUMA_graph_index<bfs_vertex>::const_iterator end_it = ((NUMA_graph_index<bfs_vertex> *) index)->end(); int num_visited = 0; for (; it != end_it; ++it) { const bfs_vertex &v = (const bfs_vertex &) *it; if (v.has_visited()) num_visited++; } if (!graph_conf.get_prof_file().empty()) ProfilerStop(); if (graph_conf.get_print_io_stat()) print_io_thread_stat(); graph_engine::destroy(graph); destroy_io_system(); printf("BFS from vertex %ld visits %d vertices. It takes %f seconds\n", (unsigned long) start_vertex, num_visited, time_diff(start, end)); } <|endoftext|>
<commit_before>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QProcess> #include <QsLog.h> #include <QFileInfo> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl()) , mMailbox(mailbox) , mState(ready) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::sendStdOutMessage); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } return true; } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::sendStdOutMessage(const QString &text) { emit sendMessage(QString("print: %1").arg(text)); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::run(const QString &script) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, "doRun", Q_ARG(QString, script)); } void PythonEngineWorker::doRun(const QString &script) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } if (script.endsWith(".py")) { int fileNameStarts = script.lastIndexOf('/'); QString pathToScript = script.left(fileNameStarts); mMainContext.evalScript("import sys; sys.append(" + pathToScript + ")"); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); } <commit_msg>Use QFileInfo instead of primitive<commit_after>/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QProcess> #include <QsLog.h> #include <QDir> #include <QFileInfo> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl()) , mMailbox(mailbox) , mState(ready) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, &PythonEngineWorker::sendStdOutMessage); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } return true; } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::sendStdOutMessage(const QString &text) { emit sendMessage(QString("print: %1").arg(text)); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::run(const QString &script) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, "doRun", Q_ARG(QString, script)); } void PythonEngineWorker::doRun(const QString &script) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } if (script.endsWith(".py")) { QFileInfo scriptInfo = QFileInfo(script); auto const & pathToScript = scriptInfo.dir(); mMainContext.evalScript("import sys; sys.append(" + pathToScript.path() + ")"); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2013-2020 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. */ #include <srs_protocol_utility.hpp> // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifndef _WIN32 #include <unistd.h> #endif #include <stdlib.h> #include <sstream> using namespace std; #include <srs_kernel_log.hpp> #include <srs_kernel_utility.hpp> #include <srs_kernel_buffer.hpp> #include <srs_rtmp_stack.hpp> #include <srs_kernel_codec.hpp> #include <srs_kernel_consts.hpp> #include <srs_rtmp_stack.hpp> #include <srs_protocol_io.hpp> /** * resolve the vhost in query string * @pram vhost, update the vhost if query contains the vhost. * @param app, may contains the vhost in query string format: * app?vhost=request_vhost * app...vhost...request_vhost * @param param, the query, for example, ?vhost=xxx */ void srs_vhost_resolve(string& vhost, string& app, string& param) { // get original param size_t pos = 0; if ((pos = app.find("?")) != std::string::npos) { param = app.substr(pos); } // filter tcUrl app = srs_string_replace(app, ",", "?"); app = srs_string_replace(app, "...", "?"); app = srs_string_replace(app, "&&", "?"); app = srs_string_replace(app, "&", "?"); app = srs_string_replace(app, "=", "?"); if (srs_string_ends_with(app, "/_definst_")) { app = srs_erase_last_substr(app, "/_definst_"); } if ((pos = app.find("?")) != std::string::npos) { std::string query = app.substr(pos + 1); app = app.substr(0, pos); if ((pos = query.find("vhost?")) != std::string::npos) { query = query.substr(pos + 6); if (!query.empty()) { vhost = query; } } } // vhost with params. if ((pos = vhost.find("?")) != std::string::npos) { vhost = vhost.substr(0, pos); } /* others */ } void srs_discovery_tc_url(string tcUrl, string& schema, string& host, string& vhost, string& app, string& stream, int& port, string& param) { size_t pos = std::string::npos; std::string url = tcUrl; if ((pos = url.find("://")) != std::string::npos) { schema = url.substr(0, pos); url = url.substr(schema.length() + 3); srs_info("discovery schema=%s", schema.c_str()); } if ((pos = url.find("/")) != std::string::npos) { host = url.substr(0, pos); url = url.substr(host.length() + 1); srs_info("discovery host=%s", host.c_str()); } port = SRS_CONSTS_RTMP_DEFAULT_PORT; if ((pos = host.find(":")) != std::string::npos) { srs_parse_hostport(host, host, port); srs_info("discovery host=%s, port=%d", host.c_str(), port); } if (url.empty()) { app = SRS_CONSTS_RTMP_DEFAULT_APP; } else { app = url; } vhost = host; srs_vhost_resolve(vhost, app, param); srs_vhost_resolve(vhost, stream, param); // Ignore when the param only contains the default vhost. if (param == "?vhost="SRS_CONSTS_RTMP_DEFAULT_VHOST) { param = ""; } } void srs_parse_query_string(string q, map<string,string>& query) { // query string flags. static vector<string> flags; if (flags.empty()) { flags.push_back("="); flags.push_back(","); flags.push_back("&&"); flags.push_back("&"); flags.push_back(";"); } vector<string> kvs = srs_string_split(q, flags); for (int i = 0; i < (int)kvs.size(); i+=2) { string k = kvs.at(i); string v = (i < (int)kvs.size() - 1)? kvs.at(i+1):""; query[k] = v; } } void srs_random_generate(char* bytes, int size) { static bool _random_initialized = false; if (!_random_initialized) { srand(0); _random_initialized = true; } for (int i = 0; i < size; i++) { // the common value in [0x0f, 0xf0] bytes[i] = 0x0f + (rand() % (256 - 0x0f - 0x0f)); } } string srs_generate_tc_url(string host, string vhost, string app, int port) { string tcUrl = "rtmp://"; if (vhost == SRS_CONSTS_RTMP_DEFAULT_VHOST) { tcUrl += host; } else { tcUrl += vhost; } if (port != SRS_CONSTS_RTMP_DEFAULT_PORT) { tcUrl += ":" + srs_int2str(port); } tcUrl += "/" + app; return tcUrl; } string srs_generate_stream_with_query(string host, string vhost, string stream, string param) { string url = stream; string query = param; // If no vhost in param, try to append one. string guessVhost; if (query.find("vhost=") == string::npos) { if (vhost != SRS_CONSTS_RTMP_DEFAULT_VHOST) { guessVhost = vhost; } else if (!srs_is_ipv4(host)) { guessVhost = host; } } // Well, if vhost exists, always append in query string. if (!guessVhost.empty()) { query += "&vhost=" + guessVhost; } // Remove the start & when param is empty. query = srs_string_trim_start(query, "&"); // Prefix query with ?. if (!query.empty() && !srs_string_starts_with(query, "?")) { url += "?"; } // Append query to url. if (!query.empty()) { url += query; } return url; } template<typename T> srs_error_t srs_do_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, T** ppmsg) { srs_error_t err = srs_success; *ppmsg = NULL; T* msg = NULL; if (type == SrsFrameTypeAudio) { SrsMessageHeader header; header.initialize_audio(size, timestamp, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else if (type == SrsFrameTypeVideo) { SrsMessageHeader header; header.initialize_video(size, timestamp, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else if (type == SrsFrameTypeScript) { SrsMessageHeader header; header.initialize_amf0_script(size, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else { return srs_error_new(ERROR_STREAM_CASTER_FLV_TAG, "unknown tag=%#x", (uint8_t)type); } *ppmsg = msg; return err; } srs_error_t srs_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, SrsSharedPtrMessage** ppmsg) { srs_error_t err = srs_success; // only when failed, we must free the data. if ((err = srs_do_rtmp_create_msg(type, timestamp, data, size, stream_id, ppmsg)) != srs_success) { srs_freepa(data); return srs_error_wrap(err, "create message"); } return err; } srs_error_t srs_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, SrsCommonMessage** ppmsg) { srs_error_t err = srs_success; // only when failed, we must free the data. if ((err = srs_do_rtmp_create_msg(type, timestamp, data, size, stream_id, ppmsg)) != srs_success) { srs_freepa(data); return srs_error_wrap(err, "create message"); } return err; } string srs_generate_stream_url(string vhost, string app, string stream) { std::string url = ""; if (SRS_CONSTS_RTMP_DEFAULT_VHOST != vhost){ url += vhost; } url += "/"; url += app; url += "/"; url += stream; return url; } void srs_parse_rtmp_url(string url, string& tcUrl, string& stream) { size_t pos; if ((pos = url.rfind("/")) != string::npos) { stream = url.substr(pos + 1); tcUrl = url.substr(0, pos); } else { tcUrl = url; } } string srs_generate_rtmp_url(string server, int port, string host, string vhost, string app, string stream, string param) { string tcUrl = "rtmp://" + server + ":" + srs_int2str(port) + "/" + app; string streamWithQuery = srs_generate_stream_with_query(host, vhost, stream, param); string url = tcUrl + "/" + streamWithQuery; return url; } srs_error_t srs_write_large_iovs(ISrsProtocolReadWriter* skt, iovec* iovs, int size, ssize_t* pnwrite) { srs_error_t err = srs_success; // the limits of writev iovs. // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifndef _WIN32 // for linux, generally it's 1024. static int limits = (int)sysconf(_SC_IOV_MAX); #else static int limits = 1024; #endif // send in a time. if (size < limits) { if ((err = skt->writev(iovs, size, pnwrite)) != srs_success) { return srs_error_wrap(err, "writev"); } return err; } // send in multiple times. int cur_iov = 0; while (cur_iov < size) { int cur_count = srs_min(limits, size - cur_iov); if ((err = skt->writev(iovs + cur_iov, cur_count, pnwrite)) != srs_success) { return srs_error_wrap(err, "writev"); } cur_iov += cur_count; } return err; } string srs_join_vector_string(vector<string>& vs, string separator) { string str = ""; for (int i = 0; i < (int)vs.size(); i++) { str += vs.at(i); if (i != (int)vs.size() - 1) { str += separator; } } return str; } bool srs_is_ipv4(string domain) { for (int i = 0; i < (int)domain.length(); i++) { char ch = domain.at(i); if (ch == '.') { continue; } if (ch >= '0' && ch <= '9') { continue; } return false; } return true; } <commit_msg>修复srs_write_large_iovs中nwrite未累加的错误<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2013-2020 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. */ #include <srs_protocol_utility.hpp> // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifndef _WIN32 #include <unistd.h> #endif #include <stdlib.h> #include <sstream> using namespace std; #include <srs_kernel_log.hpp> #include <srs_kernel_utility.hpp> #include <srs_kernel_buffer.hpp> #include <srs_rtmp_stack.hpp> #include <srs_kernel_codec.hpp> #include <srs_kernel_consts.hpp> #include <srs_rtmp_stack.hpp> #include <srs_protocol_io.hpp> /** * resolve the vhost in query string * @pram vhost, update the vhost if query contains the vhost. * @param app, may contains the vhost in query string format: * app?vhost=request_vhost * app...vhost...request_vhost * @param param, the query, for example, ?vhost=xxx */ void srs_vhost_resolve(string& vhost, string& app, string& param) { // get original param size_t pos = 0; if ((pos = app.find("?")) != std::string::npos) { param = app.substr(pos); } // filter tcUrl app = srs_string_replace(app, ",", "?"); app = srs_string_replace(app, "...", "?"); app = srs_string_replace(app, "&&", "?"); app = srs_string_replace(app, "&", "?"); app = srs_string_replace(app, "=", "?"); if (srs_string_ends_with(app, "/_definst_")) { app = srs_erase_last_substr(app, "/_definst_"); } if ((pos = app.find("?")) != std::string::npos) { std::string query = app.substr(pos + 1); app = app.substr(0, pos); if ((pos = query.find("vhost?")) != std::string::npos) { query = query.substr(pos + 6); if (!query.empty()) { vhost = query; } } } // vhost with params. if ((pos = vhost.find("?")) != std::string::npos) { vhost = vhost.substr(0, pos); } /* others */ } void srs_discovery_tc_url(string tcUrl, string& schema, string& host, string& vhost, string& app, string& stream, int& port, string& param) { size_t pos = std::string::npos; std::string url = tcUrl; if ((pos = url.find("://")) != std::string::npos) { schema = url.substr(0, pos); url = url.substr(schema.length() + 3); srs_info("discovery schema=%s", schema.c_str()); } if ((pos = url.find("/")) != std::string::npos) { host = url.substr(0, pos); url = url.substr(host.length() + 1); srs_info("discovery host=%s", host.c_str()); } port = SRS_CONSTS_RTMP_DEFAULT_PORT; if ((pos = host.find(":")) != std::string::npos) { srs_parse_hostport(host, host, port); srs_info("discovery host=%s, port=%d", host.c_str(), port); } if (url.empty()) { app = SRS_CONSTS_RTMP_DEFAULT_APP; } else { app = url; } vhost = host; srs_vhost_resolve(vhost, app, param); srs_vhost_resolve(vhost, stream, param); // Ignore when the param only contains the default vhost. if (param == "?vhost="SRS_CONSTS_RTMP_DEFAULT_VHOST) { param = ""; } } void srs_parse_query_string(string q, map<string,string>& query) { // query string flags. static vector<string> flags; if (flags.empty()) { flags.push_back("="); flags.push_back(","); flags.push_back("&&"); flags.push_back("&"); flags.push_back(";"); } vector<string> kvs = srs_string_split(q, flags); for (int i = 0; i < (int)kvs.size(); i+=2) { string k = kvs.at(i); string v = (i < (int)kvs.size() - 1)? kvs.at(i+1):""; query[k] = v; } } void srs_random_generate(char* bytes, int size) { static bool _random_initialized = false; if (!_random_initialized) { srand(0); _random_initialized = true; } for (int i = 0; i < size; i++) { // the common value in [0x0f, 0xf0] bytes[i] = 0x0f + (rand() % (256 - 0x0f - 0x0f)); } } string srs_generate_tc_url(string host, string vhost, string app, int port) { string tcUrl = "rtmp://"; if (vhost == SRS_CONSTS_RTMP_DEFAULT_VHOST) { tcUrl += host; } else { tcUrl += vhost; } if (port != SRS_CONSTS_RTMP_DEFAULT_PORT) { tcUrl += ":" + srs_int2str(port); } tcUrl += "/" + app; return tcUrl; } string srs_generate_stream_with_query(string host, string vhost, string stream, string param) { string url = stream; string query = param; // If no vhost in param, try to append one. string guessVhost; if (query.find("vhost=") == string::npos) { if (vhost != SRS_CONSTS_RTMP_DEFAULT_VHOST) { guessVhost = vhost; } else if (!srs_is_ipv4(host)) { guessVhost = host; } } // Well, if vhost exists, always append in query string. if (!guessVhost.empty()) { query += "&vhost=" + guessVhost; } // Remove the start & when param is empty. query = srs_string_trim_start(query, "&"); // Prefix query with ?. if (!query.empty() && !srs_string_starts_with(query, "?")) { url += "?"; } // Append query to url. if (!query.empty()) { url += query; } return url; } template<typename T> srs_error_t srs_do_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, T** ppmsg) { srs_error_t err = srs_success; *ppmsg = NULL; T* msg = NULL; if (type == SrsFrameTypeAudio) { SrsMessageHeader header; header.initialize_audio(size, timestamp, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else if (type == SrsFrameTypeVideo) { SrsMessageHeader header; header.initialize_video(size, timestamp, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else if (type == SrsFrameTypeScript) { SrsMessageHeader header; header.initialize_amf0_script(size, stream_id); msg = new T(); if ((err = msg->create(&header, data, size)) != srs_success) { srs_freep(msg); return srs_error_wrap(err, "create message"); } } else { return srs_error_new(ERROR_STREAM_CASTER_FLV_TAG, "unknown tag=%#x", (uint8_t)type); } *ppmsg = msg; return err; } srs_error_t srs_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, SrsSharedPtrMessage** ppmsg) { srs_error_t err = srs_success; // only when failed, we must free the data. if ((err = srs_do_rtmp_create_msg(type, timestamp, data, size, stream_id, ppmsg)) != srs_success) { srs_freepa(data); return srs_error_wrap(err, "create message"); } return err; } srs_error_t srs_rtmp_create_msg(char type, uint32_t timestamp, char* data, int size, int stream_id, SrsCommonMessage** ppmsg) { srs_error_t err = srs_success; // only when failed, we must free the data. if ((err = srs_do_rtmp_create_msg(type, timestamp, data, size, stream_id, ppmsg)) != srs_success) { srs_freepa(data); return srs_error_wrap(err, "create message"); } return err; } string srs_generate_stream_url(string vhost, string app, string stream) { std::string url = ""; if (SRS_CONSTS_RTMP_DEFAULT_VHOST != vhost){ url += vhost; } url += "/"; url += app; url += "/"; url += stream; return url; } void srs_parse_rtmp_url(string url, string& tcUrl, string& stream) { size_t pos; if ((pos = url.rfind("/")) != string::npos) { stream = url.substr(pos + 1); tcUrl = url.substr(0, pos); } else { tcUrl = url; } } string srs_generate_rtmp_url(string server, int port, string host, string vhost, string app, string stream, string param) { string tcUrl = "rtmp://" + server + ":" + srs_int2str(port) + "/" + app; string streamWithQuery = srs_generate_stream_with_query(host, vhost, stream, param); string url = tcUrl + "/" + streamWithQuery; return url; } srs_error_t srs_write_large_iovs(ISrsProtocolReadWriter* skt, iovec* iovs, int size, ssize_t* pnwrite) { srs_error_t err = srs_success; // the limits of writev iovs. // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifndef _WIN32 // for linux, generally it's 1024. static int limits = (int)sysconf(_SC_IOV_MAX); #else static int limits = 1024; #endif // send in a time. if (size < limits) { if ((err = skt->writev(iovs, size, pnwrite)) != srs_success) { return srs_error_wrap(err, "writev"); } return err; } // send in multiple times. int cur_iov = 0; ssize_t nwrite = 0; while (cur_iov < size) { int cur_count = srs_min(limits, size - cur_iov); if ((err = skt->writev(iovs + cur_iov, cur_count, &nwrite)) != srs_success) { return srs_error_wrap(err, "writev"); } cur_iov += cur_count; if (pnwrite) { *pnwrite += nwrite; } } return err; } string srs_join_vector_string(vector<string>& vs, string separator) { string str = ""; for (int i = 0; i < (int)vs.size(); i++) { str += vs.at(i); if (i != (int)vs.size() - 1) { str += separator; } } return str; } bool srs_is_ipv4(string domain) { for (int i = 0; i < (int)domain.length(); i++) { char ch = domain.at(i); if (ch == '.') { continue; } if (ch >= '0' && ch <= '9') { continue; } return false; } return true; } <|endoftext|>
<commit_before>/* Copyright (C) 2000 by W.C.A. Wijngaards Copyright (C) 2000 by Andrew Zabolotny This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #define CS_SYSDEF_PROVIDE_PATH #define CS_SYSDEF_PROVIDE_GETOPT #include "cssysdef.h" #include "cssys/sysdriv.h" #include "cstool/initapp.h" #include "ivideo/fontserv.h" #include "iutil/objreg.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "isys/plugin.h" CS_IMPLEMENT_APPLICATION csSystemDriver* System; char *programversion = "0.0.1"; char *programname; static struct option long_options[] = { {"first", required_argument, 0, 'f'}, {"glyphs", required_argument, 0, 'g'}, {"size", required_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {"text", no_argument, 0, 't'}, {"display", no_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {0, no_argument, 0, 0} }; static struct { bool verbose; bool sourcecode; bool display; int fontsize; int first; int glyphs; char *output; } opt = { false, false, false, -1, 0, 256, NULL }; static int lastglyph; static int display_help () { printf ("Crystal Space font conversion/generation utility v%s\n", programversion); printf ("Copyright (C) 2000 by W.C.A. Wijngaards and Andrew Zabolotny\n\n"); printf ("Usage: %s {option/s} [truetype font file] [...]\n\n", programname); printf ("This program allows to convert TTF font files to bitmap format CSF\n"); printf ("which is faster to load although it is non-scalable. By default the\n"); printf ("program will convert all the fonts given on command line to CSF.\n\n"); printf (" -d --display Display font rather than converting it\n"); printf (" -f# --first=# Start conversion at glyph # (default = 0)\n"); printf (" -g# --glyphs=# Convert just # (default = 256) glyphs of the font\n"); printf (" -s# --size=# Set font size # in points\n"); printf (" -o# --output=# Output CSF font to file #\n"); printf (" -t --text Generate text output (C++ code) rather than binary\n"); printf (" -h --help Display this help text\n"); printf (" -v --verbose Comment on what's happening\n"); printf (" -V --version Display program version\n"); return 1; } static bool Display (iFontServer *fs, iFont *font) { int c, l, i; for (c = opt.first; c < lastglyph; c++) { int w, h; uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (!bitmap || !w || !h) continue; printf ("---- Character:%d\n", c); for (l = 0; l < h; l++) { uint8 *line = bitmap + l * ((w + 7) / 8); for (i = 0; i < w; i++) printf ("%s", (line [i / 8] & (0x80 >> (i & 7))) ? "@" : "."); printf ("\n"); } } font->DecRef (); fs->DecRef (); return true; } static bool Convert (const char *fontfile) { if (opt.verbose) printf ("Loading font %s, size = %d\n", fontfile, opt.fontsize); iObjectRegistry* object_reg = System->GetObjectRegistry (); iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager); iFontServer *fs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_FONTSERVER, iFontServer); if (!fs) { printf ("Font server plugin has not been loaded.\n"); return false; } iFont *font = fs->LoadFont (fontfile); if (font == NULL) { printf ("Cannot load font file %s\n", fontfile); return false; } if (opt.fontsize > 0) { font->SetSize (opt.fontsize); int oldsize = opt.fontsize; opt.fontsize = font->GetSize (); if (opt.fontsize != oldsize) printf ("Could not set font size %d, using size %d\n", oldsize, opt.fontsize); } else opt.fontsize = font->GetSize (); // max height of font int maxheight, maxwidth; font->GetMaxSize (maxwidth, maxheight); if (maxwidth > 255) { fprintf (stderr, "Font too large (%dx%d): CSF format supports only widths < 256\n", maxwidth, maxheight); return false; } if (opt.display) return Display (fs, font); char fontname [MAXPATHLEN + 1]; char outfile [MAXPATHLEN + 1]; csSplitPath (fontfile, NULL, 0, fontname, sizeof (fontname)); if (fontname [0] == '*') strcpy (fontname, fontname + 1); char *dot = strchr (fontname, '.'); if (dot) *dot = 0; sprintf (outfile, "%s%d.%s", fontname, opt.fontsize, opt.sourcecode ? "inc" : "csf"); FILE *out = fopen (outfile, opt.sourcecode ? "w" : "wb"); if (!out) { printf ("Could not open output file %s\n", outfile); return false; } int i, c, w, h; if (opt.sourcecode) { /// make a text version fprintf (out, "// %s.%d %dx%d font\n", fontname, opt.fontsize, maxwidth, maxheight); fprintf (out, "// FontDef: { \"%s%d\", %d, %d, %d, %d, font_%s%d, width_%s%d }\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs, fontname, opt.fontsize, fontname, opt.fontsize); fprintf (out, "\n"); } else fprintf (out, "CSF [Font=%s.%d Width=%d Height=%d First=%d Glyphs=%d]\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs); int arrsize = 0; uint8 width [256]; for (c = opt.first; c < lastglyph; c++) { uint8 *bitmap = font->GetGlyphBitmap (c, w, h); width [c] = (bitmap && h) ? w : 0; arrsize += ((width [c] + 7) / 8) * h; } // Character widths go first if (opt.sourcecode) { fprintf (out, "unsigned char width_%s%d [%d] =\n{\n ", fontname, opt.fontsize, opt.glyphs); for (i = opt.first; i < lastglyph; i++) { fprintf (out, "%2d%s", width [i], (i < lastglyph - 1) ? "," : ""); if ((i & 15) == 15) { fprintf (out, "\t// %02x..%02x\n", i - 15, i); if (i < lastglyph - 1) fprintf (out, " "); } } if (opt.glyphs & 15) fprintf (out, "\n"); fprintf (out, "};\n\n"); fprintf (out, "unsigned char font_%s%d [%d] =\n{\n", fontname, opt.fontsize, arrsize); } else fwrite (width + opt.first, opt.glyphs, 1, out); // Output every character in turn for (c = opt.first; c < lastglyph; c++) { // get bitmap uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (opt.verbose) { if (!c) printf ("character "); printf ("%d%s", c, (c < lastglyph - 1) ? "," : "\n"); } int bpc = ((width [c] + 7) / 8) * h; if (bitmap) if (opt.sourcecode) { fprintf (out, " "); for (i = 0; i < bpc; i++) fprintf (out, "0x%02x%s", bitmap [i], (i >= bpc - 1) && (c >= lastglyph - 1) ? "" : ","); fprintf (out, "\t// %02x\n", c); } else if (width [c]) fwrite (bitmap, bpc, 1, out); } fprintf (out, "};\n\n"); fclose (out); font->DecRef (); fs->DecRef (); return true; } int main (int argc, char* argv[]) { #if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX _wildcard (&argc, &argv); #endif // Create our main class. System = new csSystemDriver (); // Load VFS (for file management) and the TTF font server System->RequestPlugin ("crystalspace.kernel.vfs:" CS_FUNCID_VFS); System->RequestPlugin ("crystalspace.font.server.freetype:" CS_FUNCID_FONTSERVER); if (!System->Initialize (argc, argv, NULL)) { fprintf (stderr, "Initialization error!\n"); return -1; } if (!csInitializeApplication (System->GetObjectRegistry ())) { fprintf (stderr, "couldn't init app! (perhaps some plugins are missing?)"); return -1; } programname = argv [0]; int c; while ((c = getopt_long (argc, argv, "f:g:s:o:tdhvV", long_options, NULL)) != EOF) switch (c) { case '?': // unknown option return -1; case 'f': opt.first = atoi (optarg); if ((opt.first < 0) || (opt.first > 255)) { fprintf (stderr, "ERROR: first glyph should be 0..255\n"); return -2; } break; case 'g': opt.glyphs = atoi (optarg); if ((opt.glyphs < 1) || (opt.glyphs > 256)) { fprintf (stderr, "ERROR: glyph count should be 1..256\n"); return -2; } break; case 's': opt.fontsize = atoi (optarg); if ((opt.fontsize < 1) || (opt.fontsize > 1000)) { fprintf (stderr, "ERROR: font size should be 1..1000\n"); return -2; } break; case 'o': opt.output = optarg; break; case 't': opt.sourcecode = true; break; case 'd': opt.display = true; break; case 'h': return display_help (); case 'v': opt.verbose = true; break; case 'V': printf ("%s version %s\n\n", programname, programversion); printf ("This program is distributed in the hope that it will be useful,\n"); printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf ("GNU Library General Public License for more details.\n"); return 0; } /* endswitch */ if (optind >= argc) return display_help (); lastglyph = opt.first + opt.glyphs; if (lastglyph > 256) { fprintf (stderr, "WARNING: Last glyph = %d, limiting to 256\n", lastglyph); lastglyph = 256; opt.glyphs = 256 - opt.first; } // Interpret the non-option arguments as file names for (; optind < argc; ++optind) if (!Convert (argv [optind])) return -2; delete System; return 0; } <commit_msg>Removed NULL from Initialize.<commit_after>/* Copyright (C) 2000 by W.C.A. Wijngaards Copyright (C) 2000 by Andrew Zabolotny This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #define CS_SYSDEF_PROVIDE_PATH #define CS_SYSDEF_PROVIDE_GETOPT #include "cssysdef.h" #include "cssys/sysdriv.h" #include "cstool/initapp.h" #include "ivideo/fontserv.h" #include "iutil/objreg.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "isys/plugin.h" CS_IMPLEMENT_APPLICATION csSystemDriver* System; char *programversion = "0.0.1"; char *programname; static struct option long_options[] = { {"first", required_argument, 0, 'f'}, {"glyphs", required_argument, 0, 'g'}, {"size", required_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {"text", no_argument, 0, 't'}, {"display", no_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {0, no_argument, 0, 0} }; static struct { bool verbose; bool sourcecode; bool display; int fontsize; int first; int glyphs; char *output; } opt = { false, false, false, -1, 0, 256, NULL }; static int lastglyph; static int display_help () { printf ("Crystal Space font conversion/generation utility v%s\n", programversion); printf ("Copyright (C) 2000 by W.C.A. Wijngaards and Andrew Zabolotny\n\n"); printf ("Usage: %s {option/s} [truetype font file] [...]\n\n", programname); printf ("This program allows to convert TTF font files to bitmap format CSF\n"); printf ("which is faster to load although it is non-scalable. By default the\n"); printf ("program will convert all the fonts given on command line to CSF.\n\n"); printf (" -d --display Display font rather than converting it\n"); printf (" -f# --first=# Start conversion at glyph # (default = 0)\n"); printf (" -g# --glyphs=# Convert just # (default = 256) glyphs of the font\n"); printf (" -s# --size=# Set font size # in points\n"); printf (" -o# --output=# Output CSF font to file #\n"); printf (" -t --text Generate text output (C++ code) rather than binary\n"); printf (" -h --help Display this help text\n"); printf (" -v --verbose Comment on what's happening\n"); printf (" -V --version Display program version\n"); return 1; } static bool Display (iFontServer *fs, iFont *font) { int c, l, i; for (c = opt.first; c < lastglyph; c++) { int w, h; uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (!bitmap || !w || !h) continue; printf ("---- Character:%d\n", c); for (l = 0; l < h; l++) { uint8 *line = bitmap + l * ((w + 7) / 8); for (i = 0; i < w; i++) printf ("%s", (line [i / 8] & (0x80 >> (i & 7))) ? "@" : "."); printf ("\n"); } } font->DecRef (); fs->DecRef (); return true; } static bool Convert (const char *fontfile) { if (opt.verbose) printf ("Loading font %s, size = %d\n", fontfile, opt.fontsize); iObjectRegistry* object_reg = System->GetObjectRegistry (); iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager); iFontServer *fs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_FONTSERVER, iFontServer); if (!fs) { printf ("Font server plugin has not been loaded.\n"); return false; } iFont *font = fs->LoadFont (fontfile); if (font == NULL) { printf ("Cannot load font file %s\n", fontfile); return false; } if (opt.fontsize > 0) { font->SetSize (opt.fontsize); int oldsize = opt.fontsize; opt.fontsize = font->GetSize (); if (opt.fontsize != oldsize) printf ("Could not set font size %d, using size %d\n", oldsize, opt.fontsize); } else opt.fontsize = font->GetSize (); // max height of font int maxheight, maxwidth; font->GetMaxSize (maxwidth, maxheight); if (maxwidth > 255) { fprintf (stderr, "Font too large (%dx%d): CSF format supports only widths < 256\n", maxwidth, maxheight); return false; } if (opt.display) return Display (fs, font); char fontname [MAXPATHLEN + 1]; char outfile [MAXPATHLEN + 1]; csSplitPath (fontfile, NULL, 0, fontname, sizeof (fontname)); if (fontname [0] == '*') strcpy (fontname, fontname + 1); char *dot = strchr (fontname, '.'); if (dot) *dot = 0; sprintf (outfile, "%s%d.%s", fontname, opt.fontsize, opt.sourcecode ? "inc" : "csf"); FILE *out = fopen (outfile, opt.sourcecode ? "w" : "wb"); if (!out) { printf ("Could not open output file %s\n", outfile); return false; } int i, c, w, h; if (opt.sourcecode) { /// make a text version fprintf (out, "// %s.%d %dx%d font\n", fontname, opt.fontsize, maxwidth, maxheight); fprintf (out, "// FontDef: { \"%s%d\", %d, %d, %d, %d, font_%s%d, width_%s%d }\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs, fontname, opt.fontsize, fontname, opt.fontsize); fprintf (out, "\n"); } else fprintf (out, "CSF [Font=%s.%d Width=%d Height=%d First=%d Glyphs=%d]\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs); int arrsize = 0; uint8 width [256]; for (c = opt.first; c < lastglyph; c++) { uint8 *bitmap = font->GetGlyphBitmap (c, w, h); width [c] = (bitmap && h) ? w : 0; arrsize += ((width [c] + 7) / 8) * h; } // Character widths go first if (opt.sourcecode) { fprintf (out, "unsigned char width_%s%d [%d] =\n{\n ", fontname, opt.fontsize, opt.glyphs); for (i = opt.first; i < lastglyph; i++) { fprintf (out, "%2d%s", width [i], (i < lastglyph - 1) ? "," : ""); if ((i & 15) == 15) { fprintf (out, "\t// %02x..%02x\n", i - 15, i); if (i < lastglyph - 1) fprintf (out, " "); } } if (opt.glyphs & 15) fprintf (out, "\n"); fprintf (out, "};\n\n"); fprintf (out, "unsigned char font_%s%d [%d] =\n{\n", fontname, opt.fontsize, arrsize); } else fwrite (width + opt.first, opt.glyphs, 1, out); // Output every character in turn for (c = opt.first; c < lastglyph; c++) { // get bitmap uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (opt.verbose) { if (!c) printf ("character "); printf ("%d%s", c, (c < lastglyph - 1) ? "," : "\n"); } int bpc = ((width [c] + 7) / 8) * h; if (bitmap) if (opt.sourcecode) { fprintf (out, " "); for (i = 0; i < bpc; i++) fprintf (out, "0x%02x%s", bitmap [i], (i >= bpc - 1) && (c >= lastglyph - 1) ? "" : ","); fprintf (out, "\t// %02x\n", c); } else if (width [c]) fwrite (bitmap, bpc, 1, out); } fprintf (out, "};\n\n"); fclose (out); font->DecRef (); fs->DecRef (); return true; } int main (int argc, char* argv[]) { #if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX _wildcard (&argc, &argv); #endif // Create our main class. System = new csSystemDriver (); // Load VFS (for file management) and the TTF font server System->RequestPlugin ("crystalspace.kernel.vfs:" CS_FUNCID_VFS); System->RequestPlugin ("crystalspace.font.server.freetype:" CS_FUNCID_FONTSERVER); if (!System->Initialize (argc, argv)) { fprintf (stderr, "Initialization error!\n"); return -1; } if (!csInitializeApplication (System->GetObjectRegistry ())) { fprintf (stderr, "couldn't init app! (perhaps some plugins are missing?)"); return -1; } programname = argv [0]; int c; while ((c = getopt_long (argc, argv, "f:g:s:o:tdhvV", long_options, NULL)) != EOF) switch (c) { case '?': // unknown option return -1; case 'f': opt.first = atoi (optarg); if ((opt.first < 0) || (opt.first > 255)) { fprintf (stderr, "ERROR: first glyph should be 0..255\n"); return -2; } break; case 'g': opt.glyphs = atoi (optarg); if ((opt.glyphs < 1) || (opt.glyphs > 256)) { fprintf (stderr, "ERROR: glyph count should be 1..256\n"); return -2; } break; case 's': opt.fontsize = atoi (optarg); if ((opt.fontsize < 1) || (opt.fontsize > 1000)) { fprintf (stderr, "ERROR: font size should be 1..1000\n"); return -2; } break; case 'o': opt.output = optarg; break; case 't': opt.sourcecode = true; break; case 'd': opt.display = true; break; case 'h': return display_help (); case 'v': opt.verbose = true; break; case 'V': printf ("%s version %s\n\n", programname, programversion); printf ("This program is distributed in the hope that it will be useful,\n"); printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf ("GNU Library General Public License for more details.\n"); return 0; } /* endswitch */ if (optind >= argc) return display_help (); lastglyph = opt.first + opt.glyphs; if (lastglyph > 256) { fprintf (stderr, "WARNING: Last glyph = %d, limiting to 256\n", lastglyph); lastglyph = 256; opt.glyphs = 256 - opt.first; } // Interpret the non-option arguments as file names for (; optind < argc; ++optind) if (!Convert (argv [optind])) return -2; delete System; return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2007 by Seth Yastrov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/scf.h" #include "cstool/initapp.h" #include "csutil/cmdhelp.h" #include "imap/saverfile.h" #include "iutil/cmdline.h" #include "iutil/stringarray.h" #include "ivaria/collider.h" #include "ivideo/graph2d.h" #include <wx/textctrl.h> #include "ieditor/panelmanager.h" #include "objectlist.h" #include "auipanelmanager.h" #include "interfacewrappermanager.h" #include "actionmanager.h" #include "editorobject.h" #include "mainframe.h" #include "editor.h" namespace CS { namespace EditorApp { Editor::Editor () : scfImplementationType (this), helper_meshes (0), transstatus (NOTHING) { } Editor::~Editor () { delete helper_meshes; // Remove ourself from object registry object_reg->Unregister (this, "iEditor"); } bool Editor::Initialize (iObjectRegistry* reg) { object_reg = reg; // Check for commandline help. if (csCommandLineHelper::CheckHelp (object_reg)) { Help (); return true; } selection.AttachNew (new ObjectList ()); objects.AttachNew (new ObjectList ()); object_reg->Register (this, "iEditor"); panelManager.AttachNew (new AUIPanelManager (object_reg)); interfaceManager.AttachNew (new InterfaceWrapperManager (object_reg)); actionManager.AttachNew (new ActionManager (object_reg)); // Create the main frame mainFrame = new MainFrame (wxT ("Crystal Space Editor"), wxDefaultPosition, wxSize (800, 600)); mainFrame->Initialize (object_reg, this); mainFrame->Show (); // Initialize CS and load plugins if (!InitCS ()) return false; mainFrame->SecondInitialize (object_reg); return true; } void Editor::Help () { csCommandLineHelper commandLineHelper; // Usage examples commandLineHelper.AddCommandLineExample ("cseditor data/castel/world"); commandLineHelper.AddCommandLineExample ("cseditor -R=data/kwartz.zip kwartz.lib"); commandLineHelper.AddCommandLineExample ("cseditor -R=data/seymour.zip Seymour.dae"); // Command line options commandLineHelper.AddCommandLineOption ("R", "Real path to be mounted in VFS", csVariant ("")); commandLineHelper.AddCommandLineOption ("C", "VFS directory where to find the files", csVariant ("/")); commandLineHelper.AddCommandLineOption ("L", "Load a library file (for textures/materials)", csVariant ("")); // Printing help commandLineHelper.PrintApplicationHelp (object_reg, "cseditor", "cseditor <OPTIONS> [filename]", "The Crystal Space editor\n\n" "If provided, it will load the given file from the specified VFS directory." " If no VFS directory is provided then it will assume the one of the file. " "An additional real path can be provided to be mounted before loading the file." " This is useful for example to mount an archive in VFS before accessing the" " files in it."); } bool Editor::InitCS () { // Request every standard plugin except for OpenGL/WXGL canvas if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_PLUGIN ("crystalspace.graphics2d.wxgl", iGraphics2D), CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_LEVELLOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN ("crystalspace.collisiondetection.opcode", iCollideSystem), CS_REQUEST_END)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Can't initialize plugins!"); return false; } engine = csQueryRegistry<iEngine> (object_reg); if (!engine) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate 3D engine!"); return false; } engine->SetSaveableFlag(true); if (!csInitializer::RequestPlugins(object_reg, CS_REQUEST_LEVELSAVER, CS_REQUEST_END)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to initialize iSaver plugin!"); return false; } // Load plugins LoadPlugins (); // Open the main system. This will open all the previously loaded plug-ins. if (!csInitializer::OpenApplication (object_reg)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Error opening system!"); return false; } vfs = csQueryRegistry<iVFS> (object_reg); if (!vfs) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iVFS plugin!"); return false; } loader = csQueryRegistry<iThreadedLoader> (object_reg); if (!loader) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iThreadedLoader plugin!"); return false; } saver = csQueryRegistry<iSaver> (object_reg); if (!saver) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iSaver plugin!"); return false; } mainCollection = engine->CreateCollection ("Main collection"); // Analyze the command line arguments csRef<iCommandLineParser> cmdline = csQueryRegistry<iCommandLineParser> (object_reg); const char* libname; for (int i = 0; (libname = cmdline->GetOption ("L", i)); i++) mainFrame->PushLibraryFile ("", libname); const char* realPath = cmdline->GetOption ("R"); if (realPath) { vfs->Mount ("/tmp/viewmesh", realPath); //vfs->ChDir ("/tmp/viewmesh"); } csString filename = cmdline->GetName (0); csString vfsDir = cmdline->GetOption ("C"); if (vfsDir.IsEmpty ()) vfsDir = realPath; if (vfsDir.IsEmpty () && filename) { size_t index = filename.FindLast ('/'); if (index != (size_t) -1) { vfsDir = filename.Slice (0, index); filename = filename.Slice (index + 1); } } if (filename) mainFrame->PushMapFile (vfsDir, filename, false); /* if (!vfsDir.IsEmpty()) { if (!vfs->ChDir (vfsDir)) { ReportError("Cannot change to path: %s\n", vfsDir.GetData ()); } else { // Update StdDlg path. CEGUI::WindowManager* winMgr = cegui->GetWindowManagerPtr (); CEGUI::Window* window = winMgr->getWindow("StdDlg/Path"); window->setProperty("Text", vfs->GetCwd()); StdDlgUpdateLists(vfs->GetCwd()); } } */ return true; } void Editor::LoadPlugins () { // TODO: Add additional plugin directories to scan, through settings system? csRef<iStringArray> pluginClasses = iSCF::SCF->QueryClassList ("crystalspace.editor.plugin."); if (pluginClasses.IsValid()) { csRef<iPluginManager> plugmgr = csQueryRegistry<iPluginManager> (object_reg); for (size_t i = 0; i < pluginClasses->GetSize (); i++) { const char* className = pluginClasses->Get (i); csRef<iComponent> c (plugmgr->LoadPluginInstance (className, iPluginManager::lpiInitialize | iPluginManager::lpiReportErrors | iPluginManager::lpiLoadDependencies)); csRef<iBase> b = scfQueryInterface<iBase> (c); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.editor", "Attempt to load plugin '%s' %s", className, b ? "successful" : "failed"); if (b) b->DecRef (); } }; } csPtr<iProgressMeter> Editor::GetProgressMeter () { return mainFrame->GetProgressMeter (); } iThreadReturn* Editor::LoadMapFile (const char* path, const char* filename, bool clearEngine) { printf ("Editor::LoadMapFile %s %s\n", path, filename); vfs->ChDir (path); csRef<iThreadReturn> loadingResult = loader->LoadMapFile (vfs->GetCwd (), filename, clearEngine, mainCollection); return loadingResult; } iThreadReturn* Editor::LoadLibraryFile (const char* path, const char* filename) { vfs->ChDir (path); iCollection* collection = engine->CreateCollection ("loading_collection"); csRef<iThreadReturn> loadingResult = loader->LoadLibraryFile (vfs->GetCwd (), filename, collection); return loadingResult; } void Editor::SaveMapFile (const char* path, const char* filename) { vfs->ChDir (path); saver->SaveCollectionFile (mainCollection, filename, CS_SAVER_FILE_WORLD); } void Editor::FireMapLoaded (const char* path, const char* filename) { //engine->Prepare (); csRef<iProgressMeter> progressMeter = GetProgressMeter (); engine->Prepare (progressMeter); // TODO: Remove me. I'm only here to test the relighting progress gauge. //engine->SetLightingCacheMode (0); // Notify map listeners csRefArray<iMapListener>::Iterator it = mapListeners.GetIterator (); while (it.HasNext ()) { it.Next ()->OnMapLoaded (path, filename); } } void Editor::FireLibraryLoaded (const char* path, const char* filename) { // Notify map listeners csRefArray<iMapListener>::Iterator it = mapListeners.GetIterator (); while (it.HasNext ()) { it.Next ()->OnLibraryLoaded (path, filename, nullptr/*collection*/); } } void Editor::AddMapListener (iMapListener* listener) { mapListeners.Push (listener); } void Editor::RemoveMapListener (iMapListener* listener) { mapListeners.Delete (listener); } csPtr<iEditorObject> Editor::CreateEditorObject (iBase* object, wxBitmap* icon) { return csPtr<iEditorObject> (new EditorObject (object_reg, object, icon)); } iObjectList* Editor::GetSelection () { return selection; } iObjectList* Editor::GetObjects () { return objects; } void Editor::SetHelperMeshes (csArray<csSimpleRenderMesh>* helpers) { delete helper_meshes; helper_meshes = helpers; } csArray<csSimpleRenderMesh>* Editor::GetHelperMeshes () { return helper_meshes; } void Editor::SetTransformStatus (TransformStatus status) { transstatus = status; } Editor::TransformStatus Editor::GetTransformStatus () { return transstatus; } } // namespace EditorApp } // namespace CS <commit_msg>Fixed loading of library files & collection management<commit_after>/* Copyright (C) 2007 by Seth Yastrov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/scf.h" #include "cstool/initapp.h" #include "csutil/cmdhelp.h" #include "imap/saverfile.h" #include "iutil/cmdline.h" #include "iutil/stringarray.h" #include "ivaria/collider.h" #include "ivideo/graph2d.h" #include <wx/textctrl.h> #include "ieditor/panelmanager.h" #include "objectlist.h" #include "auipanelmanager.h" #include "interfacewrappermanager.h" #include "actionmanager.h" #include "editorobject.h" #include "mainframe.h" #include "editor.h" namespace CS { namespace EditorApp { Editor::Editor () : scfImplementationType (this), helper_meshes (0), transstatus (NOTHING) { } Editor::~Editor () { delete helper_meshes; // Remove ourself from object registry object_reg->Unregister (this, "iEditor"); } bool Editor::Initialize (iObjectRegistry* reg) { object_reg = reg; // Check for commandline help. if (csCommandLineHelper::CheckHelp (object_reg)) { Help (); return true; } selection.AttachNew (new ObjectList ()); objects.AttachNew (new ObjectList ()); object_reg->Register (this, "iEditor"); panelManager.AttachNew (new AUIPanelManager (object_reg)); interfaceManager.AttachNew (new InterfaceWrapperManager (object_reg)); actionManager.AttachNew (new ActionManager (object_reg)); // Create the main frame mainFrame = new MainFrame (wxT ("Crystal Space Editor"), wxDefaultPosition, wxSize (800, 600)); mainFrame->Initialize (object_reg, this); mainFrame->Show (); // Initialize CS and load plugins if (!InitCS ()) return false; mainFrame->SecondInitialize (object_reg); return true; } void Editor::Help () { csCommandLineHelper commandLineHelper; // Usage examples commandLineHelper.AddCommandLineExample ("cseditor data/castel/world"); commandLineHelper.AddCommandLineExample ("cseditor -R=data/kwartz.zip kwartz.lib"); commandLineHelper.AddCommandLineExample ("cseditor -R=data/seymour.zip Seymour.dae"); // Command line options commandLineHelper.AddCommandLineOption ("R", "Real path to be mounted in VFS", csVariant ("")); commandLineHelper.AddCommandLineOption ("C", "VFS directory where to find the files", csVariant ("/")); commandLineHelper.AddCommandLineOption ("L", "Load a library file (for textures/materials)", csVariant ("")); // Printing help commandLineHelper.PrintApplicationHelp (object_reg, "cseditor", "cseditor <OPTIONS> [filename]", "The Crystal Space editor\n\n" "If provided, it will load the given file from the specified VFS directory." " If no VFS directory is provided then it will assume the one of the file. " "An additional real path can be provided to be mounted before loading the file." " This is useful for example to mount an archive in VFS before accessing the" " files in it."); } bool Editor::InitCS () { // Request every standard plugin except for OpenGL/WXGL canvas if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_PLUGIN ("crystalspace.graphics2d.wxgl", iGraphics2D), CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_LEVELLOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN ("crystalspace.collisiondetection.opcode", iCollideSystem), CS_REQUEST_END)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Can't initialize plugins!"); return false; } engine = csQueryRegistry<iEngine> (object_reg); if (!engine) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate 3D engine!"); return false; } engine->SetSaveableFlag(true); if (!csInitializer::RequestPlugins(object_reg, CS_REQUEST_LEVELSAVER, CS_REQUEST_END)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to initialize iSaver plugin!"); return false; } // Load plugins LoadPlugins (); // Open the main system. This will open all the previously loaded plug-ins. if (!csInitializer::OpenApplication (object_reg)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Error opening system!"); return false; } vfs = csQueryRegistry<iVFS> (object_reg); if (!vfs) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iVFS plugin!"); return false; } loader = csQueryRegistry<iThreadedLoader> (object_reg); if (!loader) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iThreadedLoader plugin!"); return false; } saver = csQueryRegistry<iSaver> (object_reg); if (!saver) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.editor", "Failed to locate iSaver plugin!"); return false; } mainCollection = engine->CreateCollection ("Main collection"); // Analyze the command line arguments csRef<iCommandLineParser> cmdline = csQueryRegistry<iCommandLineParser> (object_reg); const char* libname; for (int i = 0; (libname = cmdline->GetOption ("L", i)); i++) mainFrame->PushLibraryFile ("", libname); const char* realPath = cmdline->GetOption ("R"); if (realPath) { vfs->Mount ("/tmp/viewmesh", realPath); //vfs->ChDir ("/tmp/viewmesh"); } csString filename = cmdline->GetName (0); csString vfsDir = cmdline->GetOption ("C"); if (vfsDir.IsEmpty ()) vfsDir = realPath; if (vfsDir.IsEmpty () && filename) { size_t index = filename.FindLast ('/'); if (index != (size_t) -1) { vfsDir = filename.Slice (0, index); filename = filename.Slice (index + 1); } } if (filename) mainFrame->PushMapFile (vfsDir, filename, false); return true; } void Editor::LoadPlugins () { // TODO: Add additional plugin directories to scan, through settings system? csRef<iStringArray> pluginClasses = iSCF::SCF->QueryClassList ("crystalspace.editor.plugin."); if (pluginClasses.IsValid()) { csRef<iPluginManager> plugmgr = csQueryRegistry<iPluginManager> (object_reg); for (size_t i = 0; i < pluginClasses->GetSize (); i++) { const char* className = pluginClasses->Get (i); csRef<iComponent> c (plugmgr->LoadPluginInstance (className, iPluginManager::lpiInitialize | iPluginManager::lpiReportErrors | iPluginManager::lpiLoadDependencies)); csRef<iBase> b = scfQueryInterface<iBase> (c); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.editor", "Attempt to load plugin '%s' %s", className, b ? "successful" : "failed"); if (b) b->DecRef (); } }; } csPtr<iProgressMeter> Editor::GetProgressMeter () { return mainFrame->GetProgressMeter (); } iThreadReturn* Editor::LoadMapFile (const char* path, const char* filename, bool clearEngine) { vfs->ChDir (path); if (clearEngine) { engine->RemoveCollection (mainCollection); mainCollection = engine->CreateCollection ("Main collection"); } csRef<iThreadReturn> loadingResult = loader->LoadMapFile (vfs->GetCwd (), filename, clearEngine, mainCollection); return loadingResult; } iThreadReturn* Editor::LoadLibraryFile (const char* path, const char* filename) { vfs->ChDir (path); csRef<iThreadReturn> loadingResult = loader->LoadLibraryFile (vfs->GetCwd (), filename, mainCollection); return loadingResult; } void Editor::SaveMapFile (const char* path, const char* filename) { vfs->ChDir (path); saver->SaveCollectionFile (mainCollection, filename, CS_SAVER_FILE_WORLD); } void Editor::FireMapLoaded (const char* path, const char* filename) { csRef<iProgressMeter> progressMeter = GetProgressMeter (); engine->Prepare (progressMeter); // TODO: Remove me. I'm only here to test the relighting progress gauge. //engine->SetLightingCacheMode (0); // Notify map listeners csRefArray<iMapListener>::Iterator it = mapListeners.GetIterator (); while (it.HasNext ()) { it.Next ()->OnMapLoaded (path, filename); } } void Editor::FireLibraryLoaded (const char* path, const char* filename) { // Notify map listeners csRefArray<iMapListener>::Iterator it = mapListeners.GetIterator (); while (it.HasNext ()) { it.Next ()->OnLibraryLoaded (path, filename, mainCollection); } } void Editor::AddMapListener (iMapListener* listener) { mapListeners.Push (listener); } void Editor::RemoveMapListener (iMapListener* listener) { mapListeners.Delete (listener); } csPtr<iEditorObject> Editor::CreateEditorObject (iBase* object, wxBitmap* icon) { return csPtr<iEditorObject> (new EditorObject (object_reg, object, icon)); } iObjectList* Editor::GetSelection () { return selection; } iObjectList* Editor::GetObjects () { return objects; } void Editor::SetHelperMeshes (csArray<csSimpleRenderMesh>* helpers) { delete helper_meshes; helper_meshes = helpers; } csArray<csSimpleRenderMesh>* Editor::GetHelperMeshes () { return helper_meshes; } void Editor::SetTransformStatus (TransformStatus status) { transstatus = status; } Editor::TransformStatus Editor::GetTransformStatus () { return transstatus; } } // namespace EditorApp } // namespace CS <|endoftext|>
<commit_before>// Copyright (c) 2012, Sergey Zolotarev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstddef> #include <map> #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" using namespace jit; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; static std::map<AMX*, JIT*> jits; // This implementation of amx_GetAddr can accept ANY amx_addr, even out of the data section. static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } // amx_Exec_JIT compiles a public function (if needed) and runs the generated JIT code. static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { if (index >= -1) { std::map<AMX*, JIT*>::iterator iterator = jits.find(amx); if (iterator != jits.end()) { return iterator->second->CallPublicFunction(index, retval); } } return AMX_ERR_NONE; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT); new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT); logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { // nothing } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { JIT *jit = new JIT(amx); jits.insert(std::make_pair(amx, jit)); return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { JIT *jit = jits[amx]; jits.erase(amx); delete jit; return AMX_ERR_NONE; } <commit_msg>Fix Linux crash because of amx_Exec() being called before AmxLoad<commit_after>// Copyright (c) 2012, Sergey Zolotarev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstddef> #include <map> #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" using namespace jit; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; typedef std::map<AMX*, JIT*> JITMap; static JITMap jit_map; static JIT *GetJIT(AMX *amx) { JITMap::const_iterator it = jit_map.find(amx); if (it == jit_map.end()) { JIT *jit = new JIT(amx); jit_map.insert(std::make_pair(amx, jit)); return jit; } else { return it->second; } } static void DeleteJIT(AMX *amx) { JITMap::iterator it = jit_map.find(amx); if (it != jit_map.end()) { jit_map.erase(it); delete it->second; } } // This implementation of amx_GetAddr can accept ANY amx_addr, even out of the data section. static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } // amx_Exec_JIT compiles a public function (if needed) and runs the generated JIT code. static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { if (index >= -1) { GetJIT(amx)->CallPublicFunction(index, retval); } return AMX_ERR_NONE; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT); new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT); logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { // nothing } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { DeleteJIT(amx); return AMX_ERR_NONE; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "DOMString.hpp" #include "AttrImpl.hpp" #include "NodeIDMap.hpp" #include <xercesc/util/XMLString.hpp> #include <xercesc/util/RuntimeException.hpp> #include <stdio.h> XERCES_CPP_NAMESPACE_BEGIN static const int gPrimes[] = {997, 9973, 99991, 999983, 0 }; // To do - add a few more. static const float gMaxFill = 0.8f; // The maximum fraction of the total // table entries to consume before exanding. NodeIDMap::NodeIDMap(int initialSize, MemoryManager* const manager) : fMemoryManager(manager) { for (fSizeIndex = 0; gPrimes[fSizeIndex] < initialSize; fSizeIndex++) { if (gPrimes[fSizeIndex] == 0) { // We need a bigger size than the largest available one. // Big trouble. fSizeIndex--; ThrowXML(RuntimeException, XMLExcepts::NodeIDMap_GrowErr); } } fSize = gPrimes[fSizeIndex]; fNumEntries = 0; fMaxEntries = (unsigned long)(float(fSize) * gMaxFill); fTable = (AttrImpl**) manager->allocate(fSize * sizeof(AttrImpl*));// new AttrImpl *[fSize]; unsigned int i; for (i=0; i<fSize; i++) fTable[i] = 0; }; NodeIDMap::~NodeIDMap() { delete[] fTable; fMemoryManager->deallocate(fTable);//fTable = 0; }; void NodeIDMap::add(AttrImpl *attr) { // // If the table is getting too full, grow it. We arbitrarily limit // the table to 80 full, which should limit the average number of // rehashes to a reasonable value. // if (fNumEntries >= fMaxEntries) growTable(); fNumEntries++; // // Hash the value string from the ID attribute being added to the table // 0 < Initial hash value < table size. // An initial hash of zero would cause the rehash to fail. // DOMString id=attr->getValue(); unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for an empty slot for this ID. // Don't even bother checking to see if the ID is already there - // the table is only filled by the parser from valid documents, which // can not have duplicates. Behavior of invalid docs is not defined. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0 || tableSlot == (AttrImpl *)-1) break; currentHash += initalHash; // rehash if (currentHash >= fSize) currentHash = currentHash % fSize; } // // We've found our slot. Stick the pointer to the attr into it. // fTable[currentHash] = attr; }; void NodeIDMap::remove(AttrImpl *attr) { // // Hash the value string from the ID attribute being added to the table // 0 < Initial hash value < table size. // An initial hash of zero would cause the rehash to fail. // DOMString id=attr->getValue(); unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for a slot pointing to an attr with this id. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0) { // There is no matching entry in the table return; } if (tableSlot == attr) { // Found the attribute. Set the slot to -1 to indicate // that it was once used, meaning that lookups, while never // matching here, can not stop either, but must rehash again // and continue searching. fTable[currentHash] = (AttrImpl *)-1; return; } currentHash += initalHash; // rehash. if (currentHash >= fSize) currentHash = currentHash % fSize; } }; AttrImpl *NodeIDMap::find(const DOMString &id) { // // Get the hashcode for the supplied string. // unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for a slot pointing to an attr with this id. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0) { // There is no matching entry in the table return 0; } if ((tableSlot != (AttrImpl *)-1) && tableSlot->getValue().equals(id)) return tableSlot; currentHash += initalHash; // rehash if (currentHash >= fSize) currentHash = currentHash % fSize; } return 0; // Never gets here, but keeps some compilers happy. }; // // Grow the table to the next larger size. // It has gotten too full for efficient operation. // (We never fill it all the way) // void NodeIDMap::growTable() { AttrImpl **oldTable = fTable; unsigned int oldSize = fSize; // // Figure the new table size. // #if defined(XERCES_DEBUG) fprintf(stderr, "growing...\n"); #endif fSizeIndex++; fSize = gPrimes[fSizeIndex]; if (fSize == 0) { // We need to grow bigger than the largest available size. // Big trouble. fSizeIndex--; ThrowXML(RuntimeException, XMLExcepts::NodeIDMap_GrowErr); } // // Allocate the new table. // fTable = (AttrImpl**) fMemoryManager->allocate(fSize * sizeof(AttrImpl*));//new AttrImpl *[fSize]; unsigned int i; for (i=0; i<fSize; i++) fTable[i] = 0; fMaxEntries = (unsigned long)(float(fSize) * gMaxFill); // // Move entries over from the old table to the new one. // for (i=0; i<oldSize; i++) { if ((oldTable[i] != 0) && (oldTable[i] != (AttrImpl *)-1)) add(oldTable[i]); } fMemoryManager->deallocate(oldTable);//delete [] oldTable; }; XERCES_CPP_NAMESPACE_END <commit_msg>remove superfluous delete<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "DOMString.hpp" #include "AttrImpl.hpp" #include "NodeIDMap.hpp" #include <xercesc/util/XMLString.hpp> #include <xercesc/util/RuntimeException.hpp> #include <stdio.h> XERCES_CPP_NAMESPACE_BEGIN static const int gPrimes[] = {997, 9973, 99991, 999983, 0 }; // To do - add a few more. static const float gMaxFill = 0.8f; // The maximum fraction of the total // table entries to consume before exanding. NodeIDMap::NodeIDMap(int initialSize, MemoryManager* const manager) : fMemoryManager(manager) { for (fSizeIndex = 0; gPrimes[fSizeIndex] < initialSize; fSizeIndex++) { if (gPrimes[fSizeIndex] == 0) { // We need a bigger size than the largest available one. // Big trouble. fSizeIndex--; ThrowXML(RuntimeException, XMLExcepts::NodeIDMap_GrowErr); } } fSize = gPrimes[fSizeIndex]; fNumEntries = 0; fMaxEntries = (unsigned long)(float(fSize) * gMaxFill); fTable = (AttrImpl**) manager->allocate(fSize * sizeof(AttrImpl*));// new AttrImpl *[fSize]; unsigned int i; for (i=0; i<fSize; i++) fTable[i] = 0; }; NodeIDMap::~NodeIDMap() { // delete[] fTable; fMemoryManager->deallocate(fTable);//fTable = 0; }; void NodeIDMap::add(AttrImpl *attr) { // // If the table is getting too full, grow it. We arbitrarily limit // the table to 80 full, which should limit the average number of // rehashes to a reasonable value. // if (fNumEntries >= fMaxEntries) growTable(); fNumEntries++; // // Hash the value string from the ID attribute being added to the table // 0 < Initial hash value < table size. // An initial hash of zero would cause the rehash to fail. // DOMString id=attr->getValue(); unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for an empty slot for this ID. // Don't even bother checking to see if the ID is already there - // the table is only filled by the parser from valid documents, which // can not have duplicates. Behavior of invalid docs is not defined. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0 || tableSlot == (AttrImpl *)-1) break; currentHash += initalHash; // rehash if (currentHash >= fSize) currentHash = currentHash % fSize; } // // We've found our slot. Stick the pointer to the attr into it. // fTable[currentHash] = attr; }; void NodeIDMap::remove(AttrImpl *attr) { // // Hash the value string from the ID attribute being added to the table // 0 < Initial hash value < table size. // An initial hash of zero would cause the rehash to fail. // DOMString id=attr->getValue(); unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for a slot pointing to an attr with this id. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0) { // There is no matching entry in the table return; } if (tableSlot == attr) { // Found the attribute. Set the slot to -1 to indicate // that it was once used, meaning that lookups, while never // matching here, can not stop either, but must rehash again // and continue searching. fTable[currentHash] = (AttrImpl *)-1; return; } currentHash += initalHash; // rehash. if (currentHash >= fSize) currentHash = currentHash % fSize; } }; AttrImpl *NodeIDMap::find(const DOMString &id) { // // Get the hashcode for the supplied string. // unsigned int initalHash = XMLString::hashN(id.rawBuffer(), id.length(), fSize-1); initalHash++; unsigned int currentHash = initalHash; // // Loop looking for a slot pointing to an attr with this id. // while (true) { AttrImpl *tableSlot = fTable[currentHash]; if (tableSlot == 0) { // There is no matching entry in the table return 0; } if ((tableSlot != (AttrImpl *)-1) && tableSlot->getValue().equals(id)) return tableSlot; currentHash += initalHash; // rehash if (currentHash >= fSize) currentHash = currentHash % fSize; } return 0; // Never gets here, but keeps some compilers happy. }; // // Grow the table to the next larger size. // It has gotten too full for efficient operation. // (We never fill it all the way) // void NodeIDMap::growTable() { AttrImpl **oldTable = fTable; unsigned int oldSize = fSize; // // Figure the new table size. // #if defined(XERCES_DEBUG) fprintf(stderr, "growing...\n"); #endif fSizeIndex++; fSize = gPrimes[fSizeIndex]; if (fSize == 0) { // We need to grow bigger than the largest available size. // Big trouble. fSizeIndex--; ThrowXML(RuntimeException, XMLExcepts::NodeIDMap_GrowErr); } // // Allocate the new table. // fTable = (AttrImpl**) fMemoryManager->allocate(fSize * sizeof(AttrImpl*));//new AttrImpl *[fSize]; unsigned int i; for (i=0; i<fSize; i++) fTable[i] = 0; fMaxEntries = (unsigned long)(float(fSize) * gMaxFill); // // Move entries over from the old table to the new one. // for (i=0; i<oldSize; i++) { if ((oldTable[i] != 0) && (oldTable[i] != (AttrImpl *)-1)) add(oldTable[i]); } fMemoryManager->deallocate(oldTable);//delete [] oldTable; }; XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>#ifndef DOMDocumentImpl_HEADER_GUARD_ #define DOMDocumentImpl_HEADER_GUARD_ /* * 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. */ /* * $Id$ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/RefArrayOf.hpp> #include <xercesc/util/RefStackOf.hpp> #include <xercesc/util/RefHash2KeysTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/util/KeyRefPair.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMUserDataHandler.hpp> #include <xercesc/dom/DOMMemoryManager.hpp> #include "DOMNodeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMDeepNodeListPool.hpp" XERCES_CPP_NAMESPACE_BEGIN class DOMAttrImpl; class DOMCDATASectionImpl; class DOMCommentImpl; class DOMConfiguration; class DOMDeepNodeListImpl; class DOMDocumentFragmentImpl; class DOMDocumentTypeImpl; class DOMElementImpl; class DOMEntityImpl; class DOMEntityReferenceImpl; class DOMNotationImpl; class DOMProcessingInstructionImpl; class DOMTextImpl; class DOMNodeIteratorImpl; class DOMNormalizer; class DOMTreeWalkerImpl; class DOMNodeFilter; class DOMNodeFilterImpl; class DOMImplementation; class DOMNodeIDMap; class DOMRangeImpl; class DOMStringPool; class DOMBuffer; class MemoryManager; class XPathNSResolver; class XPathExpression; typedef RefVectorOf<DOMRangeImpl> Ranges; typedef RefVectorOf<DOMNodeIteratorImpl> NodeIterators; typedef KeyRefPair<void, DOMUserDataHandler> DOMUserDataRecord; typedef RefStackOf<DOMNode> DOMNodePtr; class CDOM_EXPORT DOMDocumentImpl: public XMemory, public DOMMemoryManager, public DOMDocument { public: // ----------------------------------------------------------------------- // data // ----------------------------------------------------------------------- DOMNodeImpl fNode; // Implements common node functionality. DOMParentNode fParent; // Implements common parent node functionality DOMNodeIDMap* fNodeIDMap; // for use by GetElementsById(). public: DOMDocumentImpl(DOMImplementation* domImpl, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); DOMDocumentImpl(const XMLCh* namespaceURI, //DOM Level 2 const XMLCh* qualifiedName, DOMDocumentType* doctype, DOMImplementation* domImpl, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual ~DOMDocumentImpl(); void setDocumentType(DOMDocumentType *doctype); // Add all functions that are pure virtual in DOMNODE DOMNODE_FUNCTIONS; // Add all functions that are pure virtual in DOMDocument virtual DOMAttr* createAttribute(const XMLCh *name); virtual DOMCDATASection* createCDATASection(const XMLCh *data); virtual DOMComment* createComment(const XMLCh *data); virtual DOMDocumentFragment* createDocumentFragment(); virtual DOMDocumentType* createDocumentType(const XMLCh *name); virtual DOMDocumentType* createDocumentType(const XMLCh *qName, const XMLCh *publicId, const XMLCh *systemId); virtual DOMElement* createElement(const XMLCh * tagName); virtual DOMElement* createElementNoCheck(const XMLCh *tagName); virtual DOMEntity* createEntity(const XMLCh * name); virtual DOMEntityReference* createEntityReference(const XMLCh * name); virtual DOMNotation* createNotation(const XMLCh * name); virtual DOMProcessingInstruction* createProcessingInstruction(const XMLCh * target, const XMLCh * data); virtual DOMText* createTextNode(const XMLCh * data); virtual DOMDocumentType* getDoctype() const; virtual DOMElement* getDocumentElement() const; virtual DOMNodeList* getElementsByTagName(const XMLCh * tagname) const; virtual DOMImplementation* getImplementation() const; bool isXMLName(const XMLCh * s); virtual DOMNodeIterator* createNodeIterator(DOMNode *root, unsigned long whatToShow, DOMNodeFilter* filter, bool entityReferenceExpansion); virtual DOMTreeWalker* createTreeWalker(DOMNode *root, unsigned long whatToShow, DOMNodeFilter* filter, bool entityReferenceExpansion); virtual DOMRange* createRange(); virtual Ranges* getRanges() const; //non-standard api virtual NodeIterators* getNodeIterators() const; //non-standard api virtual void removeRange(DOMRangeImpl* range); //non-standard api virtual void removeNodeIterator(DOMNodeIteratorImpl* nodeIterator); //non-standard api virtual const DOMXPathExpression* createExpression(const XMLCh *expression, const DOMXPathNSResolver *resolver); virtual const DOMXPathNSResolver* createNSResolver(DOMNode *nodeResolver); virtual void* evaluate(const XMLCh *expression, DOMNode *contextNode, const DOMXPathNSResolver *resolver, unsigned short type, void* result); // Extension to be called by the Parser DOMEntityReference* createEntityReferenceByParser(const XMLCh * name); // Add all functions that are pure virtual in DOMMemoryManager virtual XMLSize_t getMemoryAllocationBlockSize() const; virtual void setMemoryAllocationBlockSize(XMLSize_t size); virtual void* allocate(XMLSize_t amount); virtual void* allocate(XMLSize_t amount, DOMMemoryManager::NodeObjectType type); virtual void release(DOMNode* object, DOMMemoryManager::NodeObjectType type); virtual XMLCh* cloneString(const XMLCh *src); // // Functions to keep track of document mutations, so that node list chached // information can be invalidated. One global changes counter per document. // virtual void changed(); virtual int changes() const; /** * Sets whether the DOM implementation performs error checking * upon operations. Turning off error checking only affects * the following DOM checks: * <ul> * <li>Checking strings to make sure that all characters are * legal XML characters * <li>Hierarchy checking such as allowed children, checks for * cycles, etc. * </ul> * <p> * Turning off error checking does <em>not</em> turn off the * following checks: * <ul> * <li>Read only checks * <li>Checks related to DOM events * </ul> */ inline void setErrorChecking(bool check) { errorChecking = check; } /** * Returns true if the DOM implementation performs error checking. */ inline bool getErrorChecking() const { return errorChecking; } //Introduced in DOM Level 2 virtual DOMNode* importNode(const DOMNode *source, bool deep); virtual DOMElement* createElementNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName); virtual DOMElement* createElementNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName, const XMLSSize_t lineNo, const XMLSSize_t columnNo); virtual DOMAttr* createAttributeNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName); virtual DOMNodeList* getElementsByTagNameNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMElement* getElementById(const XMLCh *elementId) const; //Introduced in DOM Level 3 virtual const XMLCh* getInputEncoding() const; virtual const XMLCh* getXmlEncoding() const; virtual bool getXmlStandalone() const; virtual void setXmlStandalone(bool standalone); virtual const XMLCh* getXmlVersion() const; virtual void setXmlVersion(const XMLCh* version); virtual const XMLCh* getDocumentURI() const; virtual void setDocumentURI(const XMLCh* documentURI); virtual bool getStrictErrorChecking() const; virtual void setStrictErrorChecking(bool strictErrorChecking); virtual DOMNode* adoptNode(DOMNode* source); virtual void normalizeDocument(); virtual DOMConfiguration* getDOMConfig() const; void setInputEncoding(const XMLCh* actualEncoding); void setXmlEncoding(const XMLCh* encoding); // helper functions to prevent storing userdata pointers on every node. void* setUserData(DOMNodeImpl* n, const XMLCh* key, void* data, DOMUserDataHandler* handler); void* getUserData(const DOMNodeImpl* n, const XMLCh* key) const; void callUserDataHandlers(const DOMNodeImpl* n, DOMUserDataHandler::DOMOperationType operation, const DOMNode* src, DOMNode* dst) const; void transferUserData(DOMNodeImpl* n1, DOMNodeImpl* n2); DOMNode* renameNode(DOMNode* n, const XMLCh* namespaceURI, const XMLCh* name); //Return the index > 0 of ':' in the given qualified name qName="prefix:localName". //Return 0 if there is no ':', or -1 if qName is malformed such as ":abcd". static int indexofQualifiedName(const XMLCh * qName); static bool isKidOK(DOMNode *parent, DOMNode *child); inline DOMNodeIDMap* getNodeIDMap() {return fNodeIDMap;}; // // Memory Management Functions. All memory is allocated by and owned by // a document, and is not recovered until the // document itself is deleted. // const XMLCh* getPooledString(const XMLCh *src); void deleteHeap(); void releaseDocNotifyUserData(DOMNode* object); void releaseBuffer(DOMBuffer* buffer); DOMBuffer* popBuffer(XMLSize_t nMinSize); MemoryManager* getMemoryManager() const; // Factory methods for getting/creating node lists. // Because nothing is ever deleted, the implementation caches and recycles // previously used instances of DOMDeepNodeList // DOMNodeList* getDeepNodeList(const DOMNode *rootNode, const XMLCh *tagName); DOMNodeList* getDeepNodeList(const DOMNode *rootNode, //DOM Level 2 const XMLCh *namespaceURI, const XMLCh *localName); private: //Internal helper functions virtual DOMNode* importNode(const DOMNode *source, bool deep, bool cloningNode); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMDocumentImpl(const DOMDocumentImpl &); DOMDocumentImpl & operator = (const DOMDocumentImpl &); private: // ----------------------------------------------------------------------- // data // ----------------------------------------------------------------------- // New data introduced in DOM Level 3 const XMLCh* fInputEncoding; const XMLCh* fXmlEncoding; bool fXmlStandalone; const XMLCh* fXmlVersion; const XMLCh* fDocumentURI; DOMConfiguration* fDOMConfiguration; XMLStringPool fUserDataTableKeys; RefHash2KeysTableOf<DOMUserDataRecord>* fUserDataTable; // Per-Document heap Variables. // The heap consists of one or more biggish blocks which are // sub-allocated for individual allocations of nodes, strings, etc. // The big blocks form a linked list, allowing them to be located for deletion. // // There is no provision for deleting suballocated blocks, other than // deleting the entire heap when the document is deleted. // // There is no header on individual sub-allocated blocks. // The header on big blocks consists only of a single back pointer to // the previously allocated big block (our linked list of big blocks) // // // revisit - this heap should be encapsulated into its own // class, rather than hanging naked on Document. // void* fCurrentBlock; char* fFreePtr; XMLSize_t fFreeBytesRemaining, fHeapAllocSize; // To recycle the DOMNode pointer RefArrayOf<DOMNodePtr>* fRecycleNodePtr; // To recycle DOMBuffer pointer RefStackOf<DOMBuffer>* fRecycleBufferPtr; // Pool of DOMNodeList for getElementsByTagName DOMDeepNodeListPool<DOMDeepNodeListImpl>* fNodeListPool; // Other data DOMDocumentType* fDocType; DOMElement* fDocElement; DOMStringPool* fNamePool; DOMNormalizer* fNormalizer; Ranges* fRanges; NodeIterators* fNodeIterators; MemoryManager* fMemoryManager; // configurable memory manager DOMImplementation* fDOMImplementation; int fChanges; bool errorChecking; // Bypass error checking. }; inline MemoryManager* DOMDocumentImpl::getMemoryManager() const { return fMemoryManager; } XERCES_CPP_NAMESPACE_END // --------------------------------------------------------------------------- // // Operator new. Global overloaded version, lets any object be allocated on // the heap owned by a document. // // --------------------------------------------------------------------------- inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocumentImpl *doc, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType type) { void *p = doc->allocate(amt, type); return p; } inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType type) { XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager* mgr=(XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager*)doc->getFeature(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgXercescInterfaceDOMMemoryManager,0); void* p=0; if(mgr) p = mgr->allocate(amt, type); return p; } inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc) { XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager* mgr=(XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager*)doc->getFeature(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgXercescInterfaceDOMMemoryManager,0); void* p=0; if(mgr) p = mgr->allocate(amt); return p; } // --------------------------------------------------------------------------- // For DOM: // Bypass compiler warning: // no matching operator delete found; memory will not be freed if initialization throws an exception // --------------------------------------------------------------------------- #if _MSC_VER >= 1200 /* VC++ 6.0 */ inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocumentImpl * /*doc*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType /*type*/) { return; } inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * /*doc*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType /*type*/) { return; } inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * /*doc*/) { return; } #endif #endif <commit_msg>Use existing define from XMemory to control whether or not corresponding operator delete overloads are defined. This silences warnings on more compilers.<commit_after>#ifndef DOMDocumentImpl_HEADER_GUARD_ #define DOMDocumentImpl_HEADER_GUARD_ /* * 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. */ /* * $Id$ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/RefArrayOf.hpp> #include <xercesc/util/RefStackOf.hpp> #include <xercesc/util/RefHash2KeysTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/util/KeyRefPair.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMUserDataHandler.hpp> #include <xercesc/dom/DOMMemoryManager.hpp> #include "DOMNodeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMDeepNodeListPool.hpp" XERCES_CPP_NAMESPACE_BEGIN class DOMAttrImpl; class DOMCDATASectionImpl; class DOMCommentImpl; class DOMConfiguration; class DOMDeepNodeListImpl; class DOMDocumentFragmentImpl; class DOMDocumentTypeImpl; class DOMElementImpl; class DOMEntityImpl; class DOMEntityReferenceImpl; class DOMNotationImpl; class DOMProcessingInstructionImpl; class DOMTextImpl; class DOMNodeIteratorImpl; class DOMNormalizer; class DOMTreeWalkerImpl; class DOMNodeFilter; class DOMNodeFilterImpl; class DOMImplementation; class DOMNodeIDMap; class DOMRangeImpl; class DOMStringPool; class DOMBuffer; class MemoryManager; class XPathNSResolver; class XPathExpression; typedef RefVectorOf<DOMRangeImpl> Ranges; typedef RefVectorOf<DOMNodeIteratorImpl> NodeIterators; typedef KeyRefPair<void, DOMUserDataHandler> DOMUserDataRecord; typedef RefStackOf<DOMNode> DOMNodePtr; class CDOM_EXPORT DOMDocumentImpl: public XMemory, public DOMMemoryManager, public DOMDocument { public: // ----------------------------------------------------------------------- // data // ----------------------------------------------------------------------- DOMNodeImpl fNode; // Implements common node functionality. DOMParentNode fParent; // Implements common parent node functionality DOMNodeIDMap* fNodeIDMap; // for use by GetElementsById(). public: DOMDocumentImpl(DOMImplementation* domImpl, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); DOMDocumentImpl(const XMLCh* namespaceURI, //DOM Level 2 const XMLCh* qualifiedName, DOMDocumentType* doctype, DOMImplementation* domImpl, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); virtual ~DOMDocumentImpl(); void setDocumentType(DOMDocumentType *doctype); // Add all functions that are pure virtual in DOMNODE DOMNODE_FUNCTIONS; // Add all functions that are pure virtual in DOMDocument virtual DOMAttr* createAttribute(const XMLCh *name); virtual DOMCDATASection* createCDATASection(const XMLCh *data); virtual DOMComment* createComment(const XMLCh *data); virtual DOMDocumentFragment* createDocumentFragment(); virtual DOMDocumentType* createDocumentType(const XMLCh *name); virtual DOMDocumentType* createDocumentType(const XMLCh *qName, const XMLCh *publicId, const XMLCh *systemId); virtual DOMElement* createElement(const XMLCh * tagName); virtual DOMElement* createElementNoCheck(const XMLCh *tagName); virtual DOMEntity* createEntity(const XMLCh * name); virtual DOMEntityReference* createEntityReference(const XMLCh * name); virtual DOMNotation* createNotation(const XMLCh * name); virtual DOMProcessingInstruction* createProcessingInstruction(const XMLCh * target, const XMLCh * data); virtual DOMText* createTextNode(const XMLCh * data); virtual DOMDocumentType* getDoctype() const; virtual DOMElement* getDocumentElement() const; virtual DOMNodeList* getElementsByTagName(const XMLCh * tagname) const; virtual DOMImplementation* getImplementation() const; bool isXMLName(const XMLCh * s); virtual DOMNodeIterator* createNodeIterator(DOMNode *root, unsigned long whatToShow, DOMNodeFilter* filter, bool entityReferenceExpansion); virtual DOMTreeWalker* createTreeWalker(DOMNode *root, unsigned long whatToShow, DOMNodeFilter* filter, bool entityReferenceExpansion); virtual DOMRange* createRange(); virtual Ranges* getRanges() const; //non-standard api virtual NodeIterators* getNodeIterators() const; //non-standard api virtual void removeRange(DOMRangeImpl* range); //non-standard api virtual void removeNodeIterator(DOMNodeIteratorImpl* nodeIterator); //non-standard api virtual const DOMXPathExpression* createExpression(const XMLCh *expression, const DOMXPathNSResolver *resolver); virtual const DOMXPathNSResolver* createNSResolver(DOMNode *nodeResolver); virtual void* evaluate(const XMLCh *expression, DOMNode *contextNode, const DOMXPathNSResolver *resolver, unsigned short type, void* result); // Extension to be called by the Parser DOMEntityReference* createEntityReferenceByParser(const XMLCh * name); // Add all functions that are pure virtual in DOMMemoryManager virtual XMLSize_t getMemoryAllocationBlockSize() const; virtual void setMemoryAllocationBlockSize(XMLSize_t size); virtual void* allocate(XMLSize_t amount); virtual void* allocate(XMLSize_t amount, DOMMemoryManager::NodeObjectType type); virtual void release(DOMNode* object, DOMMemoryManager::NodeObjectType type); virtual XMLCh* cloneString(const XMLCh *src); // // Functions to keep track of document mutations, so that node list chached // information can be invalidated. One global changes counter per document. // virtual void changed(); virtual int changes() const; /** * Sets whether the DOM implementation performs error checking * upon operations. Turning off error checking only affects * the following DOM checks: * <ul> * <li>Checking strings to make sure that all characters are * legal XML characters * <li>Hierarchy checking such as allowed children, checks for * cycles, etc. * </ul> * <p> * Turning off error checking does <em>not</em> turn off the * following checks: * <ul> * <li>Read only checks * <li>Checks related to DOM events * </ul> */ inline void setErrorChecking(bool check) { errorChecking = check; } /** * Returns true if the DOM implementation performs error checking. */ inline bool getErrorChecking() const { return errorChecking; } //Introduced in DOM Level 2 virtual DOMNode* importNode(const DOMNode *source, bool deep); virtual DOMElement* createElementNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName); virtual DOMElement* createElementNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName, const XMLSSize_t lineNo, const XMLSSize_t columnNo); virtual DOMAttr* createAttributeNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName); virtual DOMNodeList* getElementsByTagNameNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMElement* getElementById(const XMLCh *elementId) const; //Introduced in DOM Level 3 virtual const XMLCh* getInputEncoding() const; virtual const XMLCh* getXmlEncoding() const; virtual bool getXmlStandalone() const; virtual void setXmlStandalone(bool standalone); virtual const XMLCh* getXmlVersion() const; virtual void setXmlVersion(const XMLCh* version); virtual const XMLCh* getDocumentURI() const; virtual void setDocumentURI(const XMLCh* documentURI); virtual bool getStrictErrorChecking() const; virtual void setStrictErrorChecking(bool strictErrorChecking); virtual DOMNode* adoptNode(DOMNode* source); virtual void normalizeDocument(); virtual DOMConfiguration* getDOMConfig() const; void setInputEncoding(const XMLCh* actualEncoding); void setXmlEncoding(const XMLCh* encoding); // helper functions to prevent storing userdata pointers on every node. void* setUserData(DOMNodeImpl* n, const XMLCh* key, void* data, DOMUserDataHandler* handler); void* getUserData(const DOMNodeImpl* n, const XMLCh* key) const; void callUserDataHandlers(const DOMNodeImpl* n, DOMUserDataHandler::DOMOperationType operation, const DOMNode* src, DOMNode* dst) const; void transferUserData(DOMNodeImpl* n1, DOMNodeImpl* n2); DOMNode* renameNode(DOMNode* n, const XMLCh* namespaceURI, const XMLCh* name); //Return the index > 0 of ':' in the given qualified name qName="prefix:localName". //Return 0 if there is no ':', or -1 if qName is malformed such as ":abcd". static int indexofQualifiedName(const XMLCh * qName); static bool isKidOK(DOMNode *parent, DOMNode *child); inline DOMNodeIDMap* getNodeIDMap() {return fNodeIDMap;}; // // Memory Management Functions. All memory is allocated by and owned by // a document, and is not recovered until the // document itself is deleted. // const XMLCh* getPooledString(const XMLCh *src); void deleteHeap(); void releaseDocNotifyUserData(DOMNode* object); void releaseBuffer(DOMBuffer* buffer); DOMBuffer* popBuffer(XMLSize_t nMinSize); MemoryManager* getMemoryManager() const; // Factory methods for getting/creating node lists. // Because nothing is ever deleted, the implementation caches and recycles // previously used instances of DOMDeepNodeList // DOMNodeList* getDeepNodeList(const DOMNode *rootNode, const XMLCh *tagName); DOMNodeList* getDeepNodeList(const DOMNode *rootNode, //DOM Level 2 const XMLCh *namespaceURI, const XMLCh *localName); private: //Internal helper functions virtual DOMNode* importNode(const DOMNode *source, bool deep, bool cloningNode); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMDocumentImpl(const DOMDocumentImpl &); DOMDocumentImpl & operator = (const DOMDocumentImpl &); private: // ----------------------------------------------------------------------- // data // ----------------------------------------------------------------------- // New data introduced in DOM Level 3 const XMLCh* fInputEncoding; const XMLCh* fXmlEncoding; bool fXmlStandalone; const XMLCh* fXmlVersion; const XMLCh* fDocumentURI; DOMConfiguration* fDOMConfiguration; XMLStringPool fUserDataTableKeys; RefHash2KeysTableOf<DOMUserDataRecord>* fUserDataTable; // Per-Document heap Variables. // The heap consists of one or more biggish blocks which are // sub-allocated for individual allocations of nodes, strings, etc. // The big blocks form a linked list, allowing them to be located for deletion. // // There is no provision for deleting suballocated blocks, other than // deleting the entire heap when the document is deleted. // // There is no header on individual sub-allocated blocks. // The header on big blocks consists only of a single back pointer to // the previously allocated big block (our linked list of big blocks) // // // revisit - this heap should be encapsulated into its own // class, rather than hanging naked on Document. // void* fCurrentBlock; char* fFreePtr; XMLSize_t fFreeBytesRemaining, fHeapAllocSize; // To recycle the DOMNode pointer RefArrayOf<DOMNodePtr>* fRecycleNodePtr; // To recycle DOMBuffer pointer RefStackOf<DOMBuffer>* fRecycleBufferPtr; // Pool of DOMNodeList for getElementsByTagName DOMDeepNodeListPool<DOMDeepNodeListImpl>* fNodeListPool; // Other data DOMDocumentType* fDocType; DOMElement* fDocElement; DOMStringPool* fNamePool; DOMNormalizer* fNormalizer; Ranges* fRanges; NodeIterators* fNodeIterators; MemoryManager* fMemoryManager; // configurable memory manager DOMImplementation* fDOMImplementation; int fChanges; bool errorChecking; // Bypass error checking. }; inline MemoryManager* DOMDocumentImpl::getMemoryManager() const { return fMemoryManager; } XERCES_CPP_NAMESPACE_END // --------------------------------------------------------------------------- // // Operator new. Global overloaded version, lets any object be allocated on // the heap owned by a document. // // --------------------------------------------------------------------------- inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocumentImpl *doc, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType type) { void *p = doc->allocate(amt, type); return p; } inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType type) { XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager* mgr=(XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager*)doc->getFeature(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgXercescInterfaceDOMMemoryManager,0); void* p=0; if(mgr) p = mgr->allocate(amt, type); return p; } inline void * operator new(size_t amt, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc) { XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager* mgr=(XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager*)doc->getFeature(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgXercescInterfaceDOMMemoryManager,0); void* p=0; if(mgr) p = mgr->allocate(amt); return p; } // --------------------------------------------------------------------------- // For DOM: // Bypass compiler warning: // no matching operator delete found; memory will not be freed if initialization throws an exception // --------------------------------------------------------------------------- #if !defined(XERCES_NO_MATCHING_DELETE_OPERATOR) inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocumentImpl * /*doc*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType /*type*/) { return; } inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * /*doc*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMMemoryManager::NodeObjectType /*type*/) { return; } inline void operator delete(void* /*ptr*/, XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * /*doc*/) { return; } #endif #endif <|endoftext|>
<commit_before> #ifndef __ADDRESSING_HPP__ #define __ADDRESSING_HPP__ /// Global Addresses for SoftXMT /// /// /// /// /// We support two types of global addresses: /// -# 2D addresses /// -# Linear addresses /// /// 2D addresses are node, address on node /// /// linear addresses are block cyclic #include "SoftXMT.hpp" typedef int Pool; /// assumes user data will have the top 16 bits all 0. static const int block_size = sizeof(int64_t) * 8; static const int tag_bits = 1; static const int pointer_bits = 48; static const int node_bits = 64 - pointer_bits - tag_bits; static const int pool_bits = 64 - pointer_bits - tag_bits; static const int tag_shift_val = 64 - tag_bits; static const int pointer_shift_val = 64 - pointer_bits; static const int node_shift_val = pointer_bits; static const int pool_shift_val = pointer_bits; static const intptr_t tag_mask = (1L << tag_shift_val); static const intptr_t node_mask = (1L << node_bits) - 1; static const intptr_t pool_mask = (1L << pool_bits) - 1; static const intptr_t pointer_mask = (1L << pointer_bits) - 1; template< typename T > class GlobalAddress { private: intptr_t storage_; //DISALLOW_COPY_AND_ASSIGN( GlobalAddress ); template< typename U > friend std::ostream& operator<<( std::ostream& o, const GlobalAddress< U >& ga ); //friend template< typename U > GlobalAddress< U > operator+( const GlobalAddress< U >& t, ptrdiff_t i ); template< typename U > friend ptrdiff_t operator-( const GlobalAddress< U >& t, const GlobalAddress< U >& u ); std::ostream& dump( std::ostream& o ) const { if( is_2D() ) { return o << "<GA 2D " << (void*)storage_ << ": node " << node() << " pointer " << pointer() << ">"; } else { return o << "<GA Linear " << (void*)storage_ << ": pool " << pool() << " pointer " << pointer() << ">"; } } // GlobalAddress( T * p, Node n = SoftXMT_mynode() ) // : storage_( ( 1L << tag_shift_val ) | // ( ( n & node_mask) << node_shift_val ) | // ( reinterpret_cast<intptr_t>( p ) ) ) // { // assert( SoftXMT_mynode() <= node_mask ); // assert( reinterpret_cast<intptr_t>( p ) >> node_shift_val == 0 ); // } public: GlobalAddress( ) : storage_( 0 ) { } /// construct a 2D global address static GlobalAddress TwoDimensional( T * t, Node n = SoftXMT_mynode() ) { GlobalAddress g; g.storage_ = ( ( 1L << tag_shift_val ) | ( ( n & node_mask) << node_shift_val ) | ( reinterpret_cast<intptr_t>( t ) ) ); assert( SoftXMT_mynode() <= node_mask ); assert( reinterpret_cast<intptr_t>( t ) >> node_shift_val == 0 ); return g; } /// construct a linear global address static GlobalAddress Linear( T * t, Pool p = 0 ) { GlobalAddress g; g.storage_ = ( ( 0L << tag_shift_val ) | //( ( n & node_mask) << node_shift_val ) | ( reinterpret_cast<intptr_t>( t ) ) ); assert( reinterpret_cast<intptr_t>( t ) >> node_shift_val == 0 ); return g; } /// construct a global address from raw bits static GlobalAddress Raw( intptr_t t ) { GlobalAddress g; g.storage_ = t; return g; } inline intptr_t raw_bits() const { return storage_; } inline Node node() const { if( is_2D() ) { return (storage_ >> node_shift_val) & node_mask; } else { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t offset = signextended % block_size; intptr_t node = (signextended / block_size) % SoftXMT_nodes(); intptr_t block = (signextended / block_size) / SoftXMT_nodes(); return node; } } inline Pool pool() const { return (storage_ >> pool_shift_val) & pool_mask; } inline T * pointer() const { if( is_2D() ) { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; return reinterpret_cast< T * >( signextended ); } else { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t offset = signextended % block_size; intptr_t node = (signextended / block_size) % SoftXMT_nodes(); intptr_t block = (signextended / block_size) / SoftXMT_nodes(); return reinterpret_cast< T * >( block * block_size + offset ); } } inline GlobalAddress< T > block_min() const { if( is_2D() ) { //intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; //GlobalAddress< U > u = GlobalAddress< U >::Raw( storage_ ); return GlobalAddress< T >::TwoDimensional( (T*) 0, node() ); } else { intptr_t first_byte = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t first_byte_offset = first_byte % block_size; intptr_t node = (first_byte / block_size) % SoftXMT_nodes(); intptr_t block = (first_byte / block_size) / SoftXMT_nodes(); return GlobalAddress< T >::Raw( this->raw_bits() - first_byte_offset ); } } inline GlobalAddress< T > block_max() const { if( is_2D() ) { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; //return reinterpret_cast< T * >( -1 ); return GlobalAddress< T >::TwoDimensional( (T*) 1, node() ); } else { intptr_t first_byte = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t first_byte_offset = first_byte % block_size; intptr_t last_byte = first_byte + sizeof(T) - 1; intptr_t last_byte_offset = last_byte % block_size; intptr_t node = (last_byte / block_size) % SoftXMT_nodes(); intptr_t block = (last_byte / block_size) / SoftXMT_nodes(); return GlobalAddress< T >::Raw( this->raw_bits() + sizeof(T) + block_size - (last_byte_offset + 1) ); } } inline bool is_2D() const { return storage_ & tag_mask; } inline bool is_linear() const { return !( storage_ & tag_mask ); } // inline size_t block_size() const { // return block_size_; // } inline GlobalAddress< T >& operator++() { storage_ += sizeof(T); return *this; } //inline GlobalAddress< T > operator++(int i) { return storage_ ++ i; } inline GlobalAddress< T >& operator--() { storage_ -= sizeof(T); return *this; } //inline GlobalAddress< T > operator--(int i) { return storage_ ++ i; } inline GlobalAddress< T >& operator+=(ptrdiff_t i) { storage_ += i * sizeof(T); return *this; } inline GlobalAddress< T >& operator-=(ptrdiff_t i) { storage_ -= i * sizeof(T); return *this; } bool equals( const GlobalAddress< T >& t ) const { return raw_bits() == t.raw_bits(); } bool operator==( const GlobalAddress< T >& t ) const { return raw_bits() == t.raw_bits(); } template< typename U > bool operator==( const GlobalAddress< U >& u ) const { return raw_bits() == u.raw_bits(); } //T& operator[]( ptrdiff_t index ) { return template< typename U > operator GlobalAddress< U >( ) { GlobalAddress< U > u = GlobalAddress< U >::Raw( storage_ ); return u; } template< typename U > operator U * ( ) { U * u = reinterpret_cast< U * >( storage_ ); return u; } }; template< typename T > GlobalAddress< T > operator+( const GlobalAddress< T >& t, ptrdiff_t i ) { GlobalAddress< T > tt(t); return tt += i; } // template< typename T > // GlobalAddress< T >&& operator+( GlobalAddress< T >&& t, ptrdiff_t i ) { // return t += i; // } template< typename T > GlobalAddress< T > operator-( const GlobalAddress< T >& t, ptrdiff_t i ) { GlobalAddress< T > tt(t); return tt -= i; } // template< typename T > // GlobalAddress< T >&& operator-( const GlobalAddress< T >&& t, ptrdiff_t i ) { // return t -= i; // } template< typename T > ptrdiff_t operator-( const GlobalAddress< T >& t, const GlobalAddress< T >& u ) { if( t.is_2D() ) { return t.pointer() - u.pointer(); } else { return (t.raw_bits() - u.raw_bits()) / sizeof(T); } } template< typename T > GlobalAddress< T > localToGlobal( T * t ) { return GlobalAddress< T >::TwoDimensional( t, SoftXMT_mynode() ); } template< typename T > GlobalAddress< T > make_global( T * t, Node n = SoftXMT_mynode() ) { return GlobalAddress< T >::TwoDimensional( t, n ); } /// takes a local pointer to a block-cyclic distributed chuck of /// memory allocated at the same base address on all nodes, and makes /// a linear global pointer pointing to that byte. template< typename T > GlobalAddress< T > make_linear( T * t ) { intptr_t tt = reinterpret_cast< intptr_t >( t ); intptr_t offset = tt % block_size; intptr_t block = tt / block_size; intptr_t node = block % SoftXMT_nodes(); intptr_t ga = ( block * SoftXMT_nodes() + node ) * block_size + offset; T * ttt = reinterpret_cast< T * >( ga ); GlobalAddress< T > tttt = GlobalAddress< T >::Linear( ttt, 0 ); CHECK_EQ( tttt.node(), node ) << "converted linear address node doesn't match"; CHECK_EQ( tttt.pointer(), t ) << "converted linear address local pointer doesn't match"; return tttt; } template< typename T > std::ostream& operator<<( std::ostream& o, const GlobalAddress< T >& ga ) { return ga.dump( o ); } //template< typename T > #endif <commit_msg>need to cast pointer to void* when passing to ostream<<, so that char* does not get printed.<commit_after> #ifndef __ADDRESSING_HPP__ #define __ADDRESSING_HPP__ /// Global Addresses for SoftXMT /// /// /// /// /// We support two types of global addresses: /// -# 2D addresses /// -# Linear addresses /// /// 2D addresses are node, address on node /// /// linear addresses are block cyclic #include "SoftXMT.hpp" typedef int Pool; /// assumes user data will have the top 16 bits all 0. static const int block_size = sizeof(int64_t) * 8; static const int tag_bits = 1; static const int pointer_bits = 48; static const int node_bits = 64 - pointer_bits - tag_bits; static const int pool_bits = 64 - pointer_bits - tag_bits; static const int tag_shift_val = 64 - tag_bits; static const int pointer_shift_val = 64 - pointer_bits; static const int node_shift_val = pointer_bits; static const int pool_shift_val = pointer_bits; static const intptr_t tag_mask = (1L << tag_shift_val); static const intptr_t node_mask = (1L << node_bits) - 1; static const intptr_t pool_mask = (1L << pool_bits) - 1; static const intptr_t pointer_mask = (1L << pointer_bits) - 1; template< typename T > class GlobalAddress { private: intptr_t storage_; //DISALLOW_COPY_AND_ASSIGN( GlobalAddress ); template< typename U > friend std::ostream& operator<<( std::ostream& o, const GlobalAddress< U >& ga ); //friend template< typename U > GlobalAddress< U > operator+( const GlobalAddress< U >& t, ptrdiff_t i ); template< typename U > friend ptrdiff_t operator-( const GlobalAddress< U >& t, const GlobalAddress< U >& u ); std::ostream& dump( std::ostream& o ) const { if( is_2D() ) { return o << "<GA 2D " << (void*)storage_ << ": node " << node() << " pointer " << static_cast<void *>( pointer() ) << ">"; } else { return o << "<GA Linear " << (void*)storage_ << ": pool " << pool() << " pointer " << static_cast<void *>( pointer() ) << ">"; } } // GlobalAddress( T * p, Node n = SoftXMT_mynode() ) // : storage_( ( 1L << tag_shift_val ) | // ( ( n & node_mask) << node_shift_val ) | // ( reinterpret_cast<intptr_t>( p ) ) ) // { // assert( SoftXMT_mynode() <= node_mask ); // assert( reinterpret_cast<intptr_t>( p ) >> node_shift_val == 0 ); // } public: GlobalAddress( ) : storage_( 0 ) { } /// construct a 2D global address static GlobalAddress TwoDimensional( T * t, Node n = SoftXMT_mynode() ) { GlobalAddress g; g.storage_ = ( ( 1L << tag_shift_val ) | ( ( n & node_mask) << node_shift_val ) | ( reinterpret_cast<intptr_t>( t ) ) ); assert( SoftXMT_mynode() <= node_mask ); assert( reinterpret_cast<intptr_t>( t ) >> node_shift_val == 0 ); return g; } /// construct a linear global address static GlobalAddress Linear( T * t, Pool p = 0 ) { GlobalAddress g; g.storage_ = ( ( 0L << tag_shift_val ) | //( ( n & node_mask) << node_shift_val ) | ( reinterpret_cast<intptr_t>( t ) ) ); assert( reinterpret_cast<intptr_t>( t ) >> node_shift_val == 0 ); return g; } /// construct a global address from raw bits static GlobalAddress Raw( intptr_t t ) { GlobalAddress g; g.storage_ = t; return g; } inline intptr_t raw_bits() const { return storage_; } inline Node node() const { if( is_2D() ) { return (storage_ >> node_shift_val) & node_mask; } else { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t offset = signextended % block_size; intptr_t node = (signextended / block_size) % SoftXMT_nodes(); intptr_t block = (signextended / block_size) / SoftXMT_nodes(); return node; } } inline Pool pool() const { return (storage_ >> pool_shift_val) & pool_mask; } inline T * pointer() const { if( is_2D() ) { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; return reinterpret_cast< T * >( signextended ); } else { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t offset = signextended % block_size; intptr_t node = (signextended / block_size) % SoftXMT_nodes(); intptr_t block = (signextended / block_size) / SoftXMT_nodes(); return reinterpret_cast< T * >( block * block_size + offset ); } } inline GlobalAddress< T > block_min() const { if( is_2D() ) { //intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; //GlobalAddress< U > u = GlobalAddress< U >::Raw( storage_ ); return GlobalAddress< T >::TwoDimensional( (T*) 0, node() ); } else { intptr_t first_byte = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t first_byte_offset = first_byte % block_size; intptr_t node = (first_byte / block_size) % SoftXMT_nodes(); intptr_t block = (first_byte / block_size) / SoftXMT_nodes(); return GlobalAddress< T >::Raw( this->raw_bits() - first_byte_offset ); } } inline GlobalAddress< T > block_max() const { if( is_2D() ) { intptr_t signextended = (storage_ << pointer_shift_val) >> pointer_shift_val; //return reinterpret_cast< T * >( -1 ); return GlobalAddress< T >::TwoDimensional( (T*) 1, node() ); } else { intptr_t first_byte = (storage_ << pointer_shift_val) >> pointer_shift_val; intptr_t first_byte_offset = first_byte % block_size; intptr_t last_byte = first_byte + sizeof(T) - 1; intptr_t last_byte_offset = last_byte % block_size; intptr_t node = (last_byte / block_size) % SoftXMT_nodes(); intptr_t block = (last_byte / block_size) / SoftXMT_nodes(); return GlobalAddress< T >::Raw( this->raw_bits() + sizeof(T) + block_size - (last_byte_offset + 1) ); } } inline bool is_2D() const { return storage_ & tag_mask; } inline bool is_linear() const { return !( storage_ & tag_mask ); } // inline size_t block_size() const { // return block_size_; // } inline GlobalAddress< T >& operator++() { storage_ += sizeof(T); return *this; } //inline GlobalAddress< T > operator++(int i) { return storage_ ++ i; } inline GlobalAddress< T >& operator--() { storage_ -= sizeof(T); return *this; } //inline GlobalAddress< T > operator--(int i) { return storage_ ++ i; } inline GlobalAddress< T >& operator+=(ptrdiff_t i) { storage_ += i * sizeof(T); return *this; } inline GlobalAddress< T >& operator-=(ptrdiff_t i) { storage_ -= i * sizeof(T); return *this; } bool equals( const GlobalAddress< T >& t ) const { return raw_bits() == t.raw_bits(); } bool operator==( const GlobalAddress< T >& t ) const { return raw_bits() == t.raw_bits(); } template< typename U > bool operator==( const GlobalAddress< U >& u ) const { return raw_bits() == u.raw_bits(); } //T& operator[]( ptrdiff_t index ) { return template< typename U > operator GlobalAddress< U >( ) { GlobalAddress< U > u = GlobalAddress< U >::Raw( storage_ ); return u; } template< typename U > operator U * ( ) { U * u = reinterpret_cast< U * >( storage_ ); return u; } }; template< typename T > GlobalAddress< T > operator+( const GlobalAddress< T >& t, ptrdiff_t i ) { GlobalAddress< T > tt(t); return tt += i; } // template< typename T > // GlobalAddress< T >&& operator+( GlobalAddress< T >&& t, ptrdiff_t i ) { // return t += i; // } template< typename T > GlobalAddress< T > operator-( const GlobalAddress< T >& t, ptrdiff_t i ) { GlobalAddress< T > tt(t); return tt -= i; } // template< typename T > // GlobalAddress< T >&& operator-( const GlobalAddress< T >&& t, ptrdiff_t i ) { // return t -= i; // } template< typename T > ptrdiff_t operator-( const GlobalAddress< T >& t, const GlobalAddress< T >& u ) { if( t.is_2D() ) { return t.pointer() - u.pointer(); } else { return (t.raw_bits() - u.raw_bits()) / sizeof(T); } } template< typename T > GlobalAddress< T > localToGlobal( T * t ) { return GlobalAddress< T >::TwoDimensional( t, SoftXMT_mynode() ); } template< typename T > GlobalAddress< T > make_global( T * t, Node n = SoftXMT_mynode() ) { return GlobalAddress< T >::TwoDimensional( t, n ); } /// takes a local pointer to a block-cyclic distributed chuck of /// memory allocated at the same base address on all nodes, and makes /// a linear global pointer pointing to that byte. template< typename T > GlobalAddress< T > make_linear( T * t ) { intptr_t tt = reinterpret_cast< intptr_t >( t ); intptr_t offset = tt % block_size; intptr_t block = tt / block_size; intptr_t node = block % SoftXMT_nodes(); intptr_t ga = ( block * SoftXMT_nodes() + node ) * block_size + offset; T * ttt = reinterpret_cast< T * >( ga ); GlobalAddress< T > tttt = GlobalAddress< T >::Linear( ttt, 0 ); CHECK_EQ( tttt.node(), node ) << "converted linear address node doesn't match"; CHECK_EQ( tttt.pointer(), t ) << "converted linear address local pointer doesn't match"; return tttt; } template< typename T > std::ostream& operator<<( std::ostream& o, const GlobalAddress< T >& ga ) { return ga.dump( o ); } //template< typename T > #endif <|endoftext|>
<commit_before>//===-- WriteInst.cpp - Functions for writing instructions -------*- C++ -*--=// // // This file implements the routines for encoding instruction opcodes to a // bytecode stream. // // Note that the performance of this library is not terribly important, because // it shouldn't be used by JIT type applications... so it is not a huge focus // at least. :) // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/Instruction.h" #include "llvm/DerivedTypes.h" #include <algorithm> typedef unsigned char uchar; // outputInstructionFormat0 - Output those wierd instructions that have a large // number of operands or have large operands themselves... // // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>] // static void outputInstructionFormat0(const Instruction *I, const SlotCalculator &Table, unsigned Type, vector<uchar> &Out) { // Opcode must have top two bits clear... output_vbr(I->getOpcode(), Out); // Instruction Opcode ID output_vbr(Type, Out); // Result type unsigned NumArgs = I->getNumOperands(); output_vbr(NumArgs, Out); for (unsigned i = 0; i < NumArgs; ++i) { int Slot = Table.getValSlot(I->getOperand(i)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); } align32(Out); // We must maintain correct alignment! } // outputInstrVarArgsCall - Output the obsurdly annoying varargs method calls. // This are more annoying than most because the signature of the call does not // tell us anything about the types of the arguments in the varargs portion. // Because of this, we encode (as type 0) all of the argument types explicitly // before the argument value. This really sucks, but you shouldn't be using // varargs functions in your code! *death to printf*! // // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>] // static void outputInstrVarArgsCall(const Instruction *I, const SlotCalculator &Table, unsigned Type, vector<uchar> &Out) { assert(I->getOpcode() == Instruction::Call /*|| I->getOpcode() == Instruction::ICall */); // Opcode must have top two bits clear... output_vbr(I->getOpcode(), Out); // Instruction Opcode ID output_vbr(Type, Out); // Result type (varargs type) unsigned NumArgs = I->getNumOperands(); output_vbr((NumArgs-2)*2+2, Out); // Don't duplicate method & Arg1 types // Output the method type without an extra type argument. int Slot = Table.getValSlot(I->getOperand(0)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); // VarArgs methods must have at least one specified operand Slot = Table.getValSlot(I->getOperand(1)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); for (unsigned i = 2; i < NumArgs; ++i) { // Output Arg Type ID Slot = Table.getValSlot(I->getOperand(i)->getType()); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); // Output arg ID itself Slot = Table.getValSlot(I->getOperand(i)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); } align32(Out); // We must maintain correct alignment! } // outputInstructionFormat1 - Output one operand instructions, knowing that no // operand index is >= 2^12. // static void outputInstructionFormat1(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 1. // 29-24: Opcode // 23-12: Resulting type plane // 11- 0: Operand #1 (if set to (2^12-1), then zero operands) // unsigned Opcode = (1 << 30) | (IType << 24) | (Type << 12) | Slots[0]; // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl; output(Opcode, Out); } // outputInstructionFormat2 - Output two operand instructions, knowing that no // operand index is >= 2^8. // static void outputInstructionFormat2(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 2. // 29-24: Opcode // 23-16: Resulting type plane // 15- 8: Operand #1 // 7- 0: Operand #2 // unsigned Opcode = (2 << 30) | (IType << 24) | (Type << 16) | (Slots[0] << 8) | (Slots[1] << 0); // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " " // << Slots[1] << endl; output(Opcode, Out); } // outputInstructionFormat3 - Output three operand instructions, knowing that no // operand index is >= 2^6. // static void outputInstructionFormat3(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 3 // 29-24: Opcode // 23-18: Resulting type plane // 17-12: Operand #1 // 11- 6: Operand #2 // 5- 0: Operand #3 // unsigned Opcode = (3 << 30) | (IType << 24) | (Type << 18) | (Slots[0] << 12) | (Slots[1] << 6) | (Slots[2] << 0); //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " " // << Slots[1] << " " << Slots[2] << endl; output(Opcode, Out); } bool BytecodeWriter::processInstruction(const Instruction *I) { assert(I->getOpcode() < 64 && "Opcode too big???"); unsigned NumOperands = I->getNumOperands(); int MaxOpSlot = 0; int Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands for (unsigned i = 0; i < NumOperands; ++i) { const Value *Def = I->getOperand(i); int slot = Table.getValSlot(Def); assert(slot != -1 && "Broken bytecode!"); if (slot > MaxOpSlot) MaxOpSlot = slot; if (i < 3) Slots[i] = slot; } // Figure out which type to encode with the instruction. Typically we want // the type of the first parameter, as opposed to the type of the instruction // (for example, with setcc, we always know it returns bool, but the type of // the first param is actually interesting). But if we have no arguments // we take the type of the instruction itself. // const Type *Ty; switch (I->getOpcode()) { case Instruction::Malloc: case Instruction::Alloca: Ty = I->getType(); // Malloc & Alloca ALWAYS want to encode the return type break; case Instruction::Store: Ty = I->getOperand(1)->getType(); // Encode the pointer type... break; default: // Otherwise use the default behavior... Ty = NumOperands ? I->getOperand(0)->getType() : I->getType(); break; } unsigned Type; int Slot = Table.getValSlot(Ty); assert(Slot != -1 && "Type not available!!?!"); Type = (unsigned)Slot; // Handle the special case for cast... if (I->getOpcode() == Instruction::Cast) { // Cast has to encode the destination type as the second argument in the // packet, or else we won't know what type to cast to! Slots[1] = Table.getValSlot(I->getType()); assert(Slots[1] != -1 && "Cast return type unknown?"); if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1]; NumOperands++; } else if (I->getOpcode() == Instruction::Call && // Handle VarArg calls I->getOperand(0)->getType()->isMethodType()->isVarArg()) { outputInstrVarArgsCall(I, Table, Type, Out); return false; } // Decide which instruction encoding to use. This is determined primarily by // the number of operands, and secondarily by whether or not the max operand // will fit into the instruction encoding. More operands == fewer bits per // operand. // switch (NumOperands) { case 0: case 1: if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops outputInstructionFormat1(I, Table, Slots, Type, Out); return false; } break; case 2: if (MaxOpSlot < (1 << 8)) { outputInstructionFormat2(I, Table, Slots, Type, Out); return false; } break; case 3: if (MaxOpSlot < (1 << 6)) { outputInstructionFormat3(I, Table, Slots, Type, Out); return false; } break; } // If we weren't handled before here, we either have a large number of // operands or a large operand index that we are refering to. outputInstructionFormat0(I, Table, Type, Out); return false; } <commit_msg>* Make sure that the size of the type field can also control the output instruction pattern.<commit_after>//===-- WriteInst.cpp - Functions for writing instructions -------*- C++ -*--=// // // This file implements the routines for encoding instruction opcodes to a // bytecode stream. // // Note that the performance of this library is not terribly important, because // it shouldn't be used by JIT type applications... so it is not a huge focus // at least. :) // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/Instruction.h" #include "llvm/DerivedTypes.h" #include <algorithm> typedef unsigned char uchar; // outputInstructionFormat0 - Output those wierd instructions that have a large // number of operands or have large operands themselves... // // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>] // static void outputInstructionFormat0(const Instruction *I, const SlotCalculator &Table, unsigned Type, vector<uchar> &Out) { // Opcode must have top two bits clear... output_vbr(I->getOpcode(), Out); // Instruction Opcode ID output_vbr(Type, Out); // Result type unsigned NumArgs = I->getNumOperands(); output_vbr(NumArgs, Out); for (unsigned i = 0; i < NumArgs; ++i) { int Slot = Table.getValSlot(I->getOperand(i)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); } align32(Out); // We must maintain correct alignment! } // outputInstrVarArgsCall - Output the obsurdly annoying varargs method calls. // This are more annoying than most because the signature of the call does not // tell us anything about the types of the arguments in the varargs portion. // Because of this, we encode (as type 0) all of the argument types explicitly // before the argument value. This really sucks, but you shouldn't be using // varargs functions in your code! *death to printf*! // // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>] // static void outputInstrVarArgsCall(const Instruction *I, const SlotCalculator &Table, unsigned Type, vector<uchar> &Out) { assert(I->getOpcode() == Instruction::Call /*|| I->getOpcode() == Instruction::ICall */); // Opcode must have top two bits clear... output_vbr(I->getOpcode(), Out); // Instruction Opcode ID output_vbr(Type, Out); // Result type (varargs type) unsigned NumArgs = I->getNumOperands(); output_vbr((NumArgs-2)*2+2, Out); // Don't duplicate method & Arg1 types // Output the method type without an extra type argument. int Slot = Table.getValSlot(I->getOperand(0)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); // VarArgs methods must have at least one specified operand Slot = Table.getValSlot(I->getOperand(1)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); for (unsigned i = 2; i < NumArgs; ++i) { // Output Arg Type ID Slot = Table.getValSlot(I->getOperand(i)->getType()); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); // Output arg ID itself Slot = Table.getValSlot(I->getOperand(i)); assert(Slot >= 0 && "No slot number for value!?!?"); output_vbr((unsigned)Slot, Out); } align32(Out); // We must maintain correct alignment! } // outputInstructionFormat1 - Output one operand instructions, knowing that no // operand index is >= 2^12. // static void outputInstructionFormat1(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 1. // 29-24: Opcode // 23-12: Resulting type plane // 11- 0: Operand #1 (if set to (2^12-1), then zero operands) // unsigned Opcode = (1 << 30) | (IType << 24) | (Type << 12) | Slots[0]; // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl; output(Opcode, Out); } // outputInstructionFormat2 - Output two operand instructions, knowing that no // operand index is >= 2^8. // static void outputInstructionFormat2(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 2. // 29-24: Opcode // 23-16: Resulting type plane // 15- 8: Operand #1 // 7- 0: Operand #2 // unsigned Opcode = (2 << 30) | (IType << 24) | (Type << 16) | (Slots[0] << 8) | (Slots[1] << 0); // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " " // << Slots[1] << endl; output(Opcode, Out); } // outputInstructionFormat3 - Output three operand instructions, knowing that no // operand index is >= 2^6. // static void outputInstructionFormat3(const Instruction *I, const SlotCalculator &Table, int *Slots, unsigned Type, vector<uchar> &Out) { unsigned IType = I->getOpcode(); // Instruction Opcode ID // bits Instruction format: // -------------------------- // 31-30: Opcode type, fixed to 3 // 29-24: Opcode // 23-18: Resulting type plane // 17-12: Operand #1 // 11- 6: Operand #2 // 5- 0: Operand #3 // unsigned Opcode = (3 << 30) | (IType << 24) | (Type << 18) | (Slots[0] << 12) | (Slots[1] << 6) | (Slots[2] << 0); //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " " // << Slots[1] << " " << Slots[2] << endl; output(Opcode, Out); } bool BytecodeWriter::processInstruction(const Instruction *I) { assert(I->getOpcode() < 64 && "Opcode too big???"); unsigned NumOperands = I->getNumOperands(); int MaxOpSlot = 0; int Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands for (unsigned i = 0; i < NumOperands; ++i) { const Value *Def = I->getOperand(i); int slot = Table.getValSlot(Def); assert(slot != -1 && "Broken bytecode!"); if (slot > MaxOpSlot) MaxOpSlot = slot; if (i < 3) Slots[i] = slot; } // Figure out which type to encode with the instruction. Typically we want // the type of the first parameter, as opposed to the type of the instruction // (for example, with setcc, we always know it returns bool, but the type of // the first param is actually interesting). But if we have no arguments // we take the type of the instruction itself. // const Type *Ty; switch (I->getOpcode()) { case Instruction::Malloc: case Instruction::Alloca: Ty = I->getType(); // Malloc & Alloca ALWAYS want to encode the return type break; case Instruction::Store: Ty = I->getOperand(1)->getType(); // Encode the pointer type... assert(Ty->isPointerType() && "Store to nonpointer type!?!?"); break; default: // Otherwise use the default behavior... Ty = NumOperands ? I->getOperand(0)->getType() : I->getType(); break; } unsigned Type; int Slot = Table.getValSlot(Ty); assert(Slot != -1 && "Type not available!!?!"); Type = (unsigned)Slot; // Make sure that we take the type number into consideration. We don't want // to overflow the field size for the instruction format we select. // if (Slot > MaxOpSlot) MaxOpSlot = Slot; // Handle the special case for cast... if (I->getOpcode() == Instruction::Cast) { // Cast has to encode the destination type as the second argument in the // packet, or else we won't know what type to cast to! Slots[1] = Table.getValSlot(I->getType()); assert(Slots[1] != -1 && "Cast return type unknown?"); if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1]; NumOperands++; } else if (I->getOpcode() == Instruction::Call && // Handle VarArg calls I->getOperand(0)->getType()->isMethodType()->isVarArg()) { outputInstrVarArgsCall(I, Table, Type, Out); return false; } // Decide which instruction encoding to use. This is determined primarily by // the number of operands, and secondarily by whether or not the max operand // will fit into the instruction encoding. More operands == fewer bits per // operand. // switch (NumOperands) { case 0: case 1: if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops outputInstructionFormat1(I, Table, Slots, Type, Out); return false; } break; case 2: if (MaxOpSlot < (1 << 8)) { outputInstructionFormat2(I, Table, Slots, Type, Out); return false; } break; case 3: if (MaxOpSlot < (1 << 6)) { outputInstructionFormat3(I, Table, Slots, Type, Out); return false; } break; } // If we weren't handled before here, we either have a large number of // operands or a large operand index that we are refering to. outputInstructionFormat0(I, Table, Type, Out); return false; } <|endoftext|>
<commit_before>/** * @copyright * ======================================================================== * Copyright FLWOR Foundation * ======================================================================== * * @author Sorin Nasoi ([email protected]) * @author Nicolae Brinza ([email protected]) * @author Dan Muresan ([email protected]) * @file utf8/xqpString.cpp * */ #include "util/utf8/xqpString.h" #include "util/utf8/utf8.h" #include "util/zorba.h" using namespace std; namespace xqp { xqpString::xqpString() : utf8String() {} xqpString::xqpString(const std::string& src){ utf8String = new xqpString_t(src); } xqpString::xqpString(const char* src){ utf8String = new xqpString_t(src); } xqpString::~xqpString() {} xqpString& xqpString::operator=(const std::string& src){ utf8String = new xqpString_t(src); return *this; } xqpString& xqpString::operator=(const char* src){ utf8String = new xqpString_t(src); return *this; } xqpString& xqpString::operator=(uint32_t cp){ utf8String->reserve(4); char seq[4] = {0,0,0,0}; UTF8Encode(cp, seq); utf8String = new xqpString_t(seq); return *this; } xqpString& xqpString::operator=(char c){ utf8String = new xqpString_t(&c); return *this; } //xqpString::operator+=() xqpString& xqpString::operator+=(const xqpString& src){ xqpString_t* temp = new xqpString_t(*utf8String); *temp += src; utf8String = temp; return *this; } xqpString& xqpString::operator+=(const char* src){ xqpString_t* temp = new xqpString_t(*utf8String); *temp += src; utf8String = temp; return *this; } xqpString& xqpString::operator+=(uint32_t cp){ utf8String->reserve(4); char seq[4] = {0,0,0,0}; UTF8Encode(cp, seq); utf8String = new xqpString_t(*utf8String+seq); return *this; } xqpString& xqpString::operator+=(char c){ utf8String = new xqpString_t(*utf8String+c); return *this; } //xqpString::stream I/O operators std::istream& operator>>(std::istream& is, xqpString& utf8_src){ std::string buffer; is >> buffer; //TODO is there a need to perform charset conversion to/from the current locale ?!?! utf8_src = buffer; return is; } std::ostream& operator<<(std::ostream& os, const xqpString& utf8_src){ //TODO is there a need to perform charset conversion to/from the current locale ?!?! os << *utf8_src.utf8String; return os; } //xqpString::compare int xqpString::compare(const xqpString& src) const{ UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); Collator::EComparisonResult result = ::Collator::EQUAL; //compare the 2 strings result = coll->compare(getUnicodeString(*utf8String), getUnicodeString(src)); return result; } int xqpString::compare(const xqpString& src, const char * loc) const{ UErrorCode status = U_ZERO_ERROR; //create the collator object ::Collator *coll = ::Collator::createInstance(Locale(loc), status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } //set level 1 comparison for the collator coll->setStrength(::Collator::PRIMARY); ::Collator::EComparisonResult result = ::Collator::EQUAL; //compare the 2 strings result = coll->compare(getUnicodeString(*utf8String), getUnicodeString(src)); //close the collator delete coll; return result; } int xqpString::compare(const char* src) const{ //TODO optimize the code here xqpString tmp(src); return compare(tmp); } //xqpString::Length xqpString::size_type xqpString::size() const{ const char* c = utf8String->c_str(); return UTF8Distance(c, c + utf8String->size()); } xqpString::size_type xqpString::length() const{ const char* c = utf8String->c_str(); return UTF8Distance(c, c + utf8String->size()); } xqpString::size_type xqpString::bytes() const{ return utf8String->size(); } bool xqpString::empty() const{ return utf8String->empty(); } void xqpString::reserve(xqpString::size_type size){ utf8String->reserve(size); } //xqpString::Clear void xqpString::clear(){ utf8String->erase(); } //xpqString::Codepoint std::vector<uint32_t> xqpString::getCodepoints(){ std::vector<uint32_t> tt; uint16_t vLength; vLength = length() + 1; const char* c = utf8String->c_str(); while( --vLength > 0 ){ tt.push_back(UTF8Decode(c)); } return tt; } //xqpString::Substring matching/ string search int32_t xqpString::indexOf(const xqpString& pattern){ //create the collator object UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), (RuleBasedCollator *)coll, NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } for(int16_t pos = search.first(status); U_SUCCESS(status) && pos != USEARCH_DONE; pos = search.next(status)) { return pos; } if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } return -1; } int32_t xqpString::indexOf(const xqpString& pattern, const char * loc){ UErrorCode status = U_ZERO_ERROR; //A collator will be created in the process, which will be owned by this instance and will be deleted during destruction StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), Locale(loc), NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } for(int16_t pos = search.first(status); U_SUCCESS(status) && pos != USEARCH_DONE; pos = search.next(status)) { return pos; } if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } return -1; } int32_t xqpString::lastIndexOf(const xqpString& pattern){ //create the collator object UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), (RuleBasedCollator *)coll, NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } int32_t pos = search.last(status); if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } if(U_SUCCESS(status) && pos != USEARCH_DONE){ //TODO check if this condition is enough return pos; } return -1; } int32_t xqpString::lastIndexOf(const xqpString& pattern, const char * loc){ UErrorCode status = U_ZERO_ERROR; //A collator will be created in the process, which will be owned by this instance and will be deleted during destruction StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), Locale(loc), NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } int32_t pos = search.last(status); if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } if(U_SUCCESS(status) && pos != USEARCH_DONE){ //TODO check if this condition is enough return pos; } return -1; } bool xqpString::endsWith(const xqpString& pattern){ //TODO check if this condition is enough return( lastIndexOf(pattern) + pattern.length() == length() ); } bool xqpString::endsWith(const xqpString& pattern, const char * loc){ //TODO check if this condition is enough return( lastIndexOf(pattern, loc) + pattern.length() == length() ); } xqpString xqpString::substr(xqpString::size_type index, xqpString::size_type length){ char* target; int32_t size = length*4 + 1; target = new char[size]; //will hold UTF-8 encoded characters UnicodeString str = getUnicodeString( *utf8String ); int32_t targetsize = str.extract(index, length, target, size, "UTF-8"); target[targetsize] = 0; /* NULL termination */ xqpString ret(&target[0]); delete target; return ret; } xqpString xqpString::substr(distance_type index){ if(index >= (int32_t)length()){ index = length(); } else if(index < 0){ xqpString ret(*utf8String); return ret; } const char * d = utf8String->c_str(); advance(d, index); xqpString ret(d); return ret; } const char* xqpString::c_str() const{ return utf8String->c_str(); } // Private methods UnicodeString xqpString::getUnicodeString(const xqpString& source) const{ UnicodeString ret; UErrorCode status = U_ZERO_ERROR; int32_t len = source.bytes(); UChar* buffer = ret.getBuffer(len); u_strFromUTF8(buffer, ret.getCapacity(), &len, source.c_str(), len, &status); ret.releaseBuffer(U_SUCCESS(status) ? len : 0); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } return ret; } xqpString xqpString::getXqpString(UnicodeString source){ char* target; int32_t targetLen = source.getCapacity()*4 + 1; target = new char[targetLen]; UErrorCode status = U_ZERO_ERROR; //open a convertor to UTF-8 UConverter *conv = ucnv_open("utf-8", &status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); delete target; return ""; } //Convert from UTF-16 to UTF-8 ucnv_fromUChars (conv, target, targetLen, source.getBuffer( source.length() ), source.length(), &status); //close the converter ucnv_close(conv); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); delete target; return ""; } xqpString ret(&target[0]); delete target; return ret; } wchar_t * xqpString::getWCS(const xqpString& source) const{ int32_t destCapacity = source.length()*2 + 1; wchar_t* destWCS; destWCS = new wchar_t[destCapacity]; int32_t destLen; UnicodeString unicodeStr = getUnicodeString(source); int32_t srcLen = unicodeStr.length(); UChar* srcBuf = unicodeStr.getBuffer(srcLen); UErrorCode status = U_ZERO_ERROR; wchar_t* ret = u_strToWCS(destWCS, destCapacity, &destLen, srcBuf, srcLen, &status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } return ret; } }/* namespace xqp */ <commit_msg>allocate utf8String in default xqpString constructor<commit_after>/** * @copyright * ======================================================================== * Copyright FLWOR Foundation * ======================================================================== * * @author Sorin Nasoi ([email protected]) * @author Nicolae Brinza ([email protected]) * @author Dan Muresan ([email protected]) * @file utf8/xqpString.cpp * */ #include "util/utf8/xqpString.h" #include "util/utf8/utf8.h" #include "util/zorba.h" using namespace std; namespace xqp { xqpString::xqpString() { utf8String = new xqpString_t(""); } xqpString::xqpString(const std::string& src){ utf8String = new xqpString_t(src); } xqpString::xqpString(const char* src){ utf8String = new xqpString_t(src); } xqpString::~xqpString() {} xqpString& xqpString::operator=(const std::string& src){ utf8String = new xqpString_t(src); return *this; } xqpString& xqpString::operator=(const char* src){ utf8String = new xqpString_t(src); return *this; } xqpString& xqpString::operator=(uint32_t cp){ utf8String->reserve(4); char seq[4] = {0,0,0,0}; UTF8Encode(cp, seq); utf8String = new xqpString_t(seq); return *this; } xqpString& xqpString::operator=(char c){ utf8String = new xqpString_t(&c); return *this; } //xqpString::operator+=() xqpString& xqpString::operator+=(const xqpString& src){ xqpString_t* temp = new xqpString_t(*utf8String); *temp += src; utf8String = temp; return *this; } xqpString& xqpString::operator+=(const char* src){ xqpString_t* temp = new xqpString_t(*utf8String); *temp += src; utf8String = temp; return *this; } xqpString& xqpString::operator+=(uint32_t cp){ utf8String->reserve(4); char seq[4] = {0,0,0,0}; UTF8Encode(cp, seq); utf8String = new xqpString_t(*utf8String+seq); return *this; } xqpString& xqpString::operator+=(char c){ utf8String = new xqpString_t(*utf8String+c); return *this; } //xqpString::stream I/O operators std::istream& operator>>(std::istream& is, xqpString& utf8_src){ std::string buffer; is >> buffer; //TODO is there a need to perform charset conversion to/from the current locale ?!?! utf8_src = buffer; return is; } std::ostream& operator<<(std::ostream& os, const xqpString& utf8_src){ //TODO is there a need to perform charset conversion to/from the current locale ?!?! os << *utf8_src.utf8String; return os; } //xqpString::compare int xqpString::compare(const xqpString& src) const{ UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); Collator::EComparisonResult result = ::Collator::EQUAL; //compare the 2 strings result = coll->compare(getUnicodeString(*utf8String), getUnicodeString(src)); return result; } int xqpString::compare(const xqpString& src, const char * loc) const{ UErrorCode status = U_ZERO_ERROR; //create the collator object ::Collator *coll = ::Collator::createInstance(Locale(loc), status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } //set level 1 comparison for the collator coll->setStrength(::Collator::PRIMARY); ::Collator::EComparisonResult result = ::Collator::EQUAL; //compare the 2 strings result = coll->compare(getUnicodeString(*utf8String), getUnicodeString(src)); //close the collator delete coll; return result; } int xqpString::compare(const char* src) const{ //TODO optimize the code here xqpString tmp(src); return compare(tmp); } //xqpString::Length xqpString::size_type xqpString::size() const{ const char* c = utf8String->c_str(); return UTF8Distance(c, c + utf8String->size()); } xqpString::size_type xqpString::length() const{ const char* c = utf8String->c_str(); return UTF8Distance(c, c + utf8String->size()); } xqpString::size_type xqpString::bytes() const{ return utf8String->size(); } bool xqpString::empty() const{ return utf8String->empty(); } void xqpString::reserve(xqpString::size_type size){ utf8String->reserve(size); } //xqpString::Clear void xqpString::clear(){ utf8String->erase(); } //xpqString::Codepoint std::vector<uint32_t> xqpString::getCodepoints(){ std::vector<uint32_t> tt; uint16_t vLength; vLength = length() + 1; const char* c = utf8String->c_str(); while( --vLength > 0 ){ tt.push_back(UTF8Decode(c)); } return tt; } //xqpString::Substring matching/ string search int32_t xqpString::indexOf(const xqpString& pattern){ //create the collator object UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), (RuleBasedCollator *)coll, NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } for(int16_t pos = search.first(status); U_SUCCESS(status) && pos != USEARCH_DONE; pos = search.next(status)) { return pos; } if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } return -1; } int32_t xqpString::indexOf(const xqpString& pattern, const char * loc){ UErrorCode status = U_ZERO_ERROR; //A collator will be created in the process, which will be owned by this instance and will be deleted during destruction StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), Locale(loc), NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } for(int16_t pos = search.first(status); U_SUCCESS(status) && pos != USEARCH_DONE; pos = search.next(status)) { return pos; } if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } return -1; } int32_t xqpString::lastIndexOf(const xqpString& pattern){ //create the collator object UErrorCode status = U_ZERO_ERROR; //get the collator for the default collation Collator *coll = zorba::getZorbaForCurrentThread()->getCollator(); StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), (RuleBasedCollator *)coll, NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } int32_t pos = search.last(status); if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } if(U_SUCCESS(status) && pos != USEARCH_DONE){ //TODO check if this condition is enough return pos; } return -1; } int32_t xqpString::lastIndexOf(const xqpString& pattern, const char * loc){ UErrorCode status = U_ZERO_ERROR; //A collator will be created in the process, which will be owned by this instance and will be deleted during destruction StringSearch search(getUnicodeString(pattern), getUnicodeString(*utf8String), Locale(loc), NULL, status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } int32_t pos = search.last(status); if (U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); return -1; } if(U_SUCCESS(status) && pos != USEARCH_DONE){ //TODO check if this condition is enough return pos; } return -1; } bool xqpString::endsWith(const xqpString& pattern){ //TODO check if this condition is enough return( lastIndexOf(pattern) + pattern.length() == length() ); } bool xqpString::endsWith(const xqpString& pattern, const char * loc){ //TODO check if this condition is enough return( lastIndexOf(pattern, loc) + pattern.length() == length() ); } xqpString xqpString::substr(xqpString::size_type index, xqpString::size_type length){ char* target; int32_t size = length*4 + 1; target = new char[size]; //will hold UTF-8 encoded characters UnicodeString str = getUnicodeString( *utf8String ); int32_t targetsize = str.extract(index, length, target, size, "UTF-8"); target[targetsize] = 0; /* NULL termination */ xqpString ret(&target[0]); delete target; return ret; } xqpString xqpString::substr(distance_type index){ if(index >= (int32_t)length()){ index = length(); } else if(index < 0){ xqpString ret(*utf8String); return ret; } const char * d = utf8String->c_str(); advance(d, index); xqpString ret(d); return ret; } const char* xqpString::c_str() const{ return utf8String->c_str(); } // Private methods UnicodeString xqpString::getUnicodeString(const xqpString& source) const{ UnicodeString ret; UErrorCode status = U_ZERO_ERROR; int32_t len = source.bytes(); UChar* buffer = ret.getBuffer(len); u_strFromUTF8(buffer, ret.getCapacity(), &len, source.c_str(), len, &status); ret.releaseBuffer(U_SUCCESS(status) ? len : 0); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } return ret; } xqpString xqpString::getXqpString(UnicodeString source){ char* target; int32_t targetLen = source.getCapacity()*4 + 1; target = new char[targetLen]; UErrorCode status = U_ZERO_ERROR; //open a convertor to UTF-8 UConverter *conv = ucnv_open("utf-8", &status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); delete target; return ""; } //Convert from UTF-16 to UTF-8 ucnv_fromUChars (conv, target, targetLen, source.getBuffer( source.length() ), source.length(), &status); //close the converter ucnv_close(conv); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); delete target; return ""; } xqpString ret(&target[0]); delete target; return ret; } wchar_t * xqpString::getWCS(const xqpString& source) const{ int32_t destCapacity = source.length()*2 + 1; wchar_t* destWCS; destWCS = new wchar_t[destCapacity]; int32_t destLen; UnicodeString unicodeStr = getUnicodeString(source); int32_t srcLen = unicodeStr.length(); UChar* srcBuf = unicodeStr.getBuffer(srcLen); UErrorCode status = U_ZERO_ERROR; wchar_t* ret = u_strToWCS(destWCS, destCapacity, &destLen, srcBuf, srcLen, &status); if(U_FAILURE(status)) { ZORBA_ERROR_ALERT( error_messages::XQP0014_SYSTEM_SHOUD_NEVER_BE_REACHED, error_messages::SYSTEM_ERROR, NULL ); } return ret; } }/* namespace xqp */ <|endoftext|>
<commit_before>#ifndef INCLUDED_COLDB_FACTORY_HPP #define INCLUDED_COLDB_FACTORY_HPP #include "types.hpp" #include "column.hpp" namespace coldb { template <typename IFType, typename PT, typename ET, typename DT> Column<IFType>* _int_column_factory_l1(E_COMPRESS compress_id, void* data_ptr, I32 data_size) { switch (compress_id) case E_COMPRESS.PLAIN: return new ColumnImpl<IFType, PlainImpl<DT>>(data_ptr, data_size); case E_COMPRESS.RUN0: return new ColumnImpl<IFType, Run0Impl<DT, PT>>(data_ptr, data_size); case E_COMPRESS.RUN1: return new ColumnImpl<IFType, Run1Impl<DT, PT>>(data_ptr, data_size); case E_COMPRESS.ENUM: return new ColumnImpl<IFType, EnumImpl<DT, ET>>(data_ptr, data_size); default: break; // TODO: exception throw } template <typename IFType, typename PT, typename ET> Column<IFType>* int_column_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { switch (data_type) case 'b': return _int_column_factory_l1<IFType, PT, ET, I8>(compress_id, data_ptr, data_size); case 'B': return _int_column_factory_l1<IFType, PT, ET, U8>(compress_id, data_ptr, data_size); case 'h': return _int_column_factory_l1<IFType, PT, ET, I16>(compress_id, data_ptr, data_size); case 'H': return _int_column_factory_l1<IFType, PT, ET, U16>(compress_id, data_ptr, data_size); case 'i': return _int_column_factory_l1<IFType, PT, ET, I32>(compress_id, data_ptr, data_size); case 'I': return _int_column_factory_l1<IFType, PT, ET, U32>(compress_id, data_ptr, data_size); default: break; // TODO: exception throw } } #endif <commit_msg>update factory.hpp<commit_after>#ifndef INCLUDED_COLDB_FACTORY_HPP #define INCLUDED_COLDB_FACTORY_HPP #include <string> #include "types.hpp" #include "column.hpp" namespace coldb { template <template<typename IFType> class IF, template<typename IFType, class Impl> class IFImpl, typename IFType, typename PT, typename ET, typename DT> IF<IFType>* _i_col_factory_l1(E_COMPRESS compress_id, void* data_ptr, I32 data_size) { switch (compress_id) { case PLAIN: return new IFImpl<IFType, PlainImpl<DT> >(data_ptr, data_size); case RUN0: return new IFImpl<IFType, Run0Impl<DT, PT> >(data_ptr, data_size); case RUN1: return new IFImpl<IFType, Run1Impl<DT, PT> >(data_ptr, data_size); case ENUM: return new IFImpl<IFType, EnumImpl<DT, ET> >(data_ptr, data_size); default: return 0; // TODO: exception throw } } template <template<typename IFType> class IF, template<typename IFType, class Impl> class IFImpl, typename IFType, typename PT, typename ET> IF<IFType>* _i_col_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { switch (data_type) { case 'b': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, I8> (compress_id, data_ptr, data_size); case 'B': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, U8> (compress_id, data_ptr, data_size); case 'h': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, I16> (compress_id, data_ptr, data_size); case 'H': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, U16> (compress_id, data_ptr, data_size); case 'i': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, I32> (compress_id, data_ptr, data_size); case 'I': return _i_col_factory_l1<IF, IFImpl, IFType, PT, ET, U32> (compress_id, data_ptr, data_size); default: return 0; // TODO: exception throw } } // normal col factory template <typename IFType, typename PT, typename ET> Column<IFType>* i_col_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { return _i_col_factory<Column, ColumnImpl, IFType, PT, ET> (data_type, compress_id, data_ptr, data_size); } // sorted col factory template <typename IFType, typename PT, typename ET> Column<IFType>* i_scol_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { return _i_col_factory<SortedColumn, SortedColumnImpl, IFType, PT, ET> (data_type, compress_id, data_ptr, data_size); } template <template<typename IFType> class IF, template<typename IFType, class Impl> class IFImpl, template<typename IFType> class TgtIF, typename IFType, typename PT, typename ET, typename DT> IF<IFType>* _i_fcol_factory_l1(E_COMPRESS compress_id, void* data_ptr, I32 data_size, TgtIF<IFType>* tgt) { switch (compress_id) { case PLAIN: return new IFImpl<IFType, PlainImpl<DT> >(data_ptr, data_size, tgt); case RUN0: return new IFImpl<IFType, Run0Impl<DT, PT> >(data_ptr, data_size, tgt); case RUN1: return new IFImpl<IFType, Run1Impl<DT, PT> >(data_ptr, data_size, tgt); case ENUM: return new IFImpl<IFType, EnumImpl<DT, ET> >(data_ptr, data_size, tgt); default: return 0; // TODO: exception throw } } template <template<typename IFType> class IF, template<typename IFType, class Impl> class IFImpl, template<typename IFType> class TgtIF, typename IFType, typename PT, typename ET> IF<IFType>* _i_fcol_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size, TgtIF<IFType>* tgt) { switch (data_type) { case 'b': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, I8> (compress_id, data_ptr, data_size, tgt); case 'B': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, U8> (compress_id, data_ptr, data_size, tgt); case 'h': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, I16> (compress_id, data_ptr, data_size, tgt); case 'H': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, U16> (compress_id, data_ptr, data_size, tgt); case 'i': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, I32> (compress_id, data_ptr, data_size, tgt); case 'I': return _i_fcol_factory_l1<IF, IFImpl, TgtIF, IFType, PT, ET, U32> (compress_id, data_ptr, data_size, tgt); default: return 0; // TODO: exception throw } } // normal fcol factory template <typename IFType, typename PT, typename ET> FKeyColumn<IFType>* i_fcol_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size, SortedColumn<IFType>* tgt) { return _i_fcol_factory<FKeyColumn, FKeyColumnImpl, SortedColumn, IFType, PT, ET> (data_type, compress_id, data_ptr, data_size, tgt); } // sorted fcol factory template <typename IFType, typename PT, typename ET> SortedFKeyColumn<IFType>* i_sfcol_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size, SortedColumn<IFType>* tgt) { return _i_fcol_factory<SortedFKeyColumn, SortedFKeyColumnImpl, SortedColumn, IFType, PT, ET> (data_type, compress_id, data_ptr, data_size, tgt); } // struct col factory template <U32 bytes> Column<std::string>* s_col_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { // struct implementation now ignores data_type and compress_id return new ColumnImpl<std::string, StructImpl<bytes> >(data_ptr, data_size); } // blob col factory template <typename PT, U32 align> Column<std::string>* b_col_factory(char data_type, E_COMPRESS compress_id, void* data_ptr, I32 data_size) { // struct implementation now ignores data_type and compress_id return new ColumnImpl<std::string, BlobImpl<PT, align> > (data_ptr, data_size); } } #endif <|endoftext|>
<commit_before>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file exercises.hpp * \brief File that students are to use to enter solutions to the * exercises that are assigned in the book. * */ #include <limits.h> #include "sparray.hpp" #ifndef _MINICOURSE_EXERCISES_H_ #define _MINICOURSE_EXERCISES_H_ /***********************************************************************/ namespace exercises { void map_incr(const value_type* source, value_type* dest) { // todo: fill in } value_type max(value_type* source, long n, value_type seed) { return seed; // todo: fill in } value_type max(value_type* source, long n) { return max(source, VALUE_MIN); } value_type plus(value_type* source, long n, value_type seed) { return seed; // todo: fill in } value_type plus(value_type* source, long n) { return plus(source, n, (value_type)0); } template <class Assoc_comb_op> value_type reduce(Assoc_comb_op op, value_type seed, const value_type* source, long n) { return seed; // todo fill in } sparray duplicate(const sparray& xs) { return empty(); // todo: fill in } sparray ktimes(const sparray& xs, long k) { return empty(); // todo: fill in } sparray pack_ex(const sparray& flags, const sparray& xs) { return empty(); // todo: fill in } // This function is the one you will debug and benchmark. // As such, use "-check filter_ex" and "-bench filter_ex" // where appropriate. template <class Predicate> sparray filter(Predicate p, const sparray& xs) { return pack_ex(map(p, xs), xs); } void merge_par(sparray& xs, sparray& tmp, long lo, long mid, long hi) { // todo: fill in } } // end namespace /***********************************************************************/ #endif /*! _MINICOURSE_EXERCISES_H_ */ <commit_msg>Comment<commit_after>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file exercises.hpp * \brief File that students are to use to enter solutions to the * exercises that are assigned in the book. * */ #include <limits.h> #include "sparray.hpp" #ifndef _MINICOURSE_EXERCISES_H_ #define _MINICOURSE_EXERCISES_H_ /***********************************************************************/ namespace exercises { void map_incr(const value_type* source, value_type* dest) { // todo: fill in } // source: pointer to the first item of the source array // n: number of items in the source array // seed: value to return in the case where `n` == 0 value_type max(value_type* source, long n, value_type seed) { return seed; // todo: fill in } value_type max(value_type* source, long n) { return max(source, VALUE_MIN); } value_type plus(value_type* source, long n, value_type seed) { return seed; // todo: fill in } value_type plus(value_type* source, long n) { return plus(source, n, (value_type)0); } template <class Assoc_comb_op> value_type reduce(Assoc_comb_op op, value_type seed, const value_type* source, long n) { return seed; // todo fill in } sparray duplicate(const sparray& xs) { return empty(); // todo: fill in } sparray ktimes(const sparray& xs, long k) { return empty(); // todo: fill in } sparray pack_ex(const sparray& flags, const sparray& xs) { return empty(); // todo: fill in } // This function is the one you will debug and benchmark. // As such, use "-check filter_ex" and "-bench filter_ex" // where appropriate. template <class Predicate> sparray filter(Predicate p, const sparray& xs) { return pack_ex(map(p, xs), xs); } void merge_par(sparray& xs, sparray& tmp, long lo, long mid, long hi) { // todo: fill in } } // end namespace /***********************************************************************/ #endif /*! _MINICOURSE_EXERCISES_H_ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2001-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "cpu/base.hh" #include "cpu/cpu_exec_context.hh" #include "cpu/exec_context.hh" #if FULL_SYSTEM #include "base/callback.hh" #include "base/cprintf.hh" #include "base/output.hh" #include "base/trace.hh" #include "cpu/profile.hh" #include "cpu/quiesce_event.hh" #include "kern/kernel_stats.hh" #include "sim/serialize.hh" #include "sim/sim_exit.hh" #include "sim/system.hh" #include "arch/stacktrace.hh" #else #include "sim/process.hh" #endif using namespace std; // constructor #if FULL_SYSTEM CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, System *_sys, AlphaITB *_itb, AlphaDTB *_dtb, FunctionalMemory *_mem) : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0), lastSuspend(0), mem(_mem), itb(_itb), dtb(_dtb), system(_sys), memctrl(_sys->memctrl), physmem(_sys->physmem), profile(NULL), func_exe_inst(0), storeCondFailures(0) { proxy = new ProxyExecContext<CPUExecContext>(this); quiesceEvent = new EndQuiesceEvent(proxy); memset(&regs, 0, sizeof(RegFile)); if (cpu->params->profile) { profile = new FunctionProfile(system->kernelSymtab); Callback *cb = new MakeCallback<CPUExecContext, &CPUExecContext::dumpFuncProfile>(this); registerExitCallback(cb); } // let's fill with a dummy node for now so we don't get a segfault // on the first cycle when there's no node available. static ProfileNode dummyNode; profileNode = &dummyNode; profilePC = 3; } #else CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, Process *_process, int _asid) : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0), lastSuspend(0), process(_process), mem(process->getMemory()), asid(_asid), func_exe_inst(0), storeCondFailures(0) { memset(&regs, 0, sizeof(RegFile)); proxy = new ProxyExecContext<CPUExecContext>(this); } CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, FunctionalMemory *_mem, int _asid) : cpu(_cpu), thread_num(_thread_num), process(0), mem(NULL), asid(_asid), func_exe_inst(0), storeCondFailures(0) { memset(&regs, 0, sizeof(RegFile)); proxy = new ProxyExecContext<CPUExecContext>(this); } CPUExecContext::CPUExecContext(RegFile *regFile) : cpu(NULL), thread_num(-1), process(NULL), mem(NULL), asid(-1), func_exe_inst(0), storeCondFailures(0) { regs = *regFile; proxy = new ProxyExecContext<CPUExecContext>(this); } #endif CPUExecContext::~CPUExecContext() { delete proxy; } #if FULL_SYSTEM void CPUExecContext::dumpFuncProfile() { std::ostream *os = simout.create(csprintf("profile.%s.dat", cpu->name())); profile->dump(proxy, *os); } void CPUExecContext::profileClear() { if (profile) profile->clear(); } void CPUExecContext::profileSample() { if (profile) profile->sample(profileNode, profilePC); } #endif void CPUExecContext::takeOverFrom(ExecContext *oldContext) { // some things should already be set up assert(mem == oldContext->getMemPtr()); #if FULL_SYSTEM assert(system == oldContext->getSystemPtr()); #else assert(process == oldContext->getProcessPtr()); #endif // copy over functional state _status = oldContext->status(); copyArchRegs(oldContext); cpu_id = oldContext->readCpuId(); #if !FULL_SYSTEM func_exe_inst = oldContext->readFuncExeInst(); #endif storeCondFailures = 0; oldContext->setStatus(ExecContext::Unallocated); } void CPUExecContext::serialize(ostream &os) { SERIALIZE_ENUM(_status); regs.serialize(os); // thread_num and cpu_id are deterministic from the config SERIALIZE_SCALAR(func_exe_inst); SERIALIZE_SCALAR(inst); #if FULL_SYSTEM Tick quiesceEndTick = 0; if (quiesceEvent->scheduled()) quiesceEndTick = quiesceEvent->when(); SERIALIZE_SCALAR(quiesceEndTick); #endif } void CPUExecContext::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_ENUM(_status); regs.unserialize(cp, section); // thread_num and cpu_id are deterministic from the config UNSERIALIZE_SCALAR(func_exe_inst); UNSERIALIZE_SCALAR(inst); #if FULL_SYSTEM Tick quiesceEndTick; UNSERIALIZE_SCALAR(quiesceEndTick); if (quiesceEndTick) quiesceEvent->schedule(quiesceEndTick); #endif } void CPUExecContext::activate(int delay) { if (status() == ExecContext::Active) return; lastActivate = curTick; if (status() == ExecContext::Unallocated) { cpu->activateWhenReady(thread_num); return; } _status = ExecContext::Active; // status() == Suspended cpu->activateContext(thread_num, delay); } void CPUExecContext::suspend() { if (status() == ExecContext::Suspended) return; lastActivate = curTick; lastSuspend = curTick; /* #if FULL_SYSTEM // Don't change the status from active if there are pending interrupts if (cpu->check_interrupts()) { assert(status() == ExecContext::Active); return; } #endif */ _status = ExecContext::Suspended; cpu->suspendContext(thread_num); } void CPUExecContext::deallocate() { if (status() == ExecContext::Unallocated) return; _status = ExecContext::Unallocated; cpu->deallocateContext(thread_num); } void CPUExecContext::halt() { if (status() == ExecContext::Halted) return; _status = ExecContext::Halted; cpu->haltContext(thread_num); } void CPUExecContext::regStats(const string &name) { } void CPUExecContext::copyArchRegs(ExecContext *xc) { // First loop through the integer registers. for (int i = 0; i < AlphaISA::NumIntRegs; ++i) { setIntReg(i, xc->readIntReg(i)); } // Then loop through the floating point registers. for (int i = 0; i < AlphaISA::NumFloatRegs; ++i) { setFloatRegDouble(i, xc->readFloatRegDouble(i)); setFloatRegInt(i, xc->readFloatRegInt(i)); } // Copy misc. registers regs.miscRegs.copyMiscRegs(xc); // Lastly copy PC/NPC setPC(xc->readPC()); setNextPC(xc->readNextPC()); } <commit_msg>Set memory properly.<commit_after>/* * Copyright (c) 2001-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "cpu/base.hh" #include "cpu/cpu_exec_context.hh" #include "cpu/exec_context.hh" #if FULL_SYSTEM #include "base/callback.hh" #include "base/cprintf.hh" #include "base/output.hh" #include "base/trace.hh" #include "cpu/profile.hh" #include "cpu/quiesce_event.hh" #include "kern/kernel_stats.hh" #include "sim/serialize.hh" #include "sim/sim_exit.hh" #include "sim/system.hh" #include "arch/stacktrace.hh" #else #include "sim/process.hh" #endif using namespace std; // constructor #if FULL_SYSTEM CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, System *_sys, AlphaITB *_itb, AlphaDTB *_dtb, FunctionalMemory *_mem) : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0), lastSuspend(0), mem(_mem), itb(_itb), dtb(_dtb), system(_sys), memctrl(_sys->memctrl), physmem(_sys->physmem), profile(NULL), func_exe_inst(0), storeCondFailures(0) { proxy = new ProxyExecContext<CPUExecContext>(this); quiesceEvent = new EndQuiesceEvent(proxy); memset(&regs, 0, sizeof(RegFile)); if (cpu->params->profile) { profile = new FunctionProfile(system->kernelSymtab); Callback *cb = new MakeCallback<CPUExecContext, &CPUExecContext::dumpFuncProfile>(this); registerExitCallback(cb); } // let's fill with a dummy node for now so we don't get a segfault // on the first cycle when there's no node available. static ProfileNode dummyNode; profileNode = &dummyNode; profilePC = 3; } #else CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, Process *_process, int _asid) : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0), lastSuspend(0), process(_process), mem(process->getMemory()), asid(_asid), func_exe_inst(0), storeCondFailures(0) { memset(&regs, 0, sizeof(RegFile)); proxy = new ProxyExecContext<CPUExecContext>(this); } CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, FunctionalMemory *_mem, int _asid) : cpu(_cpu), thread_num(_thread_num), process(0), mem(_mem), asid(_asid), func_exe_inst(0), storeCondFailures(0) { memset(&regs, 0, sizeof(RegFile)); proxy = new ProxyExecContext<CPUExecContext>(this); } CPUExecContext::CPUExecContext(RegFile *regFile) : cpu(NULL), thread_num(-1), process(NULL), mem(NULL), asid(-1), func_exe_inst(0), storeCondFailures(0) { regs = *regFile; proxy = new ProxyExecContext<CPUExecContext>(this); } #endif CPUExecContext::~CPUExecContext() { delete proxy; } #if FULL_SYSTEM void CPUExecContext::dumpFuncProfile() { std::ostream *os = simout.create(csprintf("profile.%s.dat", cpu->name())); profile->dump(proxy, *os); } void CPUExecContext::profileClear() { if (profile) profile->clear(); } void CPUExecContext::profileSample() { if (profile) profile->sample(profileNode, profilePC); } #endif void CPUExecContext::takeOverFrom(ExecContext *oldContext) { // some things should already be set up assert(mem == oldContext->getMemPtr()); #if FULL_SYSTEM assert(system == oldContext->getSystemPtr()); #else assert(process == oldContext->getProcessPtr()); #endif // copy over functional state _status = oldContext->status(); copyArchRegs(oldContext); cpu_id = oldContext->readCpuId(); #if !FULL_SYSTEM func_exe_inst = oldContext->readFuncExeInst(); #endif storeCondFailures = 0; oldContext->setStatus(ExecContext::Unallocated); } void CPUExecContext::serialize(ostream &os) { SERIALIZE_ENUM(_status); regs.serialize(os); // thread_num and cpu_id are deterministic from the config SERIALIZE_SCALAR(func_exe_inst); SERIALIZE_SCALAR(inst); #if FULL_SYSTEM Tick quiesceEndTick = 0; if (quiesceEvent->scheduled()) quiesceEndTick = quiesceEvent->when(); SERIALIZE_SCALAR(quiesceEndTick); #endif } void CPUExecContext::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_ENUM(_status); regs.unserialize(cp, section); // thread_num and cpu_id are deterministic from the config UNSERIALIZE_SCALAR(func_exe_inst); UNSERIALIZE_SCALAR(inst); #if FULL_SYSTEM Tick quiesceEndTick; UNSERIALIZE_SCALAR(quiesceEndTick); if (quiesceEndTick) quiesceEvent->schedule(quiesceEndTick); #endif } void CPUExecContext::activate(int delay) { if (status() == ExecContext::Active) return; lastActivate = curTick; if (status() == ExecContext::Unallocated) { cpu->activateWhenReady(thread_num); return; } _status = ExecContext::Active; // status() == Suspended cpu->activateContext(thread_num, delay); } void CPUExecContext::suspend() { if (status() == ExecContext::Suspended) return; lastActivate = curTick; lastSuspend = curTick; /* #if FULL_SYSTEM // Don't change the status from active if there are pending interrupts if (cpu->check_interrupts()) { assert(status() == ExecContext::Active); return; } #endif */ _status = ExecContext::Suspended; cpu->suspendContext(thread_num); } void CPUExecContext::deallocate() { if (status() == ExecContext::Unallocated) return; _status = ExecContext::Unallocated; cpu->deallocateContext(thread_num); } void CPUExecContext::halt() { if (status() == ExecContext::Halted) return; _status = ExecContext::Halted; cpu->haltContext(thread_num); } void CPUExecContext::regStats(const string &name) { } void CPUExecContext::copyArchRegs(ExecContext *xc) { // First loop through the integer registers. for (int i = 0; i < AlphaISA::NumIntRegs; ++i) { setIntReg(i, xc->readIntReg(i)); } // Then loop through the floating point registers. for (int i = 0; i < AlphaISA::NumFloatRegs; ++i) { setFloatRegDouble(i, xc->readFloatRegDouble(i)); setFloatRegInt(i, xc->readFloatRegInt(i)); } // Copy misc. registers regs.miscRegs.copyMiscRegs(xc); // Lastly copy PC/NPC setPC(xc->readPC()); setNextPC(xc->readNextPC()); } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include "LibVirtDriver.h" #include "Nebula.h" #include <sstream> #include <fstream> #include <libgen.h> int LibVirtDriver::deployment_description_kvm( const VirtualMachine * vm, const string& file_name) const { ofstream file; int num; vector<const Attribute *> attrs; string vcpu; string memory; int memory_in_kb = 0; string kernel = ""; string initrd = ""; string boot = ""; string root = ""; string kernel_cmd = ""; string bootloader = ""; string arch = ""; const VectorAttribute * disk; const VectorAttribute * context; string type = ""; string target = ""; string bus = ""; string ro = ""; string driver = ""; string default_driver = ""; bool readonly; const VectorAttribute * nic; string mac = ""; string bridge = ""; string script = ""; string model = ""; const VectorAttribute * graphics; string listen = ""; string port = ""; string passwd = ""; string keymap = ""; const VectorAttribute * input; const VectorAttribute * features; string pae = ""; string acpi = ""; const VectorAttribute * raw; string data; // ------------------------------------------------------------------------ file.open(file_name.c_str(), ios::out); if (file.fail() == true) { goto error_file; } // ------------------------------------------------------------------------ // Starting XML document // ------------------------------------------------------------------------ file << "<domain type='" << emulator << "'>" << endl; // ------------------------------------------------------------------------ // Domain name // ------------------------------------------------------------------------ file << "\t<name>one-" << vm->get_oid() << "</name>" << endl; // ------------------------------------------------------------------------ // CPU // ------------------------------------------------------------------------ vm->get_template_attribute("VCPU", vcpu); if(vcpu.empty()) { get_default("VCPU", vcpu); } if (!vcpu.empty()) { file << "\t<vcpu>" << vcpu << "</vcpu>" << endl; } // ------------------------------------------------------------------------ // Memory // ------------------------------------------------------------------------ vm->get_template_attribute("MEMORY",memory); if (memory.empty()) { get_default("MEMORY",memory); } if (!memory.empty()) { memory_in_kb = atoi(memory.c_str()) * 1024; file << "\t<memory>" << memory_in_kb << "</memory>" << endl; } else { goto error_memory; } // ------------------------------------------------------------------------ // OS and boot options // ------------------------------------------------------------------------ file << "\t<os>" << endl; num = vm->get_template_attribute("OS",attrs); // Get values & defaults if ( num > 0 ) { const VectorAttribute * os; os = dynamic_cast<const VectorAttribute *>(attrs[0]); if( os != 0 ) { kernel = os->vector_value("KERNEL"); initrd = os->vector_value("INITRD"); boot = os->vector_value("BOOT"); root = os->vector_value("ROOT"); kernel_cmd = os->vector_value("KERNEL_CMD"); bootloader = os->vector_value("BOOTLOADER"); arch = os->vector_value("ARCH"); } } if ( arch.empty() ) { get_default("OS","ARCH",arch); } if (emulator == "kvm") { file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl; } if ( kernel.empty() ) { get_default("OS","KERNEL",kernel); } if ( initrd.empty() ) { get_default("OS","INITRD",initrd); } if ( bootloader.empty() ) { get_default("OS","BOOTLOADER",bootloader); } if ( boot.empty() ) { get_default("OS","BOOT",boot); if ( boot.empty() ) { goto error_boot; } } if ( root.empty() ) { get_default("OS","ROOT",root); } if ( kernel_cmd.empty() ) { get_default("OS","KERNEL_CMD",kernel_cmd); } // Start writing to the file with the info we got if ( !kernel.empty() ) { file << "\t\t<kernel>" << kernel << "</kernel>" << endl; if ( !initrd.empty() ) { file << "\t\t<initrd>" << initrd << "</initrd>" << endl; } if ( !root.empty() ) { kernel_cmd = "root=/dev/" + root + " " + kernel_cmd; } if (!kernel_cmd.empty()) { file << "\t\t<cmdline>" << kernel_cmd << "</cmdline>" << endl; } } else if ( !bootloader.empty() ) { file << "\t\t<bootloader>" << bootloader << "</bootloader>" << endl; } file << "\t\t<boot dev='" << boot << "'/>" << endl; file << "\t</os>" << endl; attrs.clear(); // ------------------------------------------------------------------------ // Disks // ------------------------------------------------------------------------ file << "\t<devices>" << endl; if (emulator == "kvm") { file << "\t\t<emulator>/usr/bin/kvm</emulator>" << endl; } get_default("DISK","DRIVER",default_driver); if (default_driver.empty()) { default_driver = "raw"; } num = vm->get_template_attribute("DISK",attrs); for (int i=0; i < num ;i++) { disk = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( disk == 0 ) { continue; } type = disk->vector_value("TYPE"); target = disk->vector_value("TARGET"); ro = disk->vector_value("READONLY"); bus = disk->vector_value("BUS"); driver = disk->vector_value("DRIVER"); if (target.empty()) { goto error_disk; } readonly = false; if ( !ro.empty() ) { transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper); if ( ro == "YES" ) { readonly = true; } } // ---- Disk type and source for the image ---- if (type.empty() == false) { transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper); } if ( type == "BLOCK" ) { file << "\t\t<disk type='block' device='disk'>" << endl << "\t\t\t<source dev='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } else if ( type == "CDROM" ) { file << "\t\t<disk type='file' device='cdrom'>" << endl << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } else { file << "\t\t<disk type='file' device='disk'>" << endl << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } // ---- target device to map the disk ---- file << "\t\t\t<target dev='" << target << "'"; // ---- bus ---- if (!bus.empty()) { file << " bus='" << bus << "'/>" << endl; } else { file << "/>" << endl; } // ---- readonly attribute for the disk ---- if (readonly) { file << "\t\t\t<readonly/>" << endl; } // ---- Image Format using qemu driver ---- file << "\t\t\t<driver name='qemu' type='"; if ( !driver.empty() ) { file << driver << "'/>" << endl; } else { file << default_driver << "'/>" << endl; } file << "\t\t</disk>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Context Device // ------------------------------------------------------------------------ if ( vm->get_template_attribute("CONTEXT",attrs) == 1 ) { context = dynamic_cast<const VectorAttribute *>(attrs[0]); target = context->vector_value("TARGET"); driver = context->vector_value("DRIVER"); if ( !target.empty() ) { file << "\t\t<disk type='file' device='cdrom'>" << endl; file << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << num << "'/>" << endl; file << "\t\t\t<target dev='" << target << "'/>" << endl; file << "\t\t\t<readonly/>" << endl; file << "\t\t\t<driver name='qemu' type='"; if ( !driver.empty() ) { file << driver << "'/>" << endl; } else { file << default_driver << "'/>" << endl; } file << "\t\t</disk>" << endl; } else { vm->log("VMM", Log::WARNING, "Could not find target device to" " attach context, will continue without it."); } } attrs.clear(); // ------------------------------------------------------------------------ // Network interfaces // ------------------------------------------------------------------------ num = vm->get_template_attribute("NIC",attrs); for(int i=0; i<num; i++) { nic = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( nic == 0 ) { continue; } bridge = nic->vector_value("BRIDGE"); mac = nic->vector_value("MAC"); target = nic->vector_value("TARGET"); script = nic->vector_value("SCRIPT"); model = nic->vector_value("MODEL"); if ( bridge.empty() ) { file << "\t\t<interface type='ethernet'>" << endl; } else { file << "\t\t<interface type='bridge'>" << endl; file << "\t\t\t<source bridge='" << bridge << "'/>" << endl; } if( !mac.empty() ) { file << "\t\t\t<mac address='" << mac << "'/>" << endl; } if( !target.empty() ) { file << "\t\t\t<target dev='" << target << "'/>" << endl; } if( !script.empty() ) { file << "\t\t\t<script path='" << script << "'/>" << endl; } if( !model.empty() ) { file << "\t\t\t<model type='" << model << "'/>" << endl; } file << "\t\t</interface>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Graphics // ------------------------------------------------------------------------ if ( vm->get_template_attribute("GRAPHICS",attrs) > 0 ) { graphics = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( graphics != 0 ) { type = graphics->vector_value("TYPE"); listen = graphics->vector_value("LISTEN"); port = graphics->vector_value("PORT"); passwd = graphics->vector_value("PASSWD"); keymap = graphics->vector_value("KEYMAP"); if ( type == "vnc" || type == "VNC" ) { file << "\t\t<graphics type='vnc'"; if ( !listen.empty() ) { file << " listen='" << listen << "'"; } if ( !port.empty() ) { file << " port='" << port << "'"; } if ( !passwd.empty() ) { file << " passwd='" << passwd << "'"; } if ( !keymap.empty() ) { file << " keymap='" << keymap << "'"; } file << "/>" << endl; } else { vm->log("VMM", Log::WARNING, "Not supported graphics type, ignored."); } } } attrs.clear(); // ------------------------------------------------------------------------ // Input // ------------------------------------------------------------------------ if ( vm->get_template_attribute("INPUT",attrs) > 0 ) { input = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( input != 0 ) { type = input->vector_value("TYPE"); bus = input->vector_value("BUS"); if ( !type.empty() ) { file << "\t\t<input type='" << type << "'"; if ( !bus.empty() ) { file << " bus='" << bus << "'"; } file << "/>" << endl; } } } attrs.clear(); file << "\t</devices>" << endl; // ------------------------------------------------------------------------ // Features // ------------------------------------------------------------------------ num = vm->get_template_attribute("FEATURES",attrs); if ( num > 0 ) { features = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( features != 0 ) { pae = features->vector_value("PAE"); acpi = features->vector_value("ACPI"); } } if ( pae.empty() ) { get_default("FEATURES", "PAE", pae); } if ( acpi.empty() ) { get_default("FEATURES", "ACPI", acpi); } if( acpi == "yes" || pae == "yes" ) { file << "\t<features>" << endl; if ( pae == "yes" ) { file << "\t\t<pae/>" << endl; } if ( acpi == "yes" ) { file << "\t\t<acpi/>" << endl; } file << "\t</features>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Raw KVM attributes // ------------------------------------------------------------------------ num = vm->get_template_attribute("RAW",attrs); for(int i=0; i<num;i++) { raw = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( raw == 0 ) { continue; } type = raw->vector_value("TYPE"); transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper); if ( type == "KVM" ) { data = raw->vector_value("DATA"); file << "\t" << data << endl; } } file << "</domain>" << endl; file.close(); return 0; error_file: vm->log("VMM", Log::ERROR, "Could not open KVM deployment file."); return -1; error_memory: vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided."); file.close(); return -1; error_boot: vm->log("VMM", Log::ERROR, "No BOOT device defined and no default provided."); file.close(); return -1; error_disk: vm->log("VMM", Log::ERROR, "Wrong target value in DISK."); file.close(); return -1; } <commit_msg>bug #399: Added test for no arch and no default provided<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include "LibVirtDriver.h" #include "Nebula.h" #include <sstream> #include <fstream> #include <libgen.h> int LibVirtDriver::deployment_description_kvm( const VirtualMachine * vm, const string& file_name) const { ofstream file; int num; vector<const Attribute *> attrs; string vcpu; string memory; int memory_in_kb = 0; string kernel = ""; string initrd = ""; string boot = ""; string root = ""; string kernel_cmd = ""; string bootloader = ""; string arch = ""; const VectorAttribute * disk; const VectorAttribute * context; string type = ""; string target = ""; string bus = ""; string ro = ""; string driver = ""; string default_driver = ""; bool readonly; const VectorAttribute * nic; string mac = ""; string bridge = ""; string script = ""; string model = ""; const VectorAttribute * graphics; string listen = ""; string port = ""; string passwd = ""; string keymap = ""; const VectorAttribute * input; const VectorAttribute * features; string pae = ""; string acpi = ""; const VectorAttribute * raw; string data; // ------------------------------------------------------------------------ file.open(file_name.c_str(), ios::out); if (file.fail() == true) { goto error_file; } // ------------------------------------------------------------------------ // Starting XML document // ------------------------------------------------------------------------ file << "<domain type='" << emulator << "'>" << endl; // ------------------------------------------------------------------------ // Domain name // ------------------------------------------------------------------------ file << "\t<name>one-" << vm->get_oid() << "</name>" << endl; // ------------------------------------------------------------------------ // CPU // ------------------------------------------------------------------------ vm->get_template_attribute("VCPU", vcpu); if(vcpu.empty()) { get_default("VCPU", vcpu); } if (!vcpu.empty()) { file << "\t<vcpu>" << vcpu << "</vcpu>" << endl; } // ------------------------------------------------------------------------ // Memory // ------------------------------------------------------------------------ vm->get_template_attribute("MEMORY",memory); if (memory.empty()) { get_default("MEMORY",memory); } if (!memory.empty()) { memory_in_kb = atoi(memory.c_str()) * 1024; file << "\t<memory>" << memory_in_kb << "</memory>" << endl; } else { goto error_memory; } // ------------------------------------------------------------------------ // OS and boot options // ------------------------------------------------------------------------ file << "\t<os>" << endl; num = vm->get_template_attribute("OS",attrs); // Get values & defaults if ( num > 0 ) { const VectorAttribute * os; os = dynamic_cast<const VectorAttribute *>(attrs[0]); if( os != 0 ) { kernel = os->vector_value("KERNEL"); initrd = os->vector_value("INITRD"); boot = os->vector_value("BOOT"); root = os->vector_value("ROOT"); kernel_cmd = os->vector_value("KERNEL_CMD"); bootloader = os->vector_value("BOOTLOADER"); arch = os->vector_value("ARCH"); } } if ( arch.empty() ) { get_default("OS","ARCH",arch); if ( arch.empty() ) { goto error_arch; } } if (emulator == "kvm") { file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl; } if ( kernel.empty() ) { get_default("OS","KERNEL",kernel); } if ( initrd.empty() ) { get_default("OS","INITRD",initrd); } if ( bootloader.empty() ) { get_default("OS","BOOTLOADER",bootloader); } if ( boot.empty() ) { get_default("OS","BOOT",boot); if ( boot.empty() ) { goto error_boot; } } if ( root.empty() ) { get_default("OS","ROOT",root); } if ( kernel_cmd.empty() ) { get_default("OS","KERNEL_CMD",kernel_cmd); } // Start writing to the file with the info we got if ( !kernel.empty() ) { file << "\t\t<kernel>" << kernel << "</kernel>" << endl; if ( !initrd.empty() ) { file << "\t\t<initrd>" << initrd << "</initrd>" << endl; } if ( !root.empty() ) { kernel_cmd = "root=/dev/" + root + " " + kernel_cmd; } if (!kernel_cmd.empty()) { file << "\t\t<cmdline>" << kernel_cmd << "</cmdline>" << endl; } } else if ( !bootloader.empty() ) { file << "\t\t<bootloader>" << bootloader << "</bootloader>" << endl; } file << "\t\t<boot dev='" << boot << "'/>" << endl; file << "\t</os>" << endl; attrs.clear(); // ------------------------------------------------------------------------ // Disks // ------------------------------------------------------------------------ file << "\t<devices>" << endl; if (emulator == "kvm") { file << "\t\t<emulator>/usr/bin/kvm</emulator>" << endl; } get_default("DISK","DRIVER",default_driver); if (default_driver.empty()) { default_driver = "raw"; } num = vm->get_template_attribute("DISK",attrs); for (int i=0; i < num ;i++) { disk = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( disk == 0 ) { continue; } type = disk->vector_value("TYPE"); target = disk->vector_value("TARGET"); ro = disk->vector_value("READONLY"); bus = disk->vector_value("BUS"); driver = disk->vector_value("DRIVER"); if (target.empty()) { goto error_disk; } readonly = false; if ( !ro.empty() ) { transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper); if ( ro == "YES" ) { readonly = true; } } // ---- Disk type and source for the image ---- if (type.empty() == false) { transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper); } if ( type == "BLOCK" ) { file << "\t\t<disk type='block' device='disk'>" << endl << "\t\t\t<source dev='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } else if ( type == "CDROM" ) { file << "\t\t<disk type='file' device='cdrom'>" << endl << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } else { file << "\t\t<disk type='file' device='disk'>" << endl << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i << "'/>" << endl; } // ---- target device to map the disk ---- file << "\t\t\t<target dev='" << target << "'"; // ---- bus ---- if (!bus.empty()) { file << " bus='" << bus << "'/>" << endl; } else { file << "/>" << endl; } // ---- readonly attribute for the disk ---- if (readonly) { file << "\t\t\t<readonly/>" << endl; } // ---- Image Format using qemu driver ---- file << "\t\t\t<driver name='qemu' type='"; if ( !driver.empty() ) { file << driver << "'/>" << endl; } else { file << default_driver << "'/>" << endl; } file << "\t\t</disk>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Context Device // ------------------------------------------------------------------------ if ( vm->get_template_attribute("CONTEXT",attrs) == 1 ) { context = dynamic_cast<const VectorAttribute *>(attrs[0]); target = context->vector_value("TARGET"); driver = context->vector_value("DRIVER"); if ( !target.empty() ) { file << "\t\t<disk type='file' device='cdrom'>" << endl; file << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << num << "'/>" << endl; file << "\t\t\t<target dev='" << target << "'/>" << endl; file << "\t\t\t<readonly/>" << endl; file << "\t\t\t<driver name='qemu' type='"; if ( !driver.empty() ) { file << driver << "'/>" << endl; } else { file << default_driver << "'/>" << endl; } file << "\t\t</disk>" << endl; } else { vm->log("VMM", Log::WARNING, "Could not find target device to" " attach context, will continue without it."); } } attrs.clear(); // ------------------------------------------------------------------------ // Network interfaces // ------------------------------------------------------------------------ num = vm->get_template_attribute("NIC",attrs); for(int i=0; i<num; i++) { nic = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( nic == 0 ) { continue; } bridge = nic->vector_value("BRIDGE"); mac = nic->vector_value("MAC"); target = nic->vector_value("TARGET"); script = nic->vector_value("SCRIPT"); model = nic->vector_value("MODEL"); if ( bridge.empty() ) { file << "\t\t<interface type='ethernet'>" << endl; } else { file << "\t\t<interface type='bridge'>" << endl; file << "\t\t\t<source bridge='" << bridge << "'/>" << endl; } if( !mac.empty() ) { file << "\t\t\t<mac address='" << mac << "'/>" << endl; } if( !target.empty() ) { file << "\t\t\t<target dev='" << target << "'/>" << endl; } if( !script.empty() ) { file << "\t\t\t<script path='" << script << "'/>" << endl; } if( !model.empty() ) { file << "\t\t\t<model type='" << model << "'/>" << endl; } file << "\t\t</interface>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Graphics // ------------------------------------------------------------------------ if ( vm->get_template_attribute("GRAPHICS",attrs) > 0 ) { graphics = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( graphics != 0 ) { type = graphics->vector_value("TYPE"); listen = graphics->vector_value("LISTEN"); port = graphics->vector_value("PORT"); passwd = graphics->vector_value("PASSWD"); keymap = graphics->vector_value("KEYMAP"); if ( type == "vnc" || type == "VNC" ) { file << "\t\t<graphics type='vnc'"; if ( !listen.empty() ) { file << " listen='" << listen << "'"; } if ( !port.empty() ) { file << " port='" << port << "'"; } if ( !passwd.empty() ) { file << " passwd='" << passwd << "'"; } if ( !keymap.empty() ) { file << " keymap='" << keymap << "'"; } file << "/>" << endl; } else { vm->log("VMM", Log::WARNING, "Not supported graphics type, ignored."); } } } attrs.clear(); // ------------------------------------------------------------------------ // Input // ------------------------------------------------------------------------ if ( vm->get_template_attribute("INPUT",attrs) > 0 ) { input = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( input != 0 ) { type = input->vector_value("TYPE"); bus = input->vector_value("BUS"); if ( !type.empty() ) { file << "\t\t<input type='" << type << "'"; if ( !bus.empty() ) { file << " bus='" << bus << "'"; } file << "/>" << endl; } } } attrs.clear(); file << "\t</devices>" << endl; // ------------------------------------------------------------------------ // Features // ------------------------------------------------------------------------ num = vm->get_template_attribute("FEATURES",attrs); if ( num > 0 ) { features = dynamic_cast<const VectorAttribute *>(attrs[0]); if ( features != 0 ) { pae = features->vector_value("PAE"); acpi = features->vector_value("ACPI"); } } if ( pae.empty() ) { get_default("FEATURES", "PAE", pae); } if ( acpi.empty() ) { get_default("FEATURES", "ACPI", acpi); } if( acpi == "yes" || pae == "yes" ) { file << "\t<features>" << endl; if ( pae == "yes" ) { file << "\t\t<pae/>" << endl; } if ( acpi == "yes" ) { file << "\t\t<acpi/>" << endl; } file << "\t</features>" << endl; } attrs.clear(); // ------------------------------------------------------------------------ // Raw KVM attributes // ------------------------------------------------------------------------ num = vm->get_template_attribute("RAW",attrs); for(int i=0; i<num;i++) { raw = dynamic_cast<const VectorAttribute *>(attrs[i]); if ( raw == 0 ) { continue; } type = raw->vector_value("TYPE"); transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper); if ( type == "KVM" ) { data = raw->vector_value("DATA"); file << "\t" << data << endl; } } file << "</domain>" << endl; file.close(); return 0; error_file: vm->log("VMM", Log::ERROR, "Could not open KVM deployment file."); return -1; error_memory: vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided."); file.close(); return -1; error_arch: vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided."); file.close(); return -1; error_boot: vm->log("VMM", Log::ERROR, "No BOOT device defined and no default provided."); file.close(); return -1; error_disk: vm->log("VMM", Log::ERROR, "Wrong target value in DISK."); file.close(); return -1; } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include "TestSscCommon.h" #include <adios2.h> #include <gtest/gtest.h> #include <mpi.h> #include <numeric> #include <thread> using namespace adios2; int mpiRank = 0; int mpiSize = 1; MPI_Comm mpiComm; class SscEngineTest : public ::testing::Test { public: SscEngineTest() = default; }; void Writer(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto scalarInt = dataManIO.DefineVariable<int>("scalarInt"); auto stringVar = dataManIO.DefineVariable<std::string>("stringVar"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Write); for (int i = 0; i < steps; ++i) { engine.BeginStep(); GenData(myChars, i, start, count, shape); GenData(myUChars, i, start, count, shape); GenData(myShorts, i, start, count, shape); GenData(myUShorts, i, start, count, shape); GenData(myInts, i, start, count, shape); GenData(myUInts, i, start, count, shape); GenData(myFloats, i, start, count, shape); GenData(myDoubles, i, start, count, shape); GenData(myComplexes, i, start, count, shape); GenData(myDComplexes, i, start, count, shape); engine.Put(bpChars, myChars.data(), adios2::Mode::Sync); engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Put(bpInts, myInts.data(), adios2::Mode::Sync); engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); engine.Put(scalarInt, i); std::string s = "sample string sample string sample string"; engine.Put(stringVar, s); engine.EndStep(); } engine.Close(); } void Reader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("Test"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Read); size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); while (true) { adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { auto scalarInt = dataManIO.InquireVariable<int>("scalarInt"); auto blocksInfo = engine.BlocksInfo(scalarInt, engine.CurrentStep()); for (const auto &bi : blocksInfo) { ASSERT_EQ(bi.IsValue, true); ASSERT_EQ(bi.Value, engine.CurrentStep()); ASSERT_EQ(scalarInt.Min(), engine.CurrentStep()); ASSERT_EQ(scalarInt.Max(), engine.CurrentStep()); } const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 12); size_t currentStep = engine.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<std::string> stringVar = dataManIO.InquireVariable<std::string>("stringVar"); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); engine.Get(bpChars, myChars.data(), adios2::Mode::Sync); engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Get(bpInts, myInts.data(), adios2::Mode::Sync); engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); std::string s; engine.Get(stringVar, s); ASSERT_EQ(s, "sample string sample string sample string"); ASSERT_EQ(stringVar.Min(), "sample string sample string sample string"); ASSERT_EQ(stringVar.Max(), "sample string sample string sample string"); int i; engine.Get(scalarInt, i); ASSERT_EQ(i, currentStep); VerifyData(myChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myFloats.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDoubles.data(), currentStep, start, count, shape, mpiRank); VerifyData(myComplexes.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDComplexes.data(), currentStep, start, count, shape, mpiRank); engine.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { std::cout << "[Rank " + std::to_string(mpiRank) + "] SscTest reader end of stream!" << std::endl; break; } } auto attInt = dataManIO.InquireAttribute<int>("AttInt"); std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received " << attInt.Data()[0] << ", expected 110" << std::endl; ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); engine.Close(); } TEST_F(SscEngineTest, TestSscBaseUnlocked) { std::string filename = "TestSscBaseUnlocked"; adios2::Params engineParams = {}; int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); int mpiGroup = worldRank / (worldSize / 2); MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm); MPI_Comm_rank(mpiComm, &mpiRank); MPI_Comm_size(mpiComm, &mpiSize); Dims shape = {10, (size_t)mpiSize * 2}; Dims start = {2, (size_t)mpiRank * 2}; Dims count = {5, 2}; size_t steps = 10; if (mpiGroup == 0) { Writer(shape, start, count, steps, engineParams, filename); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (mpiGroup == 1) { Reader(shape, start, count, steps, engineParams, filename); } MPI_Barrier(MPI_COMM_WORLD); } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <commit_msg>try more<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include "TestSscCommon.h" #include <adios2.h> #include <gtest/gtest.h> #include <mpi.h> #include <numeric> #include <thread> using namespace adios2; int mpiRank = 0; int mpiSize = 1; MPI_Comm mpiComm; class SscEngineTest : public ::testing::Test { public: SscEngineTest() = default; }; void Writer(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto scalarInt = dataManIO.DefineVariable<int>("scalarInt"); auto stringVar = dataManIO.DefineVariable<std::string>("stringVar"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Write); for (int i = 0; i < steps; ++i) { engine.BeginStep(); GenData(myChars, i, start, count, shape); GenData(myUChars, i, start, count, shape); GenData(myShorts, i, start, count, shape); GenData(myUShorts, i, start, count, shape); GenData(myInts, i, start, count, shape); GenData(myUInts, i, start, count, shape); GenData(myFloats, i, start, count, shape); GenData(myDoubles, i, start, count, shape); GenData(myComplexes, i, start, count, shape); GenData(myDComplexes, i, start, count, shape); engine.Put(bpChars, myChars.data(), adios2::Mode::Sync); engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Put(bpInts, myInts.data(), adios2::Mode::Sync); engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); engine.Put(scalarInt, i); std::string s = "sample string sample string sample string"; engine.Put(stringVar, s); engine.EndStep(); } engine.Close(); } void Reader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("Test"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Read); size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); while (true) { adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { auto scalarInt = dataManIO.InquireVariable<int>("scalarInt"); auto blocksInfo = engine.BlocksInfo(scalarInt, engine.CurrentStep()); for (const auto &bi : blocksInfo) { ASSERT_EQ(bi.IsValue, true); ASSERT_EQ(bi.Value, engine.CurrentStep()); ASSERT_EQ(scalarInt.Min(), engine.CurrentStep()); ASSERT_EQ(scalarInt.Max(), engine.CurrentStep()); } const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 12); size_t currentStep = engine.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<std::string> stringVar = dataManIO.InquireVariable<std::string>("stringVar"); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); engine.Get(bpChars, myChars.data(), adios2::Mode::Sync); engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Get(bpInts, myInts.data(), adios2::Mode::Sync); engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); std::string s; engine.Get(stringVar, s); ASSERT_EQ(s, "sample string sample string sample string"); ASSERT_EQ(stringVar.Min(), "sample string sample string sample string"); ASSERT_EQ(stringVar.Max(), "sample string sample string sample string"); VerifyData(myChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myFloats.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDoubles.data(), currentStep, start, count, shape, mpiRank); VerifyData(myComplexes.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDComplexes.data(), currentStep, start, count, shape, mpiRank); engine.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { std::cout << "[Rank " + std::to_string(mpiRank) + "] SscTest reader end of stream!" << std::endl; break; } } auto attInt = dataManIO.InquireAttribute<int>("AttInt"); std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received " << attInt.Data()[0] << ", expected 110" << std::endl; ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); engine.Close(); } TEST_F(SscEngineTest, TestSscBaseUnlocked) { std::string filename = "TestSscBaseUnlocked"; adios2::Params engineParams = {}; int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); int mpiGroup = worldRank / (worldSize / 2); MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm); MPI_Comm_rank(mpiComm, &mpiRank); MPI_Comm_size(mpiComm, &mpiSize); Dims shape = {10, (size_t)mpiSize * 2}; Dims start = {2, (size_t)mpiRank * 2}; Dims count = {5, 2}; size_t steps = 10; if (mpiGroup == 0) { Writer(shape, start, count, steps, engineParams, filename); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (mpiGroup == 1) { Reader(shape, start, count, steps, engineParams, filename); } MPI_Barrier(MPI_COMM_WORLD); } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <|endoftext|>
<commit_before>// // Copyright (c) 2012 Ian Godin // // 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <pthread.h> #include <arpa/inet.h> #include <mysql/mysql.h> #include <mutex> #include <map> #include <thread> #include "backend.h" #include "error.h" #include "format.h" #include "guard.h" namespace { std::mutex db_mutex; std::map<std::thread::id,MYSQL*> dbs; } //////////////////////////////////////// void threadStartBackend( void ) { std::unique_lock<std::mutex> lock( db_mutex ); std::string dbhost = configuration["dbhost"]; std::string database = configuration["database"]; std::string dbuser = configuration["dbuser"]; std::string dbpassword = configuration["dbpassword"]; if ( dbhost.empty() || database.empty() || dbuser.empty() || dbpassword.empty() ) error( "Invalid configuration file" ); mysql_thread_init(); MYSQL *db = mysql_init( NULL ); if ( db == NULL ) error( "Unable to init library" ); my_bool reconnect = 1; unsigned int protocol = MYSQL_PROTOCOL_TCP; mysql_options( db, MYSQL_OPT_RECONNECT, &reconnect ); mysql_options( db, MYSQL_OPT_PROTOCOL, (const char *)&protocol ); if ( mysql_real_connect( db, dbhost.c_str(), dbuser.c_str(), dbpassword.c_str(), database.c_str(), 0, NULL, CLIENT_MULTI_STATEMENTS ) == NULL ) error( std::string( "Unable to open mysql: " ) + mysql_error( db ) ); dbs[std::this_thread::get_id()] = db; } //////////////////////////////////////// void threadStopBackend( void ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; dbs.erase( std::this_thread::get_id() ); lock.unlock(); mysql_close( db ); mysql_thread_end(); } //////////////////////////////////////// void getAllOptions( std::vector< std::tuple<uint32_t, uint32_t, std::string> > &options ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query( "SELECT ip_addr_from, ip_addr_to, options FROM dhcp_options ORDER BY ip_addr_from" ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( std::string( "Error storing result from mysql: " ) + mysql_error( db ) ); MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { unsigned long *lengths = mysql_fetch_lengths( result ); options.emplace_back( htonl( std::stoul( std::string( row[0], lengths[0] ) ) ), htonl( std::stoul( std::string( row[1], lengths[1] ) ) ), std::string( row[2], lengths[2] ) ); } } //////////////////////////////////////// std::vector<uint32_t> getIPAddresses( const uint8_t *hwaddr, bool avail ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query; if ( avail ) { query = format ( "SELECT ip_addr FROM dhcp_host " "WHERE ( mac_addr=x'{0,B16,f0,w2}' OR mac_addr=x'000000000000' ) " "AND ip_addr NOT IN ( SELECT ip_addr FROM dhcp_lease WHERE mac_addr <> x'{0,B16,f0,w2}' ) " "ORDER BY mac_addr DESC, dhcp_host.ip_addr ASC", as_hex<uint8_t>( hwaddr, 6 ) ); } else { query = format ( "SELECT ip_addr FROM dhcp_host " "WHERE mac_addr=x'{0,B16,f0,w2}' OR mac_addr=x'000000000000' " "ORDER BY mac_addr DESC, dhcp_host.ip_addr ASC", as_hex<uint8_t>( hwaddr, 6 ) ); } if ( mysql_query( db, query.c_str() ) != 0 ) error( format( "Error querying mysql: {0}", mysql_error( db ) ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( format( "Error storing result from mysql: {0}", mysql_error( db ) ) ); std::vector<uint32_t> ret; MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { if ( row != NULL && row[0] ) ret.push_back( htonl( atoi( row[0] ) ) ); } return ret; } //////////////////////////////////////// void getOptions( uint32_t ip, std::vector<std::string> &options ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "SELECT options FROM dhcp_options WHERE ( {0} >= ip_addr_from AND {0} <= ip_addr_to )", ntohl( ip ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( std::string( "Error storing result from mysql: " ) + mysql_error( db ) ); MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { unsigned long *lengths = mysql_fetch_lengths( result ); options.push_back( std::string( row[0], lengths[0] ) ); } } //////////////////////////////////////// void addHost( uint32_t ip, const uint8_t *mac ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "INSERT INTO dhcp_host ( ip_addr, mac_addr )" "VALUES( {0}, x'{1,B16,f0,w2}' )", ntohl( ip ), as_hex<uint8_t>( mac, 6 ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void removeHost( uint32_t ip ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_host WHERE ip_addr = {0}", ntohl( ip ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void addOption( uint32_t ip1, uint32_t ip2, const std::string &opt, bool replace ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query; if ( replace ) { query = format( "UPDATE dhcp_options " "SET options=x'{2,B16,f0,w2}' WHERE ( ip_addr_from = {0} AND ip_addr_to = {1} AND options LIKE x'{3,B16,f0,w2}25' )", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ), uint32_t( uint8_t( opt[0] ) ) ); } else { query = format( "INSERT INTO dhcp_options ( ip_addr_from, ip_addr_to, options )" "VALUES( {0}, {1}, x'{2,B16,f0,w2}' )", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ) ); } if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void removeOption( uint32_t ip1, uint32_t ip2, const std::string &opt ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_options WHERE ip_addr_from={0} AND ip_addr_to={1} AND options=x'{2,B16,f0,w2}'", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// bool acquireLease( uint32_t ip, const uint8_t *hwaddr, uint32_t time ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "INSERT IGNORE INTO dhcp_lease ( ip_addr, mac_addr, expiration ) " "VALUES( {0}, x'{1,B16,f0,w2}', 0 )", ntohl( ip ), as_hex<uint8_t>(hwaddr,6), time ); if ( mysql_query( db, query.c_str() ) != 0 ) { syslog( LOG_ERR, "Acquire lease: %s", mysql_error( db ) ); return false; } query = format( "UPDATE dhcp_lease SET expiration=TIMESTAMPADD( SECOND, {2}, NOW() )" "WHERE ip_addr={0} AND mac_addr = x'{1,B16,f0,w2}'", ntohl( ip ), as_hex<uint8_t>(hwaddr,6), time ); if ( mysql_query( db, query.c_str() ) != 0 ) { syslog( LOG_ERR, "Lease expiration: %s", mysql_error( db ) ); return false; } int affected = mysql_affected_rows( db ); if ( affected != 1 ) { syslog( LOG_DEBUG, "%s", query.c_str() ); syslog( LOG_ERR, "Lease expiration (%d): ip is already assigned", affected ); return false; } syslog( LOG_ERR, "Acquired lease: %u", time ); return true; } //////////////////////////////////////// bool releaseLease( uint32_t ip, const uint8_t *hwaddr ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_lease " "WHERE ip_addr = {0} AND mac_addr = x'{1,B16,f0,w2}'", ntohl( ip ), as_hex<uint8_t>(hwaddr) ); if ( mysql_query( db, query.c_str() ) != 0 ) return false; if ( mysql_affected_rows( db ) < 1 ) return false; return true; } //////////////////////////////////////// <commit_msg>Fixed bug with expiration of leases.<commit_after>// // Copyright (c) 2012 Ian Godin // // 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <pthread.h> #include <arpa/inet.h> #include <mysql/mysql.h> #include <mutex> #include <map> #include <thread> #include "backend.h" #include "error.h" #include "format.h" #include "guard.h" namespace { std::mutex db_mutex; std::map<std::thread::id,MYSQL*> dbs; } //////////////////////////////////////// void threadStartBackend( void ) { std::unique_lock<std::mutex> lock( db_mutex ); std::string dbhost = configuration["dbhost"]; std::string database = configuration["database"]; std::string dbuser = configuration["dbuser"]; std::string dbpassword = configuration["dbpassword"]; if ( dbhost.empty() || database.empty() || dbuser.empty() || dbpassword.empty() ) error( "Invalid configuration file" ); mysql_thread_init(); MYSQL *db = mysql_init( NULL ); if ( db == NULL ) error( "Unable to init library" ); my_bool reconnect = 1; unsigned int protocol = MYSQL_PROTOCOL_TCP; mysql_options( db, MYSQL_OPT_RECONNECT, &reconnect ); mysql_options( db, MYSQL_OPT_PROTOCOL, (const char *)&protocol ); if ( mysql_real_connect( db, dbhost.c_str(), dbuser.c_str(), dbpassword.c_str(), database.c_str(), 0, NULL, CLIENT_MULTI_STATEMENTS ) == NULL ) error( std::string( "Unable to open mysql: " ) + mysql_error( db ) ); dbs[std::this_thread::get_id()] = db; } //////////////////////////////////////// void threadStopBackend( void ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; dbs.erase( std::this_thread::get_id() ); lock.unlock(); mysql_close( db ); mysql_thread_end(); } //////////////////////////////////////// void getAllOptions( std::vector< std::tuple<uint32_t, uint32_t, std::string> > &options ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query( "SELECT ip_addr_from, ip_addr_to, options FROM dhcp_options ORDER BY ip_addr_from" ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( std::string( "Error storing result from mysql: " ) + mysql_error( db ) ); MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { unsigned long *lengths = mysql_fetch_lengths( result ); options.emplace_back( htonl( std::stoul( std::string( row[0], lengths[0] ) ) ), htonl( std::stoul( std::string( row[1], lengths[1] ) ) ), std::string( row[2], lengths[2] ) ); } } //////////////////////////////////////// std::vector<uint32_t> getIPAddresses( const uint8_t *hwaddr, bool avail ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query; if ( avail ) { query = format ( "SELECT ip_addr FROM dhcp_host " "WHERE ( mac_addr=x'{0,B16,f0,w2}' OR mac_addr=x'000000000000' ) " "AND ip_addr NOT IN ( SELECT ip_addr FROM dhcp_lease WHERE mac_addr <> x'{0,B16,f0,w2} AND expiration > NOW()' ) " "ORDER BY mac_addr DESC, dhcp_host.ip_addr ASC", as_hex<uint8_t>( hwaddr, 6 ) ); } else { query = format ( "SELECT ip_addr FROM dhcp_host " "WHERE mac_addr=x'{0,B16,f0,w2}' OR mac_addr=x'000000000000' " "ORDER BY mac_addr DESC, dhcp_host.ip_addr ASC", as_hex<uint8_t>( hwaddr, 6 ) ); } if ( mysql_query( db, query.c_str() ) != 0 ) error( format( "Error querying mysql: {0}", mysql_error( db ) ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( format( "Error storing result from mysql: {0}", mysql_error( db ) ) ); std::vector<uint32_t> ret; MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { if ( row != NULL && row[0] ) ret.push_back( htonl( atoi( row[0] ) ) ); } return ret; } //////////////////////////////////////// void getOptions( uint32_t ip, std::vector<std::string> &options ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "SELECT options FROM dhcp_options WHERE ( {0} >= ip_addr_from AND {0} <= ip_addr_to )", ntohl( ip ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); MYSQL_RES *result = mysql_store_result( db ); auto freeres = make_guard( [=](){ mysql_free_result( result ); } ); if ( result == NULL ) error( std::string( "Error storing result from mysql: " ) + mysql_error( db ) ); MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { unsigned long *lengths = mysql_fetch_lengths( result ); options.push_back( std::string( row[0], lengths[0] ) ); } } //////////////////////////////////////// void addHost( uint32_t ip, const uint8_t *mac ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "INSERT INTO dhcp_host ( ip_addr, mac_addr )" "VALUES( {0}, x'{1,B16,f0,w2}' )", ntohl( ip ), as_hex<uint8_t>( mac, 6 ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void removeHost( uint32_t ip ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_host WHERE ip_addr = {0}", ntohl( ip ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void addOption( uint32_t ip1, uint32_t ip2, const std::string &opt, bool replace ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query; if ( replace ) { query = format( "UPDATE dhcp_options " "SET options=x'{2,B16,f0,w2}' WHERE ( ip_addr_from = {0} AND ip_addr_to = {1} AND options LIKE x'{3,B16,f0,w2}25' )", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ), uint32_t( uint8_t( opt[0] ) ) ); } else { query = format( "INSERT INTO dhcp_options ( ip_addr_from, ip_addr_to, options )" "VALUES( {0}, {1}, x'{2,B16,f0,w2}' )", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ) ); } if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// void removeOption( uint32_t ip1, uint32_t ip2, const std::string &opt ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_options WHERE ip_addr_from={0} AND ip_addr_to={1} AND options=x'{2,B16,f0,w2}'", ntohl( ip1 ), ntohl( ip2 ), as_hex<char>( opt ) ); if ( mysql_query( db, query.c_str() ) != 0 ) error( std::string( "Error querying mysql: " ) + mysql_error( db ) ); } //////////////////////////////////////// bool acquireLease( uint32_t ip, const uint8_t *hwaddr, uint32_t time ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "INSERT IGNORE INTO dhcp_lease ( ip_addr, mac_addr, expiration ) " "VALUES( {0}, x'{1,B16,f0,w2}', 0 )", ntohl( ip ), as_hex<uint8_t>(hwaddr,6), time ); if ( mysql_query( db, query.c_str() ) != 0 ) { syslog( LOG_ERR, "Acquire lease: %s", mysql_error( db ) ); return false; } query = format( "UPDATE dhcp_lease " "SET expiration=TIMESTAMPADD( SECOND, {2}, NOW() )," "SET mac_addr=x'{1,B16,f0,w2}' " "WHERE ip_addr = {0} AND ( mac_addr = x'{1,B16,f0,w2}' OR expiration <= NOW() )", ntohl( ip ), as_hex<uint8_t>(hwaddr,6), time ); if ( mysql_query( db, query.c_str() ) != 0 ) { syslog( LOG_ERR, "Lease expiration: %s", mysql_error( db ) ); return false; } int affected = mysql_affected_rows( db ); if ( affected != 1 ) { syslog( LOG_DEBUG, "%s", query.c_str() ); syslog( LOG_ERR, "Lease expiration (%d): ip is already assigned", affected ); return false; } syslog( LOG_ERR, "Acquired lease: %u", time ); return true; } //////////////////////////////////////// bool releaseLease( uint32_t ip, const uint8_t *hwaddr ) { std::unique_lock<std::mutex> lock( db_mutex ); MYSQL *db = dbs[std::this_thread::get_id()]; lock.unlock(); std::string query = format( "DELETE FROM dhcp_lease " "WHERE ip_addr = {0} AND mac_addr = x'{1,B16,f0,w2}'", ntohl( ip ), as_hex<uint8_t>(hwaddr) ); if ( mysql_query( db, query.c_str() ) != 0 ) return false; if ( mysql_affected_rows( db ) < 1 ) return false; return true; } //////////////////////////////////////// <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "WrapHelper.h" #include "../player/BoostPython.h" #include "../graphics/Bitmap.h" #include "../base/Point.h" #include <vector> #include <sstream> using namespace boost::python; using namespace std; using namespace avg; namespace DPointHelper { int len(const DPoint&) { return 2; } double getItem(const DPoint& pt, int i) { switch(i) { case 0: return pt.x; case 1: return pt.y; default: throw std::range_error("Index out of range for Point2D. Must be 0 or 1."); } } string str(const DPoint& pt) { stringstream st; st << "(" << pt.x << "," << pt.y << ")"; return st.str(); } } void export_bitmap() { from_python_sequence<vector<double>, variable_capacity_policy>(); class_<DPoint>("Point2D", "A point in 2D space. Supports arithmetic operations on vectors.", no_init) .def(init<>()) .def(init<double, double>()) .def(init<vector<double> >()) .def(init<const DPoint&>()) .def("__len__", &DPointHelper::len) .def("__getitem__", &DPointHelper::getItem) .def("__str__", &DPointHelper::str) .def("normalize", &DPoint::normalize, "normalize()\n" "Normalizes the point so it's angle stays the same but the norm is one.") .def("getNorm", &DPoint::getNorm, "getNorm() -> norm\n" "Returns the euclidian norm of the point, that is sqrt(x*x+y*y).") .def(self == self) .def(self != self) .def(-self) .def(self + self) .def(self - self) .def(self - self) .def(float() * self) .def(self * float()) .def(self / float()) ; enum_<PixelFormat>("pixelformat") .value("B5G6R5", B5G6R5) .value("B8G8R8", B8G8R8) .value("B8G8R8A8", B8G8R8A8) .value("B8G8R8X8", B8G8R8X8) .value("A8B8G8R8", A8B8G8R8) .value("X8B8G8R8", X8B8G8R8) .value("R5G6B5", R5G6B5) .value("R8G8B8", R8G8B8) .value("R8G8B8A8", R8G8B8A8) .value("R8G8B8X8", R8G8B8X8) .value("A8R8G8B8", A8R8G8B8) .value("X8R8G8B8", X8R8G8B8) .value("I8", I8) .value("YCbCr422", YCbCr422) .export_values(); class_<Bitmap>("Bitmap", "Class representing a rectangular set of pixels. Bitmaps can be obtained\n" "from any RasterNode. For nodes of type Image, the current bitmap can be\n" "set as well.", no_init) .def(init<IntPoint, PixelFormat, std::string>()) .def(init<Bitmap>()) .def(init<std::string>()) .def("save", &Bitmap::save, "save(filename)\n" "Writes the image to a file. File format is determined using the\n" "extension. Any file format specified by ImageMagick \n" "(U{http://www.imagemagick.org}) can be used.") .def("getSize", &Bitmap::getSize, "getSize()\n\n" "Returns the size of the image in pixels.") .def("getFormat", &Bitmap::getPixelFormat, "getFormat()\n" "Returns the layout of the pixels in the bitmap.\n" "Possible return values are B5G6R5, B8G8R8, B8G8R8A8, B8G8R8X8,\n" "A8B8G8R8, X8B8G8R8, R5G6B5, R8G8B8, R8G8B8A8, R8G8B8X8, A8R8G8B8,\n" "X8R8G8B8, I8 and YCbCr422.") .def("getPixels", &Bitmap::getPixelsAsString, "getPixels()\n" "Returns the raw pixel data in the bitmap as a python string. This\n" "method can be used to interface to the python imaging library PIL\n" "(U{http://www.pythonware.com/products/pil/}).") .def("setPixels", &Bitmap::setPixelsFromString, "setPixels(pixels)\n\n" "Changes the raw pixel data in the bitmap. Doesn't change dimensions \n" "or pixel format. Can be used to interface to the python imaging\n" "library PIL (U{http://www.pythonware.com/products/pil/}).\n" "@param pixels: Image data as a python string.") .def("subtract", &Bitmap::subtract, return_value_policy<manage_new_object>(), "subtract(otherbitmap) -> bmp\n") .def("getAvg", &Bitmap::getAvg) .def("getStdDev", &Bitmap::getStdDev) .def("getName", &Bitmap::getName, return_value_policy<copy_const_reference>(), "getName() -> string\n\n") ; } <commit_msg>Point2D: throw out_of_range instead of range_error (so boost can translate it to an IndexError instead of RuntimeError<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "WrapHelper.h" #include "../player/BoostPython.h" #include "../graphics/Bitmap.h" #include "../base/Point.h" #include <vector> #include <sstream> using namespace boost::python; using namespace std; using namespace avg; namespace DPointHelper { int len(const DPoint&) { return 2; } double getItem(const DPoint& pt, int i) { switch(i) { case 0: return pt.x; case 1: return pt.y; default: throw std::out_of_range("Index out of range for Point2D. Must be 0 or 1."); } } string str(const DPoint& pt) { stringstream st; st << "(" << pt.x << "," << pt.y << ")"; return st.str(); } } void export_bitmap() { from_python_sequence<vector<double>, variable_capacity_policy>(); class_<DPoint>("Point2D", "A point in 2D space. Supports arithmetic operations on vectors.", no_init) .def(init<>()) .def(init<double, double>()) .def(init<vector<double> >()) .def(init<const DPoint&>()) .def("__len__", &DPointHelper::len) .def("__getitem__", &DPointHelper::getItem) .def("__str__", &DPointHelper::str) .def("normalize", &DPoint::normalize, "normalize()\n" "Normalizes the point so it's angle stays the same but the norm is one.") .def("getNorm", &DPoint::getNorm, "getNorm() -> norm\n" "Returns the euclidian norm of the point, that is sqrt(x*x+y*y).") .def(self == self) .def(self != self) .def(-self) .def(self + self) .def(self - self) .def(self - self) .def(float() * self) .def(self * float()) .def(self / float()) ; enum_<PixelFormat>("pixelformat") .value("B5G6R5", B5G6R5) .value("B8G8R8", B8G8R8) .value("B8G8R8A8", B8G8R8A8) .value("B8G8R8X8", B8G8R8X8) .value("A8B8G8R8", A8B8G8R8) .value("X8B8G8R8", X8B8G8R8) .value("R5G6B5", R5G6B5) .value("R8G8B8", R8G8B8) .value("R8G8B8A8", R8G8B8A8) .value("R8G8B8X8", R8G8B8X8) .value("A8R8G8B8", A8R8G8B8) .value("X8R8G8B8", X8R8G8B8) .value("I8", I8) .value("YCbCr422", YCbCr422) .export_values(); class_<Bitmap>("Bitmap", "Class representing a rectangular set of pixels. Bitmaps can be obtained\n" "from any RasterNode. For nodes of type Image, the current bitmap can be\n" "set as well.", no_init) .def(init<IntPoint, PixelFormat, std::string>()) .def(init<Bitmap>()) .def(init<std::string>()) .def("save", &Bitmap::save, "save(filename)\n" "Writes the image to a file. File format is determined using the\n" "extension. Any file format specified by ImageMagick \n" "(U{http://www.imagemagick.org}) can be used.") .def("getSize", &Bitmap::getSize, "getSize()\n\n" "Returns the size of the image in pixels.") .def("getFormat", &Bitmap::getPixelFormat, "getFormat()\n" "Returns the layout of the pixels in the bitmap.\n" "Possible return values are B5G6R5, B8G8R8, B8G8R8A8, B8G8R8X8,\n" "A8B8G8R8, X8B8G8R8, R5G6B5, R8G8B8, R8G8B8A8, R8G8B8X8, A8R8G8B8,\n" "X8R8G8B8, I8 and YCbCr422.") .def("getPixels", &Bitmap::getPixelsAsString, "getPixels()\n" "Returns the raw pixel data in the bitmap as a python string. This\n" "method can be used to interface to the python imaging library PIL\n" "(U{http://www.pythonware.com/products/pil/}).") .def("setPixels", &Bitmap::setPixelsFromString, "setPixels(pixels)\n\n" "Changes the raw pixel data in the bitmap. Doesn't change dimensions \n" "or pixel format. Can be used to interface to the python imaging\n" "library PIL (U{http://www.pythonware.com/products/pil/}).\n" "@param pixels: Image data as a python string.") .def("subtract", &Bitmap::subtract, return_value_policy<manage_new_object>(), "subtract(otherbitmap) -> bmp\n") .def("getAvg", &Bitmap::getAvg) .def("getStdDev", &Bitmap::getStdDev) .def("getName", &Bitmap::getName, return_value_policy<copy_const_reference>(), "getName() -> string\n\n") ; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "vbucket.hh" #include "ep_engine.h" #include "ep.hh" #include "backfill.hh" static bool isMemoryUsageTooHigh(EPStats &stats) { double memoryUsed = static_cast<double>(stats.getTotalMemoryUsed()); double maxSize = static_cast<double>(stats.getMaxDataSize()); return memoryUsed > (maxSize * BACKFILL_MEM_THRESHOLD); } /** * Callback class used to process an item backfilled from disk and push it into * the corresponding TAP queue. */ class BackfillDiskCallback : public Callback<GetValue> { public: BackfillDiskCallback(hrtime_t token, const std::string &n, TapConnMap &tcm, EventuallyPersistentEngine* e) : connToken(token), tapConnName(n), connMap(tcm), engine(e) { assert(engine); } void callback(GetValue &val); private: hrtime_t connToken; const std::string tapConnName; TapConnMap &connMap; EventuallyPersistentEngine *engine; }; void BackfillDiskCallback::callback(GetValue &gv) { assert(gv.getValue()); CompletedBGFetchTapOperation tapop(connToken, gv.getValue()->getVBucketId(), true); // if the tap connection is closed, then free an Item instance if (!connMap.performTapOp(tapConnName, tapop, gv.getValue())) { delete gv.getValue(); } } bool BackfillDiskLoad::callback(Dispatcher &d, TaskId t) { if (isMemoryUsageTooHigh(engine->getEpStats())) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "VBucket %d backfill task from disk is temporarily suspended " "because the current memory usage is too high.\n", vbucket); d.snooze(t, 1); return true; } if (connMap.checkConnectivity(name) && !engine->getEpStore()->isFlushAllScheduled()) { shared_ptr<Callback<GetValue> > backfill_cb(new BackfillDiskCallback(connToken, name, connMap, engine)); if (backfillType == ALL_MUTATIONS) { store->dump(vbucket, backfill_cb); } else if (store->getStorageProperties().hasPersistedDeletions() && backfillType == DELETIONS_ONLY) { store->dumpDeleted(vbucket, backfill_cb); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Underlying KVStore doesn't support this kind of backfill.\n"); abort(); } } getLogger()->log(EXTENSION_LOG_INFO, NULL, "VBucket %d backfill task from disk is completed.\n", vbucket); // Should decr the disk backfill counter regardless of the connectivity status CompleteDiskBackfillTapOperation op; connMap.performTapOp(name, op, static_cast<void*>(NULL)); return false; } std::string BackfillDiskLoad::description() { std::stringstream rv; rv << "Loading TAP backfill from disk for vb " << vbucket; return rv.str(); } bool BackFillVisitor::visitBucket(RCPtr<VBucket> &vb) { apply(); if (vBucketFilter(vb->getId())) { // When the backfill is scheduled for a given vbucket, set the TAP cursor to // the beginning of the open checkpoint. engine->tapConnMap->SetCursorToOpenCheckpoint(name, vb->getId()); VBucketVisitor::visitBucket(vb); double num_items = static_cast<double>(vb->ht.getNumItems()); double num_non_resident = static_cast<double>(vb->ht.getNumNonResidentItems()); size_t num_backfill_items = 0; if (num_items == 0) { return false; } double resident_threshold = engine->getTapConfig().getBackfillResidentThreshold(); residentRatioBelowThreshold = ((num_items - num_non_resident) / num_items) < resident_threshold ? true : false; if (efficientVBDump && residentRatioBelowThreshold) { // disk backfill for persisted items + memory backfill for resident items num_backfill_items = (vb->opsCreate - vb->opsDelete) + static_cast<size_t>(num_items - num_non_resident); vbuckets[vb->getId()] = ALL_MUTATIONS; ScheduleDiskBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); } else { if (engine->epstore->getStorageProperties().hasPersistedDeletions()) { vbuckets[vb->getId()] = DELETIONS_ONLY; ScheduleDiskBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); } num_backfill_items = static_cast<size_t>(num_items); } engine->tapConnMap->incrBackfillRemaining(name, num_backfill_items); return true; } return false; } void BackFillVisitor::visit(StoredValue *v) { // If efficient VBdump is supported and an item is not resident, // skip the item as it will be fetched by the disk backfill. if (efficientVBDump && residentRatioBelowThreshold && !v->isResident()) { return; } queued_item qi(new QueuedItem(v->getKey(), currentBucket->getId(), queue_op_set, v->getId())); queue->push_back(qi); } void BackFillVisitor::apply(void) { // If efficient VBdump is supported, schedule all the disk backfill tasks. if (efficientVBDump) { std::map<uint16_t, backfill_t>::iterator it = vbuckets.begin(); for (; it != vbuckets.end(); it++) { Dispatcher *d(engine->epstore->getTapDispatcher()); KVStore *underlying(engine->epstore->getTapUnderlying()); assert(d); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Schedule a full backfill from disk for vbucket %d.\n", it->first); shared_ptr<DispatcherCallback> cb(new BackfillDiskLoad(name, engine, *engine->tapConnMap, underlying, it->first, it->second, connToken)); d->schedule(cb, NULL, Priority::TapBgFetcherPriority); } vbuckets.clear(); } setEvents(); } void BackFillVisitor::setEvents() { if (checkValidity()) { if (!queue->empty()) { engine->tapConnMap->setEvents(name, queue); } } } bool BackFillVisitor::pauseVisitor() { bool pause(true); ssize_t theSize(engine->tapConnMap->backfillQueueDepth(name)); if (!checkValidity() || theSize < 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "TapProducer %s went away. Stopping backfill.\n", name.c_str()); valid = false; return false; } ssize_t maxBackfillSize = engine->getTapConfig().getBackfillBacklogLimit(); pause = theSize > maxBackfillSize; if (pause) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Tap queue depth is too big for %s!!! ", "Pausing backfill temporarily...\n", name.c_str()); } return pause; } void BackFillVisitor::complete() { apply(); CompleteBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Backfill dispatcher task for TapProducer %s is completed.\n", name.c_str()); } bool BackFillVisitor::checkValidity() { if (valid) { valid = engine->tapConnMap->checkConnectivity(name); if (!valid) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Backfilling connectivity for %s went invalid. " "Stopping backfill.\n", name.c_str()); } } return valid; } bool BackfillTask::callback(Dispatcher &d, TaskId t) { (void) t; epstore->visit(bfv, "Backfill task", &d, Priority::BackfillTaskPriority, true, 1); return false; } <commit_msg>MB-100 Don't backfill temp items into the TAP stream<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "vbucket.hh" #include "ep_engine.h" #include "ep.hh" #include "backfill.hh" static bool isMemoryUsageTooHigh(EPStats &stats) { double memoryUsed = static_cast<double>(stats.getTotalMemoryUsed()); double maxSize = static_cast<double>(stats.getMaxDataSize()); return memoryUsed > (maxSize * BACKFILL_MEM_THRESHOLD); } /** * Callback class used to process an item backfilled from disk and push it into * the corresponding TAP queue. */ class BackfillDiskCallback : public Callback<GetValue> { public: BackfillDiskCallback(hrtime_t token, const std::string &n, TapConnMap &tcm, EventuallyPersistentEngine* e) : connToken(token), tapConnName(n), connMap(tcm), engine(e) { assert(engine); } void callback(GetValue &val); private: hrtime_t connToken; const std::string tapConnName; TapConnMap &connMap; EventuallyPersistentEngine *engine; }; void BackfillDiskCallback::callback(GetValue &gv) { assert(gv.getValue()); CompletedBGFetchTapOperation tapop(connToken, gv.getValue()->getVBucketId(), true); // if the tap connection is closed, then free an Item instance if (!connMap.performTapOp(tapConnName, tapop, gv.getValue())) { delete gv.getValue(); } } bool BackfillDiskLoad::callback(Dispatcher &d, TaskId t) { if (isMemoryUsageTooHigh(engine->getEpStats())) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "VBucket %d backfill task from disk is temporarily suspended " "because the current memory usage is too high.\n", vbucket); d.snooze(t, 1); return true; } if (connMap.checkConnectivity(name) && !engine->getEpStore()->isFlushAllScheduled()) { shared_ptr<Callback<GetValue> > backfill_cb(new BackfillDiskCallback(connToken, name, connMap, engine)); if (backfillType == ALL_MUTATIONS) { store->dump(vbucket, backfill_cb); } else if (store->getStorageProperties().hasPersistedDeletions() && backfillType == DELETIONS_ONLY) { store->dumpDeleted(vbucket, backfill_cb); } else { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Underlying KVStore doesn't support this kind of backfill.\n"); abort(); } } getLogger()->log(EXTENSION_LOG_INFO, NULL, "VBucket %d backfill task from disk is completed.\n", vbucket); // Should decr the disk backfill counter regardless of the connectivity status CompleteDiskBackfillTapOperation op; connMap.performTapOp(name, op, static_cast<void*>(NULL)); return false; } std::string BackfillDiskLoad::description() { std::stringstream rv; rv << "Loading TAP backfill from disk for vb " << vbucket; return rv.str(); } bool BackFillVisitor::visitBucket(RCPtr<VBucket> &vb) { apply(); if (vBucketFilter(vb->getId())) { // When the backfill is scheduled for a given vbucket, set the TAP cursor to // the beginning of the open checkpoint. engine->tapConnMap->SetCursorToOpenCheckpoint(name, vb->getId()); VBucketVisitor::visitBucket(vb); double num_items = static_cast<double>(vb->ht.getNumItems()); double num_non_resident = static_cast<double>(vb->ht.getNumNonResidentItems()); size_t num_backfill_items = 0; if (num_items == 0) { return false; } double resident_threshold = engine->getTapConfig().getBackfillResidentThreshold(); residentRatioBelowThreshold = ((num_items - num_non_resident) / num_items) < resident_threshold ? true : false; if (efficientVBDump && residentRatioBelowThreshold) { // disk backfill for persisted items + memory backfill for resident items num_backfill_items = (vb->opsCreate - vb->opsDelete) + static_cast<size_t>(num_items - num_non_resident); vbuckets[vb->getId()] = ALL_MUTATIONS; ScheduleDiskBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); } else { if (engine->epstore->getStorageProperties().hasPersistedDeletions()) { vbuckets[vb->getId()] = DELETIONS_ONLY; ScheduleDiskBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); } num_backfill_items = static_cast<size_t>(num_items); } engine->tapConnMap->incrBackfillRemaining(name, num_backfill_items); return true; } return false; } void BackFillVisitor::visit(StoredValue *v) { // If efficient VBdump is supported and an item is not resident, // skip the item as it will be fetched by the disk backfill. if (efficientVBDump && residentRatioBelowThreshold && !v->isResident()) { return; } if (v->isTempItem()) { return; } queued_item qi(new QueuedItem(v->getKey(), currentBucket->getId(), queue_op_set, v->getId())); queue->push_back(qi); } void BackFillVisitor::apply(void) { // If efficient VBdump is supported, schedule all the disk backfill tasks. if (efficientVBDump) { std::map<uint16_t, backfill_t>::iterator it = vbuckets.begin(); for (; it != vbuckets.end(); it++) { Dispatcher *d(engine->epstore->getTapDispatcher()); KVStore *underlying(engine->epstore->getTapUnderlying()); assert(d); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Schedule a full backfill from disk for vbucket %d.\n", it->first); shared_ptr<DispatcherCallback> cb(new BackfillDiskLoad(name, engine, *engine->tapConnMap, underlying, it->first, it->second, connToken)); d->schedule(cb, NULL, Priority::TapBgFetcherPriority); } vbuckets.clear(); } setEvents(); } void BackFillVisitor::setEvents() { if (checkValidity()) { if (!queue->empty()) { engine->tapConnMap->setEvents(name, queue); } } } bool BackFillVisitor::pauseVisitor() { bool pause(true); ssize_t theSize(engine->tapConnMap->backfillQueueDepth(name)); if (!checkValidity() || theSize < 0) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "TapProducer %s went away. Stopping backfill.\n", name.c_str()); valid = false; return false; } ssize_t maxBackfillSize = engine->getTapConfig().getBackfillBacklogLimit(); pause = theSize > maxBackfillSize; if (pause) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Tap queue depth is too big for %s!!! ", "Pausing backfill temporarily...\n", name.c_str()); } return pause; } void BackFillVisitor::complete() { apply(); CompleteBackfillTapOperation tapop; engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL)); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Backfill dispatcher task for TapProducer %s is completed.\n", name.c_str()); } bool BackFillVisitor::checkValidity() { if (valid) { valid = engine->tapConnMap->checkConnectivity(name); if (!valid) { getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Backfilling connectivity for %s went invalid. " "Stopping backfill.\n", name.c_str()); } } return valid; } bool BackfillTask::callback(Dispatcher &d, TaskId t) { (void) t; epstore->visit(bfv, "Backfill task", &d, Priority::BackfillTaskPriority, true, 1); return false; } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <[email protected]> * based on sample.cpp sample module code * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); bool inChan(const CString& Chan); private: CString LogPath; }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command"); PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { if (sCommand.Token(0).CaseCmp("help") == 0) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Help"); return; } else if (sCommand.Token(0).CaseCmp("logpath") == 0) { LogPath = sCommand.Token(1, true); if(LogPath.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } CString Path = LogPath.substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { // store lines from file into Lines Lines.push_back(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } bool isInChan = CBacklogMod::inChan(Channel); // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { if(isInChan) { CString Line = *it; size_t FirstSpace = Line.find_first_of(' '); size_t Len = Line.find_first_of(' ', FirstSpace + 1) - FirstSpace; CString Nick = Line.substr(FirstSpace + 2, Len - 3); m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstSpace) + Line.substr(FirstSpace + Len, Line.npos), GetClient()); } else { PutModule(*it); } } if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); } } bool CBacklogMod::inChan(const CString& Chan) { const std::vector <CChan*>& vChans (m_pNetwork->GetChans()); for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) { CChan *curChan = *it; if(Chan.StrCmp(curChan->GetName()) == 0) { return true; } } return false; } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <commit_msg>messages when starting/stopping playback<commit_after>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <[email protected]> * based on sample.cpp sample module code * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); bool inChan(const CString& Chan); private: CString LogPath; }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command"); PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { if (sCommand.Token(0).CaseCmp("help") == 0) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Help"); return; } else if (sCommand.Token(0).CaseCmp("logpath") == 0) { LogPath = sCommand.Token(1, true); if(LogPath.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } CString Path = LogPath.substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { // store lines from file into Lines Lines.push_back(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } bool isInChan = CBacklogMod::inChan(Channel); if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); return; } else if (isInChan) { m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Backlog playback...", GetClient()); } else { PutModule("*** Backlog playback..."); } // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { if(isInChan) { CString Line = *it; size_t FirstSpace = Line.find_first_of(' '); size_t Len = Line.find_first_of(' ', FirstSpace + 1) - FirstSpace; CString Nick = Line.substr(FirstSpace + 2, Len - 3); m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstSpace) + Line.substr(FirstSpace + Len, Line.npos), GetClient()); } else { PutModule(*it); } } if (isInChan) { m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Playback complete.", GetClient()); } else { PutModule("*** Playback complete."); } } bool CBacklogMod::inChan(const CString& Chan) { const std::vector <CChan*>& vChans (m_pNetwork->GetChans()); for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) { CChan *curChan = *it; if(Chan.StrCmp(curChan->GetName()) == 0) { return true; } } return false; } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * Licensed under the MIT license (see LICENSE). */ #include <stdlib.h> #include <assert.h> #include "barchart.h" #include "canvas.h" #include "domain.h" #include "rendertarget.h" /** * todo: * - labels inside/outside */ namespace fnordmetric { namespace ui { BarChart::BarChart( Canvas* canvas, kBarChartOrientation orientation /* = O_HORIZONTAL */, NumericalDomain* y_domain /* = nullptr */) : canvas_(canvas), orientation_(orientation), y_domain_(y_domain), num_series_(0) {} void BarChart::addSeries(Series2D<std::string, double>* series) { for (const auto& point : series->getData()) { const auto& x_val = std::get<0>(point); const auto& y_val = std::get<1>(point); BarData* bar_data = nullptr; for (auto& candidate : data_) { if (candidate.x == x_val) { bar_data = &candidate; } } if (bar_data == nullptr) { data_.emplace_back(); bar_data = &data_.back(); bar_data->x = x_val; } bar_data->ys.emplace_back(0, y_val); //scaleValue(&y_val, &y_domain)); } num_series_++; } AxisDefinition* BarChart::addAxis(AxisDefinition::kPosition position) { switch (position) { case AxisDefinition::TOP: switch (orientation_) { case O_VERTICAL: return newLabelAxis(position); break; case O_HORIZONTAL: return canvas_->addAxis(position, getValueDomain()); break; } break; case AxisDefinition::RIGHT: switch (orientation_) { case O_VERTICAL: return canvas_->addAxis(position, getValueDomain()); break; case O_HORIZONTAL: return newLabelAxis(position); break; } break; case AxisDefinition::BOTTOM: switch (orientation_) { case O_VERTICAL: return newLabelAxis(position); break; case O_HORIZONTAL: return canvas_->addAxis(position, getValueDomain()); break; } break; case AxisDefinition::LEFT: switch (orientation_) { case O_VERTICAL: return canvas_->addAxis(position, getValueDomain()); break; case O_HORIZONTAL: return newLabelAxis(position); break; } break; } } void BarChart::render( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { switch (orientation_) { case O_VERTICAL: renderVerticalBars(target, width, height, padding); break; case O_HORIZONTAL: renderHorizontalBars(target, width, height, padding); break; } } void BarChart::renderVerticalBars( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { /* calculate bar width and padding */ auto padding_top = std::get<0>(*padding); auto padding_right = std::get<1>(*padding); auto padding_bottom = std::get<2>(*padding); auto padding_left = std::get<3>(*padding); auto inner_width = width - padding_right - padding_left; auto inner_height = height - padding_top - padding_bottom; auto bar_width = (inner_width / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (inner_width / data_.size()) * (kBarPadding * 0.5f); bar_width -= bar_padding / data_.size() * 2; /* draw the bars */ std::vector<double> x_ticks = {0.0f}; auto draw_x = padding_left + bar_padding; auto draw_width = bar_width; auto y_domain = getValueDomain(); for (const auto& bar : data_) { draw_x += bar_padding; /* single series */ if (num_series_ == 1) { auto y_min = y_domain->scale(bar.ys[0].first); auto y_max = y_domain->scale(bar.ys[0].second); auto draw_y = padding_top + ((1.0f - y_max) * inner_height); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height; target->drawRect(draw_x, draw_y, draw_width, draw_height, "color0"); } /* multi series stacked */ /*else if (stacked_) { double y_min = 0.0f; double y_max = 0.0f; for (int i = 0; i < bar.ys.size(); i++) { auto& y_val = bar.ys[i]; y_max += y_val.second - y_val.first; auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_; target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i)); y_min += y_val.second - y_val.first; } }*/ /* multi series unstacked */ else { auto draw_x_multi = draw_x; auto draw_width_multi = draw_width / (double) num_series_; for (int i = 0; i < bar.ys.size(); i++) { auto y_min = y_domain->scale(bar.ys[i].first); auto y_max = y_domain->scale(bar.ys[i].second); auto draw_y = padding_top + ((1.0f - y_max) * inner_height); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height; target->drawRect( draw_x_multi, draw_y, draw_width_multi * (1.0f - kBarPadding * 0.5f), draw_height, "color0"); draw_x_multi += (draw_width_multi * (1.0f + kBarPadding * 0.5f)); } } draw_x += bar_width + bar_padding; } } void BarChart::renderHorizontalBars( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { /* calculate bar width and padding */ auto padding_top = std::get<0>(*padding); auto padding_right = std::get<1>(*padding); auto padding_bottom = std::get<2>(*padding); auto padding_left = std::get<3>(*padding); auto inner_width = width - padding_right - padding_left; auto inner_height = height - padding_top - padding_bottom; auto bar_height = (inner_height / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (inner_height / data_.size()) * (kBarPadding * 0.5f); bar_height -= bar_padding / data_.size() * 2; /* draw the bars */ std::vector<double> y_ticks = {0.0f}; std::vector<std::pair<double, std::string>> y_labels; auto draw_y = padding_top + bar_padding; auto draw_height = bar_height; auto y_domain = getValueDomain(); for (const auto& bar : data_) { draw_y += bar_padding; /* single series */ if (num_series_ == 1) { auto& y_val = bar.ys[0]; auto y_min = y_domain->scale(bar.ys[0].first); auto y_max = y_domain->scale(bar.ys[0].second); auto draw_x = padding_left + y_min * inner_width; auto draw_width = (y_max - y_min) * inner_width; target->drawRect(draw_x, draw_y, draw_width, draw_height, "color0"); } /* multi series stacked */ /*else if (stacked_) { double y_min = 0.0f; double y_max = 0.0f; for (int i = 0; i < bar.ys.size(); i++) { auto& y_val = bar.ys[i]; y_max += y_val.second - y_val.first; auto draw_x = padding_left_ + y_min * inner_width_; auto draw_width = (y_max - y_min) * inner_width_; target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i)); y_min += y_val.second - y_val.first; } }*/ /* multi series unstacked */ else { /* auto num_series = getSeries().size(); auto draw_y_multi = draw_y; auto draw_height_multi = draw_height / num_series; for (int i = 0; i < bar.ys.size(); i++) { auto& y_val = bar.ys[i]; auto y_min = y_val.first; auto y_max = y_val.second; auto draw_x = padding_left_ + y_min * inner_width_; auto draw_width = (y_max - y_min) * inner_width_; target->drawRect( draw_x, draw_y_multi, draw_width, draw_height_multi * (1.0f - kBarPadding * 0.5f), colorName(i)); draw_y_multi += (draw_height_multi * (1.0f + kBarPadding * 0.5f)); } */ } draw_y += bar_height + bar_padding; } } NumericalDomain* BarChart::getValueDomain() const { if (y_domain_ != nullptr) { return y_domain_; } if (y_domain_auto_.get() == nullptr) { y_domain_auto_.reset(newValueDomain()); } return y_domain_auto_.get(); } NumericalDomain* BarChart::newValueDomain() const { /* calculate our domain*/ if (stacked_) { /* int num_bars = 0; for (const auto& series : getSeries()) { if (series->getData().size() > num_bars) { num_bars = series->getData().size(); } } double y_domain_max = 0.0f; for (int i = 0; i < num_bars; ++i) { int sum = 0; for (const auto& series : getSeries()) { if (i < series->getData().size()) { sum += series->getData()[i][1].getFloat(); } } if (sum > y_domain_max) { y_domain_max = sum; } } y_domain = Domain(0, y_domain_max, false); */ } else { double y_domain_min = 0.0f; double y_domain_max = 0.0f; for (const auto& group : data_) { for (const auto& y : group.ys) { if (y.first < y_domain_min) { y_domain_min = y.first; } if (y.first > y_domain_max) { y_domain_max = y.first; } if (y.second < y_domain_min) { y_domain_min = y.second; } if (y.second > y_domain_max) { y_domain_max = y.second; } } } if (y_domain_max > 0) { y_domain_max *= 1.1; } return new NumericalDomain(y_domain_min, y_domain_max, false); } } AxisDefinition* BarChart::newLabelAxis(AxisDefinition::kPosition position) const { auto axis = canvas_->addAxis(position); axis->addTick(0.0f); auto bar_width = (1.0 / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (1.0 / data_.size()) * (kBarPadding * 0.5f); bar_width -= bar_padding / data_.size() * 2; auto draw_x = bar_padding; for (int i = 0; i < data_.size(); ++i) { draw_x += bar_padding; switch (orientation_) { case O_VERTICAL: axis->addLabel(draw_x + bar_width * 0.5f, data_[i].x); break; case O_HORIZONTAL: axis->addLabel( draw_x + bar_width * 0.5f, data_[data_.size() - 1 - i].x); break; } draw_x += bar_width + bar_padding; if (i < data_.size() - 1) { axis->addTick(draw_x); } } axis->addTick(1.0f); return axis; } } } <commit_msg>draw multiseries horizontal bars<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * Licensed under the MIT license (see LICENSE). */ #include <stdlib.h> #include <assert.h> #include "barchart.h" #include "canvas.h" #include "domain.h" #include "rendertarget.h" /** * todo: * - labels inside/outside */ namespace fnordmetric { namespace ui { BarChart::BarChart( Canvas* canvas, kBarChartOrientation orientation /* = O_HORIZONTAL */, NumericalDomain* y_domain /* = nullptr */) : canvas_(canvas), orientation_(orientation), y_domain_(y_domain), num_series_(0) {} void BarChart::addSeries(Series2D<std::string, double>* series) { for (const auto& point : series->getData()) { const auto& x_val = std::get<0>(point); const auto& y_val = std::get<1>(point); BarData* bar_data = nullptr; for (auto& candidate : data_) { if (candidate.x == x_val) { bar_data = &candidate; } } if (bar_data == nullptr) { data_.emplace_back(); bar_data = &data_.back(); bar_data->x = x_val; } bar_data->ys.emplace_back(0, y_val); //scaleValue(&y_val, &y_domain)); } num_series_++; } AxisDefinition* BarChart::addAxis(AxisDefinition::kPosition position) { switch (position) { case AxisDefinition::TOP: switch (orientation_) { case O_VERTICAL: return newLabelAxis(position); break; case O_HORIZONTAL: return canvas_->addAxis(position, getValueDomain()); break; } break; case AxisDefinition::RIGHT: switch (orientation_) { case O_VERTICAL: return canvas_->addAxis(position, getValueDomain()); break; case O_HORIZONTAL: return newLabelAxis(position); break; } break; case AxisDefinition::BOTTOM: switch (orientation_) { case O_VERTICAL: return newLabelAxis(position); break; case O_HORIZONTAL: return canvas_->addAxis(position, getValueDomain()); break; } break; case AxisDefinition::LEFT: switch (orientation_) { case O_VERTICAL: return canvas_->addAxis(position, getValueDomain()); break; case O_HORIZONTAL: return newLabelAxis(position); break; } break; } } void BarChart::render( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { switch (orientation_) { case O_VERTICAL: renderVerticalBars(target, width, height, padding); break; case O_HORIZONTAL: renderHorizontalBars(target, width, height, padding); break; } } void BarChart::renderVerticalBars( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { /* calculate bar width and padding */ auto padding_top = std::get<0>(*padding); auto padding_right = std::get<1>(*padding); auto padding_bottom = std::get<2>(*padding); auto padding_left = std::get<3>(*padding); auto inner_width = width - padding_right - padding_left; auto inner_height = height - padding_top - padding_bottom; auto bar_width = (inner_width / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (inner_width / data_.size()) * (kBarPadding * 0.5f); bar_width -= bar_padding / data_.size() * 2; /* draw the bars */ std::vector<double> x_ticks = {0.0f}; auto draw_x = padding_left + bar_padding; auto draw_width = bar_width; auto y_domain = getValueDomain(); for (const auto& bar : data_) { draw_x += bar_padding; /* single series */ if (num_series_ == 1) { auto y_min = y_domain->scale(bar.ys[0].first); auto y_max = y_domain->scale(bar.ys[0].second); auto draw_y = padding_top + ((1.0f - y_max) * inner_height); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height; target->drawRect(draw_x, draw_y, draw_width, draw_height, "color0"); } /* multi series stacked */ /*else if (stacked_) { double y_min = 0.0f; double y_max = 0.0f; for (int i = 0; i < bar.ys.size(); i++) { auto& y_val = bar.ys[i]; y_max += y_val.second - y_val.first; auto draw_y = padding_top_ + ((1.0f - y_max) * inner_height_); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height_; target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i)); y_min += y_val.second - y_val.first; } }*/ /* multi series unstacked */ else { auto draw_x_multi = draw_x; auto draw_width_multi = draw_width / (double) num_series_; for (int i = 0; i < bar.ys.size(); i++) { auto y_min = y_domain->scale(bar.ys[i].first); auto y_max = y_domain->scale(bar.ys[i].second); auto draw_y = padding_top + ((1.0f - y_max) * inner_height); auto draw_height = (1.0f - ((1.0f - y_max) + y_min)) * inner_height; target->drawRect( draw_x_multi, draw_y, draw_width_multi * (1.0f - kBarPadding * 0.5f), draw_height, "color0"); draw_x_multi += (draw_width_multi * (1.0f + kBarPadding * 0.5f)); } } draw_x += bar_width + bar_padding; } } void BarChart::renderHorizontalBars( RenderTarget* target, int width, int height, std::tuple<int, int, int, int>* padding) const { /* calculate bar width and padding */ auto padding_top = std::get<0>(*padding); auto padding_right = std::get<1>(*padding); auto padding_bottom = std::get<2>(*padding); auto padding_left = std::get<3>(*padding); auto inner_width = width - padding_right - padding_left; auto inner_height = height - padding_top - padding_bottom; auto bar_height = (inner_height / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (inner_height / data_.size()) * (kBarPadding * 0.5f); bar_height -= bar_padding / data_.size() * 2; /* draw the bars */ std::vector<double> y_ticks = {0.0f}; std::vector<std::pair<double, std::string>> y_labels; auto draw_y = padding_top + bar_padding; auto draw_height = bar_height; auto y_domain = getValueDomain(); for (const auto& bar : data_) { draw_y += bar_padding; /* single series */ if (num_series_ == 1) { auto& y_val = bar.ys[0]; auto y_min = y_domain->scale(bar.ys[0].first); auto y_max = y_domain->scale(bar.ys[0].second); auto draw_x = padding_left + y_min * inner_width; auto draw_width = (y_max - y_min) * inner_width; target->drawRect(draw_x, draw_y, draw_width, draw_height, "color0"); } /* multi series stacked */ /*else if (stacked_) { double y_min = 0.0f; double y_max = 0.0f; for (int i = 0; i < bar.ys.size(); i++) { auto& y_val = bar.ys[i]; y_max += y_val.second - y_val.first; auto draw_x = padding_left_ + y_min * inner_width_; auto draw_width = (y_max - y_min) * inner_width_; target->drawRect(draw_x, draw_y, draw_width, draw_height, colorName(i)); y_min += y_val.second - y_val.first; } }*/ /* multi series unstacked */ else { auto draw_y_multi = draw_y; auto draw_height_multi = draw_height / num_series_; for (int i = 0; i < bar.ys.size(); i++) { auto y_min = y_domain->scale(bar.ys[i].first); auto y_max = y_domain->scale(bar.ys[i].second); auto draw_x = padding_left + y_min * inner_width; auto draw_width = (y_max - y_min) * inner_width; target->drawRect( draw_x, draw_y_multi, draw_width, draw_height_multi * (1.0f - kBarPadding * 0.5f), "color0"); draw_y_multi += (draw_height_multi * (1.0f + kBarPadding * 0.5f)); } } draw_y += bar_height + bar_padding; } } NumericalDomain* BarChart::getValueDomain() const { if (y_domain_ != nullptr) { return y_domain_; } if (y_domain_auto_.get() == nullptr) { y_domain_auto_.reset(newValueDomain()); } return y_domain_auto_.get(); } NumericalDomain* BarChart::newValueDomain() const { /* calculate our domain*/ if (stacked_) { /* int num_bars = 0; for (const auto& series : getSeries()) { if (series->getData().size() > num_bars) { num_bars = series->getData().size(); } } double y_domain_max = 0.0f; for (int i = 0; i < num_bars; ++i) { int sum = 0; for (const auto& series : getSeries()) { if (i < series->getData().size()) { sum += series->getData()[i][1].getFloat(); } } if (sum > y_domain_max) { y_domain_max = sum; } } y_domain = Domain(0, y_domain_max, false); */ } else { double y_domain_min = 0.0f; double y_domain_max = 0.0f; for (const auto& group : data_) { for (const auto& y : group.ys) { if (y.first < y_domain_min) { y_domain_min = y.first; } if (y.first > y_domain_max) { y_domain_max = y.first; } if (y.second < y_domain_min) { y_domain_min = y.second; } if (y.second > y_domain_max) { y_domain_max = y.second; } } } if (y_domain_max > 0) { y_domain_max *= 1.1; } return new NumericalDomain(y_domain_min, y_domain_max, false); } } AxisDefinition* BarChart::newLabelAxis(AxisDefinition::kPosition position) const { auto axis = canvas_->addAxis(position); axis->addTick(0.0f); auto bar_width = (1.0 / data_.size()) * (1.0f - kBarPadding); auto bar_padding = (1.0 / data_.size()) * (kBarPadding * 0.5f); bar_width -= bar_padding / data_.size() * 2; auto draw_x = bar_padding; for (int i = 0; i < data_.size(); ++i) { draw_x += bar_padding; switch (orientation_) { case O_VERTICAL: axis->addLabel(draw_x + bar_width * 0.5f, data_[i].x); break; case O_HORIZONTAL: axis->addLabel( draw_x + bar_width * 0.5f, data_[data_.size() - 1 - i].x); break; } draw_x += bar_width + bar_padding; if (i < data_.size() - 1) { axis->addTick(draw_x); } } axis->addTick(1.0f); return axis; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2009, Thomas Jaeger <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "actiondb.h" #include "main.h" #include "win.h" #include <glibmm/i18n.h> #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/shared_ptr.hpp> #include <X11/extensions/XTest.h> BOOST_CLASS_EXPORT(StrokeSet) BOOST_CLASS_EXPORT(Action) BOOST_CLASS_EXPORT(Command) BOOST_CLASS_EXPORT(ModAction) BOOST_CLASS_EXPORT(SendKey) BOOST_CLASS_EXPORT(Scroll) BOOST_CLASS_EXPORT(Ignore) BOOST_CLASS_EXPORT(Button) BOOST_CLASS_EXPORT(Misc) template<class Archive> void Unique::serialize(Archive & ar, const unsigned int version) {} template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) {} template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & cmd; } template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & mods; } template<class Archive> void SendKey::load(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; if (version < 1) { bool xtest; ar & xtest; } compute_code(); } template<class Archive> void SendKey::save(Archive & ar, const unsigned int version) const { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; } template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Button::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & button; } template<class Archive> void Misc::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & type; } template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<std::set<RStroke> >(*this); } template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) { ar & strokes; ar & action; if (version == 0) return; ar & name; } using namespace std; void SendKey::compute_code() { if (key) code = XKeysymToKeycode(dpy, key); } void Command::run() { pid_t pid = fork(); switch (pid) { case 0: execlp("/bin/sh", "sh", "-c", cmd.c_str(), NULL); exit(1); case -1: printf(_("Error: can't execute command \"%s\": fork() failed\n"), cmd.c_str()); } } ButtonInfo Button::get_button_info() const { ButtonInfo bi; bi.button = button; bi.state = mods; return bi; } const Glib::ustring Button::get_label() const { return get_button_info().get_button_text(); } const char *Misc::types[5] = { "None", "Unminimize", "Show/Hide", "Disable (Enable)", NULL }; template<class Archive> void ActionListDiff::serialize(Archive & ar, const unsigned int version) { ar & deleted; ar & added; ar & name; ar & children; ar & app; if (version == 0) return; ar & order; } template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) { if (version >= 2) { ar & root; } if (version == 1) { std::map<int, StrokeInfo> strokes; ar & strokes; for (std::map<int, StrokeInfo>::iterator i = strokes.begin(); i != strokes.end(); ++i) root.add(i->second); } if (version == 0) { std::map<std::string, StrokeInfo> strokes; ar & strokes; for (std::map<std::string, StrokeInfo>::iterator i = strokes.begin(); i != strokes.end(); ++i) { i->second.name = i->first; root.add(i->second); } } root.fix_tree(version == 2); root.add_apps(apps); root.name = _("Default"); } template<class Archive> void ActionDB::save(Archive & ar, const unsigned int version) const { ar & root; } Source<bool> action_dummy; void update_actions() { action_dummy.set(false); } void ActionDBWatcher::init() { std::string filename = config_dir+"actions"; for (const char **v = versions; *v; v++) if (is_file(filename + *v)) { filename += *v; try { ifstream ifs(filename.c_str(), ios::binary); if (!ifs.fail()) { boost::archive::text_iarchive ia(ifs); ia >> actions; if (verbosity >= 2) printf("Loaded actions.\n"); } } catch (exception &e) { printf(_("Error: Couldn't read action database: %s.\n"), e.what()); } break; } watch(action_dummy); } void ActionDBWatcher::timeout() { std::string filename = config_dir+"actions"+versions[0]; std::string tmp = filename + ".tmp"; try { ofstream ofs(tmp.c_str()); boost::archive::text_oarchive oa(ofs); oa << (const ActionDB &)actions; if (rename(tmp.c_str(), filename.c_str())) throw std::runtime_error(_("rename() failed")); if (verbosity >= 2) printf("Saved actions.\n"); } catch (exception &e) { printf(_("Error: Couldn't save action database: %s.\n"), e.what()); if (!good_state) return; good_state = false; new ErrorDialog(Glib::ustring::compose(_( "Couldn't save %1. Your changes will be lost. " "Make sure that \"%2\" is a directory and that you have write access to it. " "You can change the configuration directory " "using the -c or --config-dir command line options."), _("actions"), config_dir)); } } RStrokeInfo ActionListDiff::get_info(Unique *id, bool *deleted, bool *stroke, bool *name, bool *action) const { if (deleted) *deleted = this->deleted.count(id); if (stroke) *stroke = false; if (name) *name = false; if (action) *action = false; RStrokeInfo si = parent ? parent->get_info(id) : RStrokeInfo(new StrokeInfo); std::map<Unique *, StrokeInfo>::const_iterator i = added.find(id); for (i = added.begin(); i != added.end(); i++) { if (i->first == id) break; } if (i == added.end()) { return si; } if (i->second.name != "") { si->name = i->second.name; if (name) *name = parent; } if (i->second.strokes.size()) { si->strokes = i->second.strokes; if (stroke) *stroke = parent; } if (i->second.action) { si->action = i->second.action; if (action) *action = parent; } return si; } boost::shared_ptr<std::map<Unique *, StrokeSet> > ActionListDiff::get_strokes() const { boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = parent ? parent->get_strokes() : boost::shared_ptr<std::map<Unique *, StrokeSet> >(new std::map<Unique *, StrokeSet>); for (std::set<Unique *>::const_iterator i = deleted.begin(); i != deleted.end(); i++) strokes->erase(*i); for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) if (i->second.strokes.size()) (*strokes)[i->first] = i->second.strokes; return strokes; } boost::shared_ptr<std::set<Unique *> > ActionListDiff::get_ids(bool include_deleted) const { boost::shared_ptr<std::set<Unique *> > ids = parent ? parent->get_ids(false) : boost::shared_ptr<std::set<Unique *> >(new std::set<Unique *>); if (!include_deleted) for (std::set<Unique *>::const_iterator i = deleted.begin(); i != deleted.end(); i++) ids->erase(*i); for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) ids->insert(i->first); return ids; } void ActionListDiff::all_strokes(std::list<RStroke> &strokes) const { for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) for (std::set<RStroke>::const_iterator j = i->second.strokes.begin(); j != i->second.strokes.end(); j++) strokes.push_back(*j); for (std::list<ActionListDiff>::const_iterator i = children.begin(); i != children.end(); i++) i->all_strokes(strokes); } RAction ActionListDiff::handle(RStroke s, Ranking &r) const { if (!s) return RAction(); r.stroke = s; r.score = -1; r.id = NULL; boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = get_strokes(); for (std::map<Unique *, StrokeSet>::const_iterator i = strokes->begin(); i!=strokes->end(); i++) { for (StrokeSet::iterator j = i->second.begin(); j!=i->second.end(); j++) { double score; bool match = Stroke::compare(s, *j, score); if (score < 0.25) continue; RStrokeInfo si = get_info(i->first); r.r.insert(pair<double, pair<std::string, RStroke> > (score, pair<std::string, RStroke>(si->name, *j))); if (score >= r.score) { r.score = score; if (match) { r.id = i->first; r.name = si->name; r.action = si->action; r.best_stroke = *j; } } } } if (!r.action && s->trivial()) { r.action = RAction(new Click); r.name = _("click (default)"); } if (r.action) { if (verbosity >= 1) printf("Executing Action %s\n", r.name.c_str()); } else { if (verbosity >= 1) printf("Couldn't find matching stroke.\n"); } return r.action; } void ActionListDiff::handle_advanced(RStroke s, std::map<guint, RAction> &as, std::map<guint, Ranking *> &rs, int b1, int b2) const { if (!s) return; boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = get_strokes(); for (std::map<Unique *, StrokeSet>::const_iterator i = strokes->begin(); i!=strokes->end(); i++) { for (StrokeSet::iterator j = i->second.begin(); j!=i->second.end(); j++) { int b = (*j)->button; if (!s->timeout && !b) continue; s->button = b; double score; bool match = Stroke::compare(s, *j, score); if (score < 0.25) continue; Ranking *r; if (b == b1) b = b2; if (rs.count(b)) { r = rs[b]; } else { r = new Ranking; rs[b] = r; r->stroke = RStroke(new Stroke(*s)); r->score = -1; r->id = NULL; } RStrokeInfo si = get_info(i->first); r->r.insert(pair<double, pair<std::string, RStroke> > (score, pair<std::string, RStroke>(si->name, *j))); if (score >= r->score) { r->score = score; if (match) { r->id = i->first; r->name = si->name; r->action = si->action; r->best_stroke = *j; as[b] = si->action; } } } } } ActionListDiff::~ActionListDiff() { if (app) actions.apps.erase(name); } ActionDB actions; <commit_msg>We don't need to document every click<commit_after>/* * Copyright (c) 2008-2009, Thomas Jaeger <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "actiondb.h" #include "main.h" #include "win.h" #include <glibmm/i18n.h> #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/shared_ptr.hpp> #include <X11/extensions/XTest.h> BOOST_CLASS_EXPORT(StrokeSet) BOOST_CLASS_EXPORT(Action) BOOST_CLASS_EXPORT(Command) BOOST_CLASS_EXPORT(ModAction) BOOST_CLASS_EXPORT(SendKey) BOOST_CLASS_EXPORT(Scroll) BOOST_CLASS_EXPORT(Ignore) BOOST_CLASS_EXPORT(Button) BOOST_CLASS_EXPORT(Misc) template<class Archive> void Unique::serialize(Archive & ar, const unsigned int version) {} template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) {} template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & cmd; } template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & mods; } template<class Archive> void SendKey::load(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; if (version < 1) { bool xtest; ar & xtest; } compute_code(); } template<class Archive> void SendKey::save(Archive & ar, const unsigned int version) const { ar & boost::serialization::base_object<ModAction>(*this); ar & key; ar & code; } template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); } template<class Archive> void Button::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<ModAction>(*this); ar & button; } template<class Archive> void Misc::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<Action>(*this); ar & type; } template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<std::set<RStroke> >(*this); } template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) { ar & strokes; ar & action; if (version == 0) return; ar & name; } using namespace std; void SendKey::compute_code() { if (key) code = XKeysymToKeycode(dpy, key); } void Command::run() { pid_t pid = fork(); switch (pid) { case 0: execlp("/bin/sh", "sh", "-c", cmd.c_str(), NULL); exit(1); case -1: printf(_("Error: can't execute command \"%s\": fork() failed\n"), cmd.c_str()); } } ButtonInfo Button::get_button_info() const { ButtonInfo bi; bi.button = button; bi.state = mods; return bi; } const Glib::ustring Button::get_label() const { return get_button_info().get_button_text(); } const char *Misc::types[5] = { "None", "Unminimize", "Show/Hide", "Disable (Enable)", NULL }; template<class Archive> void ActionListDiff::serialize(Archive & ar, const unsigned int version) { ar & deleted; ar & added; ar & name; ar & children; ar & app; if (version == 0) return; ar & order; } template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) { if (version >= 2) { ar & root; } if (version == 1) { std::map<int, StrokeInfo> strokes; ar & strokes; for (std::map<int, StrokeInfo>::iterator i = strokes.begin(); i != strokes.end(); ++i) root.add(i->second); } if (version == 0) { std::map<std::string, StrokeInfo> strokes; ar & strokes; for (std::map<std::string, StrokeInfo>::iterator i = strokes.begin(); i != strokes.end(); ++i) { i->second.name = i->first; root.add(i->second); } } root.fix_tree(version == 2); root.add_apps(apps); root.name = _("Default"); } template<class Archive> void ActionDB::save(Archive & ar, const unsigned int version) const { ar & root; } Source<bool> action_dummy; void update_actions() { action_dummy.set(false); } void ActionDBWatcher::init() { std::string filename = config_dir+"actions"; for (const char **v = versions; *v; v++) if (is_file(filename + *v)) { filename += *v; try { ifstream ifs(filename.c_str(), ios::binary); if (!ifs.fail()) { boost::archive::text_iarchive ia(ifs); ia >> actions; if (verbosity >= 2) printf("Loaded actions.\n"); } } catch (exception &e) { printf(_("Error: Couldn't read action database: %s.\n"), e.what()); } break; } watch(action_dummy); } void ActionDBWatcher::timeout() { std::string filename = config_dir+"actions"+versions[0]; std::string tmp = filename + ".tmp"; try { ofstream ofs(tmp.c_str()); boost::archive::text_oarchive oa(ofs); oa << (const ActionDB &)actions; if (rename(tmp.c_str(), filename.c_str())) throw std::runtime_error(_("rename() failed")); if (verbosity >= 2) printf("Saved actions.\n"); } catch (exception &e) { printf(_("Error: Couldn't save action database: %s.\n"), e.what()); if (!good_state) return; good_state = false; new ErrorDialog(Glib::ustring::compose(_( "Couldn't save %1. Your changes will be lost. " "Make sure that \"%2\" is a directory and that you have write access to it. " "You can change the configuration directory " "using the -c or --config-dir command line options."), _("actions"), config_dir)); } } RStrokeInfo ActionListDiff::get_info(Unique *id, bool *deleted, bool *stroke, bool *name, bool *action) const { if (deleted) *deleted = this->deleted.count(id); if (stroke) *stroke = false; if (name) *name = false; if (action) *action = false; RStrokeInfo si = parent ? parent->get_info(id) : RStrokeInfo(new StrokeInfo); std::map<Unique *, StrokeInfo>::const_iterator i = added.find(id); for (i = added.begin(); i != added.end(); i++) { if (i->first == id) break; } if (i == added.end()) { return si; } if (i->second.name != "") { si->name = i->second.name; if (name) *name = parent; } if (i->second.strokes.size()) { si->strokes = i->second.strokes; if (stroke) *stroke = parent; } if (i->second.action) { si->action = i->second.action; if (action) *action = parent; } return si; } boost::shared_ptr<std::map<Unique *, StrokeSet> > ActionListDiff::get_strokes() const { boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = parent ? parent->get_strokes() : boost::shared_ptr<std::map<Unique *, StrokeSet> >(new std::map<Unique *, StrokeSet>); for (std::set<Unique *>::const_iterator i = deleted.begin(); i != deleted.end(); i++) strokes->erase(*i); for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) if (i->second.strokes.size()) (*strokes)[i->first] = i->second.strokes; return strokes; } boost::shared_ptr<std::set<Unique *> > ActionListDiff::get_ids(bool include_deleted) const { boost::shared_ptr<std::set<Unique *> > ids = parent ? parent->get_ids(false) : boost::shared_ptr<std::set<Unique *> >(new std::set<Unique *>); if (!include_deleted) for (std::set<Unique *>::const_iterator i = deleted.begin(); i != deleted.end(); i++) ids->erase(*i); for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) ids->insert(i->first); return ids; } void ActionListDiff::all_strokes(std::list<RStroke> &strokes) const { for (std::map<Unique *, StrokeInfo>::const_iterator i = added.begin(); i != added.end(); i++) for (std::set<RStroke>::const_iterator j = i->second.strokes.begin(); j != i->second.strokes.end(); j++) strokes.push_back(*j); for (std::list<ActionListDiff>::const_iterator i = children.begin(); i != children.end(); i++) i->all_strokes(strokes); } RAction ActionListDiff::handle(RStroke s, Ranking &r) const { if (!s) return RAction(); r.stroke = s; r.score = -1; r.id = NULL; boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = get_strokes(); for (std::map<Unique *, StrokeSet>::const_iterator i = strokes->begin(); i!=strokes->end(); i++) { for (StrokeSet::iterator j = i->second.begin(); j!=i->second.end(); j++) { double score; bool match = Stroke::compare(s, *j, score); if (score < 0.25) continue; RStrokeInfo si = get_info(i->first); r.r.insert(pair<double, pair<std::string, RStroke> > (score, pair<std::string, RStroke>(si->name, *j))); if (score >= r.score) { r.score = score; if (match) { r.id = i->first; r.name = si->name; r.action = si->action; r.best_stroke = *j; } } } } if (!r.action && s->trivial()) return RAction(new Click); if (r.action) { if (verbosity >= 1) printf("Executing Action %s\n", r.name.c_str()); } else { if (verbosity >= 1) printf("Couldn't find matching stroke.\n"); } return r.action; } void ActionListDiff::handle_advanced(RStroke s, std::map<guint, RAction> &as, std::map<guint, Ranking *> &rs, int b1, int b2) const { if (!s) return; boost::shared_ptr<std::map<Unique *, StrokeSet> > strokes = get_strokes(); for (std::map<Unique *, StrokeSet>::const_iterator i = strokes->begin(); i!=strokes->end(); i++) { for (StrokeSet::iterator j = i->second.begin(); j!=i->second.end(); j++) { int b = (*j)->button; if (!s->timeout && !b) continue; s->button = b; double score; bool match = Stroke::compare(s, *j, score); if (score < 0.25) continue; Ranking *r; if (b == b1) b = b2; if (rs.count(b)) { r = rs[b]; } else { r = new Ranking; rs[b] = r; r->stroke = RStroke(new Stroke(*s)); r->score = -1; r->id = NULL; } RStrokeInfo si = get_info(i->first); r->r.insert(pair<double, pair<std::string, RStroke> > (score, pair<std::string, RStroke>(si->name, *j))); if (score >= r->score) { r->score = score; if (match) { r->id = i->first; r->name = si->name; r->action = si->action; r->best_stroke = *j; as[b] = si->action; } } } } } ActionListDiff::~ActionListDiff() { if (app) actions.apps.erase(name); } ActionDB actions; <|endoftext|>
<commit_before>// Copyright 2022 Google LLC // // 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 // // https://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 "activity.h" #include "glog/logging.h" namespace distbench { std::unique_ptr<Activity> AllocateActivity(ParsedActivityConfig* config) { std::unique_ptr<Activity> activity; auto activity_func = config->activity_func; if (activity_func == "WasteCpu") { activity = std::make_unique<WasteCpu>(); } else if (activity_func == "PolluteDataCache") { activity = std::make_unique<PolluteDataCache>(); } activity->Initialize(config); return activity; } // Activity: WasteCpu void WasteCpu::DoActivity() { iteration_count_++; int sum = 0; std::srand(time(0)); std::generate(rand_array.begin(), rand_array.end(), std::rand); std::sort(rand_array.begin(), rand_array.end()); for (auto num : rand_array) sum += num; optimization_preventing_num_ = sum; } ActivityLog WasteCpu::GetActivityLog() { ActivityLog alog; if (iteration_count_) { auto* am = alog.add_activity_metrics(); am->set_name("iteration_count"); am->set_value_int(iteration_count_); } return alog; } void WasteCpu::Initialize(ParsedActivityConfig* config) { rand_array.resize(config->waste_cpu_config.array_size); iteration_count_ = 0; } absl::Status WasteCpu::ValidateConfig(ActivityConfig& ac) { auto array_size = GetNamedSettingInt64(ac.activity_settings(), "array_size", 1000); if (array_size < 1) { return absl::InvalidArgumentError(absl::StrCat( "Array size (", array_size, ") must be a positive integer.")); } return absl::OkStatus(); } // Activity: PolluteDataCache absl::Status PolluteDataCache::ValidateConfig(ActivityConfig& ac) { auto array_size = GetNamedSettingInt64(ac.activity_settings(), "array_size", 1000); if (array_size < 1) { return absl::InvalidArgumentError(absl::StrCat( "Array size (", array_size, ") must be a positive integer.")); } auto array_reads_per_iteration = GetNamedSettingInt64( ac.activity_settings(), "array_reads_per_iteration", 1000); if (array_reads_per_iteration < 1) { return absl::InvalidArgumentError( absl::StrCat("Array reads per iteration (", array_reads_per_iteration, ") must be a positive integer.")); } return absl::OkStatus(); } void PolluteDataCache::Initialize(ParsedActivityConfig* config) { std::srand(time(0)); auto array_size = config->pollute_data_cache_config.array_size; data_array_.resize(array_size); for (int i = 0; i < array_size; i++) { data_array_[i] = i; } random_index_ = std::uniform_int_distribution<>(0, array_size - 1); array_reads_per_iteration_ = config->pollute_data_cache_config.array_reads_per_iteration; iteration_count_ = 0; std::random_device rd; mersenne_twister_prng_ = std::mt19937(rd()); } void PolluteDataCache::DoActivity() { iteration_count_++; int64_t sum = 0; for (int i = 0; i < array_reads_per_iteration_; i++) { int index = random_index_(mersenne_twister_prng_); // This is read and write operation. sum += data_array_[index]++; } optimization_preventing_num_ = sum; } ActivityLog PolluteDataCache::GetActivityLog() { ActivityLog alog; if (iteration_count_) { auto* am = alog.add_activity_metrics(); am->set_name("iteration_count"); am->set_value_int(iteration_count_); } return alog; } } // namespace distbench <commit_msg>activity.cc: Avoid signed integer overflow undefined behavior warning.<commit_after>// Copyright 2022 Google LLC // // 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 // // https://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 "activity.h" #include "glog/logging.h" namespace distbench { std::unique_ptr<Activity> AllocateActivity(ParsedActivityConfig* config) { std::unique_ptr<Activity> activity; auto activity_func = config->activity_func; if (activity_func == "WasteCpu") { activity = std::make_unique<WasteCpu>(); } else if (activity_func == "PolluteDataCache") { activity = std::make_unique<PolluteDataCache>(); } activity->Initialize(config); return activity; } // Activity: WasteCpu void WasteCpu::DoActivity() { iteration_count_++; unsigned int sum = 0; std::srand(time(0)); std::generate(rand_array.begin(), rand_array.end(), std::rand); std::sort(rand_array.begin(), rand_array.end()); for (auto num : rand_array) sum += num; optimization_preventing_num_ = sum; } ActivityLog WasteCpu::GetActivityLog() { ActivityLog alog; if (iteration_count_) { auto* am = alog.add_activity_metrics(); am->set_name("iteration_count"); am->set_value_int(iteration_count_); } return alog; } void WasteCpu::Initialize(ParsedActivityConfig* config) { rand_array.resize(config->waste_cpu_config.array_size); iteration_count_ = 0; } absl::Status WasteCpu::ValidateConfig(ActivityConfig& ac) { auto array_size = GetNamedSettingInt64(ac.activity_settings(), "array_size", 1000); if (array_size < 1) { return absl::InvalidArgumentError(absl::StrCat( "Array size (", array_size, ") must be a positive integer.")); } return absl::OkStatus(); } // Activity: PolluteDataCache absl::Status PolluteDataCache::ValidateConfig(ActivityConfig& ac) { auto array_size = GetNamedSettingInt64(ac.activity_settings(), "array_size", 1000); if (array_size < 1) { return absl::InvalidArgumentError(absl::StrCat( "Array size (", array_size, ") must be a positive integer.")); } auto array_reads_per_iteration = GetNamedSettingInt64( ac.activity_settings(), "array_reads_per_iteration", 1000); if (array_reads_per_iteration < 1) { return absl::InvalidArgumentError( absl::StrCat("Array reads per iteration (", array_reads_per_iteration, ") must be a positive integer.")); } return absl::OkStatus(); } void PolluteDataCache::Initialize(ParsedActivityConfig* config) { std::srand(time(0)); auto array_size = config->pollute_data_cache_config.array_size; data_array_.resize(array_size); for (int i = 0; i < array_size; i++) { data_array_[i] = i; } random_index_ = std::uniform_int_distribution<>(0, array_size - 1); array_reads_per_iteration_ = config->pollute_data_cache_config.array_reads_per_iteration; iteration_count_ = 0; std::random_device rd; mersenne_twister_prng_ = std::mt19937(rd()); } void PolluteDataCache::DoActivity() { iteration_count_++; int64_t sum = 0; for (int i = 0; i < array_reads_per_iteration_; i++) { int index = random_index_(mersenne_twister_prng_); // This is read and write operation. sum += data_array_[index]++; } optimization_preventing_num_ = sum; } ActivityLog PolluteDataCache::GetActivityLog() { ActivityLog alog; if (iteration_count_) { auto* am = alog.add_activity_metrics(); am->set_name("iteration_count"); am->set_value_int(iteration_count_); } return alog; } } // namespace distbench <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include "MethodDefinition.h" #include "../execution/Program.h" void MethodDefinition::execute() { Program::create_frame(frame_size); for (unsigned int i = 0; i < arguments; i++) { Program::frame()[i] = Program::pop(); } for (int counter = 0; counter < symbols.size();) { auto symbol = symbols[counter]; std::cerr << "[" << counter << "] Executing symbol " << describe(symbol.opcode) << ": " << symbol.target << ", " << symbol.secondary << " -> ["; std::for_each(Program::frame().begin(), Program::frame().end(), [](const PThingInstance &thing) { std::cerr << (thing ? thing->text() : "?") << ","; }); std::cerr << "] -> "; std::for_each(Program::static_data.begin(), Program::static_data.end(), [](const PThingInstance &thing) { std::cerr << (thing ? thing->text() : "?") << ","; }); std::cerr << "]" << std::endl; switch (symbol.opcode) { case Opcode::NOP: break; case Opcode::PUSH: { Program::push(Program::frame()[symbol.target]); break; }; case Opcode::PUSH_NULL: { Program::push(NULL); break; } case Opcode::POP: { Program::pop(); break; } case Opcode::SET_STATIC: { Program::frame()[symbol.target] = Program::data(symbol.secondary); break; } case Opcode::SET: { Program::frame()[symbol.target] = Program::pop(); break; } case Opcode::PUSH_STATIC: { Program::push(Program::data(symbol.target)); break; } case Opcode::CALL: { auto instance = Program::top(); instance->call_method(symbol.target); break; } case Opcode::CALL_METHOD: { auto instance = Program::instance(); instance->call_method(symbol.target); break; } case Opcode::PRINT: std::cout << Program::pop()->text() << std::endl; break; case Opcode::CALL_INTERNAL: { Program::internals[symbol.target]->call_internal(symbol.secondary); break; } case Opcode::RETURN: { Program::pop_frame(); break; } case Opcode::JUMP: { counter = symbol.target; continue; } case Opcode::CONDITIONAL_JUMP: { auto value = Program::pop(); if (!value) { counter = symbol.target; continue; } break; } default: throw RuntimeError( "Cannot handle symbol " + describe(symbol.opcode) + " (" + std::to_string((int) symbol.opcode) + ")"); } counter++; }; Program::pop_frame(); } <commit_msg>Fix return opcode handling<commit_after>#include <iostream> #include <algorithm> #include "MethodDefinition.h" #include "../execution/Program.h" void MethodDefinition::execute() { Program::create_frame(frame_size); for (unsigned int i = 0; i < arguments; i++) { Program::frame()[i] = Program::pop(); } auto counter_end = symbols.size(); for (auto counter = 0; counter < counter_end;) { auto symbol = symbols[counter]; std::cerr << "[" << counter << "] Executing symbol " << describe(symbol.opcode) << ": " << symbol.target << ", " << symbol.secondary << " -> ["; std::for_each(Program::frame().begin(), Program::frame().end(), [](const PThingInstance &thing) { std::cerr << (thing ? thing->text() : "?") << ","; }); std::cerr << "] -> ["; std::for_each(Program::static_data.begin(), Program::static_data.end(), [](const PThingInstance &thing) { std::cerr << (thing ? thing->text() : "?") << ","; }); std::cerr << "]" << std::endl; switch (symbol.opcode) { case Opcode::NOP: break; case Opcode::PUSH: { Program::push(Program::frame()[symbol.target]); break; }; case Opcode::PUSH_NULL: { Program::push(NULL); break; } case Opcode::POP: { Program::pop(); break; } case Opcode::SET_STATIC: { Program::frame()[symbol.target] = Program::data(symbol.secondary); break; } case Opcode::SET: { Program::frame()[symbol.target] = Program::pop(); break; } case Opcode::PUSH_STATIC: { Program::push(Program::data(symbol.target)); break; } case Opcode::CALL: { auto instance = Program::top(); instance->call_method(symbol.target); break; } case Opcode::CALL_METHOD: { auto instance = Program::instance(); instance->call_method(symbol.target); break; } case Opcode::PRINT: std::cout << Program::pop()->text() << std::endl; break; case Opcode::CALL_INTERNAL: { Program::internals[symbol.target]->call_internal(symbol.secondary); break; } case Opcode::RETURN: { counter = counter_end; continue; } case Opcode::JUMP: { counter = symbol.target; continue; } case Opcode::CONDITIONAL_JUMP: { auto value = Program::pop(); if (!value) { counter = symbol.target; continue; } break; } default: throw RuntimeError( "Cannot handle symbol " + describe(symbol.opcode) + " (" + std::to_string((int) symbol.opcode) + ")"); } counter++; }; Program::pop_frame(); } <|endoftext|>
<commit_before>/* Copyright Eli Dupree and Isaac Dupree, 2014 This file is part of Lasercake. Lasercake is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lasercake is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_TAIL_DROP_MAP_HPP__ #define LASERCAKE_TAIL_DROP_MAP_HPP__ /* This is a bizarrely specific data structure that might be useful for the time steward. It implements only two operations: void insert (key, value), which inserts an element into the map, and tail_drop (key), which removes and returns all elements with keys after key, not necessarily in order. Inserting at the end is O(1) worst case. Inserting elsewhere is O(1), but incurs a debt of up to O(log n) which will be paid off later by tail_drop. tail_drop is merely O(number of things returned), plus paying off the debt. Since the results of tail_drop don't actually need to be sorted, we delay all or part of the O(log n) cost of sorting for as long as we can, in the hopes of never having to pay it at all. There is also discard_head (key), which can be used to save memory by assuring the tail_drop_map that you won't query before key, so it can discard some data that it knows will never be used. However, it does not guarantee that all data before key will be discarded. */ template <typename key_type, typename mapped_type> class tail_drop_map { private: //the "bucket" type is used only for collecting unsorted elements //1 at a time, then eventually iterating them and dumping them all out. typedef std:: vector bucket; typedef std:: pair <key_type, mapped_type> value_type; struct sorted_element { sorted_element (value_type const & value): value (value) {} value_type value; bucket unsorted_elements_before_or_equal_this; }; std:: vector <sorted_element> sorted_elements; bucket unsorted_elements; public: void insert (value_type const & value) { if (value.first >= sorted_elements.back ().value.first) { sorted_elements.emplace_back (value); } else { unsorted_elements.push_back (value); } } template <class output_function> void tail_drop (key_type const & key, output_function output = output_function ()) { if (sorted_elements.empty ()) { assert (unsorted_elements.empty ()); return; } while (sorted_elements.back ().value.first >key) { bucket & spilling = sorted_elements.back ().unsorted_elements_before_or_equal_this; std:: move (spilling.begin (), spilling.end (), std:: back_inserter (unsorted_elements)); output (sorted_elements.back ().value); sorted_elements.pop_back (); } remaining_sorted= sorted_elements.size (); for (value_type value: unsorted_elements) { if (value.first >key) { output (value); } else if (sorted_elements.empty () || value.first >= sorted_elements [remaining_sorted-1].value.first) { sorted_elements.emplace_back (value); } else { //do part of a binary search, but don't do more than you have to. //If there's never a tail_drop that goes back that far, //you never have to do the rest of the search, AND //if there IS a tail_drop that goes far enough back to //actually OUTPUT this element, we never have to do the rest //of the search in that scenario either. size_t dump_location = remaining_sorted>> 1; while (sorted_elements [dump_location].value.first < value.first) { dump_location = (dump_location + remaining_sorted) >> 1; } sorted_elements [dump_location].unsorted_elements_before_or_equal_this .push_back (value); } } unsorted_elements.clear (); if (sorted_elements.size () >remaining_sorted + 1) { std:: sort (sorted_elements [remaining_sorted], sorted_elements.end (), [] (e1, e2) {return e1.value.first < e2.value.first}); } } void discard_head (key_type const & key) { //this could probably be improved if (sorted_elements.empty ()) { return;} auto middle = sorted_elements.begin () + (sorted_elements.size () >> 1); if (middle -> value.first <key) { sorted_elements.erase (sorted_elements.begin (), middle); } } }; #endif <commit_msg>Made some improvements to tail_drop_map<commit_after>/* Copyright Eli Dupree and Isaac Dupree, 2014 This file is part of Lasercake. Lasercake is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lasercake is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_TAIL_DROP_MAP_HPP__ #define LASERCAKE_TAIL_DROP_MAP_HPP__ /* This is a bizarrely specific data structure that might be useful for the time steward. It implements only two operations: void insert (key, value), which inserts an element into the map, and tail_drop (key), which removes and returns all elements with keys after key, not necessarily in order. Inserting at the end is O(1) amortized. Inserting elsewhere is O(1), but incurs a debt of O(log n) which will be paid off later by tail_drop. tail_drop is merely O(number of things returned), plus paying off the debt. Since the results of tail_drop don't actually need to be sorted, we delay all or part of the O(log n) cost of sorting for as long as we can, in the hopes of never having to pay it at all. There is also discard_head (key), which can be used to save memory by assuring the tail_drop_map that you won't query before key, so it can discard some data that it knows will never be used. However, it does not guarantee that all data before key will be discarded. */ template <typename key_type, typename mapped_type> class tail_drop_map { private: typedef std:: pair <key_type, mapped_type> value_type; //the "bucket" type is used only for collecting unsorted elements //1 at a time, then eventually iterating them and dumping them all out. typedef std:: vector <value_type> bucket; struct sorted_element { sorted_element (value_type const & value): value (value) {} value_type value; bucket unsorted_elements_before_or_equal_this; }; std:: vector <sorted_element> sorted_elements; bucket unsorted_elements; public: void insert (value_type const & value) { if (value.first >= sorted_elements.back ().value.first) { sorted_elements.emplace_back (value); } else { unsorted_elements.push_back (value); } } template <class output_function> void tail_drop (key_type const & key, output_function output = output_function ()) { if (sorted_elements.empty ()) { assert (unsorted_elements.empty ()); return; } while (sorted_elements.back ().value.first >key) { bucket & spilling = sorted_elements.back ().unsorted_elements_before_or_equal_this; std:: move (spilling.begin (), spilling.end (), std:: back_inserter (unsorted_elements)); output (sorted_elements.back ().value); sorted_elements.pop_back (); } remaining_sorted= sorted_elements.size (); for (value_type value: unsorted_elements) { if (value.first >key) { output (value); } else if (sorted_elements.empty () || value.first >= sorted_elements [remaining_sorted-1].value.first) { sorted_elements.emplace_back (value); } else { //do part of a binary search, but don't do more than you have to. //If there's never a tail_drop that goes back that far, //you never have to do the rest of the search, AND //if there IS a tail_drop that goes far enough back to //actually OUTPUT this element, we never have to do the rest //of the search in that scenario either. size_t dump_location = remaining_sorted>> 1; while (sorted_elements [dump_location].value.first < value.first) { dump_location = (dump_location + remaining_sorted) >> 1; } sorted_elements [dump_location].unsorted_elements_before_or_equal_this .push_back (value); } } unsorted_elements.clear (); if (sorted_elements.size () >remaining_sorted + 1) { std:: sort (sorted_elements [remaining_sorted], sorted_elements.end (), [] (e1, e2) {return e1.value.first < e2.value.first}); } } void discard_head (key_type const & key) { //this could probably be improved if (sorted_elements.empty ()) { return;} auto middle = sorted_elements.begin () + (sorted_elements.size () >> 1); if (middle -> value.first <key) { sorted_elements.erase (sorted_elements.begin (), middle); } } }; #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../src/Repl.hpp" #include "../src/Exp.hpp" #include <sstream> #include <string> using namespace sexp_cpp; namespace { TEST(EvalSpec, EmptyListExp) { std::stringstream code("()"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "EmptyListExp"); EXPECT_EQ("", print(exp)); } TEST(EvalSpec, PairExp) { std::stringstream code("( 1 2 )"); pExp exp = read(code); EXPECT_EQ(exp->WhoAmI(), "PairExp"); exp = eval(exp); EXPECT_EQ(exp->WhoAmI(), "PairExp"); EXPECT_EQ("(1 2)", print(exp)); } TEST(EvalSpec, NestedPairExp) { std::stringstream code("( 1 2 3 4 5 )"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "PairExp"); EXPECT_EQ("(1 2 3 4 5)", print(exp)); } //TEST(EvalSpec, Quote) //{ //std::stringstream code("( quote a )"); //pExp exp = eval(read(code)); //EXPECT_EQ(exp->WhoAmI(), "PairExp"); //EXPECT_EQ("a", print(exp)); //} } <commit_msg>added integers spec test<commit_after>#include <gtest/gtest.h> #include "../src/Repl.hpp" #include "../src/Exp.hpp" #include <sstream> #include <string> using namespace sexp_cpp; namespace { TEST(EvalSpec, PositiveIntegerExp) { std::stringstream code("123"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "ValueExp"); EXPECT_EQ("123", print(exp)); } TEST(EvalSpec, NegativeIntegerExp) { std::stringstream code("-456"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "ValueExp"); EXPECT_EQ("-456", print(exp)); } TEST(EvalSpec, EmptyListExp) { std::stringstream code("()"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "EmptyListExp"); EXPECT_EQ("", print(exp)); } TEST(EvalSpec, PairExp) { std::stringstream code("( 1 2 )"); pExp exp = read(code); EXPECT_EQ(exp->WhoAmI(), "PairExp"); exp = eval(exp); EXPECT_EQ(exp->WhoAmI(), "PairExp"); EXPECT_EQ("(1 2)", print(exp)); } TEST(EvalSpec, NestedPairExp) { std::stringstream code("( 1 2 3 4 5 )"); pExp exp = eval(read(code)); EXPECT_EQ(exp->WhoAmI(), "PairExp"); EXPECT_EQ("(1 2 3 4 5)", print(exp)); } //TEST(EvalSpec, Quote) //{ //std::stringstream code("( quote a )"); //pExp exp = eval(read(code)); //EXPECT_EQ(exp->WhoAmI(), "PairExp"); //EXPECT_EQ("a", print(exp)); //} } <|endoftext|>
<commit_before>#include <stdio.h> #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H #include <unistd.h> #endif #include <iostream> #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/OstreamAppender.hh" #ifdef LOG4CPP_HAVE_SYSLOG #include "log4cpp/SyslogAppender.hh" #endif #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" int main(int argc, char** argv) { log4cpp::Appender* appender; #ifdef LOG4CPP_HAVE_SYSLOG log4cpp::SyslogAppender* syslogAppender; syslogAppender = new log4cpp::SyslogAppender("syslog", "log4cpp"); #else log4cpp::Appender* syslogAppender; syslogAppender = new log4cpp::OstreamAppender("syslogdummy", &std::cout); #endif if (argc < 2) { appender = new log4cpp::OstreamAppender("default", &std::cout); } else { appender = new log4cpp::FileAppender("default", argv[1]); } syslogAppender->setLayout(new log4cpp::BasicLayout()); appender->setLayout(new log4cpp::BasicLayout()); log4cpp::Category& root = log4cpp::Category::getRoot(); root.addAppender(syslogAppender); root.setPriority(log4cpp::Priority::ERROR); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.addAppender(appender); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); log4cpp::NDC::push(std::string("ndc1")); std::cout << " root prio = " << root.getPriority() << std::endl; std::cout << " sub1 prio = " << sub1.getPriority() << std::endl; std::cout << " sub2 prio = " << sub2.getPriority() << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub1.setPriority(log4cpp::Priority::INFO); std::cout << " root prio = " << root.getPriority() << std::endl; std::cout << " sub1 prio = " << sub1.getPriority() << std::endl; std::cout << " sub2 prio = " << sub2.getPriority() << std::endl; std::cout << "priority info" << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2" << " warn3" << log4cpp::CategoryStream::ENDLINE << " warn4"; { for(int i = 0; i < 10000; i++) { char ndc2[20]; sprintf(ndc2, "i=%d", i); log4cpp::NDC::push(ndc2); sub1.info("%s%d", "i = ", i); if ((i % 10) == 0) { sub1.log(log4cpp::Priority::NOTICE, "reopen log"); if (log4cpp::Appender::reopenAll()) { sub1.info("log reopened"); } else { sub1.warn("could not reopen log"); } } #ifndef WIN32 sleep(1); #endif log4cpp::NDC::pop(); } } } <commit_msg>have main() return 0; (bug #718941)<commit_after>#include <stdio.h> #include "log4cpp/Portability.hh" #ifdef LOG4CPP_HAVE_UNISTD_H #include <unistd.h> #endif #include <iostream> #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/OstreamAppender.hh" #ifdef LOG4CPP_HAVE_SYSLOG #include "log4cpp/SyslogAppender.hh" #endif #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" int main(int argc, char** argv) { log4cpp::Appender* appender; #ifdef LOG4CPP_HAVE_SYSLOG log4cpp::SyslogAppender* syslogAppender; syslogAppender = new log4cpp::SyslogAppender("syslog", "log4cpp"); #else log4cpp::Appender* syslogAppender; syslogAppender = new log4cpp::OstreamAppender("syslogdummy", &std::cout); #endif if (argc < 2) { appender = new log4cpp::OstreamAppender("default", &std::cout); } else { appender = new log4cpp::FileAppender("default", argv[1]); } syslogAppender->setLayout(new log4cpp::BasicLayout()); appender->setLayout(new log4cpp::BasicLayout()); log4cpp::Category& root = log4cpp::Category::getRoot(); root.addAppender(syslogAppender); root.setPriority(log4cpp::Priority::ERROR); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.addAppender(appender); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); log4cpp::NDC::push(std::string("ndc1")); std::cout << " root prio = " << root.getPriority() << std::endl; std::cout << " sub1 prio = " << sub1.getPriority() << std::endl; std::cout << " sub2 prio = " << sub2.getPriority() << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub1.setPriority(log4cpp::Priority::INFO); std::cout << " root prio = " << root.getPriority() << std::endl; std::cout << " sub1 prio = " << sub1.getPriority() << std::endl; std::cout << " sub2 prio = " << sub2.getPriority() << std::endl; std::cout << "priority info" << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2" << " warn3" << log4cpp::CategoryStream::ENDLINE << " warn4"; { for(int i = 0; i < 10000; i++) { char ndc2[20]; sprintf(ndc2, "i=%d", i); log4cpp::NDC::push(ndc2); sub1.info("%s%d", "i = ", i); if ((i % 10) == 0) { sub1.log(log4cpp::Priority::NOTICE, "reopen log"); if (log4cpp::Appender::reopenAll()) { sub1.info("log reopened"); } else { sub1.warn("could not reopen log"); } } #ifndef WIN32 sleep(1); #endif log4cpp::NDC::pop(); } } return 0; } <|endoftext|>
<commit_before>//macro illustrating how to animate a picture using a Timer Double_t pi; TF2 *f2; Float_t t = 0; Float_t phi = 30; void anim() { gStyle->SetFrameFillColor(42); TCanvas *c1 = new TCanvas("c1"); c1->SetFillColor(17); pi = TMath::Pi(); f2 = new TF2("f2","sin(2*x)*sin(2*y)*[0]",0,pi,0,pi); f2->SetParameter(0,1); f2->SetNpx(15); f2->SetNpy(15); f2->SetMaximum(1); f2->SetMinimum(-1); f2->Draw("surf1"); TTimer *timer = new TTimer(20); timer->SetCommand("Animate()"); timer->TurnOn(); } void Animate() { t += 0.05*pi; f2->SetParameter(0,TMath::Cos(t)); phi += 2; gPad->SetPhi(phi); gPad->Modified(); gPad->Update(); } <commit_msg>Protect the script in case the canvas is deleted while the script is running.<commit_after>//macro illustrating how to animate a picture using a Timer Double_t pi; TF2 *f2; Float_t t = 0; Float_t phi = 30; void anim() { gStyle->SetFrameFillColor(42); TCanvas *c1 = new TCanvas("c1"); c1->SetFillColor(17); pi = TMath::Pi(); f2 = new TF2("f2","sin(2*x)*sin(2*y)*[0]",0,pi,0,pi); f2->SetParameter(0,1); f2->SetNpx(15); f2->SetNpy(15); f2->SetMaximum(1); f2->SetMinimum(-1); f2->Draw("surf1"); TTimer *timer = new TTimer(20); timer->SetCommand("Animate()"); timer->TurnOn(); } void Animate() { if (!gROOT->GetListOfCanvases()->FindObject("c1")) return; //just in case the canvas has been deleted t += 0.05*pi; f2->SetParameter(0,TMath::Cos(t)); phi += 2; gPad->SetPhi(phi); gPad->Modified(); gPad->Update(); } <|endoftext|>
<commit_before>//===--- Stmt.cpp - Statement AST Node Implementation ---------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Stmt class and statement subclasses. // //===----------------------------------------------------------------------===// #include "clang/AST/Stmt.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/IdentifierTable.h" using namespace clang; static struct StmtClassNameTable { int enumValue; const char *className; unsigned counter; unsigned size; } sNames[] = { #define STMT(N, CLASS, PARENT) { N, #CLASS, 0, sizeof(CLASS) }, #include "clang/AST/StmtNodes.def" { 0, 0, 0, 0 } }; const char *Stmt::getStmtClassName() const { for (int i = 0; sNames[i].className; i++) { if (sClass == sNames[i].enumValue) return sNames[i].className; } return 0; // should never happen.... } void Stmt::PrintStats() { unsigned sum = 0; fprintf(stderr, "*** Stmt/Expr Stats:\n"); for (int i = 0; sNames[i].className; i++) { sum += sNames[i].counter; } fprintf(stderr, " %d stmts/exprs total.\n", sum); sum = 0; for (int i = 0; sNames[i].className; i++) { fprintf(stderr, " %d %s, %d each (%d bytes)\n", sNames[i].counter, sNames[i].className, sNames[i].size, sNames[i].counter*sNames[i].size); sum += sNames[i].counter*sNames[i].size; } fprintf(stderr, "Total bytes = %d\n", sum); } void Stmt::addStmtClass(StmtClass s) { for (int i = 0; sNames[i].className; i++) { if (s == sNames[i].enumValue) sNames[i].counter++; } } static bool StatSwitch = false; bool Stmt::CollectingStats(bool enable) { if (enable) StatSwitch = true; return StatSwitch; } const char *LabelStmt::getName() const { return getID()->getName(); } //===----------------------------------------------------------------------===// // Child Iterators for iterating over subexpressions/substatements //===----------------------------------------------------------------------===// // DeclStmt Stmt::child_iterator DeclStmt::child_begin() { return NULL; } Stmt::child_iterator DeclStmt::child_end() { return NULL; } // NullStmt Stmt::child_iterator NullStmt::child_begin() { return NULL; } Stmt::child_iterator NullStmt::child_end() { return NULL; } // CompoundStmt Stmt::child_iterator CompoundStmt::child_begin() { return &Body[0]; } Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+Body.size(); } // SwitchCase Stmt::child_iterator SwitchCase::child_begin() { return &SubStmt; } Stmt::child_iterator SwitchCase::child_end() { return child_begin()+1; } // LabelStmt Stmt::child_iterator LabelStmt::child_begin() { return &SubStmt; } Stmt::child_iterator LabelStmt::child_end() { return child_begin()+1; } // IfStmt Stmt::child_iterator IfStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator IfStmt::child_end() { return &SubExprs[0]+END_EXPR; } // SwitchStmt Stmt::child_iterator SwitchStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator SwitchStmt::child_end() { return &SubExprs[0]+END_EXPR; } // WhileStmt Stmt::child_iterator WhileStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator WhileStmt::child_end() { return &SubExprs[0]+END_EXPR; } // DoStmt Stmt::child_iterator DoStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator DoStmt::child_end() { return &SubExprs[0]+END_EXPR; } // ForStmt Stmt::child_iterator ForStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator ForStmt::child_end() { return &SubExprs[0]+END_EXPR; } // GotoStmt Stmt::child_iterator GotoStmt::child_begin() { return NULL; } Stmt::child_iterator GotoStmt::child_end() { return NULL; } // IndirectGotoStmt Stmt::child_iterator IndirectGotoStmt::child_begin() { return reinterpret_cast<Stmt**>(&Target); } Stmt::child_iterator IndirectGotoStmt::child_end() { return child_begin()+1; } // ContinueStmt Stmt::child_iterator ContinueStmt::child_begin() { return NULL; } Stmt::child_iterator ContinueStmt::child_end() { return NULL; } // BreakStmt Stmt::child_iterator BreakStmt::child_begin() { return NULL; } Stmt::child_iterator BreakStmt::child_end() { return NULL; } // ReturnStmt Stmt::child_iterator ReturnStmt::child_begin() { return reinterpret_cast<Stmt**>(&RetExpr); } Stmt::child_iterator ReturnStmt::child_end() { return child_begin()+1; } <commit_msg>rename sNames -> StmtClassInfo. Make lookups constant time.<commit_after>//===--- Stmt.cpp - Statement AST Node Implementation ---------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Stmt class and statement subclasses. // //===----------------------------------------------------------------------===// #include "clang/AST/Stmt.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/IdentifierTable.h" using namespace clang; static struct StmtClassNameTable { const char *Name; unsigned Counter; unsigned Size; } StmtClassInfo[Stmt::lastExprConstant]; static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) { static bool Initialized = false; if (Initialized) return StmtClassInfo[E]; // Intialize the table on the first use. Initialized = true; #define STMT(N, CLASS, PARENT) \ StmtClassInfo[N].Name = #CLASS; \ StmtClassInfo[N].Size = sizeof(CLASS); #include "clang/AST/StmtNodes.def" return StmtClassInfo[E]; } const char *Stmt::getStmtClassName() const { return getStmtInfoTableEntry(sClass).Name; } void Stmt::PrintStats() { // Ensure the table is primed. getStmtInfoTableEntry(Stmt::NullStmtClass); unsigned sum = 0; fprintf(stderr, "*** Stmt/Expr Stats:\n"); for (int i = 0; i != Stmt::lastExprConstant; i++) { if (StmtClassInfo[i].Name == 0) continue; sum += StmtClassInfo[i].Counter; } fprintf(stderr, " %d stmts/exprs total.\n", sum); sum = 0; for (int i = 0; i != Stmt::lastExprConstant; i++) { if (StmtClassInfo[i].Name == 0) continue; fprintf(stderr, " %d %s, %d each (%d bytes)\n", StmtClassInfo[i].Counter, StmtClassInfo[i].Name, StmtClassInfo[i].Size, StmtClassInfo[i].Counter*StmtClassInfo[i].Size); sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size; } fprintf(stderr, "Total bytes = %d\n", sum); } void Stmt::addStmtClass(StmtClass s) { ++getStmtInfoTableEntry(s).Counter; } static bool StatSwitch = false; bool Stmt::CollectingStats(bool enable) { if (enable) StatSwitch = true; return StatSwitch; } const char *LabelStmt::getName() const { return getID()->getName(); } //===----------------------------------------------------------------------===// // Child Iterators for iterating over subexpressions/substatements //===----------------------------------------------------------------------===// // DeclStmt Stmt::child_iterator DeclStmt::child_begin() { return NULL; } Stmt::child_iterator DeclStmt::child_end() { return NULL; } // NullStmt Stmt::child_iterator NullStmt::child_begin() { return NULL; } Stmt::child_iterator NullStmt::child_end() { return NULL; } // CompoundStmt Stmt::child_iterator CompoundStmt::child_begin() { return &Body[0]; } Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+Body.size(); } // SwitchCase Stmt::child_iterator SwitchCase::child_begin() { return &SubStmt; } Stmt::child_iterator SwitchCase::child_end() { return child_begin()+1; } // LabelStmt Stmt::child_iterator LabelStmt::child_begin() { return &SubStmt; } Stmt::child_iterator LabelStmt::child_end() { return child_begin()+1; } // IfStmt Stmt::child_iterator IfStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator IfStmt::child_end() { return &SubExprs[0]+END_EXPR; } // SwitchStmt Stmt::child_iterator SwitchStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator SwitchStmt::child_end() { return &SubExprs[0]+END_EXPR; } // WhileStmt Stmt::child_iterator WhileStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator WhileStmt::child_end() { return &SubExprs[0]+END_EXPR; } // DoStmt Stmt::child_iterator DoStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator DoStmt::child_end() { return &SubExprs[0]+END_EXPR; } // ForStmt Stmt::child_iterator ForStmt::child_begin() { return &SubExprs[0]; } Stmt::child_iterator ForStmt::child_end() { return &SubExprs[0]+END_EXPR; } // GotoStmt Stmt::child_iterator GotoStmt::child_begin() { return NULL; } Stmt::child_iterator GotoStmt::child_end() { return NULL; } // IndirectGotoStmt Stmt::child_iterator IndirectGotoStmt::child_begin() { return reinterpret_cast<Stmt**>(&Target); } Stmt::child_iterator IndirectGotoStmt::child_end() { return child_begin()+1; } // ContinueStmt Stmt::child_iterator ContinueStmt::child_begin() { return NULL; } Stmt::child_iterator ContinueStmt::child_end() { return NULL; } // BreakStmt Stmt::child_iterator BreakStmt::child_begin() { return NULL; } Stmt::child_iterator BreakStmt::child_end() { return NULL; } // ReturnStmt Stmt::child_iterator ReturnStmt::child_begin() { return reinterpret_cast<Stmt**>(&RetExpr); } Stmt::child_iterator ReturnStmt::child_end() { return child_begin()+1; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Deepsea * * This software may be modified and distributed under * the terms of the MIT license. See the LICENSE file * for details. * */ #include <iostream> #include <memory> #include <deque> #include "cactus-basic.hpp" namespace cactus_stack { namespace basic { /*------------------------------*/ /* Frame */ class frame { public: int v; }; /* Frame */ /*------------------------------*/ /*------------------------------*/ /* Trace */ using machine_stack_type = stack_type; using reference_stack_type = std::deque<frame>; using fork_result_tag = enum { Fork_result_none, Fork_result_some }; using fork_result_type = struct { fork_result_tag tag; reference_stack_type s1, s2; frame f1, f2; }; bool is_marked(frame& f) { return f.s.plt == Parent_link_async; } fork_result_type fork_mark(reference_stack_type& s) { fork_result_type r; constexpr int not_found = -1; size_t k = not_found; auto nb_frames = s.size(); for (size_t i = 0; i < nb_frames; i++) { if (is_marked(s[i])) { k = i; break; } } if (k == not_found) { r.tag = Fork_result_none; return r; } reference_stack_type t1(s.begin(), s.begin() + k); reference_stack_type t2(s.begin() + k, s.end()); r.tag = Fork_result_some; r.s1 = t1; r.s2 = t2; r.s1.pop_back(); r.s2.pop_front(); r.f1 = t1.back(); r.f2 = t2.front(); return r; } using trace_tag_type = enum { Trace_push_back, Trace_pop_back, Trace_fork_mark, Trace_nil }; struct trace_struct { trace_tag_type tag; struct { frame f; std::unique_ptr<struct trace_struct> k; } push_back; struct { std::unique_ptr<struct trace_struct> k; } pop_back; struct fork_mark_struct { std::unique_ptr<struct trace_struct> k1; std::unique_ptr<struct trace_struct> k2; } fork_mark; }; using trace_type = struct trace_struct; trace_type mk_push_back(frame f) { trace_type t; t.tag = Trace_push_back; t.push_back.f = f; return t; } trace_type mk_pop_back() { trace_type t; t.tag = Trace_pop_back; return t; } trace_type mk_fork_mark() { trace_type t; t.tag = Trace_fork_mark; return t; } using thread_config_type = struct { trace_type t; reference_stack_type rs; // reference stack machine_stack_type ms; }; using machine_tag_type = enum { Machine_fork_mark, Machine_thread, Machine_stuck }; using machine_config_type = struct machine_config_struct { machine_tag_type tag; struct { std::unique_ptr<struct machine_config_struct> m1; std::unique_ptr<struct machine_config_struct> m2; } fork_mark; thread_config_type thread; }; /* Trace */ /*------------------------------*/ } // end namespace } // end namespace int main(int argc, const char * argv[]) { std::cout << "Hello, World!\n"; return 0; } <commit_msg>Working on basic cactus stack<commit_after>/* * Copyright (c) 2017 Deepsea * * This software may be modified and distributed under * the terms of the MIT license. See the LICENSE file * for details. * */ #include <iostream> #include <memory> #include <deque> #include "cactus-basic.hpp" namespace cactus_stack { namespace basic { /*------------------------------*/ /* Frame */ class frame { public: int v; parent_link_type plt; }; /* Frame */ /*------------------------------*/ /*------------------------------*/ /* Trace */ using machine_stack_type = stack_type; using reference_stack_type = std::deque<frame>; using fork_result_tag = enum { Fork_result_none, Fork_result_some }; using fork_result_type = struct { fork_result_tag tag; reference_stack_type s1, s2; frame f1, f2; }; bool is_marked(frame& f) { return f.plt == Parent_link_async; } fork_result_type fork_mark(reference_stack_type& s) { fork_result_type r; constexpr int not_found = -1; size_t k = not_found; auto nb_frames = s.size(); for (size_t i = 0; i < nb_frames; i++) { if (is_marked(s[i])) { k = i; break; } } if (k == not_found) { r.tag = Fork_result_none; return r; } reference_stack_type t1(s.begin(), s.begin() + k); reference_stack_type t2(s.begin() + k, s.end()); r.tag = Fork_result_some; r.s1 = t1; r.s2 = t2; r.s1.pop_back(); r.s2.pop_front(); r.f1 = t1.back(); r.f2 = t2.front(); return r; } using trace_tag_type = enum { Trace_push_back, Trace_pop_back, Trace_fork_mark, Trace_nil }; struct trace_struct { trace_tag_type tag; struct { frame f; std::shared_ptr<struct trace_struct> k; } push_back; struct { std::shared_ptr<struct trace_struct> k; } pop_back; struct fork_mark_struct { std::shared_ptr<struct trace_struct> k1; std::shared_ptr<struct trace_struct> k2; } fork_mark; }; using trace_type = struct trace_struct; trace_type* mk_push_back(frame f) { trace_type* t = new trace_type; t->tag = Trace_push_back; t->push_back.f = f; return t; } trace_type* mk_pop_back() { trace_type* t = new trace_type; t->tag = Trace_pop_back; return t; } trace_type* mk_fork_mark() { trace_type* t = new trace_type; t->tag = Trace_fork_mark; return t; } using thread_config_type = struct { trace_type t; reference_stack_type rs; // reference stack machine_stack_type ms; }; using machine_tag_type = enum { Machine_fork_mark, Machine_thread, Machine_stuck }; using machine_config_type = struct machine_config_struct { machine_tag_type tag; struct { std::shared_ptr<struct machine_config_struct> m1; std::shared_ptr<struct machine_config_struct> m2; } fork_mark; thread_config_type thread; }; template <class Coin_flip> machine_config_type step(const Coin_flip& coin_flip, machine_config_type& m) { machine_config_type n; n.tag = Machine_stuck; switch (m.tag) { case Machine_fork_mark: { n.tag = Machine_fork_mark; if (coin_flip()) { *n.fork_mark.m1 = step(coin_flip, *m.fork_mark.m1); n.fork_mark.m2.swap(m.fork_mark.m2); } else { n.fork_mark.m1.swap(m.fork_mark.m1); *n.fork_mark.m2 = step(coin_flip, *m.fork_mark.m2); } break; } case Machine_thread: { thread_config_type& tc_m = m.thread; thread_config_type& tc_n = n.thread; switch (tc_m.t.tag) { case Trace_fork_mark: { n.tag = Machine_fork_mark; auto mp = fork_mark(tc_m.ms); auto rp = fork_mark(tc_m.rs); reference_stack_type rs1, rs2; if (rp.tag == Fork_result_some) { rs1 = rp.s1; rs1.push_back(rp.f1); rs2 = rp.s2; rs2.push_back(rp.f2); } else { rs1 = tc_m.rs; } n.fork_mark.m1.reset(new machine_config_type); n.fork_mark.m2.reset(new machine_config_type); machine_config_type& m1 = *n.fork_mark.m1; machine_config_type& m2 = *n.fork_mark.m2; m1.tag = Machine_thread; m1.thread.t = std::move(*tc_m.t.fork_mark.k1); m1.thread.ms = mp.first; m1.thread.rs = rs1; m2.tag = Machine_thread; m2.thread.t = std::move(*tc_m.t.fork_mark.k2); m2.thread.ms = mp.second; m2.thread.rs = rs2; break; } case Trace_push_back: { frame f = tc_m.t.push_back.f; n.tag = Machine_thread; tc_n.rs = tc_m.rs; tc_n.rs.push_back(f); auto init_fn = [&] (char* p) { new ((frame*)p) frame(f); }; tc_n.ms = push_back<sizeof(frame),decltype(init_fn)>(tc_m.ms, f.plt, init_fn); break; } case Trace_pop_back: { n.tag = Machine_thread; tc_n.rs = tc_m.rs; tc_n.rs.pop_back(); auto destr_fn = [&] (char* p) { ((frame*)(p))->~frame(); }; tc_n.ms = pop_back(tc_m.ms, destr_fn); break; } default: { assert(false); // todo } } break; } case Machine_stuck: { break; } default: { break; } } return n; } /* Trace */ /*------------------------------*/ void ex1() { frame f; f.v = 123; auto t2 = mk_push_back(f); t2->push_back.k.reset(mk_pop_back()); machine_config_type m; step([&] { return rand() % 2 == 0; }, m); } } // end namespace } // end namespace int main(int argc, const char * argv[]) { std::cout << "starting\n"; cactus_stack::basic::ex1(); std::cout << "finished\n"; return 0; } <|endoftext|>
<commit_before>#include <x0/buffer.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <iostream> #include <cstdlib> #include <cctype> #include <cassert> #include <strings.h> class buffer_test : public CPPUNIT_NS::TestFixture { public: CPPUNIT_TEST_SUITE(buffer_test); // buffer CPPUNIT_TEST(ctor0); CPPUNIT_TEST(const_buffer1); CPPUNIT_TEST(resize); CPPUNIT_TEST(capacity); CPPUNIT_TEST(reserve); CPPUNIT_TEST(clear); CPPUNIT_TEST(operator_bool); CPPUNIT_TEST(operator_not); CPPUNIT_TEST(iterators); CPPUNIT_TEST(const_iterators); CPPUNIT_TEST(push_back); CPPUNIT_TEST(random_access); CPPUNIT_TEST(sub); CPPUNIT_TEST(call); CPPUNIT_TEST(std_string); // buffer::view CPPUNIT_TEST(view_ctor); CPPUNIT_TEST(view_begins); CPPUNIT_TEST_SUITE_END(); private: // {{{ buffer tests void ctor0() { x0::buffer a; CPPUNIT_ASSERT(a.empty()); CPPUNIT_ASSERT(a.size() == 0); CPPUNIT_ASSERT(!a); CPPUNIT_ASSERT(!static_cast<bool>(a)); } void const_buffer1() { x0::const_buffer empty(""); CPPUNIT_ASSERT(empty.empty()); CPPUNIT_ASSERT(empty.size() == 0); CPPUNIT_ASSERT(empty == ""); x0::const_buffer hello("hello"); CPPUNIT_ASSERT(!hello.empty()); CPPUNIT_ASSERT(hello.size() == 5); CPPUNIT_ASSERT(hello == "hello"); //! \todo ensure const buffers are unmutable } void resize() { // test modifying buffer size x0::buffer buf; buf.push_back("hello"); CPPUNIT_ASSERT(buf.size() == 5); buf.size(4); CPPUNIT_ASSERT(buf.size() == 4); CPPUNIT_ASSERT(buf == "hell"); //! \todo should not be resizable (const_buffer) //x0::const_buffer cbuf("hello"); //cbuf.size(4); } // test modifying capacity void capacity() { x0::buffer buf; CPPUNIT_ASSERT(buf.capacity() == 0); buf.push_back("hello"); CPPUNIT_ASSERT(buf.capacity() >= 5); buf.capacity(4); CPPUNIT_ASSERT(buf.capacity() == 4); CPPUNIT_ASSERT(buf.size() == 4); CPPUNIT_ASSERT(buf == "hell"); } // test reserve() void reserve() { } void clear() { x0::buffer buf; buf.push_back("hello"); const std::size_t capacity = buf.capacity(); buf.clear(); CPPUNIT_ASSERT(buf.empty()); CPPUNIT_ASSERT(buf.size() == 0); // shouldn't have changed internal buffer CPPUNIT_ASSERT(buf.capacity() == capacity); } void operator_bool() { x0::buffer buf; CPPUNIT_ASSERT(buf.operator bool() == false); buf.push_back("hello"); CPPUNIT_ASSERT(buf.operator bool() == true); } void operator_not() { x0::buffer buf; CPPUNIT_ASSERT(buf.operator!() == true); buf.push_back("hello"); CPPUNIT_ASSERT(buf.operator!() == false); } void iterators() { { x0::buffer buf; buf.push_back("hello"); x0::buffer::iterator i = buf.begin(); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*i == 'h'); CPPUNIT_ASSERT(*++i == 'e'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*i++ == 'e'); CPPUNIT_ASSERT(*i == 'l'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*++i == 'l'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*++i == 'o'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(++i == buf.end()); } { x0::buffer buf; buf.push_back("hello"); for (x0::buffer::iterator i = buf.begin(); i != buf.end(); ++i) *i = std::toupper(*i); CPPUNIT_ASSERT(buf == "HELLO"); } } void const_iterators() { x0::buffer buf; buf.push_back("hello"); x0::const_buffer::const_iterator i = buf.cbegin(); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*i == 'h'); CPPUNIT_ASSERT(*++i == 'e'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*i++ == 'e'); CPPUNIT_ASSERT(*i == 'l'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*++i == 'l'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*++i == 'o'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(++i == buf.cend()); } void push_back() { x0::buffer buf; buf.push_back('h'); CPPUNIT_ASSERT(buf == "h"); buf.push_back(""); CPPUNIT_ASSERT(buf == "h"); buf.push_back("e"); CPPUNIT_ASSERT(buf == "he"); buf.push_back("llo"); CPPUNIT_ASSERT(buf == "hello"); std::string s(" world"); buf.push_back(s); CPPUNIT_ASSERT(buf == "hello world"); buf.clear(); buf.push_back(s.data(), s.size()); CPPUNIT_ASSERT(buf == " world"); } void random_access() { // test operator[](...) } void sub() { x0::const_buffer a("hello"); CPPUNIT_ASSERT(a == "hello"); CPPUNIT_ASSERT(a.sub(0) == "hello"); CPPUNIT_ASSERT(a.sub(1) == "ello"); CPPUNIT_ASSERT(a.sub(2) == "llo"); CPPUNIT_ASSERT(a.sub(5) == ""); } void call() { x0::const_buffer a("hello"); CPPUNIT_ASSERT(a() == "hello"); CPPUNIT_ASSERT(a(0) == "hello"); CPPUNIT_ASSERT(a(1) == "ello"); CPPUNIT_ASSERT(a(2) == "llo"); CPPUNIT_ASSERT(a(5) == ""); } void std_string() { // test std::string() utility functions x0::const_buffer a("hello"); std::string s(a.str()); CPPUNIT_ASSERT(a.data() != s.data()); CPPUNIT_ASSERT(a.size() == s.size()); CPPUNIT_ASSERT(s == "hello"); } // }}} // {{{ buffer::view tests void view_ctor() { } void view_ctor1() { } void view_ctor_buffer() { } void view_ctor_ctor() { } void view_operator_asn_buffer() { } void view_operator_asn_view() { } void view_empty() { } void view_offset() { } void view_size() { } void view_data() { } void view_operator_bool() { } void view_operator_not() { } void view_iterator() { } void view_find_view() { } void view_find_value_ptr() { } void view_find_value() { } void view_rfind_view() { } void view_rfind_value_ptr() { } void view_rfind_value() { } void view_begins() { x0::const_buffer b("hello"); x0::buffer::view v(b); CPPUNIT_ASSERT(v.begins((const char *)0)); CPPUNIT_ASSERT(v.begins("")); CPPUNIT_ASSERT(v.begins("hello")); } void view_ibegins() { } // }}} private: // {{{ debug helper void print(const x0::buffer& b, const char *msg = 0) { if (msg && *msg) printf("buffer(%s): '%s'\n", msg, b.str().c_str()); else printf("buffer: '%s'\n", b.str().c_str()); } void print(const x0::buffer::view& v, const char *msg = 0) { if (msg && *msg) printf("buffer.view(%s): '%s'\n", msg, v.str().c_str()); else printf("buffer.view: '%s'\n", v.str().c_str()); printf(" view.offset=%ld, size=%ld\n", v.offset(), v.size()); } //}}} }; CPPUNIT_TEST_SUITE_REGISTRATION(buffer_test); <commit_msg>added test to `void buffer::reserve(std::size_t)`<commit_after>#include <x0/buffer.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <iostream> #include <cstdlib> #include <cctype> #include <cassert> #include <strings.h> class buffer_test : public CPPUNIT_NS::TestFixture { public: CPPUNIT_TEST_SUITE(buffer_test); // buffer CPPUNIT_TEST(ctor0); CPPUNIT_TEST(const_buffer1); CPPUNIT_TEST(resize); CPPUNIT_TEST(capacity); CPPUNIT_TEST(reserve); CPPUNIT_TEST(clear); CPPUNIT_TEST(operator_bool); CPPUNIT_TEST(operator_not); CPPUNIT_TEST(iterators); CPPUNIT_TEST(const_iterators); CPPUNIT_TEST(push_back); CPPUNIT_TEST(random_access); CPPUNIT_TEST(sub); CPPUNIT_TEST(call); CPPUNIT_TEST(std_string); // buffer::view CPPUNIT_TEST(view_ctor); CPPUNIT_TEST(view_begins); CPPUNIT_TEST_SUITE_END(); private: // {{{ buffer tests void ctor0() { x0::buffer a; CPPUNIT_ASSERT(a.empty()); CPPUNIT_ASSERT(a.size() == 0); CPPUNIT_ASSERT(!a); CPPUNIT_ASSERT(!static_cast<bool>(a)); } void const_buffer1() { x0::const_buffer empty(""); CPPUNIT_ASSERT(empty.empty()); CPPUNIT_ASSERT(empty.size() == 0); CPPUNIT_ASSERT(empty == ""); x0::const_buffer hello("hello"); CPPUNIT_ASSERT(!hello.empty()); CPPUNIT_ASSERT(hello.size() == 5); CPPUNIT_ASSERT(hello == "hello"); //! \todo ensure const buffers are unmutable } void resize() { // test modifying buffer size x0::buffer buf; buf.push_back("hello"); CPPUNIT_ASSERT(buf.size() == 5); buf.size(4); CPPUNIT_ASSERT(buf.size() == 4); CPPUNIT_ASSERT(buf == "hell"); //! \todo should not be resizable (const_buffer) //x0::const_buffer cbuf("hello"); //cbuf.size(4); } // test modifying capacity void capacity() { x0::buffer buf; CPPUNIT_ASSERT(buf.capacity() == 0); buf.push_back("hello"); CPPUNIT_ASSERT(buf.capacity() >= 5); buf.capacity(4); CPPUNIT_ASSERT(buf.capacity() == 4); CPPUNIT_ASSERT(buf.size() == 4); CPPUNIT_ASSERT(buf == "hell"); } // test reserve() void reserve() { x0::buffer buf; buf.reserve(1); CPPUNIT_ASSERT(buf.size() == 0); CPPUNIT_ASSERT(buf.capacity() == x0::buffer::CHUNK_SIZE); } void clear() { x0::buffer buf; buf.push_back("hello"); const std::size_t capacity = buf.capacity(); buf.clear(); CPPUNIT_ASSERT(buf.empty()); CPPUNIT_ASSERT(buf.size() == 0); // shouldn't have changed internal buffer CPPUNIT_ASSERT(buf.capacity() == capacity); } void operator_bool() { x0::buffer buf; CPPUNIT_ASSERT(buf.operator bool() == false); buf.push_back("hello"); CPPUNIT_ASSERT(buf.operator bool() == true); } void operator_not() { x0::buffer buf; CPPUNIT_ASSERT(buf.operator!() == true); buf.push_back("hello"); CPPUNIT_ASSERT(buf.operator!() == false); } void iterators() { { x0::buffer buf; buf.push_back("hello"); x0::buffer::iterator i = buf.begin(); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*i == 'h'); CPPUNIT_ASSERT(*++i == 'e'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*i++ == 'e'); CPPUNIT_ASSERT(*i == 'l'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*++i == 'l'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(*++i == 'o'); CPPUNIT_ASSERT(i != buf.end()); CPPUNIT_ASSERT(++i == buf.end()); } { x0::buffer buf; buf.push_back("hello"); for (x0::buffer::iterator i = buf.begin(); i != buf.end(); ++i) *i = std::toupper(*i); CPPUNIT_ASSERT(buf == "HELLO"); } } void const_iterators() { x0::buffer buf; buf.push_back("hello"); x0::const_buffer::const_iterator i = buf.cbegin(); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*i == 'h'); CPPUNIT_ASSERT(*++i == 'e'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*i++ == 'e'); CPPUNIT_ASSERT(*i == 'l'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*++i == 'l'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(*++i == 'o'); CPPUNIT_ASSERT(i != buf.cend()); CPPUNIT_ASSERT(++i == buf.cend()); } void push_back() { x0::buffer buf; buf.push_back('h'); CPPUNIT_ASSERT(buf == "h"); buf.push_back(""); CPPUNIT_ASSERT(buf == "h"); buf.push_back("e"); CPPUNIT_ASSERT(buf == "he"); buf.push_back("llo"); CPPUNIT_ASSERT(buf == "hello"); std::string s(" world"); buf.push_back(s); CPPUNIT_ASSERT(buf == "hello world"); buf.clear(); buf.push_back(s.data(), s.size()); CPPUNIT_ASSERT(buf == " world"); } void random_access() { // test operator[](...) } void sub() { x0::const_buffer a("hello"); CPPUNIT_ASSERT(a == "hello"); CPPUNIT_ASSERT(a.sub(0) == "hello"); CPPUNIT_ASSERT(a.sub(1) == "ello"); CPPUNIT_ASSERT(a.sub(2) == "llo"); CPPUNIT_ASSERT(a.sub(5) == ""); } void call() { x0::const_buffer a("hello"); CPPUNIT_ASSERT(a() == "hello"); CPPUNIT_ASSERT(a(0) == "hello"); CPPUNIT_ASSERT(a(1) == "ello"); CPPUNIT_ASSERT(a(2) == "llo"); CPPUNIT_ASSERT(a(5) == ""); } void std_string() { // test std::string() utility functions x0::const_buffer a("hello"); std::string s(a.str()); CPPUNIT_ASSERT(a.data() != s.data()); CPPUNIT_ASSERT(a.size() == s.size()); CPPUNIT_ASSERT(s == "hello"); } // }}} // {{{ buffer::view tests void view_ctor() { } void view_ctor1() { } void view_ctor_buffer() { } void view_ctor_ctor() { } void view_operator_asn_buffer() { } void view_operator_asn_view() { } void view_empty() { } void view_offset() { } void view_size() { } void view_data() { } void view_operator_bool() { } void view_operator_not() { } void view_iterator() { } void view_find_view() { } void view_find_value_ptr() { } void view_find_value() { } void view_rfind_view() { } void view_rfind_value_ptr() { } void view_rfind_value() { } void view_begins() { x0::const_buffer b("hello"); x0::buffer::view v(b); CPPUNIT_ASSERT(v.begins((const char *)0)); CPPUNIT_ASSERT(v.begins("")); CPPUNIT_ASSERT(v.begins("hello")); } void view_ibegins() { } // }}} private: // {{{ debug helper void print(const x0::buffer& b, const char *msg = 0) { if (msg && *msg) printf("buffer(%s): '%s'\n", msg, b.str().c_str()); else printf("buffer: '%s'\n", b.str().c_str()); } void print(const x0::buffer::view& v, const char *msg = 0) { if (msg && *msg) printf("buffer.view(%s): '%s'\n", msg, v.str().c_str()); else printf("buffer.view: '%s'\n", v.str().c_str()); printf(" view.offset=%ld, size=%ld\n", v.offset(), v.size()); } //}}} }; CPPUNIT_TEST_SUITE_REGISTRATION(buffer_test); <|endoftext|>
<commit_before>// $Id$ // (c) Guido Kanschat // // Compute support points #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_lib.lagrange.h> #include <fe/fe_lib.dg.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <iomanip> #include <string> template <int dim> inline void check_support (FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 0., 1.); DoFHandler<dim> dof (tr); dof.distribute_dofs (finel); vector<Point<dim> > cell_points (finel.dofs_per_cell); vector<Point<dim> > face_points (finel.dofs_per_face); DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(); finel.get_support_points (cell, cell_points); cout << name << '<' << dim << '>' << " cell support points" << endl; for (unsigned int k=0;k<cell_points.size();++k) cout << setprecision(3) << cell_points[k] << endl; for (unsigned int i=0;i<GeometryInfo<dim>::faces_per_cell;++i) { cout << name << '<' << dim << '>' << " face " << i << " support points" << endl; DoFHandler<dim>::active_face_iterator face = cell->face(i); finel.get_face_support_points (face, face_points); for (unsigned int k=0;k<face_points.size();++k) cout << setprecision(3) << face_points[k] << endl; } } template <int dim> inline void check_matrices (FiniteElement<dim>& fe, const char* name) { cout << name << '<' << dim << '>' << " constraint " << endl; fe.constraints().print_formatted (cout, 7, false, 10, "~"); for (unsigned int i=0;i<GeometryInfo<dim>::children_per_cell;++i) { cout << name << '<' << dim << '>' << " restriction " << i << endl; fe.restrict(i).print_formatted (cout, 3, false, 6, "~"); cout << name << '<' << dim << '>' << " embedding " << i << endl; fe.prolongate(i).print_formatted (cout, 3, false, 6, "~"); } } #define CHECK_S(EL,dim) FE ## EL<dim> EL; check_support(EL, #EL); #define CHECK_M(EL,dim) FE ## EL<dim> EL; check_matrices(EL, #EL); #define CHECK_ALL(EL,dim) FE ## EL<dim> EL; check_support(EL, #EL); check_matrices(EL,#EL) int main() { if (true) { CHECK_ALL(Q1,2); CHECK_ALL(Q2,2); CHECK_ALL(Q3,2); CHECK_ALL(Q4,2); CHECK_ALL(DG_Q0,2); CHECK_ALL(DG_Q1,2); CHECK_ALL(DG_Q2,2); CHECK_ALL(DG_Q3,2); } if (true) { CHECK_ALL(Q1,3); CHECK_ALL(Q2,3); CHECK_ALL(DG_Q0,3); CHECK_ALL(DG_Q1,3); } return 0; } <commit_msg>more checks<commit_after>// $Id$ // (c) Guido Kanschat // // Compute support points #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_lib.lagrange.h> #include <fe/fe_lib.dg.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <iomanip> #include <string> template <int dim> inline void check_support (FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 0., 1.); DoFHandler<dim> dof (tr); dof.distribute_dofs (finel); cout << name << '<' << dim << '>' << " cell support points" << endl; vector<Point<dim> > cell_points (finel.dofs_per_cell); vector<Point<dim> > face_points (finel.dofs_per_face); DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(); finel.get_support_points (cell, cell_points); for (unsigned int k=0;k<cell_points.size();++k) cout << setprecision(3) << cell_points[k] << endl; for (unsigned int i=0;i<GeometryInfo<dim>::faces_per_cell;++i) { cout << name << '<' << dim << '>' << " face " << i << " support points" << endl; DoFHandler<dim>::active_face_iterator face = cell->face(i); finel.get_face_support_points (face, face_points); for (unsigned int k=0;k<face_points.size();++k) cout << setprecision(3) << face_points[k] << endl; } } template <int dim> inline void check_matrices (FiniteElement<dim>& fe, const char* name) { cout << name << '<' << dim << '>' << " constraint " << endl; fe.constraints().print_formatted (cout, 7, false, 10, "~"); for (unsigned int i=0;i<GeometryInfo<dim>::children_per_cell;++i) { cout << name << '<' << dim << '>' << " restriction " << i << endl; fe.restrict(i).print_formatted (cout, 3, false, 6, "~"); cout << name << '<' << dim << '>' << " embedding " << i << endl; fe.prolongate(i).print_formatted (cout, 3, false, 6, "~"); } } #define CHECK_S(EL,dim) { FE ## EL<dim> EL; check_support(EL, #EL); } #define CHECK_M(EL,dim) { FE ## EL<dim> EL; check_matrices(EL, #EL); } #define CHECK_ALL(EL,dim) { FE ## EL<dim> EL; check_support(EL, #EL); check_matrices(EL,#EL); } int main() { CHECK_M(DG_Q0,2); CHECK_M(DG_Q1,2); CHECK_M(DG_Q2,2); CHECK_M(DG_Q3,2); CHECK_ALL(Q1,2); CHECK_ALL(Q2,2); CHECK_ALL(Q3,2); CHECK_ALL(Q4,2); CHECK_ALL(Q1,3); CHECK_ALL(Q2,3); CHECK_M(DG_Q0,3); CHECK_M(DG_Q1,3); return 0; } <|endoftext|>
<commit_before>#include "storage/storage_helpers.hpp" #include "storage/country_info_getter.hpp" #include "storage/storage.hpp" #include "platform/platform.hpp" namespace storage { bool IsPointCoveredByDownloadedMaps(m2::PointD const & position, Storage const & storage, CountryInfoGetter const & countryInfoGetter) { return storage.IsNodeDownloaded(countryInfoGetter.GetRegionCountryId(position)); } bool IsDownloadFailed(Status status) { return status == Status::EDownloadFailed || status == Status::EOutOfMemFailed || status == Status::EUnknown; } bool IsEnoughSpaceForDownload(TMwmSize mwmSize) { return GetPlatform().GetWritableStorageStatus(mwmSize) == Platform::TStorageStatus::STORAGE_OK; } bool IsEnoughSpaceForDownload(TMwmSize mwmSizeDiff, TMwmSize maxMwmSize) { // Mwm size is less than |maxMwmSize|. In case of map update at first we download updated map // and only after that we do delete the obsolete map. So in such a case we might need up to // |maxMwmSize| of extra space. return IsEnoughSpaceForDownload(mwmSizeDiff + maxMwmSize); } bool IsEnoughSpaceForDownload(TCountryId const & countryId, Storage const & storage) { NodeAttrs nodeAttrs; storage.GetNodeAttrs(countryId, nodeAttrs); return IsEnoughSpaceForDownload(nodeAttrs.m_mwmSize); } bool IsEnoughSpaceForUpdate(TCountryId const & countryId, Storage const & storage) { Storage::UpdateInfo updateInfo; storage.GetUpdateInfo(countryId, updateInfo); TMwmSize spaceNeedForUpdate = updateInfo.m_sizeDifference > 0 ? updateInfo.m_sizeDifference : 0; return IsEnoughSpaceForDownload(spaceNeedForUpdate, storage.GetMaxMwmSizeBytes()); } m2::RectD CalcLimitRect(TCountryId const & countryId, Storage const & storage, CountryInfoGetter const & countryInfoGetter) { m2::RectD boundingBox; auto const accumulator = [&countryInfoGetter, &boundingBox](TCountryId const & descendantId, bool groupNode) { if (!groupNode) boundingBox.Add(countryInfoGetter.GetLimitRectForLeaf(descendantId)); }; storage.ForEachInSubtree(countryId, accumulator); ASSERT(boundingBox.IsValid(), ()); return boundingBox; } } // namespace storage <commit_msg>Review fixes.<commit_after>#include "storage/storage_helpers.hpp" #include "storage/country_info_getter.hpp" #include "storage/storage.hpp" #include "platform/platform.hpp" namespace storage { bool IsPointCoveredByDownloadedMaps(m2::PointD const & position, Storage const & storage, CountryInfoGetter const & countryInfoGetter) { return storage.IsNodeDownloaded(countryInfoGetter.GetRegionCountryId(position)); } bool IsDownloadFailed(Status status) { return status == Status::EDownloadFailed || status == Status::EOutOfMemFailed || status == Status::EUnknown; } bool IsEnoughSpaceForDownload(TMwmSize mwmSize) { // Additional size which is necessary to have on flash card to download file of mwmSize bytes. TMwmSize constexpr kExtraSizeBytes = 10 * 1024 * 1024; return GetPlatform().GetWritableStorageStatus(mwmSize + kExtraSizeBytes) == Platform::TStorageStatus::STORAGE_OK; } bool IsEnoughSpaceForDownload(TMwmSize mwmSizeDiff, TMwmSize maxMwmSize) { // Mwm size is less than |maxMwmSize|. In case of map update at first we download updated map // and only after that we do delete the obsolete map. So in such a case we might need up to // |maxMwmSize| of extra space. return IsEnoughSpaceForDownload(mwmSizeDiff + maxMwmSize); } bool IsEnoughSpaceForDownload(TCountryId const & countryId, Storage const & storage) { NodeAttrs nodeAttrs; storage.GetNodeAttrs(countryId, nodeAttrs); return IsEnoughSpaceForDownload(nodeAttrs.m_mwmSize); } bool IsEnoughSpaceForUpdate(TCountryId const & countryId, Storage const & storage) { Storage::UpdateInfo updateInfo; storage.GetUpdateInfo(countryId, updateInfo); TMwmSize spaceNeedForUpdate = updateInfo.m_sizeDifference > 0 ? updateInfo.m_sizeDifference : 0; return IsEnoughSpaceForDownload(spaceNeedForUpdate, storage.GetMaxMwmSizeBytes()); } m2::RectD CalcLimitRect(TCountryId const & countryId, Storage const & storage, CountryInfoGetter const & countryInfoGetter) { m2::RectD boundingBox; auto const accumulator = [&countryInfoGetter, &boundingBox](TCountryId const & descendantId, bool groupNode) { if (!groupNode) boundingBox.Add(countryInfoGetter.GetLimitRectForLeaf(descendantId)); }; storage.ForEachInSubtree(countryId, accumulator); ASSERT(boundingBox.IsValid(), ()); return boundingBox; } } // namespace storage <|endoftext|>
<commit_before>/* * File: AlarmClockSpeedTest.cpp * Author: Amanda Carbonari * Created: January 6, 2015 9:00am * * WARNING: This only measures CPU time */ #include <ctime> #include <iostream> #include <AlarmClock.h> #include <chrono> using namespace std; typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while(!alerter.Expired()); } int main(int, const char**) { clock_t start; clock_t end; unsigned int us = 389; cout << "Creating Alarm Clock" << endl; AlarmClock<microseconds> alerter(us); // Give some time for the countdown to start this_thread::sleep_for(chrono::microseconds(20)); cout << "Starting clock and resetting" << endl; start = clock(); alerter.Reset(); end = clock(); clock_t reset_time = (end - start) / (double) (CLOCKS_PER_SEC); cout << "Start: " << start << ", End: " << end << endl; cout << "Waiting for the clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "Time: " << reset_time << " us" << endl; }<commit_msg>Implemented timing mechanism with chrono<commit_after>/* * File: AlarmClockSpeedTest.cpp * Author: Amanda Carbonari * Created: January 6, 2015 9:00am * * WARNING: This only measures CPU time */ #include <ctime> #include <iostream> #include <AlarmClock.h> #include <chrono> using namespace std; using namespace std::chrono; typedef std::chrono::microseconds microseconds; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::seconds seconds; template<typename T> void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) { while(!alerter.Expired()); } int main(int, const char**) { unsigned int us = 389; cout << "Creating Alarm Clock" << endl; AlarmClock<microseconds> alerter(us); // Give some time for the countdown to start this_thread::sleep_for(chrono::microseconds(20)); cout << "Starting clock and resetting" << endl; high_resolution_clock::time_point start = high_resolution_clock::now(); alerter.Reset(); high_resolution_clock::time_point end = high_resolution_clock::now(); auto reset_time = duration_cast<microseconds>(end - start).count(); cout << "Start: " << start << ", End: " << end << endl; cout << "Waiting for the clock to expire" << endl; WaitForAlarmClockToExpire(alerter); cout << "Time: " << reset_time << " us" << endl; }<|endoftext|>
<commit_before>/* * source.cpp * * Created on: Feb 8, 2012 * Author: mpetkova */ #include <slsimlib.h> #include <sstream> const string escape = "#"; char dummy[300]; Source::Source(){ } SourceUniform::SourceUniform(string filename) : Source(){ readParamfile(filename); } SourceGaussian::SourceGaussian(string filename) : Source(){ readParamfile(filename); } SourceBLR::SourceBLR(string filename) : Source(){ readParamfile(filename); } SourceBLRDisk::SourceBLRDisk(string filename) : SourceBLR(filename){ } SourceBLRSph1::SourceBLRSph1(string filename) : SourceBLR(filename){ } SourceBLRSph2::SourceBLRSph2(string filename) : SourceBLR(filename){ } Source::~Source(){ } SourceUniform::~SourceUniform(){ } SourceGaussian::~SourceGaussian(){ } SourceBLR::~SourceBLR(){ } SourceBLRDisk::~SourceBLRDisk(){ } SourceBLRSph1::~SourceBLRSph1(){ } SourceBLRSph2::~SourceBLRSph2(){ } void SourceUniform::readParamfile(string filename){ string label, rlabel, rvalue; stringstream ss; double mydouble; int flag; label = "z_source"; cout << "uniform source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } flag = 1; // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; if(rlabel == label){ flag = 0; ss << rvalue; ss >> mydouble; zsource = mydouble; ss.clear(); ss.str(string()); } } file_in.close(); if(flag > 0){ ERROR_MESSAGE(); cout << "parameter " << label << " needs to be set!" << endl; exit(0); } printSource(); } void SourceGaussian::readParamfile(string filename){ string label[2], rlabel, rvalue; stringstream ss; void *addr[2]; int id[2]; int i; double mydouble; int flag; addr[0] = &zsource; id[0] = 0; label[0] = "z_source"; addr[1] = &source_gauss_r2; id[1] = 0; label[1] = "gauss_r2"; cout << "gaussian source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; flag = 1; for(i = 0; i < 2; i++){ if(rlabel == label[i]){ flag = 0; ss << rvalue; ss >> mydouble; *((double *)addr[i]) = mydouble; ss.clear(); ss.str(string()); } id[i] = -1; } } file_in.close(); for(i = 0; i < 2; i++){ if(id[i] > 0){ ERROR_MESSAGE(); cout << "parameter " << label[i] << " needs to be set!" << endl; exit(0); } } printSource(); } void SourceBLR::readParamfile(string filename){ string label[9], rlabel, rvalue; stringstream ss; void *addr[9]; int id[9]; int i, n; float myfloat; int flag; n = 0; addr[n] = &zsource; id[n] = 0; label[n++] = "z_source"; addr[n] = &source_BHmass; id[n] = 0; label[n++] = "BHmass"; addr[n] = &source_gamma; id[n] = 0; label[n++] = "gamma"; addr[n] = &source_inclination; id[n] = 0; label[n++] = "inclin"; addr[n] = &source_opening_angle; id[n] = 0; label[n++] = "opening_ang"; addr[n] = &source_r_in; id[n] = 0; label[n++] = "r_in"; addr[n] = &source_r_out; id[n] = 0; label[n++] = "r_out"; addr[n] = &source_nuo; id[n] = 0; label[n++] = "nuo"; addr[n] = &source_fK; id[n] = 0; label[n++] = "source_sigma"; cout << "BLR source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; flag = 1; for(i = 0; i < 9; i++){ if(rlabel == label[i]){ flag = 0; ss << rvalue; ss >> myfloat; *((float *)addr[i]) = myfloat; ss.clear(); ss.str(string()); id[i] = -1; } } } file_in.close(); for(i = 0; i < n; i++){ if(id[i] > 0){ ERROR_MESSAGE(); cout << "parameter " << label[i] << " needs to be set!" << endl; exit(0); } } source_inclination *= pi/180; source_opening_angle *= pi/180; source_monocrome = false; printSource(); } void SourceUniform::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl << endl; } void SourceGaussian::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl; cout << "gauss_r2 " << source_gauss_r2 << endl << endl; } void SourceBLR::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl; cout << "BHmass " << source_BHmass << endl; cout << "gamma " << source_gamma << endl; cout << "incl " << source_inclination << endl; cout << "opening angl " << source_opening_angle << endl; cout << "r_in " << source_r_in << endl; cout << "r_out " << source_r_out << endl; cout << "nuo " << source_nuo << endl; cout << "source_sigma " << source_fK << endl << endl; } double SourceUniform::source_sb_func(double *y){ return (double)( (y[0]*y[0] + y[1]*y[1]) < source_r*source_r ); } double SourceGaussian::source_sb_func(double *y){ return exp( -(y[0]*y[0] + y[1]*y[1])/source_gauss_r2 ); } // surface brightness for models of the Broad Line Region double SourceBLRDisk::source_sb_func(double *y){ return blr_surface_brightness_disk(y,this); } double SourceBLRSph1::source_sb_func(double *y){ return blr_surface_brightness_spherical_circular_motions(sqrt(y[0]*y[0] + y[1]*y[1]),this); } double SourceBLRSph2::source_sb_func(double *y){ return blr_surface_brightness_spherical_random_motions(sqrt(y[0]*y[0] + y[1]*y[1]),this); } void in_source(double *y_source,ListHndl sourcelist){ return; } <commit_msg>fixed the double/float param input for the BLR source<commit_after>/* * source.cpp * * Created on: Feb 8, 2012 * Author: mpetkova */ #include <slsimlib.h> #include <sstream> const string escape = "#"; char dummy[300]; Source::Source(){ } SourceUniform::SourceUniform(string filename) : Source(){ readParamfile(filename); } SourceGaussian::SourceGaussian(string filename) : Source(){ readParamfile(filename); } SourceBLR::SourceBLR(string filename) : Source(){ readParamfile(filename); } SourceBLRDisk::SourceBLRDisk(string filename) : SourceBLR(filename){ } SourceBLRSph1::SourceBLRSph1(string filename) : SourceBLR(filename){ } SourceBLRSph2::SourceBLRSph2(string filename) : SourceBLR(filename){ } Source::~Source(){ } SourceUniform::~SourceUniform(){ } SourceGaussian::~SourceGaussian(){ } SourceBLR::~SourceBLR(){ } SourceBLRDisk::~SourceBLRDisk(){ } SourceBLRSph1::~SourceBLRSph1(){ } SourceBLRSph2::~SourceBLRSph2(){ } void SourceUniform::readParamfile(string filename){ string label, rlabel, rvalue; stringstream ss; double mydouble; int flag; label = "z_source"; cout << "uniform source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } flag = 1; // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; if(rlabel == label){ flag = 0; ss << rvalue; ss >> mydouble; zsource = mydouble; ss.clear(); ss.str(string()); } } file_in.close(); if(flag > 0){ ERROR_MESSAGE(); cout << "parameter " << label << " needs to be set!" << endl; exit(0); } printSource(); } void SourceGaussian::readParamfile(string filename){ string label[2], rlabel, rvalue; stringstream ss; void *addr[2]; int id[2]; int i; double mydouble; int flag; addr[0] = &zsource; id[0] = 0; label[0] = "z_source"; addr[1] = &source_gauss_r2; id[1] = 0; label[1] = "gauss_r2"; cout << "gaussian source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; flag = 1; for(i = 0; i < 2; i++){ if(rlabel == label[i]){ flag = 0; ss << rvalue; ss >> mydouble; *((double *)addr[i]) = mydouble; ss.clear(); ss.str(string()); } id[i] = -1; } } file_in.close(); for(i = 0; i < 2; i++){ if(id[i] > 0){ ERROR_MESSAGE(); cout << "parameter " << label[i] << " needs to be set!" << endl; exit(0); } } printSource(); } void SourceBLR::readParamfile(string filename){ string label[9], rlabel, rvalue; stringstream ss; void *addr[9]; int id[9]; int i, n; float myfloat; double mydouble; int flag; n = 0; addr[n] = &zsource; id[n] = 1; label[n++] = "z_source"; addr[n] = &source_BHmass; id[n] = 0; label[n++] = "BHmass"; addr[n] = &source_gamma; id[n] = 0; label[n++] = "gamma"; addr[n] = &source_inclination; id[n] = 0; label[n++] = "inclin"; addr[n] = &source_opening_angle; id[n] = 0; label[n++] = "opening_ang"; addr[n] = &source_r_in; id[n] = 0; label[n++] = "r_in"; addr[n] = &source_r_out; id[n] = 0; label[n++] = "r_out"; addr[n] = &source_nuo; id[n] = 0; label[n++] = "nuo"; addr[n] = &source_fK; id[n] = 0; label[n++] = "source_sigma"; cout << "BLR source: reading from " << filename << endl; ifstream file_in(filename.c_str()); if(!file_in){ cout << "Can't open file " << filename << endl; exit(1); } // output file while(!file_in.eof()){ file_in >> rlabel >> rvalue; file_in.getline(dummy,100); if(rlabel[0] == escape[0]) continue; flag = 1; for(i = 0; i < n; i++){ if(rlabel == label[i]){ flag = 0; ss << rvalue; switch(id[i]){ case 0: ss >> myfloat; *((float *)addr[i]) = myfloat; break; case 1: ss >> mydouble; *((double *)addr[i]) = mydouble; break; } ss.clear(); ss.str(string()); id[i] = -1; } } } file_in.close(); for(i = 0; i < n; i++){ if(id[i] > 0){ ERROR_MESSAGE(); cout << "parameter " << label[i] << " needs to be set!" << endl; exit(0); } } source_inclination *= pi/180; source_opening_angle *= pi/180; source_monocrome = false; printSource(); } void SourceUniform::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl << endl; } void SourceGaussian::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl; cout << "gauss_r2 " << source_gauss_r2 << endl << endl; } void SourceBLR::printSource(){ cout << endl << "**Source model**" << endl; cout << "z_source " << zsource << endl; cout << "BHmass " << source_BHmass << endl; cout << "gamma " << source_gamma << endl; cout << "incl " << source_inclination << endl; cout << "opening angl " << source_opening_angle << endl; cout << "r_in " << source_r_in << endl; cout << "r_out " << source_r_out << endl; cout << "nuo " << source_nuo << endl; cout << "source_sigma " << source_fK << endl << endl; } double SourceUniform::source_sb_func(double *y){ return (double)( (y[0]*y[0] + y[1]*y[1]) < source_r*source_r ); } double SourceGaussian::source_sb_func(double *y){ return exp( -(y[0]*y[0] + y[1]*y[1])/source_gauss_r2 ); } // surface brightness for models of the Broad Line Region double SourceBLRDisk::source_sb_func(double *y){ return blr_surface_brightness_disk(y,this); } double SourceBLRSph1::source_sb_func(double *y){ return blr_surface_brightness_spherical_circular_motions(sqrt(y[0]*y[0] + y[1]*y[1]),this); } double SourceBLRSph2::source_sb_func(double *y){ return blr_surface_brightness_spherical_random_motions(sqrt(y[0]*y[0] + y[1]*y[1]),this); } void in_source(double *y_source,ListHndl sourcelist){ return; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 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. * */ #include <jni.h> #include <errno.h> #include <android_native_app_glue.h> #include "UtH/Platform/OpenGL.hpp" #ifndef MATH_H_UMATH namespace umath { struct vector2 { int x,y; }; } #endif //Struct containing EGL stugg and android app struct AndroidEngine { android_app* app; //Below this to Graphics-classs? EGLDisplay display; EGLSurface surface; EGLContext context; EGLConfig config; umath::vector2 resolution; }; //To Graphics init or Renderer class int displayInit(AndroidEngine* androidengine) { const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLint attribList[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLint format, numConfigs; androidengine->display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(androidengine->display,0,0); eglChooseConfig(androidengine->display, attribs, &androidengine->config, 1, &numConfigs); eglGetConfigAttrib(androidengine->display, androidengine->config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(androidengine->app->window, 0, 0, format); androidengine->surface = eglCreateWindowSurface(androidengine->display, androidengine->surface, androidengine->app->window, NULL); androidengine->context = eglCreateContext(androidengine->display, androidengine->config, NULL, attribList); if(eglMakeCurrent(androidengine->display, androidengine->surface, androidengine->surface, androidengine->context) == false) { //WriteLog("eglMakeCurrent failed"); return -1; } eglQuerySurface(androidengine->display, androidengine->surface, EGL_WIDTH, &androidengine->resolution.x); eglQuerySurface(androidengine->display, androidengine->surface, EGL_HEIGHT, &androidengine->resolution.y); glHint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glViewport(0,0,androidengine->resolution.x,androidengine->resolution.y); return 0; } void displayDestroy(AndroidEngine* androidengine) { if(androidengine->display != EGL_NO_DISPLAY) { eglMakeCurrent(androidengine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if(androidengine->display != EGL_NO_DISPLAY) { eglDestroyContext(androidengine->display, androidengine->context); } if (androidengine->surface != EGL_NO_SURFACE) { eglDestroySurface(androidengine->display, androidengine->surface); } eglTerminate(androidengine->display); } androidengine->display = EGL_NO_DISPLAY; androidengine->context = EGL_NO_CONTEXT; androidengine->surface = EGL_NO_SURFACE; } //After input manager int handle_input(android_app* app, AInputEvent* event) { AndroidEngine* androidengine = (AndroidEngine*)app->userData; //Input should be places here return 0; } void draw_frame(AndroidEngine* androidengine) { } //This is sort of state manager. Checks is Activity on top or not and does it have saved state void handle_cmd(android_app* app, int cmd) { AndroidEngine* androidengine = (AndroidEngine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: break; case APP_CMD_INIT_WINDOW: if (androidengine->app->window != NULL) { displayInit(androidengine); draw_frame(androidengine); } break; case APP_CMD_TERM_WINDOW: displayDestroy(androidengine); break; case APP_CMD_LOST_FOCUS: draw_frame(androidengine); break; } } void android_main(android_app* state) { AndroidEngine androidengine; app_dummy(); memset(&androidengine, 0, sizeof(AndroidEngine)); state->userData = &androidengine; state->onAppCmd = handle_cmd; state->onInputEvent = handle_input; androidengine.app = state; while(1) { int ident; int events; android_poll_source* source; while ((ident=ALooper_pollAll(0, NULL, &events,(void**)&source)) >= 0) { //Insteads of these two 'if' statement proper exit should be placed if (source != NULL) { source->process(state, source); } if (state->destroyRequested != 0) { displayDestroy(&androidengine); return; } } if(androidengine.display == NULL) { ;//Do nothing } else { //engine->Update(); } } }<commit_msg>Added UtH Debug<commit_after>/* * Copyright (C) 2010 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. * */ #include <jni.h> #include <errno.h> #include <android_native_app_glue.h> #include "UtH/Platform/OpenGL.hpp" #include "UtH/Platform/Debug.hpp" #ifndef MATH_H_UMATH namespace umath { struct vector2 { int x,y; }; } #endif //Struct containing EGL stugg and android app struct AndroidEngine { android_app* app; //Below this to Graphics-classs? EGLDisplay display; EGLSurface surface; EGLContext context; EGLConfig config; umath::vector2 resolution; }; //To Graphics init or Renderer class int displayInit(AndroidEngine* androidengine) { const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLint attribList[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLint format, numConfigs; androidengine->display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(androidengine->display,0,0); eglChooseConfig(androidengine->display, attribs, &androidengine->config, 1, &numConfigs); eglGetConfigAttrib(androidengine->display, androidengine->config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(androidengine->app->window, 0, 0, format); androidengine->surface = eglCreateWindowSurface(androidengine->display, androidengine->surface, androidengine->app->window, NULL); androidengine->context = eglCreateContext(androidengine->display, androidengine->config, NULL, attribList); if(eglMakeCurrent(androidengine->display, androidengine->surface, androidengine->surface, androidengine->context) == false) { WriteLog("eglMakeCurrent failed"); return -1; } eglQuerySurface(androidengine->display, androidengine->surface, EGL_WIDTH, &androidengine->resolution.x); eglQuerySurface(androidengine->display, androidengine->surface, EGL_HEIGHT, &androidengine->resolution.y); glHint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glViewport(0,0,androidengine->resolution.x,androidengine->resolution.y); return 0; } void displayDestroy(AndroidEngine* androidengine) { if(androidengine->display != EGL_NO_DISPLAY) { eglMakeCurrent(androidengine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if(androidengine->display != EGL_NO_DISPLAY) { eglDestroyContext(androidengine->display, androidengine->context); } if (androidengine->surface != EGL_NO_SURFACE) { eglDestroySurface(androidengine->display, androidengine->surface); } eglTerminate(androidengine->display); } androidengine->display = EGL_NO_DISPLAY; androidengine->context = EGL_NO_CONTEXT; androidengine->surface = EGL_NO_SURFACE; } //After input manager int handle_input(android_app* app, AInputEvent* event) { AndroidEngine* androidengine = (AndroidEngine*)app->userData; //Input should be places here return 0; } void draw_frame(AndroidEngine* androidengine) { } //This is sort of state manager. Checks is Activity on top or not and does it have saved state void handle_cmd(android_app* app, int cmd) { AndroidEngine* androidengine = (AndroidEngine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: break; case APP_CMD_INIT_WINDOW: if (androidengine->app->window != NULL) { displayInit(androidengine); draw_frame(androidengine); } break; case APP_CMD_TERM_WINDOW: displayDestroy(androidengine); break; case APP_CMD_LOST_FOCUS: draw_frame(androidengine); break; } } void android_main(android_app* state) { AndroidEngine androidengine; app_dummy(); memset(&androidengine, 0, sizeof(AndroidEngine)); state->userData = &androidengine; state->onAppCmd = handle_cmd; state->onInputEvent = handle_input; androidengine.app = state; while(1) { int ident; int events; android_poll_source* source; while ((ident=ALooper_pollAll(0, NULL, &events,(void**)&source)) >= 0) { //Insteads of these two 'if' statement proper exit should be placed if (source != NULL) { source->process(state, source); } if (state->destroyRequested != 0) { displayDestroy(&androidengine); return; } } if(androidengine.display == NULL) { ;//Do nothing } else { //engine->Update(); } } }<|endoftext|>
<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/codec.h" #include "flutter/common/task_runners.h" #include "flutter/glue/trace_event.h" #include "flutter/lib/ui/painting/frame_info.h" #include "lib/fxl/functional/make_copyable.h" #include "lib/fxl/logging.h" #include "lib/tonic/dart_binding_macros.h" #include "lib/tonic/dart_library_natives.h" #include "lib/tonic/dart_state.h" #include "lib/tonic/logging/dart_invoke.h" #include "lib/tonic/typed_data/uint8_list.h" #include "third_party/skia/include/codec/SkCodec.h" #include "third_party/skia/include/core/SkPixelRef.h" #ifdef ERROR #undef ERROR #endif using tonic::DartInvoke; using tonic::DartPersistentValue; using tonic::ToDart; namespace blink { namespace { static constexpr const char* kInitCodecTraceTag = "InitCodec"; static constexpr const char* kCodecNextFrameTraceTag = "CodecNextFrame"; static void InvokeCodecCallback(fxl::RefPtr<Codec> codec, std::unique_ptr<DartPersistentValue> callback, size_t trace_id) { tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); return; } tonic::DartState::Scope scope(dart_state); if (!codec) { DartInvoke(callback->value(), {Dart_Null()}); } else { DartInvoke(callback->value(), {ToDart(codec)}); } TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); } static sk_sp<SkImage> DecodeImage(fml::WeakPtr<GrContext> context, sk_sp<SkData> buffer, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("flutter", "DecodeImage"); if (buffer == nullptr || buffer->isEmpty()) { return nullptr; } if (context) { // This indicates that we do not want a "linear blending" decode. sk_sp<SkColorSpace> dstColorSpace = nullptr; return SkImage::MakeCrossContextFromEncoded( context.get(), std::move(buffer), false, dstColorSpace.get()); } else { // Defer decoding until time of draw later on the GPU thread. Can happen // when GL operations are currently forbidden such as in the background // on iOS. return SkImage::MakeFromEncoded(std::move(buffer)); } } fxl::RefPtr<Codec> InitCodec(fml::WeakPtr<GrContext> context, sk_sp<SkData> buffer, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("blink", "InitCodec"); if (buffer == nullptr || buffer->isEmpty()) { FXL_LOG(ERROR) << "InitCodec failed - buffer was empty "; return nullptr; } std::unique_ptr<SkCodec> skCodec = SkCodec::MakeFromData(buffer); if (!skCodec) { FXL_LOG(ERROR) << "Failed decoding image. Data is either invalid, or it is " "encoded using an unsupported format."; return nullptr; } if (skCodec->getFrameCount() > 1) { return fxl::MakeRefCounted<MultiFrameCodec>(std::move(skCodec)); } auto skImage = DecodeImage(context, buffer, trace_id); if (!skImage) { FXL_LOG(ERROR) << "DecodeImage failed"; return nullptr; } auto image = CanvasImage::Create(); image->set_image({skImage, unref_queue}); auto frameInfo = fxl::MakeRefCounted<FrameInfo>(std::move(image), 0); return fxl::MakeRefCounted<SingleFrameCodec>(std::move(frameInfo)); } void InitCodecAndInvokeCodecCallback( fxl::RefPtr<fxl::TaskRunner> ui_task_runner, fml::WeakPtr<GrContext> context, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, std::unique_ptr<DartPersistentValue> callback, sk_sp<SkData> buffer, size_t trace_id) { auto codec = InitCodec(context, std::move(buffer), std::move(unref_queue), trace_id); ui_task_runner->PostTask( fxl::MakeCopyable([callback = std::move(callback), codec = std::move(codec), trace_id]() mutable { InvokeCodecCallback(std::move(codec), std::move(callback), trace_id); })); } void InstantiateImageCodec(Dart_NativeArguments args) { static size_t trace_counter = 1; const size_t trace_id = trace_counter++; TRACE_FLOW_BEGIN("flutter", kInitCodecTraceTag, trace_id); Dart_Handle exception = nullptr; tonic::Uint8List list = tonic::DartConverter<tonic::Uint8List>::FromArguments(args, 0, exception); if (exception) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); Dart_SetReturnValue(args, exception); return; } Dart_Handle callback_handle = Dart_GetNativeArgument(args, 1); if (!Dart_IsClosure(callback_handle)) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); Dart_SetReturnValue(args, ToDart("Callback must be a function")); return; } auto buffer = SkData::MakeWithCopy(list.data(), list.num_elements()); auto dart_state = UIDartState::Current(); const auto& task_runners = dart_state->GetTaskRunners(); task_runners.GetIOTaskRunner()->PostTask(fxl::MakeCopyable( [callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle), buffer = std::move(buffer), trace_id, ui_task_runner = task_runners.GetUITaskRunner(), context = dart_state->GetResourceContext(), queue = UIDartState::Current()->GetSkiaUnrefQueue()]() mutable { InitCodecAndInvokeCodecCallback(std::move(ui_task_runner), context, std::move(queue), std::move(callback), std::move(buffer), trace_id); })); } bool copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) { SkPixmap srcPM; if (!src.peekPixels(&srcPM)) { return false; } SkBitmap tmpDst; SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType); if (!tmpDst.setInfo(dstInfo)) { return false; } if (!tmpDst.tryAllocPixels()) { return false; } SkPixmap dstPM; if (!tmpDst.peekPixels(&dstPM)) { return false; } if (!srcPM.readPixels(dstPM)) { return false; } dst->swap(tmpDst); return true; } void InvokeNextFrameCallback(fxl::RefPtr<FrameInfo> frameInfo, std::unique_ptr<DartPersistentValue> callback, size_t trace_id) { tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); return; } tonic::DartState::Scope scope(dart_state); if (!frameInfo) { DartInvoke(callback->value(), {Dart_Null()}); } else { DartInvoke(callback->value(), {ToDart(frameInfo)}); } TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); } } // namespace IMPLEMENT_WRAPPERTYPEINFO(ui, Codec); #define FOR_EACH_BINDING(V) \ V(Codec, getNextFrame) \ V(Codec, frameCount) \ V(Codec, repetitionCount) \ V(Codec, dispose) FOR_EACH_BINDING(DART_NATIVE_CALLBACK) void Codec::dispose() { ClearDartWrapper(); } MultiFrameCodec::MultiFrameCodec(std::unique_ptr<SkCodec> codec) : codec_(std::move(codec)) { repetitionCount_ = codec_->getRepetitionCount(); frameInfos_ = codec_->getFrameInfo(); frameBitmaps_.resize(frameInfos_.size()); nextFrameIndex_ = 0; } sk_sp<SkImage> MultiFrameCodec::GetNextFrameImage( fml::WeakPtr<GrContext> resourceContext) { SkBitmap& bitmap = frameBitmaps_[nextFrameIndex_]; if (!bitmap.getPixels()) { // We haven't decoded this frame yet const SkImageInfo info = codec_->getInfo().makeColorType(kN32_SkColorType); bitmap.allocPixels(info); SkCodec::Options options; options.fFrameIndex = nextFrameIndex_; const int requiredFrame = frameInfos_[nextFrameIndex_].fRequiredFrame; if (requiredFrame != SkCodec::kNone) { if (requiredFrame < 0 || static_cast<size_t>(requiredFrame) >= frameBitmaps_.size()) { FXL_LOG(ERROR) << "Frame " << nextFrameIndex_ << " depends on frame " << requiredFrame << " which out of range (0," << frameBitmaps_.size() << ")."; return NULL; } SkBitmap& requiredBitmap = frameBitmaps_[requiredFrame]; // For simplicity, do not try to cache old frames if (requiredBitmap.getPixels() && copy_to(&bitmap, requiredBitmap.colorType(), requiredBitmap)) { options.fPriorFrame = requiredFrame; } } if (SkCodec::kSuccess != codec_->getPixels(info, bitmap.getPixels(), bitmap.rowBytes(), &options)) { FXL_LOG(ERROR) << "Could not getPixels for frame " << nextFrameIndex_; return NULL; } } if (resourceContext) { SkPixmap pixmap(bitmap.info(), bitmap.pixelRef()->pixels(), bitmap.pixelRef()->rowBytes()); // This indicates that we do not want a "linear blending" decode. sk_sp<SkColorSpace> dstColorSpace = nullptr; return SkImage::MakeCrossContextFromPixmap(resourceContext.get(), pixmap, false, dstColorSpace.get()); } else { // Defer decoding until time of draw later on the GPU thread. Can happen // when GL operations are currently forbidden such as in the background // on iOS. return SkImage::MakeFromBitmap(bitmap); } } void MultiFrameCodec::GetNextFrameAndInvokeCallback( std::unique_ptr<DartPersistentValue> callback, fxl::RefPtr<fxl::TaskRunner> ui_task_runner, fml::WeakPtr<GrContext> resourceContext, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, size_t trace_id) { fxl::RefPtr<FrameInfo> frameInfo = NULL; sk_sp<SkImage> skImage = GetNextFrameImage(resourceContext); if (skImage) { fxl::RefPtr<CanvasImage> image = CanvasImage::Create(); image->set_image({skImage, std::move(unref_queue)}); frameInfo = fxl::MakeRefCounted<FrameInfo>( std::move(image), frameInfos_[nextFrameIndex_].fDuration); } nextFrameIndex_ = (nextFrameIndex_ + 1) % frameInfos_.size(); ui_task_runner->PostTask(fxl::MakeCopyable( [callback = std::move(callback), frameInfo, trace_id]() mutable { InvokeNextFrameCallback(frameInfo, std::move(callback), trace_id); })); TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); } Dart_Handle MultiFrameCodec::getNextFrame(Dart_Handle callback_handle) { static size_t trace_counter = 1; const size_t trace_id = trace_counter++; TRACE_FLOW_BEGIN("flutter", kCodecNextFrameTraceTag, trace_id); if (!Dart_IsClosure(callback_handle)) { TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); return ToDart("Callback must be a function"); } auto dart_state = UIDartState::Current(); const auto& task_runners = dart_state->GetTaskRunners(); task_runners.GetIOTaskRunner()->PostTask(fxl::MakeCopyable( [callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle), this, trace_id, ui_task_runner = task_runners.GetUITaskRunner(), queue = UIDartState::Current()->GetSkiaUnrefQueue(), context = dart_state->GetResourceContext()]() mutable { GetNextFrameAndInvokeCallback(std::move(callback), std::move(ui_task_runner), context, std::move(queue), trace_id); })); return Dart_Null(); } Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { if (!Dart_IsClosure(callback_handle)) { return ToDart("Callback must be a function"); } auto callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle); tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { return ToDart("Invalid dart state"); } tonic::DartState::Scope scope(dart_state); DartInvoke(callback->value(), {ToDart(frame_)}); return Dart_Null(); } void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({ {"instantiateImageCodec", InstantiateImageCodec, 2, true}, }); natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } } // namespace blink <commit_msg>Enable downscale of very large images when uploading on IO thread (#5011)<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/codec.h" #include "flutter/common/task_runners.h" #include "flutter/glue/trace_event.h" #include "flutter/lib/ui/painting/frame_info.h" #include "lib/fxl/functional/make_copyable.h" #include "lib/fxl/logging.h" #include "lib/tonic/dart_binding_macros.h" #include "lib/tonic/dart_library_natives.h" #include "lib/tonic/dart_state.h" #include "lib/tonic/logging/dart_invoke.h" #include "lib/tonic/typed_data/uint8_list.h" #include "third_party/skia/include/codec/SkCodec.h" #include "third_party/skia/include/core/SkPixelRef.h" #ifdef ERROR #undef ERROR #endif using tonic::DartInvoke; using tonic::DartPersistentValue; using tonic::ToDart; namespace blink { namespace { static constexpr const char* kInitCodecTraceTag = "InitCodec"; static constexpr const char* kCodecNextFrameTraceTag = "CodecNextFrame"; static void InvokeCodecCallback(fxl::RefPtr<Codec> codec, std::unique_ptr<DartPersistentValue> callback, size_t trace_id) { tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); return; } tonic::DartState::Scope scope(dart_state); if (!codec) { DartInvoke(callback->value(), {Dart_Null()}); } else { DartInvoke(callback->value(), {ToDart(codec)}); } TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); } static sk_sp<SkImage> DecodeImage(fml::WeakPtr<GrContext> context, sk_sp<SkData> buffer, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("flutter", "DecodeImage"); if (buffer == nullptr || buffer->isEmpty()) { return nullptr; } if (context) { // This indicates that we do not want a "linear blending" decode. sk_sp<SkColorSpace> dstColorSpace = nullptr; return SkImage::MakeCrossContextFromEncoded( context.get(), std::move(buffer), false, dstColorSpace.get(), true); } else { // Defer decoding until time of draw later on the GPU thread. Can happen // when GL operations are currently forbidden such as in the background // on iOS. return SkImage::MakeFromEncoded(std::move(buffer)); } } fxl::RefPtr<Codec> InitCodec(fml::WeakPtr<GrContext> context, sk_sp<SkData> buffer, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("blink", "InitCodec"); if (buffer == nullptr || buffer->isEmpty()) { FXL_LOG(ERROR) << "InitCodec failed - buffer was empty "; return nullptr; } std::unique_ptr<SkCodec> skCodec = SkCodec::MakeFromData(buffer); if (!skCodec) { FXL_LOG(ERROR) << "Failed decoding image. Data is either invalid, or it is " "encoded using an unsupported format."; return nullptr; } if (skCodec->getFrameCount() > 1) { return fxl::MakeRefCounted<MultiFrameCodec>(std::move(skCodec)); } auto skImage = DecodeImage(context, buffer, trace_id); if (!skImage) { FXL_LOG(ERROR) << "DecodeImage failed"; return nullptr; } auto image = CanvasImage::Create(); image->set_image({skImage, unref_queue}); auto frameInfo = fxl::MakeRefCounted<FrameInfo>(std::move(image), 0); return fxl::MakeRefCounted<SingleFrameCodec>(std::move(frameInfo)); } void InitCodecAndInvokeCodecCallback( fxl::RefPtr<fxl::TaskRunner> ui_task_runner, fml::WeakPtr<GrContext> context, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, std::unique_ptr<DartPersistentValue> callback, sk_sp<SkData> buffer, size_t trace_id) { auto codec = InitCodec(context, std::move(buffer), std::move(unref_queue), trace_id); ui_task_runner->PostTask( fxl::MakeCopyable([callback = std::move(callback), codec = std::move(codec), trace_id]() mutable { InvokeCodecCallback(std::move(codec), std::move(callback), trace_id); })); } void InstantiateImageCodec(Dart_NativeArguments args) { static size_t trace_counter = 1; const size_t trace_id = trace_counter++; TRACE_FLOW_BEGIN("flutter", kInitCodecTraceTag, trace_id); Dart_Handle exception = nullptr; tonic::Uint8List list = tonic::DartConverter<tonic::Uint8List>::FromArguments(args, 0, exception); if (exception) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); Dart_SetReturnValue(args, exception); return; } Dart_Handle callback_handle = Dart_GetNativeArgument(args, 1); if (!Dart_IsClosure(callback_handle)) { TRACE_FLOW_END("flutter", kInitCodecTraceTag, trace_id); Dart_SetReturnValue(args, ToDart("Callback must be a function")); return; } auto buffer = SkData::MakeWithCopy(list.data(), list.num_elements()); auto dart_state = UIDartState::Current(); const auto& task_runners = dart_state->GetTaskRunners(); task_runners.GetIOTaskRunner()->PostTask(fxl::MakeCopyable( [callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle), buffer = std::move(buffer), trace_id, ui_task_runner = task_runners.GetUITaskRunner(), context = dart_state->GetResourceContext(), queue = UIDartState::Current()->GetSkiaUnrefQueue()]() mutable { InitCodecAndInvokeCodecCallback(std::move(ui_task_runner), context, std::move(queue), std::move(callback), std::move(buffer), trace_id); })); } bool copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) { SkPixmap srcPM; if (!src.peekPixels(&srcPM)) { return false; } SkBitmap tmpDst; SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType); if (!tmpDst.setInfo(dstInfo)) { return false; } if (!tmpDst.tryAllocPixels()) { return false; } SkPixmap dstPM; if (!tmpDst.peekPixels(&dstPM)) { return false; } if (!srcPM.readPixels(dstPM)) { return false; } dst->swap(tmpDst); return true; } void InvokeNextFrameCallback(fxl::RefPtr<FrameInfo> frameInfo, std::unique_ptr<DartPersistentValue> callback, size_t trace_id) { tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); return; } tonic::DartState::Scope scope(dart_state); if (!frameInfo) { DartInvoke(callback->value(), {Dart_Null()}); } else { DartInvoke(callback->value(), {ToDart(frameInfo)}); } TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); } } // namespace IMPLEMENT_WRAPPERTYPEINFO(ui, Codec); #define FOR_EACH_BINDING(V) \ V(Codec, getNextFrame) \ V(Codec, frameCount) \ V(Codec, repetitionCount) \ V(Codec, dispose) FOR_EACH_BINDING(DART_NATIVE_CALLBACK) void Codec::dispose() { ClearDartWrapper(); } MultiFrameCodec::MultiFrameCodec(std::unique_ptr<SkCodec> codec) : codec_(std::move(codec)) { repetitionCount_ = codec_->getRepetitionCount(); frameInfos_ = codec_->getFrameInfo(); frameBitmaps_.resize(frameInfos_.size()); nextFrameIndex_ = 0; } sk_sp<SkImage> MultiFrameCodec::GetNextFrameImage( fml::WeakPtr<GrContext> resourceContext) { SkBitmap& bitmap = frameBitmaps_[nextFrameIndex_]; if (!bitmap.getPixels()) { // We haven't decoded this frame yet const SkImageInfo info = codec_->getInfo().makeColorType(kN32_SkColorType); bitmap.allocPixels(info); SkCodec::Options options; options.fFrameIndex = nextFrameIndex_; const int requiredFrame = frameInfos_[nextFrameIndex_].fRequiredFrame; if (requiredFrame != SkCodec::kNone) { if (requiredFrame < 0 || static_cast<size_t>(requiredFrame) >= frameBitmaps_.size()) { FXL_LOG(ERROR) << "Frame " << nextFrameIndex_ << " depends on frame " << requiredFrame << " which out of range (0," << frameBitmaps_.size() << ")."; return NULL; } SkBitmap& requiredBitmap = frameBitmaps_[requiredFrame]; // For simplicity, do not try to cache old frames if (requiredBitmap.getPixels() && copy_to(&bitmap, requiredBitmap.colorType(), requiredBitmap)) { options.fPriorFrame = requiredFrame; } } if (SkCodec::kSuccess != codec_->getPixels(info, bitmap.getPixels(), bitmap.rowBytes(), &options)) { FXL_LOG(ERROR) << "Could not getPixels for frame " << nextFrameIndex_; return NULL; } } if (resourceContext) { SkPixmap pixmap(bitmap.info(), bitmap.pixelRef()->pixels(), bitmap.pixelRef()->rowBytes()); // This indicates that we do not want a "linear blending" decode. sk_sp<SkColorSpace> dstColorSpace = nullptr; return SkImage::MakeCrossContextFromPixmap(resourceContext.get(), pixmap, false, dstColorSpace.get()); } else { // Defer decoding until time of draw later on the GPU thread. Can happen // when GL operations are currently forbidden such as in the background // on iOS. return SkImage::MakeFromBitmap(bitmap); } } void MultiFrameCodec::GetNextFrameAndInvokeCallback( std::unique_ptr<DartPersistentValue> callback, fxl::RefPtr<fxl::TaskRunner> ui_task_runner, fml::WeakPtr<GrContext> resourceContext, fxl::RefPtr<flow::SkiaUnrefQueue> unref_queue, size_t trace_id) { fxl::RefPtr<FrameInfo> frameInfo = NULL; sk_sp<SkImage> skImage = GetNextFrameImage(resourceContext); if (skImage) { fxl::RefPtr<CanvasImage> image = CanvasImage::Create(); image->set_image({skImage, std::move(unref_queue)}); frameInfo = fxl::MakeRefCounted<FrameInfo>( std::move(image), frameInfos_[nextFrameIndex_].fDuration); } nextFrameIndex_ = (nextFrameIndex_ + 1) % frameInfos_.size(); ui_task_runner->PostTask(fxl::MakeCopyable( [callback = std::move(callback), frameInfo, trace_id]() mutable { InvokeNextFrameCallback(frameInfo, std::move(callback), trace_id); })); TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); } Dart_Handle MultiFrameCodec::getNextFrame(Dart_Handle callback_handle) { static size_t trace_counter = 1; const size_t trace_id = trace_counter++; TRACE_FLOW_BEGIN("flutter", kCodecNextFrameTraceTag, trace_id); if (!Dart_IsClosure(callback_handle)) { TRACE_FLOW_END("flutter", kCodecNextFrameTraceTag, trace_id); return ToDart("Callback must be a function"); } auto dart_state = UIDartState::Current(); const auto& task_runners = dart_state->GetTaskRunners(); task_runners.GetIOTaskRunner()->PostTask(fxl::MakeCopyable( [callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle), this, trace_id, ui_task_runner = task_runners.GetUITaskRunner(), queue = UIDartState::Current()->GetSkiaUnrefQueue(), context = dart_state->GetResourceContext()]() mutable { GetNextFrameAndInvokeCallback(std::move(callback), std::move(ui_task_runner), context, std::move(queue), trace_id); })); return Dart_Null(); } Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { if (!Dart_IsClosure(callback_handle)) { return ToDart("Callback must be a function"); } auto callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle); tonic::DartState* dart_state = callback->dart_state().get(); if (!dart_state) { return ToDart("Invalid dart state"); } tonic::DartState::Scope scope(dart_state); DartInvoke(callback->value(), {ToDart(frame_)}); return Dart_Null(); } void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({ {"instantiateImageCodec", InstantiateImageCodec, 2, true}, }); natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } } // namespace blink <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999, 2000 Stefan Seefeld <[email protected]> * Copyright (C) 1999 Graydon Hoare <[email protected]> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Tracer.hh> #include <Prague/Sys/Signal.hh> #include <Prague/Sys/Profiler.hh> #include <Prague/Sys/Timer.hh> #include <Prague/Sys/Path.hh> #include <Prague/Sys/User.hh> #include <Prague/Sys/Fork.hh> #include <Prague/Sys/GetOpt.hh> #include <Warsaw/config.hh> #include <Warsaw/resolve.hh> #include <Warsaw/LayoutKit.hh> #include <Warsaw/ToolKit.hh> #include <Warsaw/DrawingKit.hh> #include <Berlin/RCManager.hh> #include <Berlin/ScreenImpl.hh> #include <Berlin/ScreenManager.hh> #include <Berlin/ServerImpl.hh> #include <Berlin/Console.hh> #include <Berlin/Logger.hh> #include <Berlin/DesktopImpl.hh> #include <fstream> #ifdef RC_PREFIX const std::string prefix = RC_PREFIX; #else const std::string prefix = ""; #endif #ifdef VERSION const std::string version = VERSION; #else const std::string version = "unknown"; #endif #ifdef JPROF // probably need to change include path #include "jprof.h" #endif using namespace Prague; using namespace Warsaw; struct Dump : Signal::Notifier { void notify(int signo) { switch (signo) { case Signal::usr2: Console::activate_autoplay(); Console::wakeup(); return; case Signal::hangup: Profiler::dump(cerr); break; case Signal::abort: case Signal::segv: { std::string output = "server.log"; std::ofstream ofs(output.c_str()); Logger::dump(ofs); Tracer::dump(ofs); std::cerr << "Something went wrong. '" << output << "' contains a debugging log.\n" << "Please mail this output to [email protected]\n\n"; exit(-1); } } } }; //. Execute a client using the command in 'value'. The process is stored in //. client void exec_child(Fork*& child, std::string& value) { // Fork to create child process to execute client in child = new Fork(true, true); if (child->child()) { std::vector<char*> args; // Split 'value' into command and arguments for execvp int start = 0, index = 0; value.push_back('\0'); while ( (index = value.find(' ', index)) != std::string::npos) { value[index] = '\0'; args.push_back(value.begin() + start); start = index + 1; } args.push_back(value.begin() + start); args.push_back(NULL); // Execute command execvp(args[0], args.begin()); // Should not get here perror("client execvp"); exit(1); } // Attempt to kill client on these signals child->suicide_on_signal(Signal::interrupt); child->suicide_on_signal(Signal::quit); child->suicide_on_signal(Signal::abort); child->suicide_on_signal(Signal::segv); } int main(int argc, char **argv) { /* * start with some administrative stuff... */ Dump *dump = new Dump; Signal::set(Signal::usr2, dump); Signal::set(Signal::abort, dump); Signal::set(Signal::segv, dump); Signal::set(Signal::hangup, dump); if (~prefix.empty()) RCManager::read(prefix + "/share/berlin/berlinrc"); const char *rcfile = getenv("BERLINRC"); if (rcfile) RCManager::read(Prague::Path::expand_user(rcfile)); else RCManager::read(std::string(User().home()) + "/.berlin"); GetOpt getopt(argv[0], "a berlin display server"); getopt.add('h', "help", GetOpt::novalue, "help message"); getopt.add('v', "version", GetOpt::novalue, "version number"); getopt.add('l', "logging", GetOpt::novalue, "switch logging on"); getopt.add('p', "profiling", GetOpt::novalue, "switch profiling on"); getopt.add('d', "drawing", GetOpt::mandatory, "the DrawingKit to choose"); getopt.add('r', "resource", GetOpt::mandatory, "the resource file to load"); getopt.add('e', "execute", GetOpt::mandatory, "the command to execute upon startup"); size_t argo = getopt.parse(argc, argv); argc -= argo; argv += argo; std::string value; getopt.get("version", &value); if (value == "true") { cout << "version is " << version << endl; return 0;} value = ""; getopt.get("help", &value); if (value == "true") { getopt.usage(); return 0;} value = ""; getopt.get("resource", &value); if (!value.empty()) RCManager::read(Prague::Path::expand_user(value)); value = ""; getopt.get("logging", &value); if (value == "true") { Logger::set(Logger::corba); Logger::set(Logger::focus); Logger::set(Logger::image); Logger::set(Logger::loader); Logger::set(Logger::subject); Logger::set(Logger::layout); Logger::set(Logger::picking); Logger::set(Logger::drawing); Logger::set(Logger::traversal); Logger::set(Logger::widget); Logger::set(Logger::text); Tracer::logging(true); } #ifdef JPROF value = ""; getopt.get("profiling", &value); if (value == "true") setupProfilingStuff(); #endif /* * ...then start the ORB... */ CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "omniORB3"); PortableServer::POA_var poa = resolve_init<PortableServer::POA>(orb, "RootPOA"); PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); Logger::log(Logger::corba) << "root POA is activated" << std::endl; Console::open(argc, argv, poa); Logger::log(Logger::main) << "console is initialized" << std::endl; /* * ...and finally construct the server. */ ServerImpl *server = ServerImpl::instance(); Prague::Path path = RCManager::get_path("modulepath"); for (Prague::Path::iterator i = path.begin(); i != path.end(); ++i) server->scan(*i); Logger::log(Logger::loader) << "modules are loaded" << std::endl; Kit::PropertySeq props; props.length(1); props[0].name = CORBA::string_dup("implementation"); value = ""; getopt.get("drawing", &value); if (!value.empty()) props[0].value = CORBA::string_dup(value.c_str()); else props[0].value = CORBA::string_dup("LibArtDrawingKit"); DrawingKit_var drawing = server->resolve<DrawingKit>("IDL:Warsaw/DrawingKit:1.0", props, poa); if (CORBA::is_nil(drawing)) { std::cerr << "unable to open " << "IDL:Warsaw/DrawingKit:1.0" << " with attribute " << props[0].name << '=' << props[0].value << std::endl; return -1; } Logger::log(Logger::drawing) << "drawing system is built" << std::endl; // make a Screen graphic to hold this server's scene graph ScreenImpl *screen = new ScreenImpl(); EventManager *emanager = new EventManager(Controller_var(screen->_this()), screen->allocation()); ScreenManager *smanager = new ScreenManager(Graphic_var(screen->_this()), emanager, drawing); screen->bind_managers(emanager, smanager); props.length(0); ToolKit_var tools = server->resolve<ToolKit>("IDL:Warsaw/ToolKit:1.0", props, poa); LayoutKit_var layout = server->resolve<LayoutKit>("IDL:Warsaw/LayoutKit:1.0", props, poa); Layout::Stage_var stage = layout->create_stage(); DesktopImpl *desktop = new DesktopImpl(stage); screen->body(Desktop_var(desktop->_this())); screen->append_controller(Desktop_var(desktop->_this())); Logger::log(Logger::layout) << "desktop is created" << std::endl; // initialize the client listener server->set_singleton("IDL:Warsaw/Desktop:1.0", Desktop_var(desktop->_this())); server->set_singleton("IDL:Warsaw/DrawingKit:1.0", drawing); server->start(); Logger::log(Logger::layout) << "started server" << std::endl; bind_name(orb, Server_var(server->_this()), "IDL:Warsaw/Server:1.0"); Logger::log(Logger::corba) << "listening for clients" << std::endl; // initialize the event distributor and draw thread Logger::log(Logger::corba) << "event manager is constructed" << std::endl; // Start client via --execute argument Fork *child = NULL; value = ""; getopt.get("execute", &value); if (!value.empty()) exec_child(child, value); try { smanager->run(); } catch (CORBA::SystemException &se) { std::cout << "system exception " << std::endl; } catch(omniORB::fatalException &fe) { std::cerr << "fatal exception at " << fe.file() << " " << fe.line() << ":" << fe.errmsg() << std::endl; } catch (...) { std::cout << "unknown exception caught" << std::endl; }; if (child) delete child; orb->destroy(); return 0; } <commit_msg>Increase maxTcpConnectionPerServer so that the new menutest doesnt run out<commit_after>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999, 2000 Stefan Seefeld <[email protected]> * Copyright (C) 1999 Graydon Hoare <[email protected]> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Tracer.hh> #include <Prague/Sys/Signal.hh> #include <Prague/Sys/Profiler.hh> #include <Prague/Sys/Timer.hh> #include <Prague/Sys/Path.hh> #include <Prague/Sys/User.hh> #include <Prague/Sys/Fork.hh> #include <Prague/Sys/GetOpt.hh> #include <Warsaw/config.hh> #include <Warsaw/resolve.hh> #include <Warsaw/LayoutKit.hh> #include <Warsaw/ToolKit.hh> #include <Warsaw/DrawingKit.hh> #include <Berlin/RCManager.hh> #include <Berlin/ScreenImpl.hh> #include <Berlin/ScreenManager.hh> #include <Berlin/ServerImpl.hh> #include <Berlin/Console.hh> #include <Berlin/Logger.hh> #include <Berlin/DesktopImpl.hh> #include <fstream> #ifdef RC_PREFIX const std::string prefix = RC_PREFIX; #else const std::string prefix = ""; #endif #ifdef VERSION const std::string version = VERSION; #else const std::string version = "unknown"; #endif #ifdef JPROF // probably need to change include path #include "jprof.h" #endif using namespace Prague; using namespace Warsaw; struct Dump : Signal::Notifier { void notify(int signo) { switch (signo) { case Signal::usr2: Console::activate_autoplay(); Console::wakeup(); return; case Signal::hangup: Profiler::dump(cerr); break; case Signal::abort: case Signal::segv: { std::string output = "server.log"; std::ofstream ofs(output.c_str()); Logger::dump(ofs); Tracer::dump(ofs); std::cerr << "Something went wrong. '" << output << "' contains a debugging log.\n" << "Please mail this output to [email protected]\n\n"; exit(-1); } } } }; //. Execute a client using the command in 'value'. The process is stored in //. client void exec_child(Fork*& child, std::string& value) { // Fork to create child process to execute client in child = new Fork(true, true); if (child->child()) { std::vector<char*> args; // Split 'value' into command and arguments for execvp int start = 0, index = 0; value.push_back('\0'); while ( (index = value.find(' ', index)) != std::string::npos) { value[index] = '\0'; args.push_back(value.begin() + start); start = index + 1; } args.push_back(value.begin() + start); args.push_back(NULL); // Execute command execvp(args[0], args.begin()); // Should not get here perror("client execvp"); exit(1); } // Attempt to kill client on these signals child->suicide_on_signal(Signal::interrupt); child->suicide_on_signal(Signal::quit); child->suicide_on_signal(Signal::abort); child->suicide_on_signal(Signal::segv); } int main(int argc, char **argv) { /* * start with some administrative stuff... */ Dump *dump = new Dump; Signal::set(Signal::usr2, dump); Signal::set(Signal::abort, dump); Signal::set(Signal::segv, dump); Signal::set(Signal::hangup, dump); if (~prefix.empty()) RCManager::read(prefix + "/share/berlin/berlinrc"); const char *rcfile = getenv("BERLINRC"); if (rcfile) RCManager::read(Prague::Path::expand_user(rcfile)); else RCManager::read(std::string(User().home()) + "/.berlin"); GetOpt getopt(argv[0], "a berlin display server"); getopt.add('h', "help", GetOpt::novalue, "help message"); getopt.add('v', "version", GetOpt::novalue, "version number"); getopt.add('l', "logging", GetOpt::novalue, "switch logging on"); getopt.add('p', "profiling", GetOpt::novalue, "switch profiling on"); getopt.add('d', "drawing", GetOpt::mandatory, "the DrawingKit to choose"); getopt.add('r', "resource", GetOpt::mandatory, "the resource file to load"); getopt.add('e', "execute", GetOpt::mandatory, "the command to execute upon startup"); size_t argo = getopt.parse(argc, argv); argc -= argo; argv += argo; std::string value; getopt.get("version", &value); if (value == "true") { cout << "version is " << version << endl; return 0;} value = ""; getopt.get("help", &value); if (value == "true") { getopt.usage(); return 0;} value = ""; getopt.get("resource", &value); if (!value.empty()) RCManager::read(Prague::Path::expand_user(value)); value = ""; getopt.get("logging", &value); if (value == "true") { Logger::set(Logger::corba); Logger::set(Logger::focus); Logger::set(Logger::image); Logger::set(Logger::loader); Logger::set(Logger::subject); Logger::set(Logger::layout); Logger::set(Logger::picking); Logger::set(Logger::drawing); Logger::set(Logger::traversal); Logger::set(Logger::widget); Logger::set(Logger::text); Tracer::logging(true); } #ifdef JPROF value = ""; getopt.get("profiling", &value); if (value == "true") setupProfilingStuff(); #endif /* * ...then start the ORB... */ omniORB::maxTcpConnectionPerServer = 10; CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "omniORB3"); PortableServer::POA_var poa = resolve_init<PortableServer::POA>(orb, "RootPOA"); PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); Logger::log(Logger::corba) << "root POA is activated" << std::endl; Console::open(argc, argv, poa); Logger::log(Logger::main) << "console is initialized" << std::endl; /* * ...and finally construct the server. */ ServerImpl *server = ServerImpl::instance(); Prague::Path path = RCManager::get_path("modulepath"); for (Prague::Path::iterator i = path.begin(); i != path.end(); ++i) server->scan(*i); Logger::log(Logger::loader) << "modules are loaded" << std::endl; Kit::PropertySeq props; props.length(1); props[0].name = CORBA::string_dup("implementation"); value = ""; getopt.get("drawing", &value); if (!value.empty()) props[0].value = CORBA::string_dup(value.c_str()); else props[0].value = CORBA::string_dup("LibArtDrawingKit"); DrawingKit_var drawing = server->resolve<DrawingKit>("IDL:Warsaw/DrawingKit:1.0", props, poa); if (CORBA::is_nil(drawing)) { std::cerr << "unable to open " << "IDL:Warsaw/DrawingKit:1.0" << " with attribute " << props[0].name << '=' << props[0].value << std::endl; return -1; } Logger::log(Logger::drawing) << "drawing system is built" << std::endl; // make a Screen graphic to hold this server's scene graph ScreenImpl *screen = new ScreenImpl(); EventManager *emanager = new EventManager(Controller_var(screen->_this()), screen->allocation()); ScreenManager *smanager = new ScreenManager(Graphic_var(screen->_this()), emanager, drawing); screen->bind_managers(emanager, smanager); props.length(0); ToolKit_var tools = server->resolve<ToolKit>("IDL:Warsaw/ToolKit:1.0", props, poa); LayoutKit_var layout = server->resolve<LayoutKit>("IDL:Warsaw/LayoutKit:1.0", props, poa); Layout::Stage_var stage = layout->create_stage(); DesktopImpl *desktop = new DesktopImpl(stage); screen->body(Desktop_var(desktop->_this())); screen->append_controller(Desktop_var(desktop->_this())); Logger::log(Logger::layout) << "desktop is created" << std::endl; // initialize the client listener server->set_singleton("IDL:Warsaw/Desktop:1.0", Desktop_var(desktop->_this())); server->set_singleton("IDL:Warsaw/DrawingKit:1.0", drawing); server->start(); Logger::log(Logger::layout) << "started server" << std::endl; bind_name(orb, Server_var(server->_this()), "IDL:Warsaw/Server:1.0"); Logger::log(Logger::corba) << "listening for clients" << std::endl; // initialize the event distributor and draw thread Logger::log(Logger::corba) << "event manager is constructed" << std::endl; // Start client via --execute argument Fork *child = NULL; value = ""; getopt.get("execute", &value); if (!value.empty()) exec_child(child, value); try { smanager->run(); } catch (CORBA::SystemException &se) { std::cout << "system exception " << std::endl; } catch(omniORB::fatalException &fe) { std::cerr << "fatal exception at " << fe.file() << " " << fe.line() << ":" << fe.errmsg() << std::endl; } catch (...) { std::cout << "unknown exception caught" << std::endl; }; if (child) delete child; orb->destroy(); return 0; } <|endoftext|>
<commit_before>/* Copyright 2011, Jernej Kovacic 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 * @author Jernej Kovacic * * Implementation of the class NumericUtil, a collection of some useful * numerical utilities. This is a templated class and must not be compiled. * Instead it must be included after the class declaration in the .h file */ // Deliberately there is no #include "NumericUtil.hpp" #include "rational/Rational.hpp" #include "matrix/SqMatrixGeneric.hpp" #include "polynomial/PolynomialGeneric.hpp" #include <cstddef> #include <complex> #include <limits> // Note that the optimal EPS depends on application's requirements // For float, double and long double, a suggested value for EPS can be // obtained by std::numeric_limits<type>::epsilon(). #define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \ template<> \ FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon(); // end of #define // definition of EPS for float: _MATH_NUMERICUTIL_SPECIALIZED_EPS(float) // double is a more accurate type: _MATH_NUMERICUTIL_SPECIALIZED_EPS(double) // ... and long double is even more accurate: _MATH_NUMERICUTIL_SPECIALIZED_EPS(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_EPS /* * For int and other types, EPS doesn't make sense, so set it to 0 */ template<class T> T math::NumericUtil<T>::EPS = static_cast<T>(0); /** * A constant value with the T's representation of zero (0) */ template<class T> const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) ); /** * A constant value with the T's representation of one (1) */ template<class T> const T math::NumericUtil<T>::ONE ( static_cast<T>(1) ); /** * Does the given value equal (or is close enough to) zero? * Implementation depends on the type T. * For floating point types (float, double, long double), it checks * whether its absolute value is less than a hardcoded constant 'eps'. * * @param value * * @return true or false */ template<class T> bool math::NumericUtil<T>::isZero(const T& value) { /* * The implementation for integers et al. where the == operator * does make sense and no comparison to EPS is necessary. */ bool retVal = ( ZERO==value ? true : false ); return retVal; } /* * Float, double and long double require specialized implementations of isZero(). * In case of these three types, the equality operator (==) is useless. * In numerical mathematics, two numbers are considered "equal", when * absolute value of their difference does not exceed a reasonably set EPS. * All specializations are very similar and only differ in types of an input value. * For easier maintainability, the specialization will be implemented * only once using a parameterized #define */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \ template<> \ bool math::NumericUtil<FDL>::isZero(const FDL& value) \ { \ bool retVal = false; \ retVal = ( value>-EPS && value<EPS ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO /* * Specialization for complex. * As complex is a templated class, again it must be implemented for each supported subtemplated * type. To facilitate this, a parameterized macro is introduced. * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare * it with EPS^2 than calculating its square root (the actual definition of complex abs. value). */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \ template<> \ bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \ { \ bool retVal = false; \ const FDL eps = math::NumericUtil<FDL>::getEPS(); \ retVal = ( std::norm(value)<=eps*eps ? true : false ); \ return retVal; \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX /* * Implementation for Rational */ template<> bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value) { // Rational already contains its own isZero()... return value.isZero(); } /** * @return value of 'eps' for the desired type */ template<class T> T math::NumericUtil<T>::getEPS() { return EPS; } /** * Sets the new value of 'eps' for the desired type if the default one does * not meet application's requirements. * * @note There is no check of input so make sure a sensible value * (typically a very small positive number) is entered. * * @param eps - new value of EPS */ template<class T> void math::NumericUtil<T>::setEPS(const T& eps) { EPS = eps; } /* * In C++, it is not possible to specialize a function of a templated class * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>). * However it is possible if a single function is templated. * For more details, see the discussion at: * http://www.cplusplus.com/forum/general/68298/ * * At the moment, getUnit() is only used by power(). Until it is changed, * getUnit() will be defined in this file as a templated standalone function. * Additionally, implementations of the function are "hidden" in the namespace * math::getunit which is not supposed to be known to other members of math:: */ namespace math { namespace getunit { /* * @param t - an arbitrary instance of T, ignored by the generic implementation, * at specializations it might be useful to determine unit's dimensions etc. * * @return an instance of T acting as a multiplication unit */ template<class T> T getUnit(const T& t) { (void) t; return T(math::NumericUtil<T>::ONE); } /* * Specialization for generic class math::SqMatrixGeneric<T> * * @param t - an arbitrary instance of a square matrix to determine * dimensions of the returned unit matrix * * @return a unit n x n square matrix where n is a dimension of 't' */ template<class T> math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t) { const size_t N = t.nrRows(); math::SqMatrixGeneric<T> retVal(N); retVal.setUnit(); return retVal; } /* * Specialization for generic class math::PolynomialGeneric<T> * * @param t - ignored * * @return a unit polynomial p(x) = (T)1 */ template<class T> math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t) { (void) t; return math::PolynomialGeneric<T>(math::NumericUtil<T>::ONE); } } // namespace units } // namespace math /** * Efficient calculation of positive integer power. * Complexity of the algorithm is O(log2 n). * * @note T must have implemented operator*= * * @param base - base of the exponentiation * @param n - exponent (a positive integer number) * * @return base^n */ template<class T> T math::NumericUtil<T>::power(const T& base, size_t n) { /* * "Exponentiation by squaring" algorithm will be applied. * * Exponentiation can be expanded into: * n n%2 n/2 * a = a * (a^2) * * where / and % are integer division and remainder operators. * * The expression above can be further recursively derived to: * n n%2 (n/2)%2 (n/2)/2 * a = a (a^2) (a^4) = * * n%2 (n/2)%2 (n/4)%2 ((n/2)/2)/2 * = a (a^2) (a^4) (a^8) = .... * * It is simple to develop an iterative algorithm where factor * is iteratively increased by squaring itself and coefficients * ai (i=0..n) are iteratively calculated by the remainder of * division by 2 */ // Note: it is safe to use bitwise operators for arithmetic operations // on unsigned int values as they do not depend on endianess: // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness T retVal = math::getunit::getUnit(base); T factor = base; // Obtain coefficients ai from the exponent's binary form. // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2" for ( size_t i=n; i>0; i>>=1 ) { // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0) // Note: "i&1" is a bitwise equivalent of "i%2" if ( 0!=(i & static_cast<size_t>(1) ) ) { retVal *= factor; } factor *= factor; } return retVal; } <commit_msg>simplified some methods<commit_after>/* Copyright 2011, Jernej Kovacic 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 * @author Jernej Kovacic * * Implementation of the class NumericUtil, a collection of some useful * numerical utilities. This is a templated class and must not be compiled. * Instead it must be included after the class declaration in the .h file */ // Deliberately there is no #include "NumericUtil.hpp" #include "rational/Rational.hpp" #include "matrix/SqMatrixGeneric.hpp" #include "polynomial/PolynomialGeneric.hpp" #include <cstddef> #include <complex> #include <limits> // Note that the optimal EPS depends on application's requirements // For float, double and long double, a suggested value for EPS can be // obtained by std::numeric_limits<type>::epsilon(). #define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \ template<> \ FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon(); // end of #define // definition of EPS for float: _MATH_NUMERICUTIL_SPECIALIZED_EPS(float) // double is a more accurate type: _MATH_NUMERICUTIL_SPECIALIZED_EPS(double) // ... and long double is even more accurate: _MATH_NUMERICUTIL_SPECIALIZED_EPS(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_EPS /* * For int and other types, EPS doesn't make sense, so set it to 0 */ template<class T> T math::NumericUtil<T>::EPS = static_cast<T>(0); /** * A constant value with the T's representation of zero (0) */ template<class T> const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) ); /** * A constant value with the T's representation of one (1) */ template<class T> const T math::NumericUtil<T>::ONE ( static_cast<T>(1) ); /** * Does the given value equal (or is close enough to) zero? * Implementation depends on the type T. * For floating point types (float, double, long double), it checks * whether its absolute value is less than a hardcoded constant 'eps'. * * @param value * * @return true or false */ template<class T> bool math::NumericUtil<T>::isZero(const T& value) { /* * The implementation for integers et al. where the == operator * does make sense and no comparison to EPS is necessary. */ return ( ZERO==value ? true : false ); } /* * Float, double and long double require specialized implementations of isZero(). * In case of these three types, the equality operator (==) is useless. * In numerical mathematics, two numbers are considered "equal", when * absolute value of their difference does not exceed a reasonably set EPS. * All specializations are very similar and only differ in types of an input value. * For easier maintainability, the specialization will be implemented * only once using a parameterized #define */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \ template<> \ bool math::NumericUtil<FDL>::isZero(const FDL& value) \ { \ return ( value>-EPS && value<EPS ? true : false ); \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO /* * Specialization for complex. * As complex is a templated class, again it must be implemented for each supported subtemplated * type. To facilitate this, a parameterized macro is introduced. * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare * it with EPS^2 than calculating its square root (the actual definition of complex abs. value). */ #define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \ template<> \ bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \ { \ const FDL eps = math::NumericUtil<FDL>::getEPS(); \ return ( std::norm(value)<=eps*eps ? true : false ); \ } // end of #define // derive specialization for float: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float) // ... for double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double) // ... and long double: _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double) // #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it: #undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX /* * Implementation for Rational */ template<> bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value) { // Rational already contains its own isZero()... return value.isZero(); } /** * @return value of 'eps' for the desired type */ template<class T> T math::NumericUtil<T>::getEPS() { return EPS; } /** * Sets the new value of 'eps' for the desired type if the default one does * not meet application's requirements. * * @note There is no check of input so make sure a sensible value * (typically a very small positive number) is entered. * * @param eps - new value of EPS */ template<class T> void math::NumericUtil<T>::setEPS(const T& eps) { EPS = eps; } /* * In C++, it is not possible to specialize a function of a templated class * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>). * However it is possible if a single function is templated. * For more details, see the discussion at: * http://www.cplusplus.com/forum/general/68298/ * * At the moment, getUnit() is only used by power(). Until it is changed, * getUnit() will be defined in this file as a templated standalone function. * Additionally, implementations of the function are "hidden" in the namespace * math::getunit which is not supposed to be known to other members of math:: */ namespace math { namespace getunit { /* * @param t - an arbitrary instance of T, ignored by the generic implementation, * at specializations it might be useful to determine unit's dimensions etc. * * @return an instance of T acting as a multiplication unit */ template<class T> T getUnit(const T& t) { (void) t; return T(math::NumericUtil<T>::ONE); } /* * Specialization for generic class math::SqMatrixGeneric<T> * * @param t - an arbitrary instance of a square matrix to determine * dimensions of the returned unit matrix * * @return a unit n x n square matrix where n is a dimension of 't' */ template<class T> math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t) { const size_t N = t.nrRows(); math::SqMatrixGeneric<T> retVal(N); retVal.setUnit(); return retVal; } /* * Specialization for generic class math::PolynomialGeneric<T> * * @param t - ignored * * @return a unit polynomial p(x) = (T)1 */ template<class T> math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t) { (void) t; return math::PolynomialGeneric<T>(math::NumericUtil<T>::ONE); } } // namespace units } // namespace math /** * Efficient calculation of positive integer power. * Complexity of the algorithm is O(log2 n). * * @note T must have implemented operator*= * * @param base - base of the exponentiation * @param n - exponent (a positive integer number) * * @return base^n */ template<class T> T math::NumericUtil<T>::power(const T& base, size_t n) { /* * "Exponentiation by squaring" algorithm will be applied. * * Exponentiation can be expanded into: * n n%2 n/2 * a = a * (a^2) * * where / and % are integer division and remainder operators. * * The expression above can be further recursively derived to: * n n%2 (n/2)%2 (n/2)/2 * a = a (a^2) (a^4) = * * n%2 (n/2)%2 (n/4)%2 ((n/2)/2)/2 * = a (a^2) (a^4) (a^8) = .... * * It is simple to develop an iterative algorithm where factor * is iteratively increased by squaring itself and coefficients * ai (i=0..n) are iteratively calculated by the remainder of * division by 2 */ // Note: it is safe to use bitwise operators for arithmetic operations // on unsigned int values as they do not depend on endianess: // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness T retVal = math::getunit::getUnit(base); T factor = base; // Obtain coefficients ai from the exponent's binary form. // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2" for ( size_t i=n; i>0; i>>=1 ) { // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0) // Note: "i&1" is a bitwise equivalent of "i%2" if ( 0!=(i & static_cast<size_t>(1) ) ) { retVal *= factor; } factor *= factor; } return retVal; } <|endoftext|>
<commit_before>// Time: O(1) // Space: O(1) class Solution { public: int maxA(int N) { if (N < 7) { return N; } if (N == 10) { // the following rule doesn't hold in N = 10 return 20; } auto n = N / 5 + 1; // n3 + n4 increases one every 5 keys // (1) n = n3 + n4 // (2) N + 1 = 4 * n3 + 5 * n4 // 5 x (1) - (2) => 5*n - N - 1 = n3 auto n3 = 5 * n - N - 1; auto n4 = n - n3; return pow(3, n3) * pow(4, n4); } }; // Time: O(n) // Space: O(1) class Solution2 { public: int maxA(int N) { if (N < 7) { return N; } vector<int> dp(6); iota(dp.begin(), dp.end(), 0); for (int i = 7; i <= N; ++i) { dp[i % 6] = max(dp[(i - 4) % 6] * 3, dp[(i - 5) % 6] * 4); } return dp[N % 6]; } }; <commit_msg>Update 4-keys-keyboard.cpp<commit_after>// Time: O(1) // Space: O(1) class Solution { public: int maxA(int N) { if (N < 7) { return N; } if (N == 10) { // the following rule doesn't hold when N = 10 return 20; } auto n = N / 5 + 1; // n3 + n4 increases one every 5 keys // (1) n = n3 + n4 // (2) N + 1 = 4 * n3 + 5 * n4 // 5 x (1) - (2) => 5*n - N - 1 = n3 auto n3 = 5 * n - N - 1; auto n4 = n - n3; return pow(3, n3) * pow(4, n4); } }; // Time: O(n) // Space: O(1) class Solution2 { public: int maxA(int N) { if (N < 7) { return N; } vector<int> dp(6); iota(dp.begin(), dp.end(), 0); for (int i = 7; i <= N; ++i) { dp[i % 6] = max(dp[(i - 4) % 6] * 3, dp[(i - 5) % 6] * 4); } return dp[N % 6]; } }; <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <signal.h> #include <unistd.h> #include <netinet/in.h> #include "libcmm.h" #include "libcmm_test.h" #include "common.h" #include <errno.h> #include "timeops.h" static bool running; void handler(int sig) { running = false; } void str_reverse(char *str) { char *head = str; char *tail = str + strlen(str) - 1; while (head < tail) { char tmp = *head; *head = *tail; *tail = tmp; head++; tail--; } } void * Worker(void * arg) { #ifdef NOMULTISOCK int sock = *((int*)arg); #else mc_socket_t sock = *((mc_socket_t*)arg); #endif printf("Starting up on connection %d\n", sock); while (1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); #ifdef NOMULTISOCK int s_rc = select(sock+1, &readfds, NULL, NULL, NULL); #else /* XXX: make sure this is working properly. */ int s_rc = cmm_select(sock+1, &readfds, NULL, NULL, NULL); //int s_rc = 1; #endif if (s_rc < 0) { perror("select"); break; } struct chunk ch; struct timeval begin, end, diff; TIME(begin); #ifdef NOMULTISOCK int rc = read(sock, &ch, sizeof(ch)); #else u_long sender_labels = 0; int rc = cmm_read(sock, &ch, sizeof(ch), &sender_labels); #endif TIME(end); if (rc != sizeof(ch)) { if (rc == 0) { dbgprintf_always("Connection %d closed remotely\n", sock); } else { dbgprintf_always("Connection %d had error %d\n", sock, errno); perror("cmm_read"); } break; } TIMEDIFF(begin, end, diff); dbgprintf_always("[%lu.%06lu][testapp] Received msg; took %lu.%06lu seconds\n", end.tv_sec, end.tv_usec, diff.tv_sec, diff.tv_usec); ch.data[sizeof(ch)-1] = '\0'; printf("Msg: %*s\n", (int)(sizeof(ch) - 1), ch.data); //str_reverse(ch.data); errno = 0; //struct timeval begin, end, diff; TIME(begin); dbgprintf_always("[%lu.%06lu][testapp] About to send response\n", begin.tv_sec, begin.tv_usec); #ifdef NOMULTISOCK rc = send(sock, &ch, sizeof(ch), 0); #else rc = cmm_send(sock, &ch, sizeof(ch), 0, sender_labels, NULL, NULL); #endif TIME(end); if (rc != sizeof(ch)) { dbgprintf_always("cmm_send returned %d (expected %u), errno=%d\n", rc, sizeof(ch), errno); perror("cmm_send"); break; } TIMEDIFF(begin, end, diff); dbgprintf_always("Sent message; took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); } printf("Done with connection %d\n", sock); #ifdef NOMULTISOCK close(sock); #else cmm_close(sock); #endif return NULL; } int main() { int listen_sock = socket(PF_INET, SOCK_STREAM, 0); handle_error(listen_sock < 0, "socket"); int on = 1; int rc = setsockopt (listen_sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)); if (rc < 0) { dbgprintf_always("Cannot reuse socket address"); } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(LISTEN_PORT); rc = bind(listen_sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)); handle_error(rc < 0, "bind"); #ifdef NOMULTISOCK rc = listen(listen_sock, 5); #else rc = cmm_listen(listen_sock, 5); #endif handle_error(rc < 0, "cmm_listen"); running = true; signal(SIGINT, handler); signal(SIGPIPE, SIG_IGN); while (running) { struct sockaddr_in remote_addr; socklen_t addrlen = sizeof(remote_addr); fd_set readfds; FD_ZERO(&readfds); FD_SET(listen_sock, &readfds); rc = select(listen_sock + 1, &readfds, NULL, NULL, NULL); if (rc < 0) { continue; } #ifdef NOMULTISOCK int connecting_sock = accept(listen_sock, (struct sockaddr *)&addr, &addrlen); #else mc_socket_t connecting_sock = cmm_accept(listen_sock, (struct sockaddr *)&addr, &addrlen); #endif if (connecting_sock < 0) { perror("cmm_accept"); continue; } //pthread_t tid; //(void)pthread_create(&tid, NULL, Worker, (void*)&connecting_sock); (void)Worker((void*)&connecting_sock); } return 0; } <commit_msg>Changed simple test-receiver to apply counterintutive prefer-labels in response to receiving fg/bg messages, just for testing the prefer-labels. Result: preference successfully applied.<commit_after>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <signal.h> #include <unistd.h> #include <netinet/in.h> #include "libcmm.h" #include "libcmm_test.h" #include "libcmm_net_preference.h" #include "common.h" #include <errno.h> #include "timeops.h" static bool running; void handler(int sig) { running = false; } void str_reverse(char *str) { char *head = str; char *tail = str + strlen(str) - 1; while (head < tail) { char tmp = *head; *head = *tail; *tail = tmp; head++; tail--; } } void * Worker(void * arg) { #ifdef NOMULTISOCK int sock = *((int*)arg); #else mc_socket_t sock = *((mc_socket_t*)arg); #endif printf("Starting up on connection %d\n", sock); while (1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); #ifdef NOMULTISOCK int s_rc = select(sock+1, &readfds, NULL, NULL, NULL); #else /* XXX: make sure this is working properly. */ int s_rc = cmm_select(sock+1, &readfds, NULL, NULL, NULL); //int s_rc = 1; #endif if (s_rc < 0) { perror("select"); break; } struct chunk ch; struct timeval begin, end, diff; TIME(begin); #ifdef NOMULTISOCK int rc = read(sock, &ch, sizeof(ch)); #else u_long sender_labels = 0; int rc = cmm_read(sock, &ch, sizeof(ch), &sender_labels); if (sender_labels & CMM_LABEL_ONDEMAND) { sender_labels &= (~CMM_LABEL_WIFI_PREFERRED); sender_labels |= CMM_LABEL_THREEG_PREFERRED; dbgprintf_always("Got FG request: sending prefer-3G response (for testing)\n"); } else if (sender_labels & CMM_LABEL_BACKGROUND) { sender_labels &= (~CMM_LABEL_THREEG_PREFERRED); sender_labels |= CMM_LABEL_WIFI_PREFERRED; dbgprintf_always("Got BG request: sending prefer-wifi response (for testing)\n"); } #endif TIME(end); if (rc != sizeof(ch)) { if (rc == 0) { dbgprintf_always("Connection %d closed remotely\n", sock); } else { dbgprintf_always("Connection %d had error %d\n", sock, errno); perror("cmm_read"); } break; } TIMEDIFF(begin, end, diff); dbgprintf_always("[%lu.%06lu][testapp] Received msg; took %lu.%06lu seconds\n", end.tv_sec, end.tv_usec, diff.tv_sec, diff.tv_usec); ch.data[sizeof(ch)-1] = '\0'; printf("Msg: %*s\n", (int)(sizeof(ch) - 1), ch.data); //str_reverse(ch.data); errno = 0; //struct timeval begin, end, diff; TIME(begin); dbgprintf_always("[%lu.%06lu][testapp] About to send response\n", begin.tv_sec, begin.tv_usec); #ifdef NOMULTISOCK rc = send(sock, &ch, sizeof(ch), 0); #else rc = cmm_send(sock, &ch, sizeof(ch), 0, sender_labels, NULL, NULL); #endif TIME(end); if (rc != sizeof(ch)) { dbgprintf_always("cmm_send returned %d (expected %u), errno=%d\n", rc, sizeof(ch), errno); perror("cmm_send"); break; } TIMEDIFF(begin, end, diff); dbgprintf_always("Sent message; took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); } printf("Done with connection %d\n", sock); #ifdef NOMULTISOCK close(sock); #else cmm_close(sock); #endif return NULL; } int main() { int listen_sock = socket(PF_INET, SOCK_STREAM, 0); handle_error(listen_sock < 0, "socket"); int on = 1; int rc = setsockopt (listen_sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)); if (rc < 0) { dbgprintf_always("Cannot reuse socket address"); } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(LISTEN_PORT); rc = bind(listen_sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)); handle_error(rc < 0, "bind"); #ifdef NOMULTISOCK rc = listen(listen_sock, 5); #else rc = cmm_listen(listen_sock, 5); #endif handle_error(rc < 0, "cmm_listen"); running = true; signal(SIGINT, handler); signal(SIGPIPE, SIG_IGN); while (running) { struct sockaddr_in remote_addr; socklen_t addrlen = sizeof(remote_addr); fd_set readfds; FD_ZERO(&readfds); FD_SET(listen_sock, &readfds); rc = select(listen_sock + 1, &readfds, NULL, NULL, NULL); if (rc < 0) { continue; } #ifdef NOMULTISOCK int connecting_sock = accept(listen_sock, (struct sockaddr *)&addr, &addrlen); #else mc_socket_t connecting_sock = cmm_accept(listen_sock, (struct sockaddr *)&addr, &addrlen); #endif if (connecting_sock < 0) { perror("cmm_accept"); continue; } //pthread_t tid; //(void)pthread_create(&tid, NULL, Worker, (void*)&connecting_sock); (void)Worker((void*)&connecting_sock); } return 0; } <|endoftext|>
<commit_before>/* -*- c++ -*- This file is part of KMail, the KDE mail client. Copyright (c) 2001-2002 Michael Haeckel <[email protected]> Copyright (c) 2003 Marc Mutz <[email protected]> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "servertest.h" #include <klocale.h> #include <kmessagebox.h> #include <kdebug.h> #include <kurl.h> #include <kio/scheduler.h> #include <kio/slave.h> #include <kio/job.h> #include <kio/global.h> #include <QApplication> using namespace KPIM; //----------------------------------------------------------------------------- ServerTest::ServerTest( const QString & protocol, const QString & host, int port ) : QObject(), mProtocol( protocol ), mHost( host ), mSSL( false ), mJob( 0 ), mSlave( 0 ), mConnectionErrorCount( 0 ) { KIO::Scheduler::connect( SIGNAL(slaveError(KIO::Slave *, int, const QString &)), this, SLOT(slotSlaveResult(KIO::Slave *, int, const QString &))); if ( port == 993 || port == 995 || port == 465 ) port = 0; startOffSlave( port ); } //----------------------------------------------------------------------------- ServerTest::~ServerTest() { if (mJob) mJob->kill(); } KIO::MetaData ServerTest::slaveConfig() const { KIO::MetaData md; md.insert( "nologin", "on" ); return md; } void ServerTest::startOffSlave( int port ) { KUrl url; url.setProtocol( mSSL ? mProtocol + 's' : mProtocol ); url.setHost( mHost ); if ( port ) url.setPort( port ); mSlave = KIO::Scheduler::getConnectedSlave( url, slaveConfig() ); if ( !mSlave ) { slotSlaveResult( 0, 1 ); return; } connect( mSlave, SIGNAL(metaData(const KIO::MetaData&)), SLOT(slotMetaData(const KIO::MetaData&)) ); QByteArray packedArgs; QDataStream stream( &packedArgs, QIODevice::WriteOnly ); stream << (int) 'c'; mJob = KIO::special( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( mSlave, mJob ); connect( mJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)) ); connect( mJob, SIGNAL(infoMessage(KJob*,const QString&,const QString&)), SLOT(slotData(KJob*,const QString&,const QString&)) ); } //----------------------------------------------------------------------------- void ServerTest::slotData(KJob *, const QString &data,const QString&) { if ( mSSL ) mListSSL = data.split(' ', QString::SkipEmptyParts); else mListNormal = data.split(' ', QString::SkipEmptyParts); } void ServerTest::slotMetaData( const KIO::MetaData & md ) { KIO::MetaData::const_iterator it = md.find( "PLAIN AUTH METHODS" ); if ( it != md.end() ) { mAuthNone = it.value(); kDebug(5006) << "mAuthNone: " << mAuthNone << endl; } it = md.find( "TLS AUTH METHODS" ); if ( it != md.end() ) { mAuthTLS = it.value(); kDebug(5006) << "mAuthTLS: " << mAuthTLS << endl; } it = md.find( "SSL AUTH METHODS" ); if ( it != md.end() ) { mAuthSSL = it.value(); kDebug(5006) << "mAuthSSL: " << mAuthSSL << endl; } } //----------------------------------------------------------------------------- void ServerTest::slotResult(KJob *job) { slotSlaveResult(mSlave, job->error()); } //----------------------------------------------------------------------------- void ServerTest::slotSlaveResult(KIO::Slave *aSlave, int error, const QString &errorText) { if (aSlave != mSlave) return; if ( mSSL && error == 0 ) { // add a dummy entry to the list of SSL capabilities so that the receiver // of the capabilities signal can use mListSSL.isEmpty() in order to find // out whether SSL is supported mListSSL.append("SSL"); } if (error != KIO::ERR_SLAVE_DIED && mSlave) { // disconnect slave after every connect KIO::Scheduler::disconnectSlave(mSlave); mSlave = 0; } if ( error == KIO::ERR_COULD_NOT_CONNECT ) { // if one of the two connection tests fails we ignore the error // if both fail the host is probably not correct so we display the error if ( mConnectionErrorCount == 0 ) { error = 0; } ++mConnectionErrorCount; } if ( error ) { mJob = 0; KMessageBox::error( qApp->activeWindow(), KIO::buildErrorString( error, errorText ), i18n("Error") ); emit capabilities( mListNormal, mListSSL ); emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS ); return; } if (!mSSL) { mSSL = true; mListNormal.append("NORMAL-CONNECTION"); startOffSlave(); } else { mJob = 0; emit capabilities( mListNormal, mListSSL ); emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS ); } } #include "servertest.moc" <commit_msg>Handle the special case that the ioslave could not be started and show 'Unknown error n' if KIO::buildErrorString() returns an empty string.<commit_after>/* -*- c++ -*- This file is part of KMail, the KDE mail client. Copyright (c) 2001-2002 Michael Haeckel <[email protected]> Copyright (c) 2003 Marc Mutz <[email protected]> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "servertest.h" #include <klocale.h> #include <kmessagebox.h> #include <kdebug.h> #include <kurl.h> #include <kio/scheduler.h> #include <kio/slave.h> #include <kio/job.h> #include <kio/global.h> #include <QApplication> using namespace KPIM; //----------------------------------------------------------------------------- ServerTest::ServerTest( const QString & protocol, const QString & host, int port ) : QObject(), mProtocol( protocol ), mHost( host ), mSSL( false ), mJob( 0 ), mSlave( 0 ), mConnectionErrorCount( 0 ) { KIO::Scheduler::connect( SIGNAL(slaveError(KIO::Slave *, int, const QString &)), this, SLOT(slotSlaveResult(KIO::Slave *, int, const QString &))); if ( port == 993 || port == 995 || port == 465 ) port = 0; startOffSlave( port ); } //----------------------------------------------------------------------------- ServerTest::~ServerTest() { if (mJob) mJob->kill(); } KIO::MetaData ServerTest::slaveConfig() const { KIO::MetaData md; md.insert( "nologin", "on" ); return md; } void ServerTest::startOffSlave( int port ) { KUrl url; url.setProtocol( mSSL ? mProtocol + 's' : mProtocol ); url.setHost( mHost ); if ( port ) url.setPort( port ); mSlave = KIO::Scheduler::getConnectedSlave( url, slaveConfig() ); if ( !mSlave ) { slotSlaveResult( 0, 1 ); return; } connect( mSlave, SIGNAL(metaData(const KIO::MetaData&)), SLOT(slotMetaData(const KIO::MetaData&)) ); QByteArray packedArgs; QDataStream stream( &packedArgs, QIODevice::WriteOnly ); stream << (int) 'c'; mJob = KIO::special( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( mSlave, mJob ); connect( mJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)) ); connect( mJob, SIGNAL(infoMessage(KJob*,const QString&,const QString&)), SLOT(slotData(KJob*,const QString&,const QString&)) ); } //----------------------------------------------------------------------------- void ServerTest::slotData(KJob *, const QString &data,const QString&) { if ( mSSL ) mListSSL = data.split(' ', QString::SkipEmptyParts); else mListNormal = data.split(' ', QString::SkipEmptyParts); } void ServerTest::slotMetaData( const KIO::MetaData & md ) { KIO::MetaData::const_iterator it = md.find( "PLAIN AUTH METHODS" ); if ( it != md.end() ) { mAuthNone = it.value(); kDebug(5006) << "mAuthNone: " << mAuthNone << endl; } it = md.find( "TLS AUTH METHODS" ); if ( it != md.end() ) { mAuthTLS = it.value(); kDebug(5006) << "mAuthTLS: " << mAuthTLS << endl; } it = md.find( "SSL AUTH METHODS" ); if ( it != md.end() ) { mAuthSSL = it.value(); kDebug(5006) << "mAuthSSL: " << mAuthSSL << endl; } } //----------------------------------------------------------------------------- void ServerTest::slotResult(KJob *job) { slotSlaveResult(mSlave, job->error()); } //----------------------------------------------------------------------------- void ServerTest::slotSlaveResult(KIO::Slave *aSlave, int error, const QString &errorText) { if (aSlave != mSlave) return; if ( mSSL && error == 0 ) { // add a dummy entry to the list of SSL capabilities so that the receiver // of the capabilities signal can use mListSSL.isEmpty() in order to find // out whether SSL is supported mListSSL.append("SSL"); } if (error != KIO::ERR_SLAVE_DIED && mSlave) { // disconnect slave after every connect KIO::Scheduler::disconnectSlave(mSlave); mSlave = 0; } if ( error == KIO::ERR_COULD_NOT_CONNECT ) { // if one of the two connection tests fails we ignore the error // if both fail the host is probably not correct so we display the error if ( mConnectionErrorCount == 0 ) { error = 0; } ++mConnectionErrorCount; } if ( error ) { mJob = 0; QString errorMessage; if ( error == 1 ) { // handle the special case that the slave could not be started errorMessage = i18n( "Starting the ioslave for protocol %1 failed.", mSSL ? mProtocol + 's' : mProtocol ); } else { errorMessage = KIO::buildErrorString( error, errorText ); if ( errorMessage.isEmpty() ) { errorMessage = i18n( "Unknown error %1.", error ); } } KMessageBox::error( qApp->activeWindow(), errorMessage, i18n("Error") ); emit capabilities( mListNormal, mListSSL ); emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS ); return; } if (!mSSL) { mSSL = true; mListNormal.append("NORMAL-CONNECTION"); startOffSlave(); } else { mJob = 0; emit capabilities( mListNormal, mListSSL ); emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS ); } } #include "servertest.moc" <|endoftext|>
<commit_before>/* Copyright (C) 1998-2001 by Jorrit Tyberghein csObject library (C) 1999 by Ivan Avramovic <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/csobject.h" #include "csutil/dataobj.h" #include "csutil/typedvec.h" #include <stdlib.h> #include <string.h> CS_DECLARE_TYPED_IBASE_VECTOR (csObjectContainer, iObject); /*** Object Iterators ***/ class csObjectIterator : public iObjectIterator { public: SCF_DECLARE_IBASE; csObject *Object; int Position; csObjectIterator (csObject *obj) : Object (obj) { SCF_CONSTRUCT_IBASE (NULL); Object->IncRef (); Reset (); } virtual ~csObjectIterator () { Object->DecRef (); } virtual bool Next() { if (Position < 0) return false; Position++; if (Position == Object->Children->Length ()) { Position = -1; return false; } return true; } virtual void Reset() { if (Object->Children == NULL || Object->Children->Length () < 1) Position = -1; else Position = 0; } virtual iObject *GetObject () const { return Object->Children->Get (Position); } virtual iObject* GetParentObj() const { return Object; } virtual bool IsFinished () const { return (Position < 0); } virtual bool FindName (const char* name) { while (!IsFinished ()) { if (strcmp (GetObject ()->GetName (), name) == 0) return true; Next (); } return false; } }; SCF_IMPLEMENT_IBASE (csObjectIterator) SCF_IMPLEMENTS_INTERFACE (iObjectIterator) SCF_IMPLEMENT_IBASE_END /*** csObject itself ***/ SCF_IMPLEMENT_IBASE (csObject) SCF_IMPLEMENTS_INTERFACE (iObject) SCF_IMPLEMENT_IBASE_END csObject::csObject (iBase* pParent) : Children (NULL), Name (NULL) { SCF_CONSTRUCT_IBASE (pParent); static CS_ID id = 0; csid = id++; ParentObject = NULL; } csObject::csObject (csObject &o) : Children (NULL), Name (NULL) { csObject (NULL); iObjectIterator *it = o.GetIterator (); while (!it->IsFinished ()) { ObjAdd (it->GetObject ()); it->Next (); } it->DecRef (); SetName (o.GetName ()); } csObject::~csObject () { ObjRemoveAll (); if (Children) { delete Children; Children = NULL; } delete [] Name; Name = NULL; /* * @@@ This should not be required for two reasons: * 1. If the parent keeps a pointer to this object, then the pointer was * IncRef'ed, so this object cannot be deleted. Removing the object from * its parent from here is only needed if the object was illegally * deleted, not DecRef'ed. * 2. Several objects could contain this object as a child. The 'parent' * pointer is not a safe way to find out which object contains this * object as a child. */ if (ParentObject) { ParentObject->ObjReleaseOld (this); } } void csObject::SetName (const char *iName) { delete [] Name; Name = csStrNew (iName); } const char *csObject::GetName () const { return Name; } CS_ID csObject::GetID () const { return csid; } iObject* csObject::GetObjectParent () const { return ParentObject; } void csObject::SetObjectParent (iObject *obj) { ParentObject = obj; } void csObject::ObjAdd (iObject *obj) { if (!obj) return; if (!Children) Children = new csObjectContainer (); obj->SetObjectParent (this); Children->Push (obj); } void csObject::ObjRemove (iObject *obj) { if (!Children || !obj) return; int n = Children->Find (obj); if (n>=0) { obj->SetObjectParent (NULL); Children->Delete (n); } } void csObject::ObjReleaseOld (iObject *obj) { if (!Children || !obj) return; int n = Children->Find (obj); if (n>=0) { obj->SetObjectParent (NULL); // @@@ WARNING! Doing only one DecRef() here does not prevent a second // deletion of 'obj'. Keep in mind that we are currently executing // in the destructor of 'obj' itself. If only one 'IncRef()' is used // then the Delete() from the children vector will simply destroy the // object again (with bad consequences). Doing two IncRef()'s is a // solution for this and it doesn't prevent deletion of the object // since it is being deleted already. obj->IncRef (); obj->IncRef (); Children->Delete (n); } } void csObject::ObjRemoveAll () { if (!Children) return; int i; for (i=Children->Length ()-1; i>=0; i--) { iObject* child = Children->Get (i); child->SetObjectParent (NULL); Children->Delete (i); } } void csObject::ObjAddChildren (iObject *Parent) { iObjectIterator *it = Parent->GetIterator (); while (!it->IsFinished ()) { ObjAdd (it->GetObject ()); it->Next (); } it->DecRef (); } void* csObject::GetChild (int InterfaceID, int Version, const char *Name, bool fn) const { if (!Children) return NULL; if (fn) { iObject *obj = GetChild (Name); return obj ? obj->QueryInterface (InterfaceID, Version) : NULL; } int i; for (i = 0; i < Children->Length (); i++) { if (Name) { const char *OtherName = Children->Get (i)->GetName (); if (!OtherName) continue; if (strcmp(OtherName, Name)) continue; } void *obj = Children->Get (i)->QueryInterface (InterfaceID, Version); if (obj) return obj; } return NULL; } iObject* csObject::GetChild (const char *Name) const { if (!Children || !Name) return NULL; int i; for (i = 0; i < Children->Length (); i++) { if (!strcmp (Children->Get (i)->GetName (), Name)) return Children->Get (i); } return NULL; } iObjectIterator *csObject::GetIterator () { return new csObjectIterator (this); } //------------------- miscelaneous simple classes derived from csObject -----// SCF_IMPLEMENT_IBASE_EXT (csDataObject) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iDataObject) SCF_IMPLEMENT_IBASE_EXT_END SCF_IMPLEMENT_EMBEDDED_IBASE (csDataObject::DataObject) SCF_IMPLEMENTS_INTERFACE (iDataObject) SCF_IMPLEMENT_EMBEDDED_IBASE_END <commit_msg>Formatting.<commit_after>/* Copyright (C) 1998-2001 by Jorrit Tyberghein csObject library (C) 1999 by Ivan Avramovic <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/csobject.h" #include "csutil/dataobj.h" #include "csutil/typedvec.h" #include <stdlib.h> #include <string.h> CS_DECLARE_TYPED_IBASE_VECTOR (csObjectContainer, iObject); /*** Object Iterators ***/ class csObjectIterator : public iObjectIterator { public: SCF_DECLARE_IBASE; csObject *Object; int Position; csObjectIterator (csObject *obj) : Object (obj) { SCF_CONSTRUCT_IBASE (NULL); Object->IncRef (); Reset (); } virtual ~csObjectIterator () { Object->DecRef (); } virtual bool Next() { if (Position < 0) return false; Position++; if (Position == Object->Children->Length ()) { Position = -1; return false; } return true; } virtual void Reset() { if (Object->Children == NULL || Object->Children->Length () < 1) Position = -1; else Position = 0; } virtual iObject *GetObject () const { return Object->Children->Get (Position); } virtual iObject* GetParentObj() const { return Object; } virtual bool IsFinished () const { return (Position < 0); } virtual bool FindName (const char* name) { while (!IsFinished ()) { if (strcmp (GetObject ()->GetName (), name) == 0) return true; Next (); } return false; } }; SCF_IMPLEMENT_IBASE (csObjectIterator) SCF_IMPLEMENTS_INTERFACE (iObjectIterator) SCF_IMPLEMENT_IBASE_END /*** csObject itself ***/ SCF_IMPLEMENT_IBASE (csObject) SCF_IMPLEMENTS_INTERFACE (iObject) SCF_IMPLEMENT_IBASE_END csObject::csObject (iBase* pParent) : Children (NULL), Name (NULL) { SCF_CONSTRUCT_IBASE (pParent); static CS_ID id = 0; csid = id++; ParentObject = NULL; } csObject::csObject (csObject &o) : Children (NULL), Name (NULL) { csObject (NULL); iObjectIterator *it = o.GetIterator (); while (!it->IsFinished ()) { ObjAdd (it->GetObject ()); it->Next (); } it->DecRef (); SetName (o.GetName ()); } csObject::~csObject () { ObjRemoveAll (); if (Children) { delete Children; Children = NULL; } delete [] Name; Name = NULL; /* * @@@ This should not be required for two reasons: * 1. If the parent keeps a pointer to this object, then the pointer was * IncRef'ed, so this object cannot be deleted. Removing the object from * its parent from here is only needed if the object was illegally * deleted, not DecRef'ed. * 2. Several objects could contain this object as a child. The 'parent' * pointer is not a safe way to find out which object contains this * object as a child. */ if (ParentObject) { ParentObject->ObjReleaseOld (this); } } void csObject::SetName (const char *iName) { delete [] Name; Name = csStrNew (iName); } const char *csObject::GetName () const { return Name; } CS_ID csObject::GetID () const { return csid; } iObject* csObject::GetObjectParent () const { return ParentObject; } void csObject::SetObjectParent (iObject *obj) { ParentObject = obj; } void csObject::ObjAdd (iObject *obj) { if (!obj) return; if (!Children) Children = new csObjectContainer (); obj->SetObjectParent (this); Children->Push (obj); } void csObject::ObjRemove (iObject *obj) { if (!Children || !obj) return; int n = Children->Find (obj); if (n>=0) { obj->SetObjectParent (NULL); Children->Delete (n); } } void csObject::ObjReleaseOld (iObject *obj) { if (!Children || !obj) return; int n = Children->Find (obj); if (n>=0) { obj->SetObjectParent (NULL); // @@@ WARNING! Doing only one DecRef() here does not prevent a second // deletion of 'obj'. Keep in mind that we are currently executing // in the destructor of 'obj' itself. If only one 'IncRef()' is used // then the Delete() from the children vector will simply destroy the // object again (with bad consequences). Doing two IncRef()'s is a // solution for this and it doesn't prevent deletion of the object // since it is being deleted already. obj->IncRef (); obj->IncRef (); Children->Delete (n); } } void csObject::ObjRemoveAll () { if (!Children) return; int i; for (i=Children->Length ()-1; i>=0; i--) { iObject* child = Children->Get (i); child->SetObjectParent (NULL); Children->Delete (i); } } void csObject::ObjAddChildren (iObject *Parent) { iObjectIterator *it = Parent->GetIterator (); while (!it->IsFinished ()) { ObjAdd (it->GetObject ()); it->Next (); } it->DecRef (); } void* csObject::GetChild (int InterfaceID, int Version, const char *Name, bool fn) const { if (!Children) return NULL; if (fn) { iObject *obj = GetChild (Name); return obj ? obj->QueryInterface (InterfaceID, Version) : NULL; } int i; for (i = 0; i < Children->Length (); i++) { if (Name) { const char *OtherName = Children->Get (i)->GetName (); if (!OtherName) continue; if (strcmp(OtherName, Name)) continue; } void *obj = Children->Get (i)->QueryInterface (InterfaceID, Version); if (obj) return obj; } return NULL; } iObject* csObject::GetChild (const char *Name) const { if (!Children || !Name) return NULL; int i; for (i = 0; i < Children->Length (); i++) { if (!strcmp (Children->Get (i)->GetName (), Name)) return Children->Get (i); } return NULL; } iObjectIterator *csObject::GetIterator () { return new csObjectIterator (this); } //------------------- miscelaneous simple classes derived from csObject -----// SCF_IMPLEMENT_IBASE_EXT (csDataObject) SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iDataObject) SCF_IMPLEMENT_IBASE_EXT_END SCF_IMPLEMENT_EMBEDDED_IBASE (csDataObject::DataObject) SCF_IMPLEMENTS_INTERFACE (iDataObject) SCF_IMPLEMENT_EMBEDDED_IBASE_END <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unopracc.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:25:09 $ * * 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 _SVX_UNOPRACC_HXX #define _SVX_UNOPRACC_HXX #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif #ifndef _SVX_UNOTEXT_HXX #include <svx/unotext.hxx> #endif class SvxEditSource; /** Wraps SvxUnoTextRangeBase and provides us with the text properties Inherits from SvxUnoTextRangeBase and provides XPropertySet and XMultiPropertySet interfaces. Just set the selection to the required text range and return a reference to a XPropertySet. */ class SvxAccessibleTextPropertySet : public SvxUnoTextRangeBase, public ::com::sun::star::lang::XTypeProvider, public ::cppu::OWeakObject { public: SvxAccessibleTextPropertySet( const SvxEditSource*, const SfxItemPropertyMap* ); virtual ~SvxAccessibleTextPropertySet() throw(); // XTextRange virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException); // uno::XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // lang::XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // lang::XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException); // XServiceName ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/04/01 12:49:10 thb 1.4.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:22 rt 1.4.368.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: unopracc.hxx,v $ * $Revision: 1.5 $ * * 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 _SVX_UNOPRACC_HXX #define _SVX_UNOPRACC_HXX #include <svx/unoshape.hxx> #include <svx/unotext.hxx> class SvxEditSource; /** Wraps SvxUnoTextRangeBase and provides us with the text properties Inherits from SvxUnoTextRangeBase and provides XPropertySet and XMultiPropertySet interfaces. Just set the selection to the required text range and return a reference to a XPropertySet. */ class SvxAccessibleTextPropertySet : public SvxUnoTextRangeBase, public ::com::sun::star::lang::XTypeProvider, public ::cppu::OWeakObject { public: SvxAccessibleTextPropertySet( const SvxEditSource*, const SfxItemPropertyMap* ); virtual ~SvxAccessibleTextPropertySet() throw(); // XTextRange virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException); // uno::XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // lang::XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // lang::XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException); // XServiceName ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before>/* libscratch - Multipurpose objective C++ library. Copyright (C) 2012 - 2013 Angelo Geels This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdio> // for printf #include <iostream> // for std::cin.get #include <Scratch.h> static INDEX _ctFailed = 0; #define TEST(expr) { \ BOOL bSuccess = (expr); \ ASSERT(bSuccess); \ printf(" Test: (%s) ", #expr); \ if(!bSuccess) { \ _ctFailed++; \ printf("FAILED!\n"); \ } else { \ printf("OK\n"); \ } \ } /// String testing void TestString() { printf("Testing strings\n"); CString strTest; strTest += "Lib"; strTest += "Scratch"; strTest = strTest.ToLower(); TEST(strTest == "libscratch"); strTest += " is great"; CStackArray<CString> astrParse = strTest.Split(" "); TEST(astrParse[2] == "great"); TEST(astrParse[2][1] == 'r'); CString strTest2 = strTest.Replace("great", "cool"); TEST(strTest2 == "libscratch is cool"); } /// Stack array testing void TestStackArray() { printf("Testing stack arrays\n"); CStackArray<INDEX> aiNumbers; TEST(aiNumbers.Count() == 0); aiNumbers.Push() = 5; aiNumbers.Push() = 10; aiNumbers.Push() = 15; TEST(aiNumbers.Count() == 3); TEST(aiNumbers[0] == 5); TEST(aiNumbers[1] == 10); TEST(aiNumbers[2] + aiNumbers[0] == 20); TEST(aiNumbers.Pop() == 15); TEST(aiNumbers.Count() == 2); } int main() { // perform tests TestString(); TestStackArray(); // check if all went OK if(_ctFailed == 0) { // it did! no failures. :) printf("\n\nAll OK!\n"); } else { // oops, there's a bug somewhere. please report! printf("\n\nSome problems seem to have popped up. Please report a bug.\n"); } std::cin.get(); return 0; } <commit_msg>Added dictionary tests<commit_after>/* libscratch - Multipurpose objective C++ library. Copyright (C) 2012 - 2013 Angelo Geels This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdio> // for printf #include <iostream> // for std::cin.get #include <Scratch.h> static INDEX _ctFailed = 0; #define TEST(expr) { \ BOOL bSuccess = (expr); \ ASSERT(bSuccess); \ printf(" Test: (%s) ", #expr); \ if(!bSuccess) { \ _ctFailed++; \ printf("FAILED!\n"); \ } else { \ printf("OK\n"); \ } \ } /// String testing void TestString() { printf("Testing strings\n"); CString strTest; strTest += "Lib"; strTest += "Scratch"; strTest = strTest.ToLower(); TEST(strTest == "libscratch"); strTest += " is great"; CStackArray<CString> astrParse = strTest.Split(" "); TEST(astrParse[2] == "great"); TEST(astrParse[2][1] == 'r'); CString strTest2 = strTest.Replace("great", "cool"); TEST(strTest2 == "libscratch is cool"); } /// Stack array testing void TestStackArray() { printf("Testing stack arrays\n"); CStackArray<INDEX> aiNumbers; TEST(aiNumbers.Count() == 0); aiNumbers.Push() = 5; aiNumbers.Push() = 10; aiNumbers.Push() = 15; TEST(aiNumbers.Count() == 3); TEST(aiNumbers[0] == 5); TEST(aiNumbers[1] == 10); TEST(aiNumbers[2] + aiNumbers[0] == 20); TEST(aiNumbers.Pop() == 15); TEST(aiNumbers.Count() == 2); } /// Dictionary testing void TestDictionary() { printf("Testing dictionary\n"); CDictionary<CString, INDEX> diTest; TEST(!diTest.HasKey("Test")); diTest["Test"] = 100; diTest["Test2"] = 200; TEST(diTest.HasKey("Test")); TEST(diTest["Test"] == 100); diTest.RemoveByKey("Test"); TEST(diTest.Count() == 1); TEST(!diTest.HasKey("Test")); } int main() { // perform tests TestString(); TestStackArray(); TestDictionary(); // check if all went OK if(_ctFailed == 0) { // it did! no failures. :) printf("\n\nAll OK!\n"); } else { // oops, there's a bug somewhere. please report! printf("\n\nSome problems seem to have popped up. Please report a bug.\n"); } std::cin.get(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inpdlg.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-11-06 14:53:00 $ * * 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 _INPDLG_HXX #define _INPDLG_HXX #ifndef _SVX_STDDLG_HXX //autogen #include <svx/stddlg.hxx> #endif #ifndef _SV_SVMEDIT_HXX //autogen #include <svtools/svmedit.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif class SwInputField; class SwSetExpField; class SwUserFieldType; class SwField; class SwWrtShell; /*-------------------------------------------------------------------- Beschreibung: Einfuegen Felder --------------------------------------------------------------------*/ class SwFldInputDlg: public SvxStandardDialog { virtual void Apply(); virtual void StateChanged( StateChangedType ); SwWrtShell &rSh; SwInputField* pInpFld; SwSetExpField* pSetFld; SwUserFieldType* pUsrType; Edit aLabelED; MultiLineEdit aEditED; FixedLine aEditFL; OKButton aOKBT; CancelButton aCancelBT; PushButton aNextBT; HelpButton aHelpBT; DECL_LINK(NextHdl, PushButton*); public: SwFldInputDlg( Window *pParent, SwWrtShell &rSh, SwField* pField, BOOL bNextButton = FALSE ); ~SwFldInputDlg(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.656); FILE MERGED 2008/04/01 15:59:14 thb 1.5.656.2: #i85898# Stripping all external header guards 2008/03/31 16:58:33 rt 1.5.656.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: inpdlg.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 _INPDLG_HXX #define _INPDLG_HXX #include <svx/stddlg.hxx> #ifndef _SV_SVMEDIT_HXX //autogen #include <svtools/svmedit.hxx> #endif #include <vcl/fixed.hxx> #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif class SwInputField; class SwSetExpField; class SwUserFieldType; class SwField; class SwWrtShell; /*-------------------------------------------------------------------- Beschreibung: Einfuegen Felder --------------------------------------------------------------------*/ class SwFldInputDlg: public SvxStandardDialog { virtual void Apply(); virtual void StateChanged( StateChangedType ); SwWrtShell &rSh; SwInputField* pInpFld; SwSetExpField* pSetFld; SwUserFieldType* pUsrType; Edit aLabelED; MultiLineEdit aEditED; FixedLine aEditFL; OKButton aOKBT; CancelButton aCancelBT; PushButton aNextBT; HelpButton aHelpBT; DECL_LINK(NextHdl, PushButton*); public: SwFldInputDlg( Window *pParent, SwWrtShell &rSh, SwField* pField, BOOL bNextButton = FALSE ); ~SwFldInputDlg(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: detreg.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:28:24 $ * * 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_sw.hxx" #include "swdetect.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; extern "C" { SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment ) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo( void* pServiceManager , void* pRegistryKey ) { Reference< ::registry::XRegistryKey > xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ; OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") ); OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ); // Eigentliche Implementierung und ihre Services registrieren sal_Int32 i; Reference< ::registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() + aUnoServices ); Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames(); for(i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i] ); return sal_True; } SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey ) { // Set default return value for this operation - if it failed. void* pReturn = NULL ; if ( ( pImplementationName != NULL ) && ( pServiceManager != NULL ) ) { // Define variables which are used in following macros. Reference< XSingleServiceFactory > xFactory ; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) ) { xFactory = ::cppu::createSingleFactory( xServiceManager, SwFilterDetect::impl_getStaticImplementationName(), SwFilterDetect::impl_createInstance, SwFilterDetect::impl_getStaticSupportedServiceNames() ); } // Factory is valid - service was found. if ( xFactory.is() ) { xFactory->acquire(); pReturn = xFactory.get(); } } // Return with result of this operation. return pReturn ; } } // extern "C" <commit_msg>INTEGRATION: CWS swwarnings (1.6.222); FILE MERGED 2007/03/26 12:09:31 tl 1.6.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: detreg.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:41:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "swdetect.hxx" using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; extern "C" { SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** /*ppEnvironment*/ ) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/, void* pRegistryKey ) { Reference< ::registry::XRegistryKey > xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ; OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") ); OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ); // Eigentliche Implementierung und ihre Services registrieren sal_Int32 i; Reference< ::registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() + aUnoServices ); Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames(); for(i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i] ); return sal_True; } SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* /*pRegistryKey*/ ) { // Set default return value for this operation - if it failed. void* pReturn = NULL ; if ( ( pImplementationName != NULL ) && ( pServiceManager != NULL ) ) { // Define variables which are used in following macros. Reference< XSingleServiceFactory > xFactory ; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) ) { xFactory = ::cppu::createSingleFactory( xServiceManager, SwFilterDetect::impl_getStaticImplementationName(), SwFilterDetect::impl_createInstance, SwFilterDetect::impl_getStaticSupportedServiceNames() ); } // Factory is valid - service was found. if ( xFactory.is() ) { xFactory->acquire(); pReturn = xFactory.get(); } } // Return with result of this operation. return pReturn ; } } // extern "C" <|endoftext|>
<commit_before>/* Copyright 2015 The Trustees of Princeton University 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 "driver.h" #include "impl.h" #include "read.h" #include "write.h" #include "client.h" #include "core.h" #include "consistency.h" // connect to the CDN // return 0 on success // return -ENOMEM on OOM static int UG_impl_connect_cache( struct SG_gateway* gateway, CURL* curl, char const* url, void* cls ) { int rc = 0; char* out_url = NULL; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); rc = UG_driver_cdn_url( ug, url, &out_url ); if( rc != 0 ) { return rc; } // set up the curl handle curl_easy_setopt( curl, CURLOPT_URL, out_url ); SG_safe_free( out_url ); return 0; } // update a file's manifest, in response to a remote call // return 0 on success // return -ENOENT if not found // return -ESTALE if not local // return -errno on error // NOTE: the permissions will already have been checked by the server static int UG_impl_manifest_patch( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_manifest* write_delta, void* cls ) { int rc = 0; int ref_rc = 0; struct fskit_entry* fent = NULL; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct UG_inode* inode = NULL; struct ms_client* ms = SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); rc = UG_consistency_path_ensure_fresh( gateway, reqdat->fs_path ); if( rc != 0 ) { SG_error("UG_consistency_path_ensure_fresh('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } rc = UG_consistency_manifest_ensure_fresh( gateway, reqdat->fs_path ); if( rc != 0 ) { SG_error("UG_consistency_manifest_ensure_fresh('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } // look up fent = fskit_entry_resolve_path( fs, reqdat->fs_path, reqdat->user_id, volume_id, true, &rc ); if( fent == NULL ) { return rc; } inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); // must be coordinated by us if( UG_inode_coordinator_id( inode ) != SG_gateway_id( gateway ) ) { fskit_entry_unlock( fent ); return -ESTALE; } // update the manifest fskit_entry_ref_entry( fent ); rc = UG_write_patch_manifest( gateway, reqdat, inode, write_delta ); fskit_entry_unlock( fent ); ref_rc = fskit_entry_unref( fs, reqdat->fs_path, fent ); if( ref_rc != 0 ) { SG_warn("fskit_entry_unref('%s') rc = %d\n", reqdat->fs_path, rc ); } return rc; } // stat a file--build a manifest request, and set its mode // return 0 on success // return -ESTALE if the inode is not local // return -ENOENT if we don't have it // return -ENOMEM on OOM // return -errno on error static int UG_impl_stat( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_request_data* entity_info, mode_t* mode, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct md_entry ent_info; rc = UG_stat_raw( ug, reqdat->fs_path, &ent_info ); if( rc != 0 ) { SG_error("UG_stat_raw('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } if( ent_info.coordinator != SG_gateway_id( gateway ) ) { // not ours SG_error("Not the coordinator of '%s' (it is now %" PRIu64 ")\n", reqdat->fs_path, ent_info.coordinator ); md_entry_free( &ent_info ); return -ESTALE; } if( mode != NULL ) { *mode = ent_info.mode; } if( entity_info != NULL ) { rc = SG_request_data_init_manifest( gateway, reqdat->fs_path, ent_info.file_id, ent_info.version, ent_info.manifest_mtime_sec, ent_info.manifest_mtime_nsec, entity_info ); if( rc != 0 ) { // OOM md_entry_free( &ent_info ); return -ENOMEM; } if( ent_info.type != MD_ENTRY_FILE ) { // not a file md_entry_free( &ent_info ); return -ENOENT; } } md_entry_free( &ent_info ); return 0; } // stat a file's block--build a manifest request, and set its mode // return 0 on success // return -ESTALE if the inode is not local // return -ENOENT if we don't have it // return -ENOMEM on OOM // return -errno on error static int UG_impl_stat_block( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_request_data* entity_info, mode_t* mode, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); int64_t block_version = 0; UG_handle_t* fi = NULL; struct fskit_entry* fent = NULL; struct UG_inode* inode = NULL; uint64_t file_id = 0; int64_t file_version = 0; int close_rc = 0; fi = UG_open( ug, reqdat->fs_path, O_RDONLY, &rc ); if( fi == NULL ) { SG_error("UG_open('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } fskit_file_handle_rlock( fi->fh ); fent = fskit_file_handle_get_entry( fi->fh ); if( fent == NULL ) { SG_error("BUG: no entry for handle %p\n", fi->fh ); exit(1); } fskit_entry_rlock( fent ); inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( inode == NULL ) { SG_error("BUG: no inode for entry %p\n", fent ); exit(1); } if( UG_inode_coordinator_id( inode ) != SG_gateway_id( gateway ) ) { // not ours SG_error("Not the coordinator of '%s' (it is now %" PRIu64 ")\n", reqdat->fs_path, UG_inode_coordinator_id( inode ) ); fskit_entry_unlock( fent ); fskit_file_handle_unlock( fi->fh ); rc = UG_close( ug, fi ); if( rc != 0 ) { SG_error("UG_close('%s') rc = %d\n", reqdat->fs_path, rc ); } return rc; } file_id = UG_inode_file_id( inode ); file_version = UG_inode_file_version( inode ); if( mode != NULL ) { *mode = fskit_entry_get_mode( fent ); } if( entity_info != NULL ) { rc = UG_getblockinfo( ug, reqdat->block_id, &block_version, NULL, fi ); } fskit_entry_unlock( fent ); fskit_file_handle_unlock( fi->fh ); inode = NULL; if( rc != 0 ) { SG_error("UG_getblockinfo(%s[%" PRIu64 "]) rc = %d\n", reqdat->fs_path, reqdat->block_id, rc); goto UG_impl_stat_block_out; } rc = SG_request_data_init_block( gateway, reqdat->fs_path, file_id, file_version, reqdat->block_id, block_version, entity_info ); if( rc != 0 ) { SG_error("SG_request_data_init_block rc = %d\n", rc ); goto UG_impl_stat_block_out; } UG_impl_stat_block_out: close_rc = UG_close( ug, fi ); if( close_rc != 0 ) { SG_error("UG_close('%s') rc = %d\n", reqdat->fs_path, close_rc ); } return rc; } // remote request to rename a file. // there can be at most one ongoing rename at a given moment. // return 0 on success // return -ENOMEM on OOM // return -EBUSY if the given path is being renamed already // return -ESTALE if the node is not local // return -errno on error static int UG_impl_rename( struct SG_gateway* gateway, struct SG_request_data* reqdat, char const* new_path, void* cls ) { struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); return UG_rename( ug, reqdat->fs_path, new_path ); } // truncate a file // return 0 on success // return -errno on error static int UG_impl_truncate( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t new_size, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct ms_client* ms = (struct ms_client*)SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); // truncate locally. The MS will be informed as part of the user route. rc = fskit_trunc( fs, reqdat->fs_path, reqdat->user_id, volume_id, new_size ); if( rc != 0 ) { SG_error("fskit_trunc( '%s', %" PRIu64 ") rc = %d\n", reqdat->fs_path, new_size, rc); } return rc; } // detach a file // return 0 on success // return -errno on error static int UG_impl_detach( struct SG_gateway* gateway, struct SG_request_data* reqdat, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct ms_client* ms = (struct ms_client*)SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); struct stat sb; char const* method = NULL; // file or directory? rc = fskit_stat( fs, reqdat->fs_path, 0, 0, &sb ); if( rc != 0 ) { return rc; } if( S_ISREG( sb.st_mode ) ) { // unlink locally. The MS will be informed as part of the user route. method = "fskit_unlink"; rc = fskit_unlink( fs, reqdat->fs_path, reqdat->user_id, volume_id ); } else { // rmdir locally. The MS will be informed as part of the user route method = "fskit_rmdir"; rc = fskit_rmdir( fs, reqdat->fs_path, reqdat->user_id, volume_id ); } if( rc != 0 ) { SG_error("%s( '%s' ) rc = %d\n", method, reqdat->fs_path, rc); } return 0; } // on config reload, re-calculate the set of replica gateway IDs // return 0 on success // return negative on error static int UG_impl_config_change( struct SG_gateway* gateway, int driver_reload_rc, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)cls; rc = UG_state_reload_replica_gateway_ids( ug ); if( rc != 0 ) { SG_error("UG_state_reload_replica_gateway_ids rc = %d\n", rc ); } return rc; } // set up the gateway's method implementation // always succeeds int UG_impl_install_methods( struct SG_gateway* gateway ) { SG_impl_connect_cache( gateway, UG_impl_connect_cache ); SG_impl_stat( gateway, UG_impl_stat ); SG_impl_stat_block( gateway, UG_impl_stat_block ); SG_impl_truncate( gateway, UG_impl_truncate ); SG_impl_rename( gateway, UG_impl_rename ); SG_impl_detach( gateway, UG_impl_detach ); SG_impl_patch_manifest( gateway, UG_impl_manifest_patch ); SG_impl_config_change( gateway, UG_impl_config_change ); SG_impl_serialize( gateway, UG_driver_chunk_serialize ); SG_impl_deserialize( gateway, UG_driver_chunk_deserialize ); return 0; } <commit_msg>write_delta carries new file size on write<commit_after>/* Copyright 2015 The Trustees of Princeton University 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 "driver.h" #include "impl.h" #include "read.h" #include "write.h" #include "client.h" #include "core.h" #include "consistency.h" // connect to the CDN // return 0 on success // return -ENOMEM on OOM static int UG_impl_connect_cache( struct SG_gateway* gateway, CURL* curl, char const* url, void* cls ) { int rc = 0; char* out_url = NULL; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); rc = UG_driver_cdn_url( ug, url, &out_url ); if( rc != 0 ) { return rc; } // set up the curl handle curl_easy_setopt( curl, CURLOPT_URL, out_url ); SG_safe_free( out_url ); return 0; } // update a file's manifest, in response to a remote call // write_delta must contain the new file size // return 0 on success // return -ENOENT if not found // return -ESTALE if not local // return -errno on error // NOTE: the permissions will already have been checked by the server static int UG_impl_manifest_patch( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_manifest* write_delta, void* cls ) { int rc = 0; int ref_rc = 0; struct fskit_entry* fent = NULL; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct UG_inode* inode = NULL; struct ms_client* ms = SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); rc = UG_consistency_path_ensure_fresh( gateway, reqdat->fs_path ); if( rc != 0 ) { SG_error("UG_consistency_path_ensure_fresh('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } rc = UG_consistency_manifest_ensure_fresh( gateway, reqdat->fs_path ); if( rc != 0 ) { SG_error("UG_consistency_manifest_ensure_fresh('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } // look up fent = fskit_entry_resolve_path( fs, reqdat->fs_path, reqdat->user_id, volume_id, true, &rc ); if( fent == NULL ) { return rc; } inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); // must be coordinated by us if( UG_inode_coordinator_id( inode ) != SG_gateway_id( gateway ) ) { fskit_entry_unlock( fent ); return -ESTALE; } // update the manifest fskit_entry_ref_entry( fent ); rc = UG_write_patch_manifest( gateway, reqdat, inode, write_delta ); fskit_entry_unlock( fent ); ref_rc = fskit_entry_unref( fs, reqdat->fs_path, fent ); if( ref_rc != 0 ) { SG_warn("fskit_entry_unref('%s') rc = %d\n", reqdat->fs_path, rc ); } return rc; } // stat a file--build a manifest request, and set its mode // return 0 on success // return -ESTALE if the inode is not local // return -ENOENT if we don't have it // return -ENOMEM on OOM // return -errno on error static int UG_impl_stat( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_request_data* entity_info, mode_t* mode, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct md_entry ent_info; rc = UG_stat_raw( ug, reqdat->fs_path, &ent_info ); if( rc != 0 ) { SG_error("UG_stat_raw('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } if( ent_info.coordinator != SG_gateway_id( gateway ) ) { // not ours SG_error("Not the coordinator of '%s' (it is now %" PRIu64 ")\n", reqdat->fs_path, ent_info.coordinator ); md_entry_free( &ent_info ); return -ESTALE; } if( mode != NULL ) { *mode = ent_info.mode; } if( entity_info != NULL ) { rc = SG_request_data_init_manifest( gateway, reqdat->fs_path, ent_info.file_id, ent_info.version, ent_info.manifest_mtime_sec, ent_info.manifest_mtime_nsec, entity_info ); if( rc != 0 ) { // OOM md_entry_free( &ent_info ); return -ENOMEM; } if( ent_info.type != MD_ENTRY_FILE ) { // not a file md_entry_free( &ent_info ); return -ENOENT; } } md_entry_free( &ent_info ); return 0; } // stat a file's block--build a manifest request, and set its mode // return 0 on success // return -ESTALE if the inode is not local // return -ENOENT if we don't have it // return -ENOMEM on OOM // return -errno on error static int UG_impl_stat_block( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_request_data* entity_info, mode_t* mode, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); int64_t block_version = 0; UG_handle_t* fi = NULL; struct fskit_entry* fent = NULL; struct UG_inode* inode = NULL; uint64_t file_id = 0; int64_t file_version = 0; int close_rc = 0; fi = UG_open( ug, reqdat->fs_path, O_RDONLY, &rc ); if( fi == NULL ) { SG_error("UG_open('%s') rc = %d\n", reqdat->fs_path, rc ); return rc; } fskit_file_handle_rlock( fi->fh ); fent = fskit_file_handle_get_entry( fi->fh ); if( fent == NULL ) { SG_error("BUG: no entry for handle %p\n", fi->fh ); exit(1); } fskit_entry_rlock( fent ); inode = (struct UG_inode*)fskit_entry_get_user_data( fent ); if( inode == NULL ) { SG_error("BUG: no inode for entry %p\n", fent ); exit(1); } if( UG_inode_coordinator_id( inode ) != SG_gateway_id( gateway ) ) { // not ours SG_error("Not the coordinator of '%s' (it is now %" PRIu64 ")\n", reqdat->fs_path, UG_inode_coordinator_id( inode ) ); fskit_entry_unlock( fent ); fskit_file_handle_unlock( fi->fh ); rc = UG_close( ug, fi ); if( rc != 0 ) { SG_error("UG_close('%s') rc = %d\n", reqdat->fs_path, rc ); } return rc; } file_id = UG_inode_file_id( inode ); file_version = UG_inode_file_version( inode ); if( mode != NULL ) { *mode = fskit_entry_get_mode( fent ); } if( entity_info != NULL ) { rc = UG_getblockinfo( ug, reqdat->block_id, &block_version, NULL, fi ); } fskit_entry_unlock( fent ); fskit_file_handle_unlock( fi->fh ); inode = NULL; if( rc != 0 ) { SG_error("UG_getblockinfo(%s[%" PRIu64 "]) rc = %d\n", reqdat->fs_path, reqdat->block_id, rc); goto UG_impl_stat_block_out; } rc = SG_request_data_init_block( gateway, reqdat->fs_path, file_id, file_version, reqdat->block_id, block_version, entity_info ); if( rc != 0 ) { SG_error("SG_request_data_init_block rc = %d\n", rc ); goto UG_impl_stat_block_out; } UG_impl_stat_block_out: close_rc = UG_close( ug, fi ); if( close_rc != 0 ) { SG_error("UG_close('%s') rc = %d\n", reqdat->fs_path, close_rc ); } return rc; } // remote request to rename a file. // there can be at most one ongoing rename at a given moment. // return 0 on success // return -ENOMEM on OOM // return -EBUSY if the given path is being renamed already // return -ESTALE if the node is not local // return -errno on error static int UG_impl_rename( struct SG_gateway* gateway, struct SG_request_data* reqdat, char const* new_path, void* cls ) { struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); return UG_rename( ug, reqdat->fs_path, new_path ); } // truncate a file // return 0 on success // return -errno on error static int UG_impl_truncate( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t new_size, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct ms_client* ms = (struct ms_client*)SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); // truncate locally. The MS will be informed as part of the user route. rc = fskit_trunc( fs, reqdat->fs_path, reqdat->user_id, volume_id, new_size ); if( rc != 0 ) { SG_error("fskit_trunc( '%s', %" PRIu64 ") rc = %d\n", reqdat->fs_path, new_size, rc); } return rc; } // detach a file // return 0 on success // return -errno on error static int UG_impl_detach( struct SG_gateway* gateway, struct SG_request_data* reqdat, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)SG_gateway_cls( gateway ); struct fskit_core* fs = UG_state_fs( ug ); struct ms_client* ms = (struct ms_client*)SG_gateway_ms( gateway ); uint64_t volume_id = ms_client_get_volume_id( ms ); struct stat sb; char const* method = NULL; // file or directory? rc = fskit_stat( fs, reqdat->fs_path, 0, 0, &sb ); if( rc != 0 ) { return rc; } if( S_ISREG( sb.st_mode ) ) { // unlink locally. The MS will be informed as part of the user route. method = "fskit_unlink"; rc = fskit_unlink( fs, reqdat->fs_path, reqdat->user_id, volume_id ); } else { // rmdir locally. The MS will be informed as part of the user route method = "fskit_rmdir"; rc = fskit_rmdir( fs, reqdat->fs_path, reqdat->user_id, volume_id ); } if( rc != 0 ) { SG_error("%s( '%s' ) rc = %d\n", method, reqdat->fs_path, rc); } return 0; } // on config reload, re-calculate the set of replica gateway IDs // return 0 on success // return negative on error static int UG_impl_config_change( struct SG_gateway* gateway, int driver_reload_rc, void* cls ) { int rc = 0; struct UG_state* ug = (struct UG_state*)cls; rc = UG_state_reload_replica_gateway_ids( ug ); if( rc != 0 ) { SG_error("UG_state_reload_replica_gateway_ids rc = %d\n", rc ); } return rc; } // set up the gateway's method implementation // always succeeds int UG_impl_install_methods( struct SG_gateway* gateway ) { SG_impl_connect_cache( gateway, UG_impl_connect_cache ); SG_impl_stat( gateway, UG_impl_stat ); SG_impl_stat_block( gateway, UG_impl_stat_block ); SG_impl_truncate( gateway, UG_impl_truncate ); SG_impl_rename( gateway, UG_impl_rename ); SG_impl_detach( gateway, UG_impl_detach ); SG_impl_patch_manifest( gateway, UG_impl_manifest_patch ); SG_impl_config_change( gateway, UG_impl_config_change ); SG_impl_serialize( gateway, UG_driver_chunk_serialize ); SG_impl_deserialize( gateway, UG_driver_chunk_deserialize ); return 0; } <|endoftext|>
<commit_before>/** * @file UvUtils.hpp * @brief UvUtils class prototype. * @author zer0 * @date 2016-11-03 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Noncopyable.hpp> #include <libtbag/debug/ErrorCode.hpp> #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) # include <cstdint> typedef intptr_t ssize_t; # define _SSIZE_T_ # define _SSIZE_T_DEFINED #endif #include <string> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace util { #ifndef TBAG_UTIL_UV_HANDLE_MAP #define TBAG_UTIL_UV_HANDLE_MAP(_TBAG_HANDLE_XX, _TBAG_REQ_XX, _TBAG_ETC_XX) \ /* Handle types. */ \ _TBAG_HANDLE_XX(LOOP , uv_loop_t) \ _TBAG_HANDLE_XX(HANDLE , uv_handle_t) \ _TBAG_HANDLE_XX(STREAM , uv_stream_t) \ _TBAG_HANDLE_XX(TCP , uv_tcp_t) \ _TBAG_HANDLE_XX(UDP , uv_udp_t) \ _TBAG_HANDLE_XX(PIPE , uv_pipe_t) \ _TBAG_HANDLE_XX(TTY , uv_tty_t) \ _TBAG_HANDLE_XX(POLL , uv_poll_t) \ _TBAG_HANDLE_XX(TIMER , uv_timer_t) \ _TBAG_HANDLE_XX(PREPARE , uv_prepare_t) \ _TBAG_HANDLE_XX(CHECK , uv_check_t) \ _TBAG_HANDLE_XX(IDLE , uv_idle_t) \ _TBAG_HANDLE_XX(ASYNC , uv_async_t) \ _TBAG_HANDLE_XX(PROCESS , uv_process_t) \ _TBAG_HANDLE_XX(FS_EVENT, uv_fs_event_t) \ _TBAG_HANDLE_XX(FS_POLL , uv_fs_poll_t) \ _TBAG_HANDLE_XX(SIGNAL , uv_signal_t) \ /* Request types. */ \ _TBAG_REQ_XX(REQ , uv_req_t) \ _TBAG_REQ_XX(GETADDRINFO, uv_getaddrinfo_t) \ _TBAG_REQ_XX(GETNAMEINFO, uv_getnameinfo_t) \ _TBAG_REQ_XX(SHUTDOWN , uv_shutdown_t) \ _TBAG_REQ_XX(WRITE , uv_write_t) \ _TBAG_REQ_XX(CONNECT , uv_connect_t) \ _TBAG_REQ_XX(UDP_SEND , uv_udp_send_t) \ _TBAG_REQ_XX(FS , uv_fs_t) \ _TBAG_REQ_XX(WORK , uv_work_t) \ /* None of the above. */ \ _TBAG_ETC_XX(CPU_INFO , uv_cpu_info_t) \ _TBAG_ETC_XX(INTERFACE_ADDRESS, uv_interface_address_t) \ _TBAG_ETC_XX(DIRENT , uv_dirent_t) \ _TBAG_ETC_XX(PASSWD , uv_passwd_t) \ /* -- END -- */ #endif #ifndef TBAG_UTIL_UV_HANDLE_MAP_ALL #define TBAG_UTIL_UV_HANDLE_MAP_ALL(_TBAG_XX) \ TBAG_UTIL_UV_HANDLE_MAP(_TBAG_XX, _TBAG_XX, _TBAG_XX) #endif /** * Table of libuv types. * * @author zer0 * @date 2016-12-07 */ enum class UvType : int { UNKNOWN = 0, #define _TBAG_XX(name, type) name, TBAG_UTIL_UV_HANDLE_MAP_ALL(_TBAG_XX) #undef _TBAG_XX SIZE }; /** * Table of libuv handle types. * * @author zer0 * @date 2016-12-17 */ enum class UvHandleType : int { UNKNOWN = 0, #define _TBAG_XX(name, type) name = static_cast<int>(UvType::name), #define _TBAG_NX(name, type) TBAG_UTIL_UV_HANDLE_MAP(_TBAG_XX, _TBAG_NX, _TBAG_NX) #undef _TBAG_XX #undef _TBAG_NX SIZE }; TBAG_API void initUv(); TBAG_API char const * getUvHandleName(void * handle); /** * @remarks * Same this code: * @code * const char* uv_strerror(int err); * @endcode */ TBAG_API std::string getUvErrorString(int uv_error_code); /** * @remarks * Same this code: * @code * const char* uv_err_name(int err); * @endcode */ TBAG_API std::string getUvErrorName(int uv_error_code); TBAG_API bool isUvHandle(UvType type); TBAG_API bool isUvRequest(UvType type); /** * libuv native type utility class. * * @author zer0 * @date 2016-12-07 */ class TBAG_API UvNative : public Noncopyable { public: using Type = UvType; private: Type const TYPE; void * _native; public: UvNative(Type type); ~UvNative(); public: inline operator bool() const TBAG_NOEXCEPT { return _native != nullptr; } public: inline Type getType() const TBAG_NOEXCEPT { return TYPE; } inline bool isHandle() const TBAG_NOEXCEPT { return isUvHandle(TYPE); } inline bool isRequest() const TBAG_NOEXCEPT { return isUvRequest(TYPE); } public: inline void * getNative() TBAG_NOEXCEPT { return _native; } inline void const * getNative() const TBAG_NOEXCEPT { return _native; } public: template <typename T> inline T * castNative() const TBAG_NOEXCEPT { return static_cast<T*>(_native); } }; /** * libuv handle type utility class. * * @author zer0 * @date 2016-12-17 */ class TBAG_API UvHandle : public UvNative { public: struct OnCloseCallback { virtual void onClose() = 0; }; private: OnCloseCallback * _on_close_cb; public: UvHandle(UvHandleType type); ~UvHandle(); public: inline void setOnCloseCallback(OnCloseCallback * callback) TBAG_NOEXCEPT { _on_close_cb = callback; } public: bool isClosing() const TBAG_NOEXCEPT; ErrorCode close(); public: void onClose(void * handle); }; } // namespace util // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ <commit_msg>Refactoring enum types in UvUtils package.<commit_after>/** * @file UvUtils.hpp * @brief UvUtils class prototype. * @author zer0 * @date 2016-11-03 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Noncopyable.hpp> #include <libtbag/debug/ErrorCode.hpp> #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) # include <cstdint> typedef intptr_t ssize_t; # define _SSIZE_T_ # define _SSIZE_T_DEFINED #endif #include <string> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace util { #ifndef TBAG_UTIL_UV_HANDLE_MAP #define TBAG_UTIL_UV_HANDLE_MAP(_TBAG_HANDLE_XX, _TBAG_REQ_XX, _TBAG_ETC_XX) \ /* Handle types. */ \ _TBAG_HANDLE_XX(LOOP , uv_loop_t) \ _TBAG_HANDLE_XX(HANDLE , uv_handle_t) \ _TBAG_HANDLE_XX(STREAM , uv_stream_t) \ _TBAG_HANDLE_XX(TCP , uv_tcp_t) \ _TBAG_HANDLE_XX(UDP , uv_udp_t) \ _TBAG_HANDLE_XX(PIPE , uv_pipe_t) \ _TBAG_HANDLE_XX(TTY , uv_tty_t) \ _TBAG_HANDLE_XX(POLL , uv_poll_t) \ _TBAG_HANDLE_XX(TIMER , uv_timer_t) \ _TBAG_HANDLE_XX(PREPARE , uv_prepare_t) \ _TBAG_HANDLE_XX(CHECK , uv_check_t) \ _TBAG_HANDLE_XX(IDLE , uv_idle_t) \ _TBAG_HANDLE_XX(ASYNC , uv_async_t) \ _TBAG_HANDLE_XX(PROCESS , uv_process_t) \ _TBAG_HANDLE_XX(FS_EVENT, uv_fs_event_t) \ _TBAG_HANDLE_XX(FS_POLL , uv_fs_poll_t) \ _TBAG_HANDLE_XX(SIGNAL , uv_signal_t) \ /* Request types. */ \ _TBAG_REQ_XX(REQ , uv_req_t) \ _TBAG_REQ_XX(GETADDRINFO, uv_getaddrinfo_t) \ _TBAG_REQ_XX(GETNAMEINFO, uv_getnameinfo_t) \ _TBAG_REQ_XX(SHUTDOWN , uv_shutdown_t) \ _TBAG_REQ_XX(WRITE , uv_write_t) \ _TBAG_REQ_XX(CONNECT , uv_connect_t) \ _TBAG_REQ_XX(UDP_SEND , uv_udp_send_t) \ _TBAG_REQ_XX(FS , uv_fs_t) \ _TBAG_REQ_XX(WORK , uv_work_t) \ /* None of the above. */ \ _TBAG_ETC_XX(CPU_INFO , uv_cpu_info_t) \ _TBAG_ETC_XX(INTERFACE_ADDRESS, uv_interface_address_t) \ _TBAG_ETC_XX(DIRENT , uv_dirent_t) \ _TBAG_ETC_XX(PASSWD , uv_passwd_t) \ /* -- END -- */ #endif #ifndef TBAG_UTIL_UV_HANDLE_MAP_ALL #define TBAG_UTIL_UV_HANDLE_MAP_ALL(_TBAG_XX) \ TBAG_UTIL_UV_HANDLE_MAP(_TBAG_XX, _TBAG_XX, _TBAG_XX) #endif typedef int UvPodType; /** * Table of libuv types. * * @author zer0 * @date 2016-12-07 */ enum class UvType : UvPodType { UNKNOWN = 0, #define _TBAG_XX(name, type) name, TBAG_UTIL_UV_HANDLE_MAP_ALL(_TBAG_XX) #undef _TBAG_XX _SIZE_ }; // @formatter:off #define _TBAG_XX(name, type) name = static_cast<UvPodType>(UvType::name), #define _TBAG_NOT(name, type) enum class UvHandleType : UvPodType { _START_NUMBER_ = -1, TBAG_UTIL_UV_HANDLE_MAP(_TBAG_XX, _TBAG_NOT, _TBAG_NOT) _SIZE_ }; enum class UvRequsetType : UvPodType { _START_NUMBER_ = -1, TBAG_UTIL_UV_HANDLE_MAP(_TBAG_NOT, _TBAG_XX, _TBAG_NOT) _SIZE_ }; enum class UvEtcType : UvPodType { _START_NUMBER_ = -1, TBAG_UTIL_UV_HANDLE_MAP(_TBAG_NOT, _TBAG_NOT, _TBAG_XX) _SIZE_ }; #undef _TBAG_XX #undef _TBAG_NOT // @formatter:on TBAG_API void initUv(); TBAG_API char const * getUvHandleName(void * handle); /** * @remarks * Same this code: * @code * const char* uv_strerror(int err); * @endcode */ TBAG_API std::string getUvErrorString(int uv_error_code); /** * @remarks * Same this code: * @code * const char* uv_err_name(int err); * @endcode */ TBAG_API std::string getUvErrorName(int uv_error_code); TBAG_API bool isUvHandle(UvType type); TBAG_API bool isUvRequest(UvType type); /** * libuv native type utility class. * * @author zer0 * @date 2016-12-07 */ class TBAG_API UvNative : public Noncopyable { public: using Type = UvType; private: Type const TYPE; void * _native; public: UvNative(Type type); ~UvNative(); public: inline operator bool() const TBAG_NOEXCEPT { return _native != nullptr; } public: inline Type getType() const TBAG_NOEXCEPT { return TYPE; } inline bool isHandle() const TBAG_NOEXCEPT { return isUvHandle(TYPE); } inline bool isRequest() const TBAG_NOEXCEPT { return isUvRequest(TYPE); } public: inline void * getNative() TBAG_NOEXCEPT { return _native; } inline void const * getNative() const TBAG_NOEXCEPT { return _native; } public: template <typename T> inline T * castNative() const TBAG_NOEXCEPT { return static_cast<T*>(_native); } }; /** * libuv handle type utility class. * * @author zer0 * @date 2016-12-17 */ class TBAG_API UvHandle : public UvNative { public: struct OnCloseCallback { virtual void onClose() = 0; }; private: OnCloseCallback * _on_close_cb; public: UvHandle(UvHandleType type); ~UvHandle(); public: inline void setOnCloseCallback(OnCloseCallback * callback) TBAG_NOEXCEPT { _on_close_cb = callback; } public: bool isClosing() const TBAG_NOEXCEPT; ErrorCode close(); public: void onClose(void * handle); }; } // namespace util // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_UVUTILS_HPP__ <|endoftext|>
<commit_before>// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // $Id: exampleB4a.cc 75215 2013-10-29 16:07:06Z gcosmo $ // /// \file exampleB4a.cc /// \brief Main program of the B4a example #include "DetectorConstruction.hh" #include "ActionInitialization.hh" #ifdef G4MULTITHREADED #include "G4MTRunManager.hh" #else #include "G4RunManager.hh" #endif #include "G4UImanager.hh" #include "G4UIcommand.hh" #include "FTFP_BERT.hh" #include "QGSP_BERT.hh" #include "QGSP_BERT_HP.hh" #include "G4PhysListFactory.hh" #include "G4RadioactiveDecayPhysics.hh" #include "Randomize.hh" #ifdef G4VIS_USE #include "G4VisExecutive.hh" #endif #ifdef G4UI_USE #include "G4UIExecutive.hh" #endif //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... namespace { void PrintUsage() { G4cerr << " Usage: " << G4endl; G4cerr << " exampleB4a [-m macro ] [-u UIsession] [-t nThreads]" << G4endl; G4cerr << " note: -t option is available only for multi-threaded mode." << G4endl; } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... int main(int argc,char** argv) { // Evaluate arguments // if ( argc > 7 ) { PrintUsage(); return 1; } G4String macro; G4String session; #ifdef G4MULTITHREADED G4int nThreads = 0; #endif for ( G4int i=1; i<argc; i=i+2 ) { if ( G4String(argv[i]) == "-m" ) macro = argv[i+1]; else if ( G4String(argv[i]) == "-u" ) session = argv[i+1]; #ifdef G4MULTITHREADED else if ( G4String(argv[i]) == "-t" ) { nThreads = G4UIcommand::ConvertToInt(argv[i+1]); } #endif else { PrintUsage(); return 1; } } // Choose the Random engine // //G4Random::setTheEngine(new CLHEP::RanecuEngine); CLHEP::RanluxEngine defaultEngine( 1234567, 4 ); G4Random::setTheEngine( &defaultEngine ); G4int seed = time( NULL ); G4Random::setTheSeed( seed ); // Construct the default run manager // #ifdef G4MULTITHREADED G4MTRunManager * runManager = new G4MTRunManager; runManager->SetNumberOfThreads(1); /* if ( nThreads > 0 ) { runManager->SetNumberOfThreads(4); } */ #else G4RunManager * runManager = new G4RunManager; #endif // Set mandatory initialization classes // DetectorConstruction* detConstruction = new DetectorConstruction(); runManager->SetUserInitialization(detConstruction); /* G4VModularPhysicsList* physicsList = new QGSP_BERT; runManager->SetUserInitialization(physicsList); */ //////////////////////////////////////////////////////////////////// // Initialising the Physics List with Radioactive Decay //////////////////////////////////////////////////////////////////// G4PhysListFactory factory; G4VModularPhysicsList* phys = 0; G4String physName = "QGSP_BERT"; // reference PhysicsList via its name phys = factory.GetReferencePhysList(physName); phys->RegisterPhysics(new G4RadioactiveDecayPhysics()); runManager->SetUserInitialization(phys); ActionInitialization* actionInitialization = new ActionInitialization(detConstruction); runManager->SetUserInitialization(actionInitialization); // Initialize G4 kernel // runManager->Initialize(); #ifdef G4VIS_USE // Initialize visualization G4VisManager* visManager = new G4VisExecutive; // G4VisExecutive can take a verbosity argument - see /vis/verbose guidance. // G4VisManager* visManager = new G4VisExecutive("Quiet"); visManager->Initialize(); #endif // Get the pointer to the User Interface manager G4UImanager* UImanager = G4UImanager::GetUIpointer(); if ( macro.size() ) { // batch mode G4String command = "/control/execute "; UImanager->ApplyCommand(command+macro); } else { // interactive mode : define UI session #ifdef G4UI_USE G4UIExecutive* ui = new G4UIExecutive(argc, argv, session); #ifdef G4VIS_USE UImanager->ApplyCommand("/control/execute init_vis.mac"); #else UImanager->ApplyCommand("/control/execute init.mac"); #endif if (ui->IsGUI()) UImanager->ApplyCommand("/control/execute gui.mac"); ui->SessionStart(); delete ui; #endif } // Job termination // Free the store: user actions, physics_list and detector_description are // owned and deleted by the run manager, so they should not be deleted // in the main() program ! #ifdef G4VIS_USE delete visManager; #endif delete runManager; return 0; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... <commit_msg>remove<commit_after><|endoftext|>
<commit_before>/**********************************************************\ Auto-generated Chimera.cpp This file contains the auto-generated main plugin object implementation for the Chimera project \**********************************************************/ #include "ChimeraAPI.h" #include "Chimera.h" #include "parrot/api.h" /////////////////////////////////////////////////////////////////////////////// /// @fn Chimera::StaticInitialize() /// /// @brief Called from PluginFactory::globalPluginInitialize() /// /// @see FB::FactoryBase::globalPluginInitialize /////////////////////////////////////////////////////////////////////////////// void Chimera::StaticInitialize() { // Place one-time initialization stuff here; As of FireBreath 1.4 this should only // be called once per process } /////////////////////////////////////////////////////////////////////////////// /// @fn Chimera::StaticInitialize() /// /// @brief Called from PluginFactory::globalPluginDeinitialize() /// /// @see FB::FactoryBase::globalPluginDeinitialize /////////////////////////////////////////////////////////////////////////////// void Chimera::StaticDeinitialize() { // Place one-time deinitialization stuff here. As of FireBreath 1.4 this should // always be called just before the plugin library is unloaded } /////////////////////////////////////////////////////////////////////////////// /// @brief Chimera constructor. Note that your API is not available /// at this point, nor the window. For best results wait to use /// the JSAPI object until the onPluginReady method is called /////////////////////////////////////////////////////////////////////////////// Chimera::Chimera() { } /////////////////////////////////////////////////////////////////////////////// /// @brief Chimera destructor. /////////////////////////////////////////////////////////////////////////////// Chimera::~Chimera() { // This is optional, but if you reset m_api (the shared_ptr to your JSAPI // root object) and tell the host to free the retained JSAPI objects then // unless you are holding another shared_ptr reference to your JSAPI object // they will be released here. releaseRootJSAPI(); m_host->freeRetainedObjects(); } void Chimera::onPluginReady() { // When this is called, the BrowserHost is attached, the JSAPI object is // created, and we are ready to interact with the page and such. The // PluginWindow may or may not have already fire the AttachedEvent at // this point. } void Chimera::shutdown() { // This will be called when it is time for the plugin to shut down; // any threads or anything else that may hold a shared_ptr to this // object should be released here so that this object can be safely // destroyed. This is the last point that shared_from_this and weak_ptr // references to this object will be valid } /////////////////////////////////////////////////////////////////////////////// /// @brief Creates an instance of the JSAPI object that provides your main /// Javascript interface. /// /// Note that m_host is your BrowserHost and shared_ptr returns a /// FB::PluginCorePtr, which can be used to provide a /// boost::weak_ptr<Chimera> for your JSAPI class. /// /// Be very careful where you hold a shared_ptr to your plugin class from, /// as it could prevent your plugin class from getting destroyed properly. /////////////////////////////////////////////////////////////////////////////// FB::JSAPIPtr Chimera::createJSAPI() { // m_host is the BrowserHost return boost::make_shared<ChimeraAPI>(FB::ptr_cast<Chimera>(shared_from_this()), m_host); } bool Chimera::onMouseDown(FB::MouseDownEvent *evt, FB::PluginWindow *) { //printf("Mouse down at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onMouseUp(FB::MouseUpEvent *evt, FB::PluginWindow *) { //printf("Mouse up at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onMouseMove(FB::MouseMoveEvent *evt, FB::PluginWindow *) { //printf("Mouse move at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onWindowAttached(FB::AttachedEvent *evt, FB::PluginWindow *) { // The window is attached; act appropriately return false; } bool Chimera::onWindowDetached(FB::DetachedEvent *evt, FB::PluginWindow *) { // The window is about to be detached; act appropriately return false; } <commit_msg>Add the code to actually create a Parrot interpreter. Doesn't compile yet because we haven't told cmake to compile against libparrot yet<commit_after>/**********************************************************\ Auto-generated Chimera.cpp This file contains the auto-generated main plugin object implementation for the Chimera project \**********************************************************/ #include "ChimeraAPI.h" #include "Chimera.h" #include "parrot/api.h" #include "stdio.h" /////////////////////////////////////////////////////////////////////////////// /// @fn Chimera::StaticInitialize() /// /// @brief Called from PluginFactory::globalPluginInitialize() /// /// @see FB::FactoryBase::globalPluginInitialize /////////////////////////////////////////////////////////////////////////////// void Chimera::StaticInitialize() { // Place one-time initialization stuff here; As of FireBreath 1.4 this should only // be called once per process Parrot_PMC interp = NULL; if (!Parrot_api_make_interpreter(NULL, NULL, 0, &interp)) { fprintf(stderr, "Cannot create Parrot interpreter!\n"); } else { printf("Parrot interp created!\n"); } } /////////////////////////////////////////////////////////////////////////////// /// @fn Chimera::StaticInitialize() /// /// @brief Called from PluginFactory::globalPluginDeinitialize() /// /// @see FB::FactoryBase::globalPluginDeinitialize /////////////////////////////////////////////////////////////////////////////// void Chimera::StaticDeinitialize() { // Place one-time deinitialization stuff here. As of FireBreath 1.4 this should // always be called just before the plugin library is unloaded } /////////////////////////////////////////////////////////////////////////////// /// @brief Chimera constructor. Note that your API is not available /// at this point, nor the window. For best results wait to use /// the JSAPI object until the onPluginReady method is called /////////////////////////////////////////////////////////////////////////////// Chimera::Chimera() { } /////////////////////////////////////////////////////////////////////////////// /// @brief Chimera destructor. /////////////////////////////////////////////////////////////////////////////// Chimera::~Chimera() { // This is optional, but if you reset m_api (the shared_ptr to your JSAPI // root object) and tell the host to free the retained JSAPI objects then // unless you are holding another shared_ptr reference to your JSAPI object // they will be released here. releaseRootJSAPI(); m_host->freeRetainedObjects(); } void Chimera::onPluginReady() { // When this is called, the BrowserHost is attached, the JSAPI object is // created, and we are ready to interact with the page and such. The // PluginWindow may or may not have already fire the AttachedEvent at // this point. } void Chimera::shutdown() { // This will be called when it is time for the plugin to shut down; // any threads or anything else that may hold a shared_ptr to this // object should be released here so that this object can be safely // destroyed. This is the last point that shared_from_this and weak_ptr // references to this object will be valid } /////////////////////////////////////////////////////////////////////////////// /// @brief Creates an instance of the JSAPI object that provides your main /// Javascript interface. /// /// Note that m_host is your BrowserHost and shared_ptr returns a /// FB::PluginCorePtr, which can be used to provide a /// boost::weak_ptr<Chimera> for your JSAPI class. /// /// Be very careful where you hold a shared_ptr to your plugin class from, /// as it could prevent your plugin class from getting destroyed properly. /////////////////////////////////////////////////////////////////////////////// FB::JSAPIPtr Chimera::createJSAPI() { // m_host is the BrowserHost return boost::make_shared<ChimeraAPI>(FB::ptr_cast<Chimera>(shared_from_this()), m_host); } bool Chimera::onMouseDown(FB::MouseDownEvent *evt, FB::PluginWindow *) { //printf("Mouse down at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onMouseUp(FB::MouseUpEvent *evt, FB::PluginWindow *) { //printf("Mouse up at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onMouseMove(FB::MouseMoveEvent *evt, FB::PluginWindow *) { //printf("Mouse move at: %d, %d\n", evt->m_x, evt->m_y); return false; } bool Chimera::onWindowAttached(FB::AttachedEvent *evt, FB::PluginWindow *) { // The window is attached; act appropriately return false; } bool Chimera::onWindowDetached(FB::DetachedEvent *evt, FB::PluginWindow *) { // The window is about to be detached; act appropriately return false; } <|endoftext|>
<commit_before>/*********************************************************************** created: Sun Jul 19 2009 author: Paul D Turner <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/Font_xmlHandler.h" #include "CEGUI/Exceptions.h" #include "CEGUI/Logger.h" #include "CEGUI/XMLAttributes.h" #include "CEGUI/System.h" #include "CEGUI/XMLParser.h" #include "CEGUI/PixmapFont.h" #include "CEGUI/SharedStringStream.h" #ifdef CEGUI_HAS_FREETYPE # include "CEGUI/FreeTypeFont.h" #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const String Font_xmlHandler::FontSchemaName("Font.xsd"); const String Font_xmlHandler::FontElement("Font"); const String Font_xmlHandler::FontsElement("Fonts"); const String Font_xmlHandler::MappingElement("Mapping"); const String Font_xmlHandler::FontTypeAttribute("type"); const String Font_xmlHandler::FontNameAttribute("name"); const String Font_xmlHandler::FontFilenameAttribute("filename"); const String Font_xmlHandler::FontResourceGroupAttribute("resourceGroup"); const String Font_xmlHandler::FontAutoScaledAttribute("autoScaled"); const String Font_xmlHandler::FontNativeHorzResAttribute("nativeHorzRes"); const String Font_xmlHandler::FontNativeVertResAttribute("nativeVertRes"); const String Font_xmlHandler::FontLineSpacingAttribute("lineSpacing"); const String Font_xmlHandler::FontSizeAttribute("size"); const String Font_xmlHandler::FontAntiAliasedAttribute("antiAlias"); const String Font_xmlHandler::MappingCodepointAttribute("codepoint"); const String Font_xmlHandler::MappingImageAttribute("image"); const String Font_xmlHandler::MappingHorzAdvanceAttribute("horzAdvance"); const String Font_xmlHandler::FontVersionAttribute( "version" ); const String Font_xmlHandler::FontTypeFreeType("FreeType"); const String Font_xmlHandler::FontTypePixmap("Pixmap"); //----------------------------------------------------------------------------// // note: The assets' versions aren't usually the same as CEGUI version, they // are versioned from version 1 onwards! // // previous versions (though not specified in files until 3) // 1 - CEGUI up to and including 0.4.x // 2 - CEGUI versions 0.5.x through 0.7.x (Static/Dynamic types renamed to Pixmap/TrueType // Removed facility to pre-declare glyphs and glyph ranges) // 3 - CEGUI version 1.x.x (changed case of attr names, added version support) const String NativeVersion( "4" ); //----------------------------------------------------------------------------// Font_xmlHandler::Font_xmlHandler(): d_font(0), d_isFontLoadingDone(false) {} //----------------------------------------------------------------------------// Font_xmlHandler::~Font_xmlHandler() { if (!d_isFontLoadingDone && d_font != 0) { Logger::getSingleton().logEvent("Font_xmlHandler::~Font_xmlHandler: " "Font XML Handler is being destroyed, but loading of Font with name \"" + d_font->getName() + "\" has not been completed.", Warnings); delete d_font; } } //----------------------------------------------------------------------------// std::vector<Font*>& Font_xmlHandler::getObjects() { if (d_loadedFonts.empty()) throw InvalidRequestException("Attempting to return the loaded Fonts but the container of loaded Fonts is empty."); if (d_loadedFonts.empty()) throw InvalidRequestException("Attempting to return the loaded Fonts but loading of font \"" + d_font->getName() + "\" has not been finished."); d_isFontLoadingDone = true; return d_loadedFonts; } //----------------------------------------------------------------------------// const String& Font_xmlHandler::getSchemaName() const { return FontSchemaName; } //----------------------------------------------------------------------------// const String& Font_xmlHandler::getDefaultResourceGroup() const { return Font::getDefaultResourceGroup(); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes) { // handle root Font element if (element == FontsElement) elementFontsStart(attributes); // handle root Font element else if (element == FontElement) elementFontStart(attributes); // handle a Mapping element else if (element == MappingElement) elementMappingStart(attributes); // anything else is a non-fatal error. else Logger::getSingleton().logEvent("Font_xmlHandler::elementStart: " "Unknown element encountered: <" + element + ">", Errors); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementEnd(const String& element) { if (element == FontsElement) elementFontsEnd(); else if (element == FontElement) elementFontEnd(); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementFontsStart(const XMLAttributes& attributes) { validateFontFileVersion(attributes); } void Font_xmlHandler::elementFontStart(const XMLAttributes& attributes) { if (d_font != 0) { throw InvalidRequestException( "Attempting to load a new font but the loading of the " "previous font \"" + d_font->getName() + "\" has not been completed."); } // get type of font being created const String font_type(attributes.getValueAsString(FontTypeAttribute)); // log the start of font creation. CEGUI_LOGINSANE( "Started creation of Font from XML specification:"); if (font_type == FontTypeFreeType) createFreeTypeFont(attributes); else if (font_type == FontTypePixmap) createPixmapFont(attributes); else throw InvalidRequestException( "Encountered unknown font type of '" + font_type + "'"); } //----------------------------------------------------------------------------// void Font_xmlHandler::validateFontFileVersion(const XMLAttributes& attrs) { const String version(attrs.getValueAsString(FontVersionAttribute, "unknown")); if (version == NativeVersion) return; throw InvalidRequestException( "You are attempting to load a font of version '" + version + "' but " "this CEGUI version is only meant to load fonts of version '" + NativeVersion + "'. Consider using the migrate.py script bundled with " "CEGUI Unified Editor to migrate your data."); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementFontEnd() { String addressStr = SharedStringstream::GetPointerAddressAsString(d_font); Logger::getSingleton().logEvent("Finished creation of Font '" + d_font->getName() + "' via XML file. " + addressStr, Informative); d_loadedFonts.push_back(d_font); d_font = 0; } void Font_xmlHandler::elementFontsEnd() { if (d_font != 0) throw InvalidRequestException( "The Fonts node was closed but the loading for the last font has not been completed."); Logger::getSingleton().logEvent("Finished Fonts loading. Number of loaded fonts: " + d_loadedFonts.size(), Informative); } void Font_xmlHandler::elementMappingStart(const XMLAttributes& attributes) { if (!d_font) throw InvalidRequestException( "Attempt to access null object."); // double-check font type just in case - report issues as 'soft' errors if (d_font->getTypeName() != FontTypePixmap) Logger::getSingleton().logEvent( "Imageset_xmlHandler::elementMappingStart: <Mapping> element is " "only valid for Pixmap type fonts.", Errors); else static_cast<PixmapFont*>(d_font)->defineMapping( attributes.getValueAsInteger(MappingCodepointAttribute), attributes.getValueAsString(MappingImageAttribute), attributes.getValueAsFloat(MappingHorzAdvanceAttribute, -1.0f)); } //----------------------------------------------------------------------------// void Font_xmlHandler::createFreeTypeFont(const XMLAttributes& attributes) { const String name(attributes.getValueAsString(FontNameAttribute)); const String filename(attributes.getValueAsString(FontFilenameAttribute)); const String resource_group(attributes.getValueAsString(FontResourceGroupAttribute)); #ifdef CEGUI_HAS_FREETYPE if (d_font != 0) { throw InvalidRequestException( "Attempting to create a FreeTypeFont but loading of a " " previous font has not been finished."); } CEGUI_LOGINSANE("---- CEGUI font name: " + name); CEGUI_LOGINSANE("---- Font type: FreeType"); CEGUI_LOGINSANE("---- Source file: " + filename + " in resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); CEGUI_LOGINSANE("---- Real point size: " + attributes.getValueAsString(FontSizeAttribute, "12")); d_font = new FreeTypeFont(name, attributes.getValueAsFloat(FontSizeAttribute, 12.0f), attributes.getValueAsBool(FontAntiAliasedAttribute, true), filename, resource_group, PropertyHelper<AutoScaledMode>::fromString( attributes.getValueAsString(FontAutoScaledAttribute)), Sizef(attributes.getValueAsFloat(FontNativeHorzResAttribute, 640.0f), attributes.getValueAsFloat(FontNativeVertResAttribute, 480.0f)), attributes.getValueAsFloat(FontLineSpacingAttribute, 0.0f)); #else throw InvalidRequestException( "CEGUI was compiled without freetype support."); #endif } //----------------------------------------------------------------------------// void Font_xmlHandler::createPixmapFont(const XMLAttributes& attributes) { const String name(attributes.getValueAsString(FontNameAttribute)); const String filename(attributes.getValueAsString(FontFilenameAttribute)); const String resource_group(attributes.getValueAsString(FontResourceGroupAttribute)); if (d_font != 0) { throw InvalidRequestException( "Attempting to create a PixmapFont but loading of a " " previous font has not been finished."); } CEGUI_LOGINSANE("---- CEGUI font name: " + name); CEGUI_LOGINSANE("---- Font type: Pixmap"); CEGUI_LOGINSANE("---- Source file: " + filename + " in resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); d_font = new PixmapFont(name, filename, resource_group, PropertyHelper<AutoScaledMode>::fromString( attributes.getValueAsString(FontAutoScaledAttribute)), Sizef(attributes.getValueAsFloat(FontNativeHorzResAttribute, 640.0f), attributes.getValueAsFloat(FontNativeVertResAttribute, 480.0f))); } } <commit_msg>MOD: use std::ostringstream to append numbers to log output<commit_after>/*********************************************************************** created: Sun Jul 19 2009 author: Paul D Turner <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/Font_xmlHandler.h" #include "CEGUI/Exceptions.h" #include "CEGUI/Logger.h" #include "CEGUI/XMLAttributes.h" #include "CEGUI/System.h" #include "CEGUI/XMLParser.h" #include "CEGUI/PixmapFont.h" #include "CEGUI/SharedStringStream.h" #ifdef CEGUI_HAS_FREETYPE # include "CEGUI/FreeTypeFont.h" #endif #include <sstream> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const String Font_xmlHandler::FontSchemaName("Font.xsd"); const String Font_xmlHandler::FontElement("Font"); const String Font_xmlHandler::FontsElement("Fonts"); const String Font_xmlHandler::MappingElement("Mapping"); const String Font_xmlHandler::FontTypeAttribute("type"); const String Font_xmlHandler::FontNameAttribute("name"); const String Font_xmlHandler::FontFilenameAttribute("filename"); const String Font_xmlHandler::FontResourceGroupAttribute("resourceGroup"); const String Font_xmlHandler::FontAutoScaledAttribute("autoScaled"); const String Font_xmlHandler::FontNativeHorzResAttribute("nativeHorzRes"); const String Font_xmlHandler::FontNativeVertResAttribute("nativeVertRes"); const String Font_xmlHandler::FontLineSpacingAttribute("lineSpacing"); const String Font_xmlHandler::FontSizeAttribute("size"); const String Font_xmlHandler::FontAntiAliasedAttribute("antiAlias"); const String Font_xmlHandler::MappingCodepointAttribute("codepoint"); const String Font_xmlHandler::MappingImageAttribute("image"); const String Font_xmlHandler::MappingHorzAdvanceAttribute("horzAdvance"); const String Font_xmlHandler::FontVersionAttribute( "version" ); const String Font_xmlHandler::FontTypeFreeType("FreeType"); const String Font_xmlHandler::FontTypePixmap("Pixmap"); //----------------------------------------------------------------------------// // note: The assets' versions aren't usually the same as CEGUI version, they // are versioned from version 1 onwards! // // previous versions (though not specified in files until 3) // 1 - CEGUI up to and including 0.4.x // 2 - CEGUI versions 0.5.x through 0.7.x (Static/Dynamic types renamed to Pixmap/TrueType // Removed facility to pre-declare glyphs and glyph ranges) // 3 - CEGUI version 1.x.x (changed case of attr names, added version support) const String NativeVersion( "4" ); //----------------------------------------------------------------------------// Font_xmlHandler::Font_xmlHandler(): d_font(0), d_isFontLoadingDone(false) {} //----------------------------------------------------------------------------// Font_xmlHandler::~Font_xmlHandler() { if (!d_isFontLoadingDone && d_font != 0) { Logger::getSingleton().logEvent("Font_xmlHandler::~Font_xmlHandler: " "Font XML Handler is being destroyed, but loading of Font with name \"" + d_font->getName() + "\" has not been completed.", Warnings); delete d_font; } } //----------------------------------------------------------------------------// std::vector<Font*>& Font_xmlHandler::getObjects() { if (d_loadedFonts.empty()) throw InvalidRequestException("Attempting to return the loaded Fonts but the container of loaded Fonts is empty."); if (d_loadedFonts.empty()) throw InvalidRequestException("Attempting to return the loaded Fonts but loading of font \"" + d_font->getName() + "\" has not been finished."); d_isFontLoadingDone = true; return d_loadedFonts; } //----------------------------------------------------------------------------// const String& Font_xmlHandler::getSchemaName() const { return FontSchemaName; } //----------------------------------------------------------------------------// const String& Font_xmlHandler::getDefaultResourceGroup() const { return Font::getDefaultResourceGroup(); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes) { // handle root Font element if (element == FontsElement) elementFontsStart(attributes); // handle root Font element else if (element == FontElement) elementFontStart(attributes); // handle a Mapping element else if (element == MappingElement) elementMappingStart(attributes); // anything else is a non-fatal error. else Logger::getSingleton().logEvent("Font_xmlHandler::elementStart: " "Unknown element encountered: <" + element + ">", Errors); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementEnd(const String& element) { if (element == FontsElement) elementFontsEnd(); else if (element == FontElement) elementFontEnd(); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementFontsStart(const XMLAttributes& attributes) { validateFontFileVersion(attributes); } void Font_xmlHandler::elementFontStart(const XMLAttributes& attributes) { if (d_font != 0) { throw InvalidRequestException( "Attempting to load a new font but the loading of the " "previous font \"" + d_font->getName() + "\" has not been completed."); } // get type of font being created const String font_type(attributes.getValueAsString(FontTypeAttribute)); // log the start of font creation. CEGUI_LOGINSANE( "Started creation of Font from XML specification:"); if (font_type == FontTypeFreeType) createFreeTypeFont(attributes); else if (font_type == FontTypePixmap) createPixmapFont(attributes); else throw InvalidRequestException( "Encountered unknown font type of '" + font_type + "'"); } //----------------------------------------------------------------------------// void Font_xmlHandler::validateFontFileVersion(const XMLAttributes& attrs) { const String version(attrs.getValueAsString(FontVersionAttribute, "unknown")); if (version == NativeVersion) return; throw InvalidRequestException( "You are attempting to load a font of version '" + version + "' but " "this CEGUI version is only meant to load fonts of version '" + NativeVersion + "'. Consider using the migrate.py script bundled with " "CEGUI Unified Editor to migrate your data."); } //----------------------------------------------------------------------------// void Font_xmlHandler::elementFontEnd() { String addressStr = SharedStringstream::GetPointerAddressAsString(d_font); Logger::getSingleton().logEvent("Finished creation of Font '" + d_font->getName() + "' via XML file. " + addressStr, Informative); d_loadedFonts.push_back(d_font); d_font = 0; } void Font_xmlHandler::elementFontsEnd() { if (d_font != 0) throw InvalidRequestException( "The Fonts node was closed but the loading for the last font has not been completed."); std::ostringstream stream; stream << "Finished Fonts loading. Number of loaded fonts: " << d_loadedFonts.size(); Logger::getSingleton().logEvent(stream.str(), Informative); } void Font_xmlHandler::elementMappingStart(const XMLAttributes& attributes) { if (!d_font) throw InvalidRequestException( "Attempt to access null object."); // double-check font type just in case - report issues as 'soft' errors if (d_font->getTypeName() != FontTypePixmap) Logger::getSingleton().logEvent( "Imageset_xmlHandler::elementMappingStart: <Mapping> element is " "only valid for Pixmap type fonts.", Errors); else static_cast<PixmapFont*>(d_font)->defineMapping( attributes.getValueAsInteger(MappingCodepointAttribute), attributes.getValueAsString(MappingImageAttribute), attributes.getValueAsFloat(MappingHorzAdvanceAttribute, -1.0f)); } //----------------------------------------------------------------------------// void Font_xmlHandler::createFreeTypeFont(const XMLAttributes& attributes) { const String name(attributes.getValueAsString(FontNameAttribute)); const String filename(attributes.getValueAsString(FontFilenameAttribute)); const String resource_group(attributes.getValueAsString(FontResourceGroupAttribute)); #ifdef CEGUI_HAS_FREETYPE if (d_font != 0) { throw InvalidRequestException( "Attempting to create a FreeTypeFont but loading of a " " previous font has not been finished."); } CEGUI_LOGINSANE("---- CEGUI font name: " + name); CEGUI_LOGINSANE("---- Font type: FreeType"); CEGUI_LOGINSANE("---- Source file: " + filename + " in resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); CEGUI_LOGINSANE("---- Real point size: " + attributes.getValueAsString(FontSizeAttribute, "12")); d_font = new FreeTypeFont(name, attributes.getValueAsFloat(FontSizeAttribute, 12.0f), attributes.getValueAsBool(FontAntiAliasedAttribute, true), filename, resource_group, PropertyHelper<AutoScaledMode>::fromString( attributes.getValueAsString(FontAutoScaledAttribute)), Sizef(attributes.getValueAsFloat(FontNativeHorzResAttribute, 640.0f), attributes.getValueAsFloat(FontNativeVertResAttribute, 480.0f)), attributes.getValueAsFloat(FontLineSpacingAttribute, 0.0f)); #else throw InvalidRequestException( "CEGUI was compiled without freetype support."); #endif } //----------------------------------------------------------------------------// void Font_xmlHandler::createPixmapFont(const XMLAttributes& attributes) { const String name(attributes.getValueAsString(FontNameAttribute)); const String filename(attributes.getValueAsString(FontFilenameAttribute)); const String resource_group(attributes.getValueAsString(FontResourceGroupAttribute)); if (d_font != 0) { throw InvalidRequestException( "Attempting to create a PixmapFont but loading of a " " previous font has not been finished."); } CEGUI_LOGINSANE("---- CEGUI font name: " + name); CEGUI_LOGINSANE("---- Font type: Pixmap"); CEGUI_LOGINSANE("---- Source file: " + filename + " in resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); d_font = new PixmapFont(name, filename, resource_group, PropertyHelper<AutoScaledMode>::fromString( attributes.getValueAsString(FontAutoScaledAttribute)), Sizef(attributes.getValueAsFloat(FontNativeHorzResAttribute, 640.0f), attributes.getValueAsFloat(FontNativeVertResAttribute, 480.0f))); } } <|endoftext|>
<commit_before>// Day23.cpp : Defines the entry point for the console application. // #include "stdafx.h" enum class OpCode { Inc, Dec, Copy, Jump, Toggle, Noop }; struct Registers; struct Instruction; typedef std::vector<Instruction> InstructionVector; typedef std::function<signed&(Registers &)> FetchFunction; typedef std::function<signed(Registers &)> FetchValueFunction; struct Registers { signed A = 0; signed B = 0; signed C = 0; signed D = 0; size_t IP = 0; Registers() = default; Registers(signed A, signed B, signed C, signed D, size_t IP) :A(A), B(B), C(C), D(D), IP(IP) {} void Print() const { std::cout.width(8); std::cout << IP << " | "; std::cout.width(8); std::cout << A; std::cout.width(8); std::cout << B; std::cout.width(8); std::cout << C; std::cout.width(8); std::cout << D; } }; struct Instruction { OpCode Code; FetchFunction RefFetch; FetchValueFunction Arg1; FetchValueFunction Arg2; Instruction() :Code(OpCode::Noop), RefFetch(nullptr), Arg1(nullptr), Arg2(nullptr) {} Instruction(OpCode Code, FetchFunction RefFetch) :Code(Code), RefFetch(RefFetch), Arg1(nullptr), Arg2(nullptr) {} Instruction(OpCode Code, FetchValueFunction Arg1) :Code(Code), RefFetch(nullptr), Arg1(Arg1), Arg2(nullptr) {} Instruction(OpCode Code, FetchFunction RefFetch, FetchValueFunction Arg1) :Code(Code), RefFetch(RefFetch), Arg1(Arg1), Arg2(nullptr) {} Instruction(OpCode Code, FetchValueFunction Arg1, FetchValueFunction Arg2) :Code(Code), RefFetch(nullptr), Arg1(Arg1), Arg2(Arg2) {} void operator() (Registers & State, InstructionVector & Instructions) { switch (Code) { case OpCode::Inc: if(RefFetch) RefFetch(State)++; break; case OpCode::Dec: if (RefFetch) RefFetch(State)--; break; case OpCode::Copy: if (RefFetch) RefFetch(State) = Arg1(State); break; case OpCode::Jump: if (Arg1(State) != 0) { signed JumpDistance = RefFetch ? RefFetch(State) : Arg2(State); State.IP += JumpDistance; return; } break; case OpCode::Toggle: { size_t Instruction = State.IP + (RefFetch ? RefFetch(State) : Arg1(State)); if (Instruction < Instructions.size()) { Instructions[Instruction].Toggle(); } } break; default: std::cout << "Unknown Op Code" << std::endl; case OpCode::Noop: break; }; State.IP++; }; void Toggle() { switch(Code) { case OpCode::Inc: Code = OpCode::Dec; break; case OpCode::Dec: case OpCode::Toggle: Code = OpCode::Inc; break; case OpCode::Copy: Code = OpCode::Jump; break; case OpCode::Jump: Code = OpCode::Copy; break; } } void Print() const { std::cout << " | "; switch (Code) { case OpCode::Inc: std::cout << "Inc"; break; case OpCode::Dec: std::cout << "Dec"; break; case OpCode::Copy: std::cout << "Copy"; break; case OpCode::Jump: std::cout << "Jump"; break; case OpCode::Toggle: std::cout << "Toogle"; break; case OpCode::Noop: std::cout << "Noop"; break; default: std::cout << "Unknown Op Code"; break; }; } }; Instruction ParseInc(const StringVector & Line); Instruction ParseDec(const StringVector & Line); Instruction ParseCpy(const StringVector & Line); Instruction ParseJnz(const StringVector & Line); Instruction ParseTgl(const StringVector & Line); static const std::map<std::string, std::function<Instruction(const StringVector &)>> AssemblyParserMap = { { "inc", &ParseInc }, { "dec", &ParseDec }, { "cpy", &ParseCpy }, { "jnz", &ParseJnz }, { "tgl", &ParseTgl } }; static const std::map<std::string, FetchFunction> RegisterFetchMap = { { "a", [](Registers & State)->signed& { return State.A; } }, { "b", [](Registers & State)->signed& { return State.B; } }, { "c", [](Registers & State)->signed& { return State.C; } }, { "d", [](Registers & State)->signed& { return State.D; } }, }; InstructionVector ParseAssembly(const StringVectorVector & Lines); Registers Run(InstructionVector & Instructions, Registers InitialState = Registers()); int main() { StringVectorVector Lines = GetFileLineParts("Input.txt"); InstructionVector Instructions = ParseAssembly(Lines); Registers PartOne = Run(Instructions, { 7, 0, 0, 0, 0 }); std::cout << "A: " << PartOne.A << std::endl; system("pause"); return 0; } InstructionVector ParseAssembly(const StringVectorVector & Lines) { InstructionVector Instructions; Instructions.reserve(Lines.size()); for(const StringVector & Line : Lines) { auto Parser = AssemblyParserMap.find(Line[0]); if (Parser == AssemblyParserMap.end()) { std::cout << "Unknwon Assembly: " << Line[0] << std::endl; __debugbreak(); Instructions.emplace_back(); } else { Instructions.push_back(Parser->second(Line)); } } return Instructions; } void PrintDebug(const Registers & State, const Instruction & Instruction) { State.Print(); Instruction.Print(); std::cout << std::endl; getchar(); } Registers Run(InstructionVector & Instructions, Registers InitialState) { Registers & State = InitialState; while (State.IP < Instructions.size()) { //PrintDebug(State, Instructions[State.IP]); Instructions[State.IP](State, Instructions); } return State; } FetchFunction GetFetchFunction(const std::string & Identifier) { auto RegisterFetch = RegisterFetchMap.find(Identifier); if (RegisterFetch == RegisterFetchMap.end()) { return nullptr; } else { return RegisterFetch->second; } } FetchValueFunction GetFetchValueFunction(const std::string & Identifier) { auto RegisterFetchFunction = GetFetchFunction(Identifier); if (RegisterFetchFunction == nullptr) { signed Value = std::stoi(Identifier); return [Value](Registers & State) { return Value; }; } else { return [RegisterFetchFunction](Registers & State) { return static_cast<signed>(RegisterFetchFunction(State)); }; } } Instruction ParseInc(const StringVector & Line) { return Instruction(OpCode::Inc, GetFetchFunction(Line[1])); } Instruction ParseDec(const StringVector & Line) { return Instruction(OpCode::Dec, GetFetchFunction(Line[1])); } Instruction ParseCpy(const StringVector & Line) { // Get First Argument as Value FetchValueFunction FetchValue = GetFetchValueFunction(Line[1]); FetchFunction RegisterFetch = GetFetchFunction(Line[2]); return Instruction(OpCode::Copy, RegisterFetch, FetchValue); } Instruction ParseJnz(const StringVector & Line) { // Get Second Argument as Value FetchValueFunction FetchTestValue = GetFetchValueFunction(Line[1]); FetchFunction FetchJumpValue = GetFetchFunction(Line[2]); if (FetchJumpValue) { return Instruction(OpCode::Jump, FetchJumpValue, FetchTestValue); } else { return Instruction(OpCode::Jump, FetchTestValue, GetFetchValueFunction(Line[2])); } } Instruction ParseTgl(const StringVector & Line) { FetchFunction FetchValue = GetFetchFunction(Line[1]); if (FetchValue) { return Instruction(OpCode::Toggle, FetchValue); } else { return Instruction(OpCode::Toggle, GetFetchValueFunction(Line[1])); } }<commit_msg>Day 23 part two<commit_after>// Day23.cpp : Defines the entry point for the console application. // #include "stdafx.h" enum class OpCode { Inc, Dec, Copy, Jump, Toggle, Noop }; struct Registers; struct Instruction; typedef std::vector<Instruction> InstructionVector; typedef std::function<signed&(Registers &)> FetchFunction; typedef std::function<signed(Registers &)> FetchValueFunction; struct Registers { signed A = 0; signed B = 0; signed C = 0; signed D = 0; size_t IP = 0; Registers() = default; Registers(signed A, signed B, signed C, signed D, size_t IP) :A(A), B(B), C(C), D(D), IP(IP) {} void Print() const { std::cout.width(8); std::cout << IP << " | "; std::cout.width(8); std::cout << A; std::cout.width(8); std::cout << B; std::cout.width(8); std::cout << C; std::cout.width(8); std::cout << D; } }; struct Instruction { OpCode Code; FetchFunction RefFetch; FetchValueFunction Arg1; FetchValueFunction Arg2; Instruction() :Code(OpCode::Noop), RefFetch(nullptr), Arg1(nullptr), Arg2(nullptr) {} Instruction(OpCode Code, FetchFunction RefFetch) :Code(Code), RefFetch(RefFetch), Arg1(nullptr), Arg2(nullptr) {} Instruction(OpCode Code, FetchValueFunction Arg1) :Code(Code), RefFetch(nullptr), Arg1(Arg1), Arg2(nullptr) {} Instruction(OpCode Code, FetchFunction RefFetch, FetchValueFunction Arg1) :Code(Code), RefFetch(RefFetch), Arg1(Arg1), Arg2(nullptr) {} Instruction(OpCode Code, FetchValueFunction Arg1, FetchValueFunction Arg2) :Code(Code), RefFetch(nullptr), Arg1(Arg1), Arg2(Arg2) {} void operator() (Registers & State, InstructionVector & Instructions) { switch (Code) { case OpCode::Inc: if(RefFetch) RefFetch(State)++; break; case OpCode::Dec: if (RefFetch) RefFetch(State)--; break; case OpCode::Copy: if (RefFetch) RefFetch(State) = Arg1(State); break; case OpCode::Jump: if (Arg1(State) != 0) { signed JumpDistance = RefFetch ? RefFetch(State) : Arg2(State); State.IP += JumpDistance; return; } break; case OpCode::Toggle: { State.Print(); std::cout << std::endl; size_t Instruction = State.IP + (RefFetch ? RefFetch(State) : Arg1(State)); if (Instruction < Instructions.size()) { Instructions[Instruction].Toggle(); } } break; default: std::cout << "Unknown Op Code" << std::endl; case OpCode::Noop: break; }; State.IP++; }; void Toggle() { switch(Code) { case OpCode::Inc: Code = OpCode::Dec; break; case OpCode::Dec: case OpCode::Toggle: Code = OpCode::Inc; break; case OpCode::Copy: Code = OpCode::Jump; break; case OpCode::Jump: Code = OpCode::Copy; break; } } void Print() const { std::cout << " | "; switch (Code) { case OpCode::Inc: std::cout << "Inc"; break; case OpCode::Dec: std::cout << "Dec"; break; case OpCode::Copy: std::cout << "Copy"; break; case OpCode::Jump: std::cout << "Jump"; break; case OpCode::Toggle: std::cout << "Toogle"; break; case OpCode::Noop: std::cout << "Noop"; break; default: std::cout << "Unknown Op Code"; break; }; } }; Instruction ParseInc(const StringVector & Line); Instruction ParseDec(const StringVector & Line); Instruction ParseCpy(const StringVector & Line); Instruction ParseJnz(const StringVector & Line); Instruction ParseTgl(const StringVector & Line); static const std::map<std::string, std::function<Instruction(const StringVector &)>> AssemblyParserMap = { { "inc", &ParseInc }, { "dec", &ParseDec }, { "cpy", &ParseCpy }, { "jnz", &ParseJnz }, { "tgl", &ParseTgl } }; static const std::map<std::string, FetchFunction> RegisterFetchMap = { { "a", [](Registers & State)->signed& { return State.A; } }, { "b", [](Registers & State)->signed& { return State.B; } }, { "c", [](Registers & State)->signed& { return State.C; } }, { "d", [](Registers & State)->signed& { return State.D; } }, }; InstructionVector ParseAssembly(const StringVectorVector & Lines); Registers Run(InstructionVector Instructions, Registers InitialState = Registers()); int main() { StringVectorVector Lines = GetFileLineParts("Input.txt"); InstructionVector Instructions = ParseAssembly(Lines); // A = 7! + 81 * 73 Registers PartOne = Run(Instructions, { 7, 0, 0, 0, 0 }); std::cout << "Part One: " << PartOne.A << std::endl; // A = 12! + 81 * 73 Registers PartTwo = Run(Instructions, { 12, 0, 0, 0, 0 }); std::cout << "Part Two: " << PartTwo.A << std::endl; system("pause"); return 0; } InstructionVector ParseAssembly(const StringVectorVector & Lines) { InstructionVector Instructions; Instructions.reserve(Lines.size()); for(const StringVector & Line : Lines) { auto Parser = AssemblyParserMap.find(Line[0]); if (Parser == AssemblyParserMap.end()) { std::cout << "Unknwon Assembly: " << Line[0] << std::endl; __debugbreak(); Instructions.emplace_back(); } else { Instructions.push_back(Parser->second(Line)); } } return Instructions; } void PrintDebug(const Registers & State, const Instruction & Instruction) { State.Print(); Instruction.Print(); std::cout << std::endl; getchar(); } Registers Run(InstructionVector Instructions, Registers InitialState) { Registers & State = InitialState; while (State.IP < Instructions.size()) { //PrintDebug(State, Instructions[State.IP]); Instructions[State.IP](State, Instructions); } return State; } FetchFunction GetFetchFunction(const std::string & Identifier) { auto RegisterFetch = RegisterFetchMap.find(Identifier); if (RegisterFetch == RegisterFetchMap.end()) { return nullptr; } else { return RegisterFetch->second; } } FetchValueFunction GetFetchValueFunction(const std::string & Identifier) { auto RegisterFetchFunction = GetFetchFunction(Identifier); if (RegisterFetchFunction == nullptr) { signed Value = std::stoi(Identifier); return [Value](Registers & State) { return Value; }; } else { return [RegisterFetchFunction](Registers & State) { return static_cast<signed>(RegisterFetchFunction(State)); }; } } Instruction ParseInc(const StringVector & Line) { return Instruction(OpCode::Inc, GetFetchFunction(Line[1])); } Instruction ParseDec(const StringVector & Line) { return Instruction(OpCode::Dec, GetFetchFunction(Line[1])); } Instruction ParseCpy(const StringVector & Line) { // Get First Argument as Value FetchValueFunction FetchValue = GetFetchValueFunction(Line[1]); FetchFunction RegisterFetch = GetFetchFunction(Line[2]); return Instruction(OpCode::Copy, RegisterFetch, FetchValue); } Instruction ParseJnz(const StringVector & Line) { // Get Second Argument as Value FetchValueFunction FetchTestValue = GetFetchValueFunction(Line[1]); FetchFunction FetchJumpValue = GetFetchFunction(Line[2]); if (FetchJumpValue) { return Instruction(OpCode::Jump, FetchJumpValue, FetchTestValue); } else { return Instruction(OpCode::Jump, FetchTestValue, GetFetchValueFunction(Line[2])); } } Instruction ParseTgl(const StringVector & Line) { FetchFunction FetchValue = GetFetchFunction(Line[1]); if (FetchValue) { return Instruction(OpCode::Toggle, FetchValue); } else { return Instruction(OpCode::Toggle, GetFetchValueFunction(Line[1])); } } /* cpy a b dec b cpy a d cpy 0 a cpy b c inc a dec c jnz c -2 dec d jnz d -5 dec b cpy b c cpy c d dec d inc c jnz d -2 tgl c cpy -16 c jnz 1 c cpy 81 c jnz 73 d inc a inc d jnz d -2 inc c jnz c -5 */<|endoftext|>
<commit_before>#include "SkinV2.h" #include "../Logger.h" #include "../MeterWnd/Meters/MeterTypes.h" #include "../StringUtils.h" #include "MeterComponent.h" #include "OSDComponent.h" #include "SkinUtils.h" SkinV2::SkinV2(std::wstring skinXML) : SkinInfo(skinXML) { } SkinV2::~SkinV2() { } OSDComponent *SkinV2::VolumeOSD() { OSDComponent *volume = new OSDComponent; /* Images */ volume->background = LoadImg(_skinDir + L"\\OSD\\back.png"); volume->mask = LoadImg(_skinDir + L"\\OSD\\glassMask.png"); /* Sound */ std::wstring soundName = _skinDir + L"\\sound.wav"; SoundPlayer *player = new SoundPlayer(soundName); if (player->Ready() == false) { delete player; player = NULL; } volume->sound = player; /* Determine the number of units */ int units = 10; tinyxml2::XMLElement *meterMax = SubElement("osd", "meterMax"); if (meterMax) { meterMax->QueryIntText(&units); } volume->defaultUnits = units; /* Load the meter(s) */ const char *meterType = nullptr; tinyxml2::XMLElement *meterOrientation = SubElement("osd", "meterOrientation"); if (meterOrientation) { meterType = meterOrientation->GetText(); } int x = 0; int y = 0; tinyxml2::XMLElement *pos = SubElement("osd", "meterPosition"); if (pos) { tinyxml2::XMLElement *xelem = pos->FirstChildElement("X"); tinyxml2::XMLElement *yelem = pos->FirstChildElement("Y"); if (xelem) { xelem->QueryIntText(&x); } if (yelem) { yelem->QueryIntText(&y); } } std::wstring meterImg = _skinDir + L"\\OSD\\meter.png"; if (meterType == "vertical") { volume->meters.push_back( new VerticalBar(meterImg, x, y, units)); } else if (meterType == "bitstrip") { volume->meters.push_back( new Bitstrip(meterImg, x, y, units)); } else { /* Horizontal meter is the default */ volume->meters.push_back( new HorizontalBar(meterImg, x, y, units)); } return volume; } OSDComponent *SkinV2::MuteOSD() { OSDComponent *mute = new OSDComponent; mute->background = LoadImg(_skinDir + L"\\OSD\\mute.png"); mute->mask = LoadImg(_skinDir + L"\\OSD\\glassMask.png"); return mute; } OSDComponent *SkinV2::EjectOSD() { return nullptr; } std::vector<HICON> SkinV2::VolumeIconset() { std::wstring iconDir = _skinDir + L"\\Notification Icons\\"; return SkinUtils::ReadIconDirectory(iconDir); } SliderComponent *SkinV2::VolumeSlider() { return nullptr; }<commit_msg>Implement v2 eject OSD<commit_after>#include "SkinV2.h" #include "../Logger.h" #include "../MeterWnd/Meters/MeterTypes.h" #include "../StringUtils.h" #include "MeterComponent.h" #include "OSDComponent.h" #include "SkinUtils.h" SkinV2::SkinV2(std::wstring skinXML) : SkinInfo(skinXML) { } SkinV2::~SkinV2() { } OSDComponent *SkinV2::VolumeOSD() { OSDComponent *volume = new OSDComponent; /* Images */ volume->background = LoadImg(_skinDir + L"\\OSD\\back.png"); volume->mask = LoadImg(_skinDir + L"\\OSD\\glassMask.png"); /* Sound */ std::wstring soundName = _skinDir + L"\\sound.wav"; SoundPlayer *player = new SoundPlayer(soundName); if (player->Ready() == false) { delete player; player = NULL; } volume->sound = player; /* Determine the number of units */ int units = 10; tinyxml2::XMLElement *meterMax = SubElement("osd", "meterMax"); if (meterMax) { meterMax->QueryIntText(&units); } volume->defaultUnits = units; /* Load the meter(s) */ const char *meterType = nullptr; tinyxml2::XMLElement *meterOrientation = SubElement("osd", "meterOrientation"); if (meterOrientation) { meterType = meterOrientation->GetText(); } int x = 0; int y = 0; tinyxml2::XMLElement *pos = SubElement("osd", "meterPosition"); if (pos) { tinyxml2::XMLElement *xelem = pos->FirstChildElement("X"); tinyxml2::XMLElement *yelem = pos->FirstChildElement("Y"); if (xelem) { xelem->QueryIntText(&x); } if (yelem) { yelem->QueryIntText(&y); } } std::wstring meterImg = _skinDir + L"\\OSD\\meter.png"; if (meterType == "vertical") { volume->meters.push_back( new VerticalBar(meterImg, x, y, units)); } else if (meterType == "bitstrip") { volume->meters.push_back( new Bitstrip(meterImg, x, y, units)); } else { /* Horizontal meter is the default */ volume->meters.push_back( new HorizontalBar(meterImg, x, y, units)); } return volume; } OSDComponent *SkinV2::MuteOSD() { OSDComponent *mute = new OSDComponent; mute->background = LoadImg(_skinDir + L"\\OSD\\mute.png"); mute->mask = LoadImg(_skinDir + L"\\OSD\\glassMask.png"); return mute; } OSDComponent *SkinV2::EjectOSD() { OSDComponent *eject = new OSDComponent; eject->background = LoadImg(_skinDir + L"\\OSD\\eject.png"); eject->mask = LoadImg(_skinDir + L"\\OSD\\glassMask.png"); return eject; } std::vector<HICON> SkinV2::VolumeIconset() { std::wstring iconDir = _skinDir + L"\\Notification Icons\\"; return SkinUtils::ReadIconDirectory(iconDir); } SliderComponent *SkinV2::VolumeSlider() { return nullptr; }<|endoftext|>
<commit_before>/* Copyright (c) 2014, Madd Games. 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. */ #include <Apoc/Math/Vector.h> Vector::Vector() { coords[0] = 0.0; coords[1] = 0.0; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y) { coords[0] = x; coords[1] = y; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z, float w) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = w; }; Vector::Vector(const Vector &vec) { int i; for (i=0; i<4; i++) { coords[i] = vec.coords[i]; }; }; float& Vector::x() { return coords[0]; }; float& Vector::y() { return coords[1]; }; float& Vector::z() { return coords[2]; }; float& Vector::w() { return coords[3]; }; float& Vector::operator[](int i) { return coords[i]; }; Vector& Vector::operator=(Vector vec) { int i; for (i=0; i<4; i++) { coords[i] = vec[i]; }; return *this; }; Vector Vector::operator+(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] + b[i]; }; return out; }; Vector Vector::operator-(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] - b[i]; }; return out; }; Vector Vector::operator*(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] * b[i]; }; return out; }; Vector Vector::operator/(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] / b[i]; }; return out; }; Vector Vector::operator*(float x) { return Vector(coords[0]*x, coords[1]*x, coords[2]*x, coords[3]*x); }; float Vector::dot(Vector b) { float out = 0.0; int i; for (i=0; i<4; i++) { out += coords[i] * b[i]; }; return out; }; Vector Vector::cross(Vector b) { Vector out; out[0] = coords[0]*b[2] - coords[2]*b[1]; // X out[1] = coords[2]*b[0] - coords[0]*b[2]; // Y out[2] = coords[0]*b[1] - coords[1]*b[0]; // Z out[3] = 1.0; // W, is this right? return out; }; ostream& operator<<(ostream &os, Vector vec) { os << "(" << vec.x() << ", " << vec.y() << ", " << vec.z() << ", " << vec.w() << ")"; return os; }; <commit_msg>Update Vector.cpp<commit_after>/* Copyright (c) 2014, Madd Games. 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. */ #include <Apoc/Math/Vector.h> #include <math.h> Vector::Vector() { coords[0] = 0.0; coords[1] = 0.0; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y) { coords[0] = x; coords[1] = y; coords[2] = 0.0; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = 1.0; }; Vector::Vector(float x, float y, float z, float w) { coords[0] = x; coords[1] = y; coords[2] = z; coords[3] = w; }; Vector::Vector(const Vector &vec) { int i; for (i=0; i<4; i++) { coords[i] = vec.coords[i]; }; }; float& Vector::x() { return coords[0]; }; float& Vector::y() { return coords[1]; }; float& Vector::z() { return coords[2]; }; float& Vector::w() { return coords[3]; }; float& Vector::operator[](int i) { return coords[i]; }; Vector& Vector::operator=(Vector vec) { int i; for (i=0; i<4; i++) { coords[i] = vec[i]; }; return *this; }; Vector Vector::operator+(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] + b[i]; }; return out; }; Vector Vector::operator-(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] - b[i]; }; return out; }; Vector Vector::operator*(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] * b[i]; }; return out; }; Vector Vector::operator/(Vector b) { Vector out; int i; for (i=0; i<4; i++) { out[i] = coords[i] / b[i]; }; return out; }; Vector Vector::operator*(float x) { return Vector(coords[0]*x, coords[1]*x, coords[2]*x, coords[3]*x); }; float Vector::dot(Vector b) { float out = 0.0; int i; for (i=0; i<4; i++) { out += coords[i] * b[i]; }; return out; }; Vector Vector::cross(Vector b) { Vector out; out[0] = coords[0]*b[2] - coords[2]*b[1]; // X out[1] = coords[2]*b[0] - coords[0]*b[2]; // Y out[2] = coords[0]*b[1] - coords[1]*b[0]; // Z out[3] = 1.0; // W, is this right? return out; }; Vector Vector::normalize() { return (*this) * (1.0/length()); }; float Vector::length() { return sqrt(x()*x()/w() + y()*y()/w() + z()*z()/w()); }; ostream& operator<<(ostream &os, Vector vec) { os << "(" << vec.x() << ", " << vec.y() << ", " << vec.z() << ", " << vec.w() << ")"; return os; }; <|endoftext|>
<commit_before> # include "TIPS4.hpp" // ------------------------------------------------------------------------- // Constructor: // ------------------------------------------------------------------------- TIPS4::TIPS4(const CommonParams& pin, const GetPot& input_params) : p(pin), c(p) { // --------------------------------------- // set needed parameters: // --------------------------------------- nxyz = p.nx*p.ny*p.nz; nx = p.nx; ny = p.ny; nz = p.nz; deli = (nz+2)*(ny+2); delj = (nz+2); delk = 1; co = input_params("PFApp/co",0.5); M = input_params("PFApp/M",1.0); kap = input_params("PFApp/kap",1.0); alpha = input_params("PFApp/alpha",1.0); beta = input_params("PFApp/beta",1.0); N = input_params("PFApp/N",100.0); A = input_params("PFApp/A",1.0); Tstart = input_params("PFApp/Tstart",273.0); Tend = input_params("PFApp/Tend",273.0); } // ------------------------------------------------------------------------- // Destructor: // ------------------------------------------------------------------------- TIPS4::~TIPS4() { } // ------------------------------------------------------------------------- // Initialize phase-field method: // ------------------------------------------------------------------------- void TIPS4::initPhaseField() { // --------------------------------------- // initialize the concentration field: // --------------------------------------- srand(time(NULL)*(p.rank+1)); // set the random seed for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double r = (double)rand()/RAND_MAX; double val = co + 0.1*(r-0.5); c.setValue(ndx,val); } } } // --------------------------------------- // Output the initial configuration: // --------------------------------------- current_step = 0; outputPhaseField(); } // ------------------------------------------------------------------------- // Step forward in time the phase-field method: // ------------------------------------------------------------------------- void TIPS4::updatePhaseField() { // --------------------------------------- // calculate thermodynamics parameters // --------------------------------------- double T = Tstart - (Tstart-Tend)*(double(current_step)/double(p.nstep)); double kT = T/273.0; double chi = alpha/T + beta; // --------------------------------------- // calculate chemical potential & mobility // --------------------------------------- c.updateBoundaryConditions(); MPI::COMM_WORLD.Barrier(); SfieldFD mu(p); SfieldFD mob(p); for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double cc = c.getValue(ndx); // chemical potential... double df = (log(cc) + 1.0)/N - log(1.0-cc) - 1.0 + chi*(1.0-2.0*cc); df *= kT; if (cc <= 0.0) df = -1.5*A*sqrt(-cc); double lapc = c.Laplacian(ndx); mu.setValue(ndx,df - kap*lapc); // mobility... double Mc = 1.0; if (cc > 0.1) Mc = 0.018/(pow(cc,1.75)); mob.setValue(ndx,Mc); } } } // --------------------------------------- // update CH equation: // --------------------------------------- mu.updateBoundaryConditions(); MPI::COMM_WORLD.Barrier(); //c += p.dt*M*mu.Laplacian(); c += p.dt*mu.Laplacian(mob); // --------------------------------------- // Add random fluctuations: // --------------------------------------- for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double r = (double)rand()/RAND_MAX; double val = 0.1*(r-0.5); c.addValue(ndx,p.dt*val); } } } } // ------------------------------------------------------------------------- // Write output for the phase-field method: // ------------------------------------------------------------------------- void TIPS4::outputPhaseField() { int iskip = p.iskip; int jskip = p.jskip; int kskip = p.kskip; c.writeVTKFile("c",current_step,iskip,jskip,kskip); } <commit_msg>Fix bug in TIPS4<commit_after> # include "TIPS4.hpp" // ------------------------------------------------------------------------- // Constructor: // ------------------------------------------------------------------------- TIPS4::TIPS4(const CommonParams& pin, const GetPot& input_params) : p(pin), c(p) { // --------------------------------------- // set needed parameters: // --------------------------------------- nxyz = p.nx*p.ny*p.nz; nx = p.nx; ny = p.ny; nz = p.nz; deli = (nz+2)*(ny+2); delj = (nz+2); delk = 1; co = input_params("PFApp/co",0.5); M = input_params("PFApp/M",1.0); kap = input_params("PFApp/kap",1.0); alpha = input_params("PFApp/alpha",1.0); beta = input_params("PFApp/beta",1.0); N = input_params("PFApp/N",100.0); A = input_params("PFApp/A",1.0); Tstart = input_params("PFApp/Tstart",273.0); Tend = input_params("PFApp/Tend",273.0); } // ------------------------------------------------------------------------- // Destructor: // ------------------------------------------------------------------------- TIPS4::~TIPS4() { } // ------------------------------------------------------------------------- // Initialize phase-field method: // ------------------------------------------------------------------------- void TIPS4::initPhaseField() { // --------------------------------------- // initialize the concentration field: // --------------------------------------- srand(time(NULL)*(p.rank+1)); // set the random seed for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double r = (double)rand()/RAND_MAX; double val = co + 0.1*(r-0.5); c.setValue(ndx,val); } } } // --------------------------------------- // Output the initial configuration: // --------------------------------------- current_step = 0; outputPhaseField(); } // ------------------------------------------------------------------------- // Step forward in time the phase-field method: // ------------------------------------------------------------------------- void TIPS4::updatePhaseField() { // --------------------------------------- // calculate thermodynamics parameters // --------------------------------------- double T = Tstart - (Tstart-Tend)*(double(current_step)/double(p.nstep)); double kT = T/273.0; double chi = alpha/T + beta; // --------------------------------------- // calculate chemical potential & mobility // --------------------------------------- c.updateBoundaryConditions(); MPI::COMM_WORLD.Barrier(); SfieldFD mu(p); SfieldFD mob(p); for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double cc = c.getValue(ndx); // chemical potential... double df = (log(cc) + 1.0)/N - log(1.0-cc) - 1.0 + chi*(1.0-2.0*cc); df *= kT; if (cc <= 0.0) df = -1.5*A*sqrt(-cc); double lapc = c.Laplacian(ndx); mu.setValue(ndx,df - kap*lapc); // mobility... double Mc = 1.0; if (cc > 0.1) Mc = 0.018/(pow(cc,1.75)); mob.setValue(ndx,Mc); } } } // --------------------------------------- // update CH equation: // --------------------------------------- mu.updateBoundaryConditions(); mob.updateBoundaryConditions(); MPI::COMM_WORLD.Barrier(); //c += p.dt*M*mu.Laplacian(); c += p.dt*mu.Laplacian(mob); // --------------------------------------- // Add random fluctuations: // --------------------------------------- for (int i=1; i<nx+1; i++) { for (int j=1; j<ny+1; j++) { for (int k=1; k<nz+1; k++) { int ndx = i*deli + j*delj + k*delk; double r = (double)rand()/RAND_MAX; double val = 0.1*(r-0.5); c.addValue(ndx,p.dt*val); } } } } // ------------------------------------------------------------------------- // Write output for the phase-field method: // ------------------------------------------------------------------------- void TIPS4::outputPhaseField() { int iskip = p.iskip; int jskip = p.jskip; int kskip = p.kskip; c.writeVTKFile("c",current_step,iskip,jskip,kskip); } <|endoftext|>
<commit_before>#include "Scene.h" #include "MaterialElement.h" #include <iostream> //************************************************************************************** //-----------------------------------SCENE------------------------------------ //Constructors and destructor Scene::Scene() { } Scene::~Scene() { for (auto it = S.begin(); it != S.end(); it++) { delete *it; } } //Accessors MaterialElement *Scene::getElement(unsigned int i) { MaterialElement *M = nullptr; if (i < S.size()) { M = S[i]; } else { std::cout << "No element" << '\n'; } return M; } double Scene::getTime() { return Time; } //Display void Scene::consoleShow() { if (0 < S.size()) { for (unsigned int i = 0; i < S.size(); i++) { std::cout << "element " << i + 1 << ": " << '\n'; //from 1 to number of elements S[i]->consoleShow(); } } else { std::cout << "empty scene " << '\n'; } } //Modifier void Scene::addExternalAction(Vect F, unsigned int place) // add force to element i { S[place]->addExternalAction(F); } void Scene::update(double dt) { for (auto it = S.begin(); it != S.end(); it++) { (*it)->update(dt); } } void Scene::simulate(double step, double duration) { double t = 0; while (t < duration) { update(step); t = t + step; } Time += t; } //----------Model interface----------------------- void Scene::addMatPoint() { MaterialPoint *Mp = new MaterialPoint; S.push_back(Mp); } void Scene::addMatPoint(double x, double y, double z, double mass, double charge) { MaterialPoint *Mp = new MaterialPoint; Mp->place(x, y, z); Mp->setMass(mass); Mp->setCharge(charge); Mp->setMass(mass); Mp->place(x, y, z); S.push_back(Mp); } <commit_msg>updated to match MaterialElement changes<commit_after>#include "Scene.h" #include "MaterialElement.h" #include <iostream> //************************************************************************************** //-----------------------------------SCENE------------------------------------ //Constructors and destructor Scene::Scene() { } Scene::~Scene() { for (auto it = S.begin(); it != S.end(); it++) { delete *it; } } //Accessors MaterialElement *Scene::getElement(unsigned int i) { MaterialElement *M = nullptr; if (i < S.size()) { M = S[i]; } else { std::cout << "No element" << '\n'; } return M; } double Scene::getTime() { return Time; } //Display void Scene::consoleShow() { if (0 < S.size()) { for (unsigned int i = 0; i < S.size(); i++) { std::cout << "element " << i + 1 << ": " << '\n'; //from 1 to number of elements S[i]->consoleShow(); } } else { std::cout << "empty scene " << '\n'; } } //Modifier void Scene::addExternalAction(unsigned int place, Vect F, Torsor T) // adds force to element i starting from 0 { S[place]->addExternalAction(F, T); } void Scene::addExternalAction(unsigned int place, Torsor T) { addExternalAction(place, Vect(0, 0, 0), T); } void Scene::update(double dt) { for (auto it = S.begin(); it != S.end(); it++) { (*it)->update(dt); } } void Scene::simulate(double step, double duration) { double t = 0; while (t < duration) { update(step); t = t + step; } Time += t; } //----------Model interface----------------------- void Scene::addMatPoint() { MaterialPoint *Mp = new MaterialPoint; S.push_back(Mp); } void Scene::addMatPoint(Point p, Vect velocity, double mass, double charge_) { MaterialElement *Mp = new MaterialPoint(p, velocity, mass, charge_); S.push_back(Mp); } void Scene::addSolid() { Solid *Sol = new Solid; S.push_back(Sol); } void Scene::addSolid(Point p, Vect velocity, double mass, double charge_) { Solid *Sol = new Solid(p, velocity, mass, charge_); S.push_back(Sol); } <|endoftext|>
<commit_before>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "Differentiator.h" #include <better/map.h> #include <better/small_vector.h> #include <react/core/LayoutableShadowNode.h> #include <react/debug/SystraceSection.h> #include "ShadowView.h" namespace facebook { namespace react { /* * Extremely simple and naive implementation of a map. * The map is simple but it's optimized for particular constraints that we have * here. * * A regular map implementation (e.g. `std::unordered_map`) has some basic * performance guarantees like constant average insertion and lookup complexity. * This is nice, but it's *average* complexity measured on a non-trivial amount * of data. The regular map is a very complex data structure that using hashing, * buckets, multiple comprising operations, multiple allocations and so on. * * In our particular case, we need a map for `int` to `void *` with a dozen * values. In these conditions, nothing can beat a naive implementation using a * stack-allocated vector. And this implementation is exactly this: no * allocation, no hashing, no complex branching, no buckets, no iterators, no * rehashing, no other guarantees. It's crazy limited, unsafe, and performant on * a trivial amount of data. * * Besides that, we also need to optimize for insertion performance (the case * where a bunch of views appears on the screen first time); in this * implementation, this is as performant as vector `push_back`. */ template <typename KeyT, typename ValueT, int DefaultSize = 16> class TinyMap final { public: using Pair = std::pair<KeyT, ValueT>; using Iterator = Pair *; inline Iterator begin() { return (Pair *)vector_; } inline Iterator end() { return nullptr; } inline Iterator find(KeyT key) { for (auto &item : vector_) { if (item.first == key) { return &item; } } return end(); } inline void insert(Pair pair) { assert(pair.first != 0); vector_.push_back(pair); } inline void erase(Iterator iterator) { static_assert( std::is_same<KeyT, Tag>::value, "The collection is designed to store only `Tag`s as keys."); // Zero is a invalid tag. iterator->first = 0; } private: better::small_vector<Pair, DefaultSize> vector_; }; static void sliceChildShadowNodeViewPairsRecursively( ShadowViewNodePair::List &pairList, Point layoutOffset, ShadowNode const &shadowNode) { for (auto const &childShadowNode : shadowNode.getChildren()) { auto shadowView = ShadowView(*childShadowNode); auto const layoutableShadowNode = dynamic_cast<LayoutableShadowNode const *>(childShadowNode.get()); #ifndef ANDROID // New approach (iOS): // Non-view components are treated as layout-only views (they aren't // represented as `ShadowView`s). if (!layoutableShadowNode || layoutableShadowNode->isLayoutOnly()) { #else // Previous approach (Android): // Non-view components are treated as normal views with an empty layout // (they are represented as `ShadowView`s). if (layoutableShadowNode && layoutableShadowNode->isLayoutOnly()) { #endif sliceChildShadowNodeViewPairsRecursively( pairList, layoutOffset + shadowView.layoutMetrics.frame.origin, *childShadowNode); } else { shadowView.layoutMetrics.frame.origin += layoutOffset; pairList.push_back({shadowView, childShadowNode.get()}); } } } static ShadowViewNodePair::List sliceChildShadowNodeViewPairs( ShadowNode const &shadowNode) { auto pairList = ShadowViewNodePair::List{}; sliceChildShadowNodeViewPairsRecursively(pairList, {0, 0}, shadowNode); return pairList; } static void calculateShadowViewMutations( ShadowViewMutation::List &mutations, ShadowView const &parentShadowView, ShadowViewNodePair::List const &oldChildPairs, ShadowViewNodePair::List const &newChildPairs) { // The current version of the algorithm is otimized for simplicity, // not for performance or optimal result. if (oldChildPairs == newChildPairs) { return; } if (oldChildPairs.size() == 0 && newChildPairs.size() == 0) { return; } auto index = int{0}; // Maps inserted node tags to pointers to them in `newChildPairs`. auto insertedPairs = TinyMap<Tag, ShadowViewNodePair const *>{}; // Lists of mutations auto createMutations = ShadowViewMutation::List{}; auto deleteMutations = ShadowViewMutation::List{}; auto insertMutations = ShadowViewMutation::List{}; auto removeMutations = ShadowViewMutation::List{}; auto updateMutations = ShadowViewMutation::List{}; auto downwardMutations = ShadowViewMutation::List{}; auto destructiveDownwardMutations = ShadowViewMutation::List{}; // Stage 1: Collecting `Update` mutations for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; auto const &newChildPair = newChildPairs[index]; if (oldChildPair.shadowView.tag != newChildPair.shadowView.tag) { // Totally different nodes, updating is impossible. break; } if (oldChildPair.shadowView != newChildPair.shadowView) { updateMutations.push_back(ShadowViewMutation::UpdateMutation( parentShadowView, oldChildPair.shadowView, newChildPair.shadowView, index)); } auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), oldChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } int lastIndexAfterFirstStage = index; // Stage 2: Collecting `Insert` mutations for (; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; insertMutations.push_back(ShadowViewMutation::InsertMutation( parentShadowView, newChildPair.shadowView, index)); insertedPairs.insert({newChildPair.shadowView.tag, &newChildPair}); } // Stage 3: Collecting `Delete` and `Remove` mutations for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; // Even if the old view was (re)inserted, we have to generate `remove` // mutation. removeMutations.push_back(ShadowViewMutation::RemoveMutation( parentShadowView, oldChildPair.shadowView, index)); auto const it = insertedPairs.find(oldChildPair.shadowView.tag); if (it == insertedPairs.end()) { // The old view was *not* (re)inserted. // We have to generate `delete` mutation and apply the algorithm // recursively. deleteMutations.push_back( ShadowViewMutation::DeleteMutation(oldChildPair.shadowView)); // We also have to call the algorithm recursively to clean up the entire // subtree starting from the removed view. calculateShadowViewMutations( destructiveDownwardMutations, oldChildPair.shadowView, sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode), {}); } else { // The old view *was* (re)inserted. // We have to call the algorithm recursively if the inserted view // is *not* the same as removed one. auto const &newChildPair = *it->second; if (newChildPair != oldChildPair) { auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), newChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } // In any case we have to remove the view from `insertedPairs` as // indication that the view was actually removed (which means that // the view existed before), hence we don't have to generate // `create` mutation. insertedPairs.erase(it); } } // Stage 4: Collecting `Create` mutations for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; if (insertedPairs.find(newChildPair.shadowView.tag) == insertedPairs.end()) { // The new view was (re)inserted, so there is no need to create it. continue; } createMutations.push_back( ShadowViewMutation::CreateMutation(newChildPair.shadowView)); calculateShadowViewMutations( downwardMutations, newChildPair.shadowView, {}, sliceChildShadowNodeViewPairs(*newChildPair.shadowNode)); } // All mutations in an optimal order: std::move( destructiveDownwardMutations.begin(), destructiveDownwardMutations.end(), std::back_inserter(mutations)); std::move( updateMutations.begin(), updateMutations.end(), std::back_inserter(mutations)); std::move( removeMutations.rbegin(), removeMutations.rend(), std::back_inserter(mutations)); std::move( deleteMutations.begin(), deleteMutations.end(), std::back_inserter(mutations)); std::move( createMutations.begin(), createMutations.end(), std::back_inserter(mutations)); std::move( downwardMutations.begin(), downwardMutations.end(), std::back_inserter(mutations)); std::move( insertMutations.begin(), insertMutations.end(), std::back_inserter(mutations)); } ShadowViewMutation::List calculateShadowViewMutations( ShadowNode const &oldRootShadowNode, ShadowNode const &newRootShadowNode) { SystraceSection s("calculateShadowViewMutations"); // Root shadow nodes must be belong the same family. assert(ShadowNode::sameFamily(oldRootShadowNode, newRootShadowNode)); auto mutations = ShadowViewMutation::List{}; mutations.reserve(256); auto oldRootShadowView = ShadowView(oldRootShadowNode); auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { mutations.push_back(ShadowViewMutation::UpdateMutation( ShadowView(), oldRootShadowView, newRootShadowView, -1)); } calculateShadowViewMutations( mutations, ShadowView(oldRootShadowNode), sliceChildShadowNodeViewPairs(oldRootShadowNode), sliceChildShadowNodeViewPairs(newRootShadowNode)); return mutations; } } // namespace react } // namespace facebook <commit_msg>Backout Force Diffing algorithm to insert views Bottom Up<commit_after>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "Differentiator.h" #include <better/map.h> #include <better/small_vector.h> #include <react/core/LayoutableShadowNode.h> #include <react/debug/SystraceSection.h> #include "ShadowView.h" namespace facebook { namespace react { /* * Extremely simple and naive implementation of a map. * The map is simple but it's optimized for particular constraints that we have * here. * * A regular map implementation (e.g. `std::unordered_map`) has some basic * performance guarantees like constant average insertion and lookup complexity. * This is nice, but it's *average* complexity measured on a non-trivial amount * of data. The regular map is a very complex data structure that using hashing, * buckets, multiple comprising operations, multiple allocations and so on. * * In our particular case, we need a map for `int` to `void *` with a dozen * values. In these conditions, nothing can beat a naive implementation using a * stack-allocated vector. And this implementation is exactly this: no * allocation, no hashing, no complex branching, no buckets, no iterators, no * rehashing, no other guarantees. It's crazy limited, unsafe, and performant on * a trivial amount of data. * * Besides that, we also need to optimize for insertion performance (the case * where a bunch of views appears on the screen first time); in this * implementation, this is as performant as vector `push_back`. */ template <typename KeyT, typename ValueT, int DefaultSize = 16> class TinyMap final { public: using Pair = std::pair<KeyT, ValueT>; using Iterator = Pair *; inline Iterator begin() { return (Pair *)vector_; } inline Iterator end() { return nullptr; } inline Iterator find(KeyT key) { for (auto &item : vector_) { if (item.first == key) { return &item; } } return end(); } inline void insert(Pair pair) { assert(pair.first != 0); vector_.push_back(pair); } inline void erase(Iterator iterator) { static_assert( std::is_same<KeyT, Tag>::value, "The collection is designed to store only `Tag`s as keys."); // Zero is a invalid tag. iterator->first = 0; } private: better::small_vector<Pair, DefaultSize> vector_; }; static void sliceChildShadowNodeViewPairsRecursively( ShadowViewNodePair::List &pairList, Point layoutOffset, ShadowNode const &shadowNode) { for (auto const &childShadowNode : shadowNode.getChildren()) { auto shadowView = ShadowView(*childShadowNode); auto const layoutableShadowNode = dynamic_cast<LayoutableShadowNode const *>(childShadowNode.get()); #ifndef ANDROID // New approach (iOS): // Non-view components are treated as layout-only views (they aren't // represented as `ShadowView`s). if (!layoutableShadowNode || layoutableShadowNode->isLayoutOnly()) { #else // Previous approach (Android): // Non-view components are treated as normal views with an empty layout // (they are represented as `ShadowView`s). if (layoutableShadowNode && layoutableShadowNode->isLayoutOnly()) { #endif sliceChildShadowNodeViewPairsRecursively( pairList, layoutOffset + shadowView.layoutMetrics.frame.origin, *childShadowNode); } else { shadowView.layoutMetrics.frame.origin += layoutOffset; pairList.push_back({shadowView, childShadowNode.get()}); } } } static ShadowViewNodePair::List sliceChildShadowNodeViewPairs( ShadowNode const &shadowNode) { auto pairList = ShadowViewNodePair::List{}; sliceChildShadowNodeViewPairsRecursively(pairList, {0, 0}, shadowNode); return pairList; } static void calculateShadowViewMutations( ShadowViewMutation::List &mutations, ShadowView const &parentShadowView, ShadowViewNodePair::List const &oldChildPairs, ShadowViewNodePair::List const &newChildPairs) { // The current version of the algorithm is otimized for simplicity, // not for performance or optimal result. if (oldChildPairs == newChildPairs) { return; } if (oldChildPairs.size() == 0 && newChildPairs.size() == 0) { return; } auto index = int{0}; // Maps inserted node tags to pointers to them in `newChildPairs`. auto insertedPairs = TinyMap<Tag, ShadowViewNodePair const *>{}; // Lists of mutations auto createMutations = ShadowViewMutation::List{}; auto deleteMutations = ShadowViewMutation::List{}; auto insertMutations = ShadowViewMutation::List{}; auto removeMutations = ShadowViewMutation::List{}; auto updateMutations = ShadowViewMutation::List{}; auto downwardMutations = ShadowViewMutation::List{}; auto destructiveDownwardMutations = ShadowViewMutation::List{}; // Stage 1: Collecting `Update` mutations for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; auto const &newChildPair = newChildPairs[index]; if (oldChildPair.shadowView.tag != newChildPair.shadowView.tag) { // Totally different nodes, updating is impossible. break; } if (oldChildPair.shadowView != newChildPair.shadowView) { updateMutations.push_back(ShadowViewMutation::UpdateMutation( parentShadowView, oldChildPair.shadowView, newChildPair.shadowView, index)); } auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), oldChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } int lastIndexAfterFirstStage = index; // Stage 2: Collecting `Insert` mutations for (; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; insertMutations.push_back(ShadowViewMutation::InsertMutation( parentShadowView, newChildPair.shadowView, index)); insertedPairs.insert({newChildPair.shadowView.tag, &newChildPair}); } // Stage 3: Collecting `Delete` and `Remove` mutations for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; // Even if the old view was (re)inserted, we have to generate `remove` // mutation. removeMutations.push_back(ShadowViewMutation::RemoveMutation( parentShadowView, oldChildPair.shadowView, index)); auto const it = insertedPairs.find(oldChildPair.shadowView.tag); if (it == insertedPairs.end()) { // The old view was *not* (re)inserted. // We have to generate `delete` mutation and apply the algorithm // recursively. deleteMutations.push_back( ShadowViewMutation::DeleteMutation(oldChildPair.shadowView)); // We also have to call the algorithm recursively to clean up the entire // subtree starting from the removed view. calculateShadowViewMutations( destructiveDownwardMutations, oldChildPair.shadowView, sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode), {}); } else { // The old view *was* (re)inserted. // We have to call the algorithm recursively if the inserted view // is *not* the same as removed one. auto const &newChildPair = *it->second; if (newChildPair != oldChildPair) { auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), newChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } // In any case we have to remove the view from `insertedPairs` as // indication that the view was actually removed (which means that // the view existed before), hence we don't have to generate // `create` mutation. insertedPairs.erase(it); } } // Stage 4: Collecting `Create` mutations for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; if (insertedPairs.find(newChildPair.shadowView.tag) == insertedPairs.end()) { // The new view was (re)inserted, so there is no need to create it. continue; } createMutations.push_back( ShadowViewMutation::CreateMutation(newChildPair.shadowView)); calculateShadowViewMutations( downwardMutations, newChildPair.shadowView, {}, sliceChildShadowNodeViewPairs(*newChildPair.shadowNode)); } // All mutations in an optimal order: std::move( destructiveDownwardMutations.begin(), destructiveDownwardMutations.end(), std::back_inserter(mutations)); std::move( updateMutations.begin(), updateMutations.end(), std::back_inserter(mutations)); std::move( removeMutations.rbegin(), removeMutations.rend(), std::back_inserter(mutations)); std::move( deleteMutations.begin(), deleteMutations.end(), std::back_inserter(mutations)); std::move( createMutations.begin(), createMutations.end(), std::back_inserter(mutations)); std::move( insertMutations.begin(), insertMutations.end(), std::back_inserter(mutations)); std::move( downwardMutations.begin(), downwardMutations.end(), std::back_inserter(mutations)); } ShadowViewMutation::List calculateShadowViewMutations( ShadowNode const &oldRootShadowNode, ShadowNode const &newRootShadowNode) { SystraceSection s("calculateShadowViewMutations"); // Root shadow nodes must be belong the same family. assert(ShadowNode::sameFamily(oldRootShadowNode, newRootShadowNode)); auto mutations = ShadowViewMutation::List{}; mutations.reserve(256); auto oldRootShadowView = ShadowView(oldRootShadowNode); auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { mutations.push_back(ShadowViewMutation::UpdateMutation( ShadowView(), oldRootShadowView, newRootShadowView, -1)); } calculateShadowViewMutations( mutations, ShadowView(oldRootShadowNode), sliceChildShadowNodeViewPairs(oldRootShadowNode), sliceChildShadowNodeViewPairs(newRootShadowNode)); return mutations; } } // namespace react } // namespace facebook <|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 "options.hpp" #include <proton/connection.hpp> #include <proton/connection_options.hpp> #include <proton/container.hpp> #include <proton/default_container.hpp> #include <proton/delivery.hpp> #include <proton/error_condition.hpp> #include <proton/function.hpp> #include <proton/listen_handler.hpp> #include <proton/listener.hpp> #include <proton/message.hpp> #include <proton/messaging_handler.hpp> #include <proton/receiver_options.hpp> #include <proton/sender_options.hpp> #include <proton/source_options.hpp> #include <proton/target.hpp> #include <proton/target_options.hpp> #include <proton/thread_safe.hpp> #include <proton/tracker.hpp> #include <proton/transport.hpp> #include <deque> #include <iostream> #include <map> #include <string> #include "fake_cpp11.hpp" // This is a simplified model for a message broker, that only allows for messages to go to a // single receiver. // // Queues are only created and never destroyed // // Broker Entities (that need to be individually serialised) // QueueManager - Creates new queues, finds queues // Queue - Queues msgs, records subscribers, sends msgs to subscribers // Connection - Receives Messages from network, sends messages to network. // Work // FindQueue(queueName, connection) - From a Connection to the QueueManager // This will create the queue if it doesn't already exist and send a BoundQueue // message back to the connection. // BoundQueue(queue) - From the QueueManager to a Connection // // QueueMsg(msg) - From a Connection (receiver) to a Queue // Subscribe(sender) - From a Connection (sender) to a Queue // Flow(sender, credit) - From a Connection (sender) to a Queue // Unsubscribe(sender) - From a Connection (sender) to a Queue // // SendMsg(msg) - From a Queue to a Connection (sender) // Unsubscribed() - From a Queue to a Connection (sender) // Simple debug output bool verbose; #define DOUT(x) do {if (verbose) {x};} while (false) class Queue; class Sender; typedef std::map<proton::sender, Sender*> senders; class Sender : public proton::messaging_handler { friend class connection_handler; proton::sender sender_; senders& senders_; proton::work_queue& work_queue_; std::string queue_name_; Queue* queue_; int pending_credit_; // Messaging handlers void on_sendable(proton::sender &sender) OVERRIDE; void on_sender_close(proton::sender &sender) OVERRIDE; public: Sender(proton::sender s, senders& ss) : sender_(s), senders_(ss), work_queue_(s.work_queue()), queue_(0), pending_credit_(0) {} bool add(proton::work f) { return work_queue_.add(f); } void boundQueue(Queue* q, std::string qn); void sendMsg(proton::message m) { DOUT(std::cerr << "Sender: " << this << " sending\n";); sender_.send(m); } void unsubscribed() { DOUT(std::cerr << "Sender: " << this << " deleting\n";); delete this; } }; // Queue - round robin subscriptions class Queue { proton::work_queue work_queue_; const std::string name_; std::deque<proton::message> messages_; typedef std::map<Sender*, int> subscriptions; // With credit subscriptions subscriptions_; subscriptions::iterator current_; void tryToSend() { DOUT(std::cerr << "Queue: " << this << " tryToSend: " << subscriptions_.size();); // Starting at current_, send messages to subscriptions with credit: // After each send try to find another subscription; Wrap around; // Finish when we run out of messages or credit. size_t outOfCredit = 0; while (!messages_.empty() && outOfCredit<subscriptions_.size()) { // If we got the end (or haven't started yet) start at the beginning if (current_==subscriptions_.end()) { current_=subscriptions_.begin(); } // If we have credit send the message DOUT(std::cerr << "(" << current_->second << ") ";); if (current_->second>0) { DOUT(std::cerr << current_->first << " ";); proton::schedule_work(current_->first, &Sender::sendMsg, current_->first, messages_.front()); messages_.pop_front(); --current_->second; ++current_; } else { ++outOfCredit; } } DOUT(std::cerr << "\n";); } public: Queue(proton::container& c, const std::string& n) : work_queue_(c), name_(n), current_(subscriptions_.end()) {} bool add(proton::work f) { return work_queue_.add(f); } void queueMsg(proton::message m) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") queueMsg\n";); messages_.push_back(m); tryToSend(); } void flow(Sender* s, int c) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") flow: " << c << " to " << s << "\n";); subscriptions_[s] = c; tryToSend(); } void subscribe(Sender* s) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") subscribe Sender: " << s << "\n";); subscriptions_[s] = 0; } void unsubscribe(Sender* s) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") unsubscribe Sender: " << s << "\n";); // If we're about to erase the current subscription move on if (current_ != subscriptions_.end() && current_->first==s) ++current_; subscriptions_.erase(s); proton::schedule_work(s, &Sender::unsubscribed, s); } }; // We have credit to send a message. void Sender::on_sendable(proton::sender &sender) { if (queue_) { proton::schedule_work(queue_, &Queue::flow, queue_, this, sender.credit()); } else { pending_credit_ = sender.credit(); } } void Sender::on_sender_close(proton::sender &sender) { if (queue_) { proton::schedule_work(queue_, &Queue::unsubscribe, queue_, this); } else { // TODO: Is it possible to be closed before we get the queue allocated? // If so, we should have a way to mark the sender deleted, so we can delete // on queue binding } senders_.erase(sender); } void Sender::boundQueue(Queue* q, std::string qn) { DOUT(std::cerr << "Sender: " << this << " bound to Queue: " << q <<"(" << qn << ")\n";); queue_ = q; queue_name_ = qn; proton::schedule_work(q, &Queue::subscribe, q, this); sender_.open(proton::sender_options() .source((proton::source_options().address(queue_name_))) .handler(*this)); if (pending_credit_>0) { proton::schedule_work(queue_, &Queue::flow, queue_, this, pending_credit_); } std::cout << "sending from " << queue_name_ << std::endl; } class Receiver : public proton::messaging_handler { friend class connection_handler; proton::receiver receiver_; proton::work_queue& work_queue_; Queue* queue_; std::deque<proton::message> messages_; // A message is received. void on_message(proton::delivery &, proton::message &m) OVERRIDE { messages_.push_back(m); if (queue_) { queueMsgs(); } } void queueMsgs() { DOUT(std::cerr << "Receiver: " << this << " queueing " << messages_.size() << " msgs to: " << queue_ << "\n";); while (!messages_.empty()) { proton::schedule_work(queue_, &Queue::queueMsg, queue_, messages_.front()); messages_.pop_front(); } } public: Receiver(proton::receiver r) : receiver_(r), work_queue_(r.work_queue()), queue_(0) {} bool add(proton::work f) { return work_queue_.add(f); } void boundQueue(Queue* q, std::string qn) { DOUT(std::cerr << "Receiver: " << this << " bound to Queue: " << q << "(" << qn << ")\n";); queue_ = q; receiver_.open(proton::receiver_options() .source((proton::source_options().address(qn))) .handler(*this)); std::cout << "receiving to " << qn << std::endl; queueMsgs(); } }; class QueueManager { proton::container& container_; proton::work_queue work_queue_; typedef std::map<std::string, Queue*> queues; queues queues_; int next_id_; // Use to generate unique queue IDs. public: QueueManager(proton::container& c) : container_(c), work_queue_(c), next_id_(0) {} bool add(proton::work f) { return work_queue_.add(f); } template <class T> void findQueue(T& connection, std::string& qn) { if (qn.empty()) { // Dynamic queue creation std::ostringstream os; os << "_dynamic_" << next_id_++; qn = os.str(); } Queue* q = 0; queues::iterator i = queues_.find(qn); if (i==queues_.end()) { q = new Queue(container_, qn); queues_[qn] = q; } else { q = i->second; } proton::schedule_work(&connection, &T::boundQueue, &connection, q, qn); } void findQueueSender(Sender* s, std::string qn) { findQueue(*s, qn); } void findQueueReceiver(Receiver* r, std::string qn) { findQueue(*r, qn); } }; class connection_handler : public proton::messaging_handler { QueueManager& queue_manager_; senders senders_; public: connection_handler(QueueManager& qm) : queue_manager_(qm) {} void on_connection_open(proton::connection& c) OVERRIDE { c.open(); // Accept the connection } // A sender sends messages from a queue to a subscriber. void on_sender_open(proton::sender &sender) OVERRIDE { std::string qn = sender.source().dynamic() ? "" : sender.source().address(); Sender* s = new Sender(sender, senders_); senders_[sender] = s; proton::schedule_work(&queue_manager_, &QueueManager::findQueueSender, &queue_manager_, s, qn); } // A receiver receives messages from a publisher to a queue. void on_receiver_open(proton::receiver &receiver) OVERRIDE { std::string qname = receiver.target().address(); if (qname == "shutdown") { std::cout << "broker shutting down" << std::endl; // Sending to the special "shutdown" queue stops the broker. receiver.connection().container().stop( proton::error_condition("shutdown", "stop broker")); } else { if (qname.empty()) { DOUT(std::cerr << "ODD - trying to attach to a empty address\n";); } Receiver* r = new Receiver(receiver); proton::schedule_work(&queue_manager_, &QueueManager::findQueueReceiver, &queue_manager_, r, qname); } } void on_session_close(proton::session &session) OVERRIDE { // Unsubscribe all senders that belong to session. for (proton::sender_iterator i = session.senders().begin(); i != session.senders().end(); ++i) { senders::iterator j = senders_.find(*i); if (j == senders_.end()) continue; Sender* s = j->second; if (s->queue_) { proton::schedule_work(s->queue_, &Queue::unsubscribe, s->queue_, s); } senders_.erase(j); } } void on_error(const proton::error_condition& e) OVERRIDE { std::cerr << "error: " << e.what() << std::endl; } // The container calls on_transport_close() last. void on_transport_close(proton::transport& t) OVERRIDE { // Unsubscribe all senders. for (proton::sender_iterator i = t.connection().senders().begin(); i != t.connection().senders().end(); ++i) { senders::iterator j = senders_.find(*i); if (j == senders_.end()) continue; Sender* s = j->second; if (s->queue_) { proton::schedule_work(s->queue_, &Queue::unsubscribe, s->queue_, s); } } delete this; // All done. } }; class broker { public: broker(const std::string addr) : container_("broker"), queues_(container_), listener_(queues_) { container_.listen(addr, listener_); std::cout << "broker listening on " << addr << std::endl; } void run() { container_.run(/* std::thread::hardware_concurrency() */); } private: struct listener : public proton::listen_handler { listener(QueueManager& c) : queues_(c) {} proton::connection_options on_accept(proton::listener&) OVERRIDE{ return proton::connection_options().handler(*(new connection_handler(queues_))); } void on_error(proton::listener&, const std::string& s) OVERRIDE { std::cerr << "listen error: " << s << std::endl; throw std::runtime_error(s); } QueueManager& queues_; }; proton::container container_; QueueManager queues_; listener listener_; }; int main(int argc, char **argv) { // Command line options std::string address("0.0.0.0"); example::options opts(argc, argv); opts.add_flag(verbose, 'v', "verbose", "verbose (debugging) output"); opts.add_value(address, 'a', "address", "listen on URL", "URL"); try { verbose = false; opts.parse(); broker(address).run(); return 0; } catch (const example::bad_option& e) { std::cout << opts << std::endl << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << "broker shutdown: " << e.what() << std::endl; } return 1; } <commit_msg>PROTON-1400: [C++ example] Use multiple threads in broker example if available<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 "options.hpp" #include <proton/connection.hpp> #include <proton/connection_options.hpp> #include <proton/container.hpp> #include <proton/default_container.hpp> #include <proton/delivery.hpp> #include <proton/error_condition.hpp> #include <proton/function.hpp> #include <proton/listen_handler.hpp> #include <proton/listener.hpp> #include <proton/message.hpp> #include <proton/messaging_handler.hpp> #include <proton/receiver_options.hpp> #include <proton/sender_options.hpp> #include <proton/source_options.hpp> #include <proton/target.hpp> #include <proton/target_options.hpp> #include <proton/thread_safe.hpp> #include <proton/tracker.hpp> #include <proton/transport.hpp> #include <deque> #include <iostream> #include <map> #include <string> #if PN_CPP_SUPPORTS_THREADS #include <thread> #endif #include "fake_cpp11.hpp" // This is a simplified model for a message broker, that only allows for messages to go to a // single receiver. // // This broker is multithread safe and if compiled with C++11 with a multithreaded Proton // binding library will use as many threads as there are thread resources available (usually // cores) // // Queues are only created and never destroyed // // Broker Entities (that need to be individually serialised) // QueueManager - Creates new queues, finds queues // Queue - Queues msgs, records subscribers, sends msgs to subscribers // Connection - Receives Messages from network, sends messages to network. // Work // FindQueue(queueName, connection) - From a Connection to the QueueManager // This will create the queue if it doesn't already exist and send a BoundQueue // message back to the connection. // BoundQueue(queue) - From the QueueManager to a Connection // // QueueMsg(msg) - From a Connection (receiver) to a Queue // Subscribe(sender) - From a Connection (sender) to a Queue // Flow(sender, credit) - From a Connection (sender) to a Queue // Unsubscribe(sender) - From a Connection (sender) to a Queue // // SendMsg(msg) - From a Queue to a Connection (sender) // Unsubscribed() - From a Queue to a Connection (sender) // Simple debug output bool verbose; #define DOUT(x) do {if (verbose) {x};} while (false) class Queue; class Sender; typedef std::map<proton::sender, Sender*> senders; class Sender : public proton::messaging_handler { friend class connection_handler; proton::sender sender_; senders& senders_; proton::work_queue& work_queue_; std::string queue_name_; Queue* queue_; int pending_credit_; // Messaging handlers void on_sendable(proton::sender &sender) OVERRIDE; void on_sender_close(proton::sender &sender) OVERRIDE; public: Sender(proton::sender s, senders& ss) : sender_(s), senders_(ss), work_queue_(s.work_queue()), queue_(0), pending_credit_(0) {} bool add(proton::work f) { return work_queue_.add(f); } void boundQueue(Queue* q, std::string qn); void sendMsg(proton::message m) { DOUT(std::cerr << "Sender: " << this << " sending\n";); sender_.send(m); } void unsubscribed() { DOUT(std::cerr << "Sender: " << this << " deleting\n";); delete this; } }; // Queue - round robin subscriptions class Queue { proton::work_queue work_queue_; const std::string name_; std::deque<proton::message> messages_; typedef std::map<Sender*, int> subscriptions; // With credit subscriptions subscriptions_; subscriptions::iterator current_; void tryToSend() { DOUT(std::cerr << "Queue: " << this << " tryToSend: " << subscriptions_.size();); // Starting at current_, send messages to subscriptions with credit: // After each send try to find another subscription; Wrap around; // Finish when we run out of messages or credit. size_t outOfCredit = 0; while (!messages_.empty() && outOfCredit<subscriptions_.size()) { // If we got the end (or haven't started yet) start at the beginning if (current_==subscriptions_.end()) { current_=subscriptions_.begin(); } // If we have credit send the message DOUT(std::cerr << "(" << current_->second << ") ";); if (current_->second>0) { DOUT(std::cerr << current_->first << " ";); proton::schedule_work(current_->first, &Sender::sendMsg, current_->first, messages_.front()); messages_.pop_front(); --current_->second; ++current_; } else { ++outOfCredit; } } DOUT(std::cerr << "\n";); } public: Queue(proton::container& c, const std::string& n) : work_queue_(c), name_(n), current_(subscriptions_.end()) {} bool add(proton::work f) { return work_queue_.add(f); } void queueMsg(proton::message m) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") queueMsg\n";); messages_.push_back(m); tryToSend(); } void flow(Sender* s, int c) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") flow: " << c << " to " << s << "\n";); subscriptions_[s] = c; tryToSend(); } void subscribe(Sender* s) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") subscribe Sender: " << s << "\n";); subscriptions_[s] = 0; } void unsubscribe(Sender* s) { DOUT(std::cerr << "Queue: " << this << "(" << name_ << ") unsubscribe Sender: " << s << "\n";); // If we're about to erase the current subscription move on if (current_ != subscriptions_.end() && current_->first==s) ++current_; subscriptions_.erase(s); proton::schedule_work(s, &Sender::unsubscribed, s); } }; // We have credit to send a message. void Sender::on_sendable(proton::sender &sender) { if (queue_) { proton::schedule_work(queue_, &Queue::flow, queue_, this, sender.credit()); } else { pending_credit_ = sender.credit(); } } void Sender::on_sender_close(proton::sender &sender) { if (queue_) { proton::schedule_work(queue_, &Queue::unsubscribe, queue_, this); } else { // TODO: Is it possible to be closed before we get the queue allocated? // If so, we should have a way to mark the sender deleted, so we can delete // on queue binding } senders_.erase(sender); } void Sender::boundQueue(Queue* q, std::string qn) { DOUT(std::cerr << "Sender: " << this << " bound to Queue: " << q <<"(" << qn << ")\n";); queue_ = q; queue_name_ = qn; proton::schedule_work(q, &Queue::subscribe, q, this); sender_.open(proton::sender_options() .source((proton::source_options().address(queue_name_))) .handler(*this)); if (pending_credit_>0) { proton::schedule_work(queue_, &Queue::flow, queue_, this, pending_credit_); } std::cout << "sending from " << queue_name_ << std::endl; } class Receiver : public proton::messaging_handler { friend class connection_handler; proton::receiver receiver_; proton::work_queue& work_queue_; Queue* queue_; std::deque<proton::message> messages_; // A message is received. void on_message(proton::delivery &, proton::message &m) OVERRIDE { messages_.push_back(m); if (queue_) { queueMsgs(); } } void queueMsgs() { DOUT(std::cerr << "Receiver: " << this << " queueing " << messages_.size() << " msgs to: " << queue_ << "\n";); while (!messages_.empty()) { proton::schedule_work(queue_, &Queue::queueMsg, queue_, messages_.front()); messages_.pop_front(); } } public: Receiver(proton::receiver r) : receiver_(r), work_queue_(r.work_queue()), queue_(0) {} bool add(proton::work f) { return work_queue_.add(f); } void boundQueue(Queue* q, std::string qn) { DOUT(std::cerr << "Receiver: " << this << " bound to Queue: " << q << "(" << qn << ")\n";); queue_ = q; receiver_.open(proton::receiver_options() .source((proton::source_options().address(qn))) .handler(*this)); std::cout << "receiving to " << qn << std::endl; queueMsgs(); } }; class QueueManager { proton::container& container_; proton::work_queue work_queue_; typedef std::map<std::string, Queue*> queues; queues queues_; int next_id_; // Use to generate unique queue IDs. public: QueueManager(proton::container& c) : container_(c), work_queue_(c), next_id_(0) {} bool add(proton::work f) { return work_queue_.add(f); } template <class T> void findQueue(T& connection, std::string& qn) { if (qn.empty()) { // Dynamic queue creation std::ostringstream os; os << "_dynamic_" << next_id_++; qn = os.str(); } Queue* q = 0; queues::iterator i = queues_.find(qn); if (i==queues_.end()) { q = new Queue(container_, qn); queues_[qn] = q; } else { q = i->second; } proton::schedule_work(&connection, &T::boundQueue, &connection, q, qn); } void findQueueSender(Sender* s, std::string qn) { findQueue(*s, qn); } void findQueueReceiver(Receiver* r, std::string qn) { findQueue(*r, qn); } }; class connection_handler : public proton::messaging_handler { QueueManager& queue_manager_; senders senders_; public: connection_handler(QueueManager& qm) : queue_manager_(qm) {} void on_connection_open(proton::connection& c) OVERRIDE { c.open(); // Accept the connection } // A sender sends messages from a queue to a subscriber. void on_sender_open(proton::sender &sender) OVERRIDE { std::string qn = sender.source().dynamic() ? "" : sender.source().address(); Sender* s = new Sender(sender, senders_); senders_[sender] = s; proton::schedule_work(&queue_manager_, &QueueManager::findQueueSender, &queue_manager_, s, qn); } // A receiver receives messages from a publisher to a queue. void on_receiver_open(proton::receiver &receiver) OVERRIDE { std::string qname = receiver.target().address(); if (qname == "shutdown") { std::cout << "broker shutting down" << std::endl; // Sending to the special "shutdown" queue stops the broker. receiver.connection().container().stop( proton::error_condition("shutdown", "stop broker")); } else { if (qname.empty()) { DOUT(std::cerr << "ODD - trying to attach to a empty address\n";); } Receiver* r = new Receiver(receiver); proton::schedule_work(&queue_manager_, &QueueManager::findQueueReceiver, &queue_manager_, r, qname); } } void on_session_close(proton::session &session) OVERRIDE { // Unsubscribe all senders that belong to session. for (proton::sender_iterator i = session.senders().begin(); i != session.senders().end(); ++i) { senders::iterator j = senders_.find(*i); if (j == senders_.end()) continue; Sender* s = j->second; if (s->queue_) { proton::schedule_work(s->queue_, &Queue::unsubscribe, s->queue_, s); } senders_.erase(j); } } void on_error(const proton::error_condition& e) OVERRIDE { std::cerr << "error: " << e.what() << std::endl; } // The container calls on_transport_close() last. void on_transport_close(proton::transport& t) OVERRIDE { // Unsubscribe all senders. for (proton::sender_iterator i = t.connection().senders().begin(); i != t.connection().senders().end(); ++i) { senders::iterator j = senders_.find(*i); if (j == senders_.end()) continue; Sender* s = j->second; if (s->queue_) { proton::schedule_work(s->queue_, &Queue::unsubscribe, s->queue_, s); } } delete this; // All done. } }; class broker { public: broker(const std::string addr) : container_("broker"), queues_(container_), listener_(queues_) { container_.listen(addr, listener_); std::cout << "broker listening on " << addr << std::endl; } void run() { #if PN_CPP_SUPPORTS_THREADS std::cout << "starting " << std::thread::hardware_concurrency() << " listening threads\n"; container_.run(std::thread::hardware_concurrency()); #else container_.run(); #endif } private: struct listener : public proton::listen_handler { listener(QueueManager& c) : queues_(c) {} proton::connection_options on_accept(proton::listener&) OVERRIDE{ return proton::connection_options().handler(*(new connection_handler(queues_))); } void on_error(proton::listener&, const std::string& s) OVERRIDE { std::cerr << "listen error: " << s << std::endl; throw std::runtime_error(s); } QueueManager& queues_; }; proton::container container_; QueueManager queues_; listener listener_; }; int main(int argc, char **argv) { // Command line options std::string address("0.0.0.0"); example::options opts(argc, argv); opts.add_flag(verbose, 'v', "verbose", "verbose (debugging) output"); opts.add_value(address, 'a', "address", "listen on URL", "URL"); try { verbose = false; opts.parse(); broker(address).run(); return 0; } catch (const example::bad_option& e) { std::cout << opts << std::endl << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << "broker shutdown: " << e.what() << std::endl; } return 1; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> void carr_func(int * vec) { std::cout << "carr_func - vec: " << vec << std::endl; } int main(void) { std::vector<int> v1 = {-1, 3, 5, -8, 0}; //initialize with list std::vector<int> v2; //don't initialize auto v3(v1); //initialize v3 via copy /** * Managing std::vector capacity */ //Unlike std::array, std::vector has a more sensible empty() function //v2 is currently empty std::cout << "v1.empty(): " << v1.empty() << std::endl; std::cout << "v2.empty(): " << v2.empty() << std::endl; // size() tells you the number of elements std::cout << "v1.size(): " << v1.size() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; // max_size() is huuuuuuuuuge for my host machine std::cout << "v1.max_size(): " << v1.max_size() << std::endl; std::cout << "v2.max_size(): " << v2.max_size() << std::endl; // Capacity tells you how many elements can be stored in the currently allocated memory std::cout << "v1.capacity(): " << v1.capacity() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.reserve(10); std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; //If you have reserved space greater than your current needs, you can shrink the buffer v2.shrink_to_fit(); std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl; /** * Accessing std::vector elements */ std::cout << "v1.front(): " << v1.front() << std::endl; std::cout << "v1.back(): " << v1.back() << std::endl; std::cout << "v1[0]: " << v1[0] << std::endl; std::cout << "v1.at(4): " << v1.at(4) << std::endl; // Bounds checking will generate exceptions. Try: //auto b = v2.at(10); //However, operator [] is not bounds checked! //This may or may not seg fault //std::cout << "v2[6]: " << v2[6] << std::endl; /* * If you need to interface with legacy code or libraries requiring * a C-style array interface, you can get to the underlying array data ptr */ //Error: //carr_func(v1); //OK: carr_func(v1.data()); /** * Playing around with vectors */ v2 = v1; //copy std::cout << "v2.size() after copy: " << v2.size() << std::endl; v2.clear(); std::cout << "v2.size() after clear: " << v2.size() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.insert(v2.begin(), -1); //insert an element - you need an iterator v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator v2.push_back(0); //adds element to end v2.emplace_back(int(10)); //constructs an element in place at the end std::cout << std::endl << "v2: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(7); //resize to 7. The new elements will be 0-initialized v2.resize(10, -1); //resize to 10. New elements initialized with -1 v2.pop_back(); //removes last element v2.erase(v2.begin()); //removes first element std::cout << std::endl << "v2 resized: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(4); //shrink and strip off extra elements //Container operations work std::sort(v2.begin(), v2.end()); std::cout << std::endl << "v2 shrunk & sorted: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; return 0; } <commit_msg>vector example expansion<commit_after>#include <iostream> #include <vector> void carr_func(int * vec) { std::cout << "carr_func - vec: " << vec << std::endl; } int main(void) { std::vector<int> v1 = {-1, 3, 5, -8, 0}; //initialize with list std::vector<int> v2; //don't initialize auto v3(v1); //initialize v3 via copy /** * Managing std::vector capacity */ //Unlike std::array, std::vector has a more sensible empty() function //v2 is currently empty std::cout << "v1.empty(): " << v1.empty() << std::endl; std::cout << "v2.empty(): " << v2.empty() << std::endl; // size() tells you the number of elements std::cout << "v1.size(): " << v1.size() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; // max_size() is huuuuuuuuuge for my host machine std::cout << "v1.max_size(): " << v1.max_size() << std::endl; std::cout << "v2.max_size(): " << v2.max_size() << std::endl; // Capacity tells you how many elements can be stored in the currently allocated memory std::cout << "v1.capacity(): " << v1.capacity() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.reserve(10); std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; //If you have reserved space greater than your current needs, you can shrink the buffer v2.shrink_to_fit(); std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl; /** * Accessing std::vector elements */ std::cout << "v1.front(): " << v1.front() << std::endl; std::cout << "v1.back(): " << v1.back() << std::endl; std::cout << "v1[0]: " << v1[0] << std::endl; std::cout << "v1.at(4): " << v1.at(4) << std::endl; // Bounds checking will generate exceptions. Try: //auto b = v2.at(10); //However, operator [] is not bounds checked! //This may or may not seg fault //std::cout << "v2[6]: " << v2[6] << std::endl; /* * If you need to interface with legacy code or libraries requiring * a C-style array interface, you can get to the underlying array data ptr */ //Error: //carr_func(v1); //OK: carr_func(v1.data()); /** * Playing around with vectors */ v2 = v1; //copy std::cout << "v2.size() after copy: " << v2.size() << std::endl; v2.clear(); std::cout << "v2.size() after clear: " << v2.size() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.insert(v2.begin(), -1); //insert an element - you need an iterator v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator int x = 10; v2.push_back(x); //adds element to end v2.emplace_back(10); //constructs an element in place at the end std::cout << std::endl << "v2: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(7); //resize to 7. The new elements will be 0-initialized v2.resize(10, -1); //resize to 10. New elements initialized with -1 v2.pop_back(); //removes last element v2.erase(v2.begin()); //removes first element std::cout << std::endl << "v2 resized: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(4); //shrink and strip off extra elements //Container operations work std::sort(v2.begin(), v2.end()); std::cout << std::endl << "v2 shrunk & sorted: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; std::cout << "std::vector size: " << sizeof(std::vector<char>) << std::endl; return 0; } <|endoftext|>
<commit_before>#include "LightShaderHandler.h" LightShaderHandler::LightShaderHandler() { } LightShaderHandler::~LightShaderHandler() { } int LightShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution) { HRESULT hResult; ID3D10Blob* vertexShaderBuffer = nullptr; ID3D10Blob* pixelShaderBuffer = nullptr; //Insert shader path here WCHAR* vsFilename = L"../GraphicsDLL/LightVertexShader.hlsl"; WCHAR* psFilename = L"../GraphicsDLL/LightPixelShader.hlsl"; // Compile the shaders \\ hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } // Create the shaders \\ hResult = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &this->m_vertexShader[0]); if (FAILED(hResult)) { return 1; } hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader); if (FAILED(hResult)) { return 1; } // Create the input layout \\ D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); //Create the vertex input layout. hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &this->m_layout); if (FAILED(hResult)) { return 1; } //Release and nullptr the buffers as they are no longer needed vertexShaderBuffer->Release(); vertexShaderBuffer = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // Create the matrix buffer \\ D3D11_BUFFER_DESC matrixBufferDesc; ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc)); //Fill the description of the dynamic matrix constant buffer that is in the vertex shader matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(ShaderLib::LightConstantBuffer); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer); if (FAILED(hResult)) { return 1; } // Create the sampler \\ D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); //Fill the texture sampler state description samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the texture sampler state hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState); if (FAILED(hResult)) { return 1; } return 0; } int LightShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType) { ShaderHandler::SetActive(deviceContext, shaderType); //Set the sampler state in pixel shader deviceContext->PSSetSamplers(0, 1, &this->m_samplerState); return 0; } void LightShaderHandler::Shutdown() { ShaderHandler::Shutdown(); //Release the sampler state if (this->m_samplerState) { this->m_samplerState->Release(); this->m_samplerState = nullptr; } } int LightShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::LightConstantBuffer * shaderParams) { return 0; } <commit_msg>ADD LightShaderHandler SetShaderParameters() implemented<commit_after>#include "LightShaderHandler.h" LightShaderHandler::LightShaderHandler() { } LightShaderHandler::~LightShaderHandler() { } int LightShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution) { HRESULT hResult; ID3D10Blob* vertexShaderBuffer = nullptr; ID3D10Blob* pixelShaderBuffer = nullptr; //Insert shader path here WCHAR* vsFilename = L"../GraphicsDLL/LightVertexShader.hlsl"; WCHAR* psFilename = L"../GraphicsDLL/LightPixelShader.hlsl"; // Compile the shaders \\ hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } // Create the shaders \\ hResult = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &this->m_vertexShader[0]); if (FAILED(hResult)) { return 1; } hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader); if (FAILED(hResult)) { return 1; } // Create the input layout \\ D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); //Create the vertex input layout. hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &this->m_layout); if (FAILED(hResult)) { return 1; } //Release and nullptr the buffers as they are no longer needed vertexShaderBuffer->Release(); vertexShaderBuffer = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // Create the matrix buffer \\ D3D11_BUFFER_DESC matrixBufferDesc; ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc)); //Fill the description of the dynamic matrix constant buffer that is in the vertex shader matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(ShaderLib::LightConstantBuffer); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer); if (FAILED(hResult)) { return 1; } // Create the sampler \\ D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); //Fill the texture sampler state description samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the texture sampler state hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState); if (FAILED(hResult)) { return 1; } return 0; } int LightShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType) { ShaderHandler::SetActive(deviceContext, shaderType); //Set the sampler state in pixel shader deviceContext->PSSetSamplers(0, 1, &this->m_samplerState); return 0; } void LightShaderHandler::Shutdown() { ShaderHandler::Shutdown(); //Release the sampler state if (this->m_samplerState) { this->m_samplerState->Release(); this->m_samplerState = nullptr; } } int LightShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::LightConstantBuffer * shaderParams) { HRESULT hResult; D3D11_MAPPED_SUBRESOURCE mappedResource; ShaderLib::LightConstantBuffer* dataPtr; unsigned int bufferNumber; //Map the constant buffer so we can write to it (denies GPU access) hResult = deviceContext->Map(this->m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(hResult)) { return 1; } //Get pointer to the data dataPtr = (ShaderLib::LightConstantBuffer*)mappedResource.pData; //Copy the matrices to the constant buffer dataPtr->viewMatrix = shaderParams->viewMatrix; dataPtr->projectionMatrix = shaderParams->projectionMatrix; dataPtr->camPos = shaderParams->camPos; //Unmap the constant buffer to give the GPU access agin deviceContext->Unmap(this->m_matrixBuffer, 0); //Set constant buffer position in vertex shader bufferNumber = 0; //Set the constant buffer in vertex and pixel shader with updated values deviceContext->VSSetConstantBuffers(bufferNumber, 1, &this->m_matrixBuffer); deviceContext->PSSetConstantBuffers(bufferNumber, 1, &this->m_matrixBuffer); return 0; } <|endoftext|>
<commit_before>/* MIT License Copyright (c) 2016 Mark Allender 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 <string> #include <fstream> #include "imgui/imgui.h" #include "imgui/imgui_impl_sdl.h" #include "interface.h" #include "6502/video.h" #include "6502/disk.h" #include "utils/path_utils.h" #include "apple2emu.h" #include "nfd.h" static bool Show_main_menu = false; static bool Show_debug_menu = false; static bool Menu_open_at_start = false; static bool Imgui_initialized = false; static const int32_t Line_length = 256; static const char *Settings_filename = "settings.txt"; // settings to be stored static int32_t Video_color_type = static_cast<int>(video_display_types::MONO_WHITE); static const uint32_t Cycles_array_size = 64; static uint32_t Cycles_per_frame[Cycles_array_size]; static uint32_t Current_cycles_array_entry = 0; // inserts disk image into the given disk drive static void ui_insert_disk(const char *disk_filename, int slot) { FILE *fp = fopen(disk_filename, "rb"); if (fp == nullptr) { return; } fclose(fp); disk_insert(disk_filename, slot); } static void ui_load_settings() { std::ifstream infile(Settings_filename); std::string line; while(std::getline(infile, line)) { int pos = line.find('='); if (pos > 0) { std::string setting = line.substr(0, pos - 1); std::string value = line.substr(pos + 1); while (value[0] == ' ') { value.erase(0, 1); } if (setting == "auto_start") { int i_val = strtol(value.c_str(), nullptr, 10); Auto_start = i_val ? true : false; } else if (setting == "emulator_type") { int i_val = strtol(value.c_str(), nullptr, 10); Emulator_type = static_cast<emulator_type>(i_val); } else if (setting == "open_at_start") { int i_val = strtol(value.c_str(), nullptr, 10); Menu_open_at_start = i_val ? true : false; Show_main_menu = Menu_open_at_start; } else if (setting == "disk1") { ui_insert_disk(value.c_str(), 1); } else if (setting == "disk2") { ui_insert_disk(value.c_str(), 2); } else if (setting == "video") { Video_color_type = (uint8_t)strtol(value.c_str(), nullptr, 10); video_set_mono_type(static_cast<video_display_types>(Video_color_type)); } else if (setting == "speed") { Speed_multiplier = (int)strtol(value.c_str(), nullptr, 10); } } } } static void ui_save_settings() { FILE *fp = fopen(Settings_filename, "wt"); if (fp == nullptr) { printf("Unable to open settings file for writing\n"); return; } fprintf(fp, "auto_start = %d\n", Auto_start == true ? 1 : 0); fprintf(fp, "emulator_type = %d\n", static_cast<uint8_t>(Emulator_type)); fprintf(fp, "open_at_start = %d\n", Menu_open_at_start == true ? 1 : 0); fprintf(fp, "disk1 = %s\n", disk_get_mounted_filename(1)); fprintf(fp, "disk2 = %s\n", disk_get_mounted_filename(2)); fprintf(fp, "video = %d\n", Video_color_type); fprintf(fp, "speed = %d\n", Speed_multiplier); fclose(fp); } static void ui_show_general_options() { ImGui::Text("General Options:"); ImGui::Checkbox("Auto Start", &Auto_start); ImGui::SameLine(200); if (Emulator_state == emulator_state::SPLASH_SCREEN) { if (ImGui::Button("Start")) { Emulator_state = emulator_state::EMULATOR_STARTED; } } else { if (ImGui::Button("Reboot")) { reset_machine(); Show_main_menu = true; } } ImGui::Separator(); static int type = static_cast<uint8_t>(Emulator_type); int old_type = type; ImGui::ListBox("Emulation Type", &type, Emulator_names, static_cast<uint8_t>(emulator_type::NUM_EMULATOR_TYPES)); // if the emulator type changed, then reset the machine (if we haven't // started yet. Otherwise tell user that we need to reset machine // for this change to take effect if (old_type != type && Emulator_state == emulator_state::SPLASH_SCREEN) { Emulator_type = static_cast<emulator_type>(type); reset_machine(); } else { } ImGui::Checkbox("Open Menu on startup", &Menu_open_at_start); } static void ui_get_disk_image(uint8_t slot_num) { nfdchar_t *outPath = NULL; nfdresult_t result = NFD_OpenDialog("dsk,do", nullptr, &outPath); if (result == NFD_OKAY) { disk_insert(outPath, slot_num); free(outPath); } } static void ui_show_disk_menu() { ImGui::Text("Disk Drive Options:"); ImGui::Spacing(); ImGui::Spacing(); ImGui::Text("Slot 6, Disk 1:"); std::string filename; path_utils_get_filename(disk_get_mounted_filename(1), filename); if (filename.empty()) { filename = "<none>"; } ImGui::SameLine(); if (ImGui::Button(filename.c_str())) { ui_get_disk_image(1); } ImGui::SameLine(); if (ImGui::Button("Eject")) { disk_eject(1); } ImGui::Spacing(); ImGui::Text("Slot 6, Disk 2:"); path_utils_get_filename(disk_get_mounted_filename(2), filename); if (filename.empty()) { filename = "<none>"; } ImGui::SameLine(); if (ImGui::Button(filename.c_str())) { ui_get_disk_image(2); } ImGui::SameLine(); if (ImGui::Button("Eject")) { disk_eject(2); } } static void ui_show_video_output_menu() { ImGui::Text("Video Output Options:"); ImGui::RadioButton("White", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_WHITE)); ImGui::SameLine(); ImGui::RadioButton("Amber", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_AMBER)); ImGui::SameLine(); ImGui::RadioButton("Green", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_GREEN)); ImGui::SameLine(); ImGui::RadioButton("Color", &Video_color_type, static_cast<uint8_t>(video_display_types::COLOR)); video_set_mono_type(static_cast<video_display_types>(Video_color_type)); } static void ui_show_speed_menu() { if (ImGui::SliderInt("Emulator Speed", (int *)&Speed_multiplier, 1, 10) == true) { } } static void ui_show_main_menu() { ImGui::Begin("Options"); ui_show_general_options(); ImGui::Separator(); ui_show_video_output_menu(); ImGui::Separator(); ui_show_disk_menu(); ImGui::Separator(); ui_show_speed_menu(); ImGui::End(); } static void ui_show_debug_menu() { static bool animate = true; static float cycles[Cycles_array_size]; ImGui::Begin("Debug"); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Separator(); ImGui::Checkbox("Animate", &animate); if (animate == true) { auto index = 0; auto i = Current_cycles_array_entry; while (true) { cycles[index++] = static_cast<float>(Cycles_per_frame[i]); i = (i + 1) % Cycles_array_size; if (i == Current_cycles_array_entry) { break; } } } ImGui::PlotLines("Cycles/Frame", cycles, Cycles_array_size, 0, nullptr, 17020.0f, 17050.0f, ImVec2(0, 50)); ImGui::End(); } void ui_init() { static bool settings_loaded = false; // only load settings when we first start // the emulator if (settings_loaded == false) { ui_load_settings(); settings_loaded = true; } for (auto i = 0; i < Cycles_array_size; i++) { Cycles_per_frame[i] = 0; } } void ui_shutdown() { ImGui_ImplSdl_Shutdown(); Imgui_initialized = false; ui_save_settings(); } void ui_do_frame(SDL_Window *window) { // initlialize imgui if it has not been initialized yet if (Imgui_initialized == false) { ImGui_ImplSdl_Init(window); Imgui_initialized = true; } ImGui_ImplSdl_NewFrame(window); if (Show_main_menu) { ui_show_main_menu(); } if (Show_debug_menu) { ui_show_debug_menu(); } //ImGui::ShowTestWindow(); ImGui::Render(); } void ui_toggle_main_menu() { Show_main_menu = !Show_main_menu; } void ui_toggle_debug_menu() { Show_debug_menu = !Show_debug_menu; } // since rendering is decoupled from cycles on the machine, extra // function to store off cycles for debug display void ui_update_cycle_count() { Cycles_per_frame[Current_cycles_array_entry] = Total_cycles_this_frame; Current_cycles_array_entry = (Current_cycles_array_entry + 1) % Cycles_array_size; } <commit_msg>small ui improvements<commit_after>/* MIT License Copyright (c) 2016 Mark Allender 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 <string> #include <fstream> #include "imgui/imgui.h" #include "imgui/imgui_impl_sdl.h" #include "interface.h" #include "6502/video.h" #include "6502/disk.h" #include "utils/path_utils.h" #include "apple2emu.h" #include "nfd.h" static bool Show_main_menu = false; static bool Show_debug_menu = false; static bool Menu_open_at_start = false; static bool Imgui_initialized = false; static const int32_t Line_length = 256; static const char *Settings_filename = "settings.txt"; // settings to be stored static int32_t Video_color_type = static_cast<int>(video_display_types::MONO_WHITE); static const uint32_t Cycles_array_size = 64; static uint32_t Cycles_per_frame[Cycles_array_size]; static uint32_t Current_cycles_array_entry = 0; // inserts disk image into the given disk drive static void ui_insert_disk(const char *disk_filename, int slot) { FILE *fp = fopen(disk_filename, "rb"); if (fp == nullptr) { return; } fclose(fp); disk_insert(disk_filename, slot); } static void ui_load_settings() { std::ifstream infile(Settings_filename); std::string line; while(std::getline(infile, line)) { int pos = line.find('='); if (pos > 0) { std::string setting = line.substr(0, pos - 1); std::string value = line.substr(pos + 1); while (value[0] == ' ') { value.erase(0, 1); } if (setting == "auto_start") { int i_val = strtol(value.c_str(), nullptr, 10); Auto_start = i_val ? true : false; } else if (setting == "emulator_type") { int i_val = strtol(value.c_str(), nullptr, 10); Emulator_type = static_cast<emulator_type>(i_val); } else if (setting == "open_at_start") { int i_val = strtol(value.c_str(), nullptr, 10); Menu_open_at_start = i_val ? true : false; Show_main_menu = Menu_open_at_start; } else if (setting == "disk1") { ui_insert_disk(value.c_str(), 1); } else if (setting == "disk2") { ui_insert_disk(value.c_str(), 2); } else if (setting == "video") { Video_color_type = (uint8_t)strtol(value.c_str(), nullptr, 10); video_set_mono_type(static_cast<video_display_types>(Video_color_type)); } else if (setting == "speed") { Speed_multiplier = (int)strtol(value.c_str(), nullptr, 10); } } } } static void ui_save_settings() { FILE *fp = fopen(Settings_filename, "wt"); if (fp == nullptr) { printf("Unable to open settings file for writing\n"); return; } fprintf(fp, "auto_start = %d\n", Auto_start == true ? 1 : 0); fprintf(fp, "emulator_type = %d\n", static_cast<uint8_t>(Emulator_type)); fprintf(fp, "open_at_start = %d\n", Menu_open_at_start == true ? 1 : 0); fprintf(fp, "disk1 = %s\n", disk_get_mounted_filename(1)); fprintf(fp, "disk2 = %s\n", disk_get_mounted_filename(2)); fprintf(fp, "video = %d\n", Video_color_type); fprintf(fp, "speed = %d\n", Speed_multiplier); fclose(fp); } static void ui_show_general_options() { ImGui::Text("General Options:"); ImGui::Checkbox("Auto Start", &Auto_start); ImGui::SameLine(200); if (Emulator_state == emulator_state::SPLASH_SCREEN) { if (ImGui::Button("Start")) { Emulator_state = emulator_state::EMULATOR_STARTED; } } else { if (ImGui::Button("Reboot")) { reset_machine(); Show_main_menu = true; } } ImGui::Checkbox("Open Menu on startup", &Menu_open_at_start); ImGui::Separator(); static int type = static_cast<uint8_t>(Emulator_type); int old_type = type; ImGui::ListBox("Emulation Type", &type, Emulator_names, static_cast<uint8_t>(emulator_type::NUM_EMULATOR_TYPES)); // if the emulator type changed, then reset the machine (if we haven't // started yet. Otherwise tell user that we need to reset machine // for this change to take effect if (old_type != type && Emulator_state == emulator_state::SPLASH_SCREEN) { Emulator_type = static_cast<emulator_type>(type); reset_machine(); } else { } } static void ui_get_disk_image(uint8_t slot_num) { nfdchar_t *outPath = NULL; nfdresult_t result = NFD_OpenDialog("dsk,do", nullptr, &outPath); if (result == NFD_OKAY) { disk_insert(outPath, slot_num); free(outPath); } } static void ui_show_disk_menu() { ImGui::Text("Disk Drive Options:"); ImGui::Spacing(); ImGui::Spacing(); ImGui::Text("Slot 6, Disk 1:"); std::string filename; path_utils_get_filename(disk_get_mounted_filename(1), filename); if (filename.empty()) { filename = "<none>"; } ImGui::SameLine(); if (ImGui::Button(filename.c_str())) { ui_get_disk_image(1); } ImGui::SameLine(); if (ImGui::Button("Eject")) { disk_eject(1); } ImGui::Spacing(); ImGui::Text("Slot 6, Disk 2:"); path_utils_get_filename(disk_get_mounted_filename(2), filename); if (filename.empty()) { filename = "<none>"; } ImGui::SameLine(); if (ImGui::Button(filename.c_str())) { ui_get_disk_image(2); } ImGui::SameLine(); if (ImGui::Button("Eject")) { disk_eject(2); } } static void ui_show_video_output_menu() { ImGui::Text("Video Output Options:"); ImGui::RadioButton("White", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_WHITE)); ImGui::SameLine(); ImGui::RadioButton("Amber", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_AMBER)); ImGui::SameLine(); ImGui::RadioButton("Green", &Video_color_type, static_cast<uint8_t>(video_display_types::MONO_GREEN)); ImGui::SameLine(); ImGui::RadioButton("Color", &Video_color_type, static_cast<uint8_t>(video_display_types::COLOR)); video_set_mono_type(static_cast<video_display_types>(Video_color_type)); } static void ui_show_speed_menu() { if (ImGui::SliderInt("Emulator Speed", (int *)&Speed_multiplier, 1, 100) == true) { } } static void ui_show_main_menu() { ImGui::Begin("Options", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_ShowBorders); ui_show_general_options(); ImGui::Separator(); ui_show_video_output_menu(); ImGui::Separator(); ui_show_disk_menu(); ImGui::Separator(); ui_show_speed_menu(); ImGui::End(); } static void ui_show_debug_menu() { static bool animate = true; static float cycles[Cycles_array_size]; ImGui::Begin("Debug"); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Separator(); ImGui::Checkbox("Animate", &animate); if (animate == true) { auto index = 0; auto i = Current_cycles_array_entry; while (true) { cycles[index++] = static_cast<float>(Cycles_per_frame[i]); i = (i + 1) % Cycles_array_size; if (i == Current_cycles_array_entry) { break; } } } ImGui::PlotLines("Cycles/Frame", cycles, Cycles_array_size, 0, nullptr, 17020.0f, 17050.0f, ImVec2(0, 50)); ImGui::End(); } void ui_init() { static bool settings_loaded = false; // only load settings when we first start // the emulator if (settings_loaded == false) { ui_load_settings(); settings_loaded = true; } for (auto i = 0; i < Cycles_array_size; i++) { Cycles_per_frame[i] = 0; } } void ui_shutdown() { ImGui_ImplSdl_Shutdown(); Imgui_initialized = false; ui_save_settings(); } void ui_do_frame(SDL_Window *window) { // initlialize imgui if it has not been initialized yet if (Imgui_initialized == false) { ImGui_ImplSdl_Init(window); // maybe use apple 2 font here //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontFromFileTTF("printchar21.ttf", 8.0f); Imgui_initialized = true; } ImGui_ImplSdl_NewFrame(window); if (Show_main_menu) { ui_show_main_menu(); } if (Show_debug_menu) { ui_show_debug_menu(); } //ImGui::ShowTestWindow(); if (Show_main_menu || Show_debug_menu) { ImGui::Render(); } } void ui_toggle_main_menu() { Show_main_menu = !Show_main_menu; } void ui_toggle_debug_menu() { Show_debug_menu = !Show_debug_menu; } // since rendering is decoupled from cycles on the machine, extra // function to store off cycles for debug display void ui_update_cycle_count() { Cycles_per_frame[Current_cycles_array_entry] = Total_cycles_this_frame; Current_cycles_array_entry = (Current_cycles_array_entry + 1) % Cycles_array_size; } <|endoftext|>
<commit_before>/* Copyright (c) 2017 Hans-Kristian Arntzen * * 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 "hdr.hpp" #include "math.hpp" #include "application.hpp" namespace Granite { struct FrameEvent : EventHandler { FrameEvent() { EVENT_MANAGER_REGISTER(FrameEvent, on_frame_time, FrameTickEvent); } bool on_frame_time(const FrameTickEvent &tick) { frame_time = float(tick.get_frame_time()); return true; } float frame_time = 0.0f; }; static FrameEvent timer; static void luminance_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &output = pass.get_graph().get_physical_buffer_resource(pass.get_storage_outputs()[0]->get_physical_index()); cmd.set_storage_buffer(0, 0, output); cmd.set_texture(0, 1, input, Vulkan::StockSampler::LinearClamp); unsigned half_width = input.get_image().get_create_info().width / 2; unsigned half_height = input.get_image().get_create_info().height / 2; auto *program = cmd.get_device().get_shader_manager().register_compute("builtin://shaders/post/luminance.comp"); unsigned variant = program->register_variant({}); cmd.set_program(*program->get_program(variant)); struct Registers { uvec2 size; float lerp; float minimum; float maximum; } push; push.size = uvec2(half_width, half_height); push.lerp = 1.0f - pow(0.5f, timer.frame_time); push.minimum = -2.0f; push.maximum = 1.0f; cmd.push_constants(&push, 0, sizeof(push)); cmd.dispatch(1, 1, 1); } static void bloom_threshold_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &ubo = pass.get_graph().get_physical_buffer_resource(pass.get_uniform_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); cmd.set_uniform_buffer(0, 1, ubo); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_threshold.frag"); } static void bloom_downsample_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd, bool feedback) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); if (feedback) { auto *feedback_texture = pass.get_graph().get_physical_history_texture_resource( pass.get_history_inputs()[0]->get_physical_index()); if (feedback_texture) { struct Push { vec2 inv_size; float lerp; } push; push.inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); float lerp = 1.0f - pow(0.001f, timer.frame_time); push.lerp = lerp; cmd.push_constants(&push, 0, sizeof(push)); cmd.set_texture(0, 1, *feedback_texture, Vulkan::StockSampler::NearestClamp); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag", {{"FEEDBACK", 1}}); } else { vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag"); } } else { vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag"); } } static void bloom_upsample_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_upsample.frag"); } static void tonemap_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &hdr = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &bloom = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[1]->get_physical_index()); auto &ubo = pass.get_graph().get_physical_buffer_resource(pass.get_uniform_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, hdr, Vulkan::StockSampler::LinearClamp); cmd.set_texture(0, 1, bloom, Vulkan::StockSampler::LinearClamp); cmd.set_uniform_buffer(0, 2, ubo); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/tonemap.frag"); } void setup_hdr_postprocess(RenderGraph &graph, const std::string &input, const std::string &output) { BufferInfo buffer_info; buffer_info.size = 3 * sizeof(float); buffer_info.persistent = true; buffer_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; auto &lum = graph.get_buffer_resource("average-luminance"); lum.set_buffer_info(buffer_info); auto &adapt_pass = graph.add_pass("adapt-luminance", VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); adapt_pass.add_storage_output("average-luminance-updated", buffer_info, "average-luminance"); adapt_pass.add_texture_input("bloom-downsample-3"); adapt_pass.set_build_render_pass([&adapt_pass](Vulkan::CommandBuffer &cmd) { luminance_build_render_pass(adapt_pass, cmd); }); auto &threshold = graph.add_pass("bloom-threshold", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); AttachmentInfo threshold_info; threshold_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; threshold_info.size_x = 0.5f; threshold_info.size_y = 0.5f; threshold_info.size_class = SizeClass::InputRelative; threshold_info.size_relative_name = input; threshold.add_color_output("threshold", threshold_info); threshold.add_texture_input(input); threshold.add_uniform_input("average-luminance"); threshold.set_build_render_pass([&threshold](Vulkan::CommandBuffer &cmd) { bloom_threshold_build_render_pass(threshold, cmd); }); AttachmentInfo blur_info; blur_info.size_x = 0.25f; blur_info.size_y = 0.25f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; blur_info.size_class = SizeClass::InputRelative; blur_info.size_relative_name = input; auto &blur0 = graph.add_pass("bloom-downsample-0", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur0.add_color_output("bloom-downsample-0", blur_info); blur0.add_texture_input("threshold"); blur0.set_build_render_pass([&blur0](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur0, cmd, false); }); blur_info.size_x = 0.125f; blur_info.size_y = 0.125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur1 = graph.add_pass("bloom-downsample-1", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur1.add_color_output("bloom-downsample-1", blur_info); blur1.add_texture_input("bloom-downsample-0"); blur1.set_build_render_pass([&blur1](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur1, cmd, false); }); blur_info.size_x = 0.0625f; blur_info.size_y = 0.0625f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur2 = graph.add_pass("bloom-downsample-2", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur2.add_color_output("bloom-downsample-2", blur_info); blur2.add_texture_input("bloom-downsample-1"); blur2.set_build_render_pass([&blur2](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur2, cmd, false); }); blur_info.size_x = 0.03125f; blur_info.size_y = 0.03125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur3 = graph.add_pass("bloom-downsample-3", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur3.add_color_output("bloom-downsample-3", blur_info); blur3.add_texture_input("bloom-downsample-2"); blur3.add_history_input("bloom-downsample-3"); blur3.set_build_render_pass([&blur3](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur3, cmd, true); }); blur_info.size_x = 0.0625f; blur_info.size_y = 0.0625f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur4 = graph.add_pass("bloom-upsample-0", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur4.add_color_output("bloom-upsample-0", blur_info); blur4.add_texture_input("bloom-downsample-3"); blur4.set_build_render_pass([&blur4](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur4, cmd); }); blur_info.size_x = 0.125f; blur_info.size_y = 0.125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur5 = graph.add_pass("bloom-upsample-1", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur5.add_color_output("bloom-upsample-1", blur_info); blur5.add_texture_input("bloom-upsample-0"); blur5.set_build_render_pass([&blur5](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur5, cmd); }); blur_info.size_x = 0.25f; blur_info.size_y = 0.25f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur6 = graph.add_pass("bloom-upsample-2", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur6.add_color_output("bloom-upsample-2", blur_info); blur6.add_texture_input("bloom-upsample-1"); blur6.set_build_render_pass([&blur6](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur6, cmd); }); AttachmentInfo tonemap_info; tonemap_info.size_class = SizeClass::InputRelative; tonemap_info.size_relative_name = input; auto &tonemap = graph.add_pass("tonemap", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); tonemap.add_color_output(output, tonemap_info); tonemap.add_texture_input(input); tonemap.add_texture_input("bloom-upsample-2"); tonemap.add_uniform_input("average-luminance-updated"); tonemap.set_build_render_pass([&tonemap](Vulkan::CommandBuffer &cmd) { tonemap_build_render_pass(tonemap, cmd); }); } } <commit_msg>Change luminance range.<commit_after>/* Copyright (c) 2017 Hans-Kristian Arntzen * * 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 "hdr.hpp" #include "math.hpp" #include "application.hpp" namespace Granite { struct FrameEvent : EventHandler { FrameEvent() { EVENT_MANAGER_REGISTER(FrameEvent, on_frame_time, FrameTickEvent); } bool on_frame_time(const FrameTickEvent &tick) { frame_time = float(tick.get_frame_time()); return true; } float frame_time = 0.0f; }; static FrameEvent timer; static void luminance_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &output = pass.get_graph().get_physical_buffer_resource(pass.get_storage_outputs()[0]->get_physical_index()); cmd.set_storage_buffer(0, 0, output); cmd.set_texture(0, 1, input, Vulkan::StockSampler::LinearClamp); unsigned half_width = input.get_image().get_create_info().width / 2; unsigned half_height = input.get_image().get_create_info().height / 2; auto *program = cmd.get_device().get_shader_manager().register_compute("builtin://shaders/post/luminance.comp"); unsigned variant = program->register_variant({}); cmd.set_program(*program->get_program(variant)); struct Registers { uvec2 size; float lerp; float minimum; float maximum; } push; push.size = uvec2(half_width, half_height); push.lerp = 1.0f - pow(0.5f, timer.frame_time); push.minimum = -5.0f; push.maximum = 4.0f; cmd.push_constants(&push, 0, sizeof(push)); cmd.dispatch(1, 1, 1); } static void bloom_threshold_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &ubo = pass.get_graph().get_physical_buffer_resource(pass.get_uniform_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); cmd.set_uniform_buffer(0, 1, ubo); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_threshold.frag"); } static void bloom_downsample_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd, bool feedback) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); if (feedback) { auto *feedback_texture = pass.get_graph().get_physical_history_texture_resource( pass.get_history_inputs()[0]->get_physical_index()); if (feedback_texture) { struct Push { vec2 inv_size; float lerp; } push; push.inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); float lerp = 1.0f - pow(0.001f, timer.frame_time); push.lerp = lerp; cmd.push_constants(&push, 0, sizeof(push)); cmd.set_texture(0, 1, *feedback_texture, Vulkan::StockSampler::NearestClamp); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag", {{"FEEDBACK", 1}}); } else { vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag"); } } else { vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_downsample.frag"); } } static void bloom_upsample_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &input = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); vec2 inv_size = vec2(1.0f / input.get_image().get_create_info().width, 1.0f / input.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); cmd.set_texture(0, 0, input, Vulkan::StockSampler::LinearClamp); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/bloom_upsample.frag"); } static void tonemap_build_render_pass(RenderPass &pass, Vulkan::CommandBuffer &cmd) { auto &hdr = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[0]->get_physical_index()); auto &bloom = pass.get_graph().get_physical_texture_resource(pass.get_texture_inputs()[1]->get_physical_index()); auto &ubo = pass.get_graph().get_physical_buffer_resource(pass.get_uniform_inputs()[0]->get_physical_index()); cmd.set_texture(0, 0, hdr, Vulkan::StockSampler::LinearClamp); cmd.set_texture(0, 1, bloom, Vulkan::StockSampler::LinearClamp); cmd.set_uniform_buffer(0, 2, ubo); Vulkan::CommandBufferUtil::draw_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/tonemap.frag"); } void setup_hdr_postprocess(RenderGraph &graph, const std::string &input, const std::string &output) { BufferInfo buffer_info; buffer_info.size = 3 * sizeof(float); buffer_info.persistent = true; buffer_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; auto &lum = graph.get_buffer_resource("average-luminance"); lum.set_buffer_info(buffer_info); auto &adapt_pass = graph.add_pass("adapt-luminance", VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); adapt_pass.add_storage_output("average-luminance-updated", buffer_info, "average-luminance"); adapt_pass.add_texture_input("bloom-downsample-3"); adapt_pass.set_build_render_pass([&adapt_pass](Vulkan::CommandBuffer &cmd) { luminance_build_render_pass(adapt_pass, cmd); }); auto &threshold = graph.add_pass("bloom-threshold", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); AttachmentInfo threshold_info; threshold_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; threshold_info.size_x = 0.5f; threshold_info.size_y = 0.5f; threshold_info.size_class = SizeClass::InputRelative; threshold_info.size_relative_name = input; threshold.add_color_output("threshold", threshold_info); threshold.add_texture_input(input); threshold.add_uniform_input("average-luminance"); threshold.set_build_render_pass([&threshold](Vulkan::CommandBuffer &cmd) { bloom_threshold_build_render_pass(threshold, cmd); }); AttachmentInfo blur_info; blur_info.size_x = 0.25f; blur_info.size_y = 0.25f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; blur_info.size_class = SizeClass::InputRelative; blur_info.size_relative_name = input; auto &blur0 = graph.add_pass("bloom-downsample-0", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur0.add_color_output("bloom-downsample-0", blur_info); blur0.add_texture_input("threshold"); blur0.set_build_render_pass([&blur0](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur0, cmd, false); }); blur_info.size_x = 0.125f; blur_info.size_y = 0.125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur1 = graph.add_pass("bloom-downsample-1", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur1.add_color_output("bloom-downsample-1", blur_info); blur1.add_texture_input("bloom-downsample-0"); blur1.set_build_render_pass([&blur1](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur1, cmd, false); }); blur_info.size_x = 0.0625f; blur_info.size_y = 0.0625f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur2 = graph.add_pass("bloom-downsample-2", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur2.add_color_output("bloom-downsample-2", blur_info); blur2.add_texture_input("bloom-downsample-1"); blur2.set_build_render_pass([&blur2](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur2, cmd, false); }); blur_info.size_x = 0.03125f; blur_info.size_y = 0.03125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur3 = graph.add_pass("bloom-downsample-3", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur3.add_color_output("bloom-downsample-3", blur_info); blur3.add_texture_input("bloom-downsample-2"); blur3.add_history_input("bloom-downsample-3"); blur3.set_build_render_pass([&blur3](Vulkan::CommandBuffer &cmd) { bloom_downsample_build_render_pass(blur3, cmd, true); }); blur_info.size_x = 0.0625f; blur_info.size_y = 0.0625f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur4 = graph.add_pass("bloom-upsample-0", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur4.add_color_output("bloom-upsample-0", blur_info); blur4.add_texture_input("bloom-downsample-3"); blur4.set_build_render_pass([&blur4](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur4, cmd); }); blur_info.size_x = 0.125f; blur_info.size_y = 0.125f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur5 = graph.add_pass("bloom-upsample-1", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur5.add_color_output("bloom-upsample-1", blur_info); blur5.add_texture_input("bloom-upsample-0"); blur5.set_build_render_pass([&blur5](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur5, cmd); }); blur_info.size_x = 0.25f; blur_info.size_y = 0.25f; blur_info.format = VK_FORMAT_R16G16B16A16_SFLOAT; auto &blur6 = graph.add_pass("bloom-upsample-2", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); blur6.add_color_output("bloom-upsample-2", blur_info); blur6.add_texture_input("bloom-upsample-1"); blur6.set_build_render_pass([&blur6](Vulkan::CommandBuffer &cmd) { bloom_upsample_build_render_pass(blur6, cmd); }); AttachmentInfo tonemap_info; tonemap_info.size_class = SizeClass::InputRelative; tonemap_info.size_relative_name = input; auto &tonemap = graph.add_pass("tonemap", VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); tonemap.add_color_output(output, tonemap_info); tonemap.add_texture_input(input); tonemap.add_texture_input("bloom-upsample-2"); tonemap.add_uniform_input("average-luminance-updated"); tonemap.set_build_render_pass([&tonemap](Vulkan::CommandBuffer &cmd) { tonemap_build_render_pass(tonemap, cmd); }); } } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "user_db.h" #include "seeks_proxy.h" #include "proxy_configuration.h" #include "errlog.h" #include "plugin_manager.h" #include <iostream> #include <stdlib.h> using namespace sp; int main(int argc, char **argv) { if (argc < 3) { std::cout << "Usage: <db_file> <seeks base dir>\n"; exit(0); } std::string dbfile = argv[1]; std::string basedir = argv[2]; seeks_proxy::_configfile = "config"; seeks_proxy::_configfile = basedir + "/config"; seeks_proxy::initialize_mutexes(); errlog::init_log_module(); errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO); seeks_proxy::_basedir = basedir.c_str(); plugin_manager::_plugin_repository = basedir + "/plugins/"; seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile); seeks_proxy::_user_db = new user_db(dbfile); seeks_proxy::_user_db->open_db_readonly(); plugin_manager::load_all_plugins(); plugin_manager::instanciate_plugins(); seeks_proxy::_user_db->print(std::cout); seeks_proxy::_user_db->close_db(); } <commit_msg>fixed db print config file location<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "user_db.h" #include "seeks_proxy.h" #include "proxy_configuration.h" #include "errlog.h" #include "plugin_manager.h" #include <iostream> #include <stdlib.h> using namespace sp; int main(int argc, char **argv) { if (argc < 3) { std::cout << "Usage: <db_file> <seeks base dir>\n"; exit(0); } std::string dbfile = argv[1]; std::string basedir = argv[2]; seeks_proxy::_configfile = basedir + "/config"; seeks_proxy::initialize_mutexes(); errlog::init_log_module(); errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO); seeks_proxy::_basedir = basedir.c_str(); plugin_manager::_plugin_repository = basedir + "/plugins/"; seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile); seeks_proxy::_user_db = new user_db(dbfile); seeks_proxy::_user_db->open_db_readonly(); plugin_manager::load_all_plugins(); plugin_manager::instanciate_plugins(); seeks_proxy::_user_db->print(std::cout); seeks_proxy::_user_db->close_db(); } <|endoftext|>
<commit_before>/* This file is part of libkpimexchange Copyright (c) 2002 Jan-Pascal van Best <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qlayout.h> #include <qlabel.h> #include <qcombobox.h> #include <klocale.h> #include <kmessagebox.h> #include <kapplication.h> #include <kglobal.h> #include <kconfig.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include "exchangeprogress.h" using namespace KPIM; ExchangeProgress::ExchangeProgress(QWidget *parent) : KProgressDialog(parent, i18n("Exchange Download Progress"), i18n("Exchange Plugin"), "text" ) { m_finished = 0; m_total = 0; setAutoClose( false ); setLabel( i18n( "Listing appointments" ) ); } ExchangeProgress::~ExchangeProgress() { } void ExchangeProgress::slotTransferStarted() { m_total++; progressBar()->setTotalSteps( m_total ); updateLabel(); } void ExchangeProgress::slotTransferFinished() { m_finished++; updateLabel(); if ( m_finished == m_total ) { emit complete( this ); } } void ExchangeProgress::updateLabel() { progressBar()->setValue( m_finished ); QString str = QString( i18n( "Downloading, %1 of %2" ) ).arg( m_finished ).arg( m_total ); setLabel( str ); } #include "exchangeprogress.moc" <commit_msg>QString( i18n ( ) ) ? No way !<commit_after>/* This file is part of libkpimexchange Copyright (c) 2002 Jan-Pascal van Best <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qlayout.h> #include <qlabel.h> #include <qcombobox.h> #include <klocale.h> #include <kmessagebox.h> #include <kapplication.h> #include <kglobal.h> #include <kconfig.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include "exchangeprogress.h" using namespace KPIM; ExchangeProgress::ExchangeProgress(QWidget *parent) : KProgressDialog(parent, i18n("Exchange Download Progress"), i18n("Exchange Plugin"), "text" ) { m_finished = 0; m_total = 0; setAutoClose( false ); setLabel( i18n( "Listing appointments" ) ); } ExchangeProgress::~ExchangeProgress() { } void ExchangeProgress::slotTransferStarted() { m_total++; progressBar()->setTotalSteps( m_total ); updateLabel(); } void ExchangeProgress::slotTransferFinished() { m_finished++; updateLabel(); if ( m_finished == m_total ) { emit complete( this ); } } void ExchangeProgress::updateLabel() { progressBar()->setValue( m_finished ); QString str = i18n( "Downloading, %1 of %2" ).arg( m_finished ).arg( m_total ); setLabel( str ); } #include "exchangeprogress.moc" <|endoftext|>
<commit_before>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/math.hpp" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rgba_t make_dark_color() { random_t<rgba_t> rng_red(0, 125); random_t<rgba_t> rng_green(0, 125); random_t<rgba_t> rng_blue(0, 125); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(2, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h) { random_t<coord_t> rng(3, std::min(w / 4, h / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height()); } image_t make_filled_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_filled_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); return image; } image_t make_hollow_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); image.fill_ellipse(make_interior_rect(rect), make_transparent_color()); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) / scalar_t(8)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); const bool is_dark_background = (rng_protocol() % 2) == 0; const rgba_t back_color = is_dark_background ? make_dark_color() : make_light_color(); const rgba_t shape_color = is_dark_background ? make_light_color() : make_dark_color(); // generate random image background image_t image(irows(), icols(), color()); image.fill(back_color); image.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols, shape_color); break; case 2: shape = make_hollow_rect(rows, cols, shape_color); break; case 3: shape = make_filled_ellipse(rows, cols, shape_color); break; case 4: shape = make_hollow_ellipse(rows, cols, shape_color); break; default: break; } shape.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss() * 0.5); image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; case 3: sample.m_label = "filled_ellipse"; break; case 4: sample.m_label = "hollow_ellipse"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <commit_msg>fix some synthetic ellipses<commit_after>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/math.hpp" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rgba_t make_dark_color() { random_t<rgba_t> rng_red(0, 125); random_t<rgba_t> rng_green(0, 125); random_t<rgba_t> rng_blue(0, 125); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(3, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h) { random_t<coord_t> rng(4, std::min(w / 4, h / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height()); } image_t make_filled_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_filled_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); return image; } image_t make_hollow_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); image.fill_ellipse(make_interior_rect(rect), make_transparent_color()); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(0.5), math::cast<scalar_t>(icols() + irows()) / scalar_t(8)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); const bool is_dark_background = (rng_protocol() % 2) == 0; const rgba_t back_color = is_dark_background ? make_dark_color() : make_light_color(); const rgba_t shape_color = is_dark_background ? make_light_color() : make_dark_color(); // generate random image background image_t image(irows(), icols(), color()); image.fill(back_color); image.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols, shape_color); break; case 2: shape = make_hollow_rect(rows, cols, shape_color); break; case 3: shape = make_filled_ellipse(rows, cols, shape_color); break; case 4: shape = make_hollow_ellipse(rows, cols, shape_color); break; default: break; } shape.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss() * 0.5); image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; case 3: sample.m_label = "filled_ellipse"; break; case 4: sample.m_label = "hollow_ellipse"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <|endoftext|>
<commit_before>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto disconnect = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.controllerActive()) { response.success = false; response.message = "Controller is active. Cannont disconnect while a controller is running."; return true; } response.success = true; response.message = ""; services.reset(); recovery_action_server.reset(); return franka_control.disconnect(); }; auto connect = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { if (franka_control.connected()) { response.success = false; response.message = "Already conneceted to robot. Cannot connect twice."; return true; } franka_control.connect(); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); auto& robot = franka_control.robot(); // ServiceContainer services; franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); recovery_action_server->start(); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); response.success = true; response.message = ""; return true; }; std_srvs::Trigger::Request request; std_srvs::Trigger::Response response; if (!connect(request, response)) { ROS_ERROR("franka_control_node: Initial connect failed. Shutting down."); return 1; } ros::ServiceServer connectServer = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connect); ros::ServiceServer disconnectServer = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnect); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); } ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ros::Duration(0.001).sleep(); } return 0; } <commit_msg>fixed freezing issues, debug prints<commit_after>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <algorithm> #include <atomic> #include <thread> #include <chrono> #include <actionlib/server/simple_action_server.h> #include <controller_manager/controller_manager.h> #include <franka/exception.h> #include <franka/robot.h> #include <franka_hw/franka_hw.h> #include <franka_hw/services.h> #include <franka_msgs/ErrorRecoveryAction.h> #include <ros/ros.h> #include <std_srvs/Trigger.h> using franka_hw::ServiceContainer; using namespace std::chrono_literals; int main(int argc, char** argv) { ros::init(argc, argv, "franka_control_node"); ros::NodeHandle public_node_handle; ros::NodeHandle node_handle("~"); franka_hw::FrankaHW franka_control; if (!franka_control.init(public_node_handle, node_handle)) { ROS_ERROR("franka_control_node: Failed to initialize FrankaHW class. Shutting down!"); return 1; } auto services = std::make_unique<ServiceContainer>(); std::unique_ptr<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>> recovery_action_server; std::atomic_bool has_error(false); auto disconnect = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { ROS_INFO("franka_control, disconnect, db1"); if (franka_control.controllerActive()) { response.success = false; response.message = "Controller is active. Cannont disconnect while a controller is running."; return true; } ROS_INFO("franka_control, disconnect, db2"); response.success = true; response.message = ""; services.reset(); ROS_INFO("franka_control, disconnect, db3"); recovery_action_server.reset(); ROS_INFO("franka_control, disconnect, db4"); auto result = franka_control.disconnect(); ROS_INFO("franka_control, disconnect, db5 finished destroying robot"); return true; }; auto connect = [&](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { ROS_INFO("Connect db1"); if (franka_control.connected()) { response.success = false; response.message = "Already conneceted to robot. Cannot connect twice."; return true; } ROS_INFO("Connect db2"); franka_control.connect(); ROS_INFO("Connect db3"); std::lock_guard<std::mutex> lock(franka_control.robotMutex()); ROS_INFO("Connect db4"); auto& robot = franka_control.robot(); ROS_INFO("Connect db5"); // ServiceContainer services; services = std::make_unique<ServiceContainer>(); franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services); ROS_INFO("Connect db6"); recovery_action_server = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( node_handle, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); robot.automaticErrorRecovery(); has_error = false; recovery_action_server->setSucceeded(); ROS_INFO("Recovered from error"); } catch (const franka::Exception& ex) { recovery_action_server->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); ROS_INFO("Connect db7"); recovery_action_server->start(); ROS_INFO("Connect db8"); // Initialize robot state before loading any controller franka_control.update(robot.readOnce()); ROS_INFO("Connect db9"); response.success = true; response.message = ""; return true; }; std_srvs::Trigger::Request request; std_srvs::Trigger::Response response; if (!connect(request, response)) { ROS_ERROR("franka_control_node: Initial connect failed. Shutting down."); return 1; } ros::ServiceServer connectServer = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", connect); ros::ServiceServer disconnectServer = node_handle.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", disconnect); controller_manager::ControllerManager control_manager(&franka_control, public_node_handle); // Start background threads for message handling ros::AsyncSpinner spinner(4); spinner.start(); while (ros::ok()) { ros::Time last_time = ros::Time::now(); // Wait until controller has been activated or error has been recovered while (!franka_control.controllerActive() || has_error) { if (franka_control.connected()) { std::lock_guard<std::mutex> lock(franka_control.robotMutex()); franka_control.update(franka_control.robot().readOnce()); ros::Time now = ros::Time::now(); control_manager.update(now, now - last_time); franka_control.checkJointLimits(); last_time = now; } else { std::this_thread::sleep_for(10ms); } if (!ros::ok()) { return 0; } } if (franka_control.connected()) { try { // Run control loop. Will exit if the controller is switched. franka_control.control([&](const ros::Time& now, const ros::Duration& period) { if (period.toSec() == 0.0) { // Reset controllers before starting a motion control_manager.update(now, period, true); franka_control.checkJointLimits(); franka_control.reset(); } else { control_manager.update(now, period); franka_control.checkJointLimits(); franka_control.enforceLimits(period); } return ros::ok(); }); } catch (const franka::ControlException& e) { ROS_ERROR("%s", e.what()); has_error = true; } } ROS_INFO_THROTTLE(1, "franka_control, main loop"); } return 0; } <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_PETSC // C++ includes // Local Includes #include "auto_ptr.h" #include "petsc_preconditioner.h" #include "petsc_macro.h" #include "petsc_matrix.h" #include "petsc_vector.h" #include "petsc_macro.h" #include "libmesh_common.h" namespace libMesh { template <typename T> void PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y) { PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x)); PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y)); Vec x_vec = x_pvec.vec(); Vec y_vec = y_pvec.vec(); PCApply(_pc,x_vec,y_vec); } template <typename T> void PetscPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } //Clear the preconditioner in case it has been created in the past if(!this->_is_initialized) { //Create the preconditioning object PCCreate(libMesh::COMM_WORLD,&_pc); //Set the PCType set_petsc_preconditioner_type(this->_preconditioner_type, _pc); #ifdef LIBMESH_HAVE_PETSC_HYPRE if(this->_preconditioner_type == AMG_PRECOND) PCHYPRESetType(this->_pc, "boomeramg"); #endif PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = pmatrix->mat(); } PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN); this->_is_initialized = true; } template <typename T> void PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc) { int ierr = 0; switch (preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case CHOLESKY_PRECOND: ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ICC_PRECOND: ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ILU_PRECOND: ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case LU_PRECOND: ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ASM_PRECOND: ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case SOR_PRECOND: ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case EISENSTAT_PRECOND: ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case AMG_PRECOND: ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #if !(PETSC_VERSION_LESS_THAN(2,1,2)) // Only available for PETSC >= 2.1.2 case USER_PRECOND: ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #endif case SHELL_PRECOND: ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; default: libMesh::err << "ERROR: Unsupported PETSC Preconditioner: " << preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } //Let the commandline override stuff if( preconditioner_type != AMG_PRECOND ) PCSetFromOptions(pc); } //------------------------------------------------------------------ // Explicit instantiations template class PetscPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC <commit_msg>Added missing calls to CHKERRABORT().<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_PETSC // C++ includes // Local Includes #include "auto_ptr.h" #include "petsc_preconditioner.h" #include "petsc_macro.h" #include "petsc_matrix.h" #include "petsc_vector.h" #include "petsc_macro.h" #include "libmesh_common.h" namespace libMesh { template <typename T> void PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y) { PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x)); PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y)); Vec x_vec = x_pvec.vec(); Vec y_vec = y_pvec.vec(); int ierr = PCApply(_pc,x_vec,y_vec); CHKERRABORT(libMesh::COMM_WORLD,ierr); } template <typename T> void PetscPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } //Clear the preconditioner in case it has been created in the past if(!this->_is_initialized) { //Create the preconditioning object int ierr = PCCreate(libMesh::COMM_WORLD,&_pc); CHKERRABORT(libMesh::COMM_WORLD,ierr); //Set the PCType set_petsc_preconditioner_type(this->_preconditioner_type, _pc); #ifdef LIBMESH_HAVE_PETSC_HYPRE if(this->_preconditioner_type == AMG_PRECOND) { PCHYPRESetType(this->_pc, "boomeramg"); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = pmatrix->mat(); } int ierr = PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN); CHKERRABORT(libMesh::COMM_WORLD,ierr); this->_is_initialized = true; } template <typename T> void PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc) { int ierr = 0; switch (preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case CHOLESKY_PRECOND: ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ICC_PRECOND: ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ILU_PRECOND: ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case LU_PRECOND: ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case ASM_PRECOND: ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case SOR_PRECOND: ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case EISENSTAT_PRECOND: ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; case AMG_PRECOND: ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #if !(PETSC_VERSION_LESS_THAN(2,1,2)) // Only available for PETSC >= 2.1.2 case USER_PRECOND: ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; #endif case SHELL_PRECOND: ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break; default: libMesh::err << "ERROR: Unsupported PETSC Preconditioner: " << preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } //Let the commandline override stuff if( preconditioner_type != AMG_PRECOND ) { PCSetFromOptions(pc); CHKERRABORT(libMesh::COMM_WORLD,ierr); } } //------------------------------------------------------------------ // Explicit instantiations template class PetscPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Peter Colberg * * This file is part of cuda-wrapper. * * This software may be modified and distributed under the terms of the * 3-clause BSD license. See accompanying file LICENSE for details. */ #ifndef CUDA_TRAITS_HPP #define CUDA_TRAITS_HPP #include <cstddef> #include <cuda.h> namespace cuda { typedef std::size_t size_type; } // namespace cuda #endif /* ! CUDA_TRAITS_HPP */ <commit_msg>Remove traits.hpp<commit_after><|endoftext|>
<commit_before>#include "SFZDebug.h" static LogFifo* fifo = NULL; LogFifo::LogFifo() : fifo(capacity) { } LogFifo::~LogFifo() { } void LogFifo::logMessage(const String& message) { const char* p; // Stupid String class doesn't really let us get number of bytes. const char* bytes = message.getCharPointer(); unsigned long msgSize = strlen(bytes); int totalSize = sizeof(unsigned long) + msgSize; int start1, size1, start2, size2; fifo.prepareToWrite(totalSize, start1, size1, start2, size2); int givenSize = size1 + size2; if (givenSize < totalSize) msgSize -= givenSize - totalSize; // Write the count. if (size1 >= sizeof(unsigned long)) { memcpy(&buffer[start1], &msgSize, sizeof(unsigned long)); size1 -= sizeof(unsigned long); start1 += sizeof(unsigned long); } else { p = (const char*) &msgSize; memcpy(&buffer[start1], p, size1); p += size1; size1 = 0; int bytesLeft = sizeof(unsigned long) - size1; memcpy(&buffer[start2], p, bytesLeft); start2 += bytesLeft; size2 -= bytesLeft; } // Write the string. p = bytes; if (size1 > 0) { memcpy(&buffer[start1], p, size1); p += size1; } if (size2 > 0) memcpy(&buffer[start2], p, size2); fifo.finishedWrite(givenSize); } void LogFifo::relayMessages() { while (hasMessage()) { String message = nextMessage(); Logger::writeToLog(message); } } String LogFifo::nextMessage() { // Read the count. unsigned long msgSize = 0; int start1, size1, start2, size2; fifo.prepareToRead(sizeof(unsigned long), start1, size1, start2, size2); char* p = (char*) &msgSize; if (size1 > 0) { memcpy(p, &buffer[start1], size1); p += size1; } if (size2 > 0) memcpy(p, &buffer[start2], size2); fifo.finishedRead(size1 + size2); // Read the string. String result; fifo.prepareToRead(msgSize, start1, size1, start2, size2); if (start1 > 0) { p = &buffer[start1]; result = String(CharPointer_UTF8(p), CharPointer_UTF8(p + size1)); } if (start2 > 0) { p = &buffer[start2]; result += String(CharPointer_UTF8(p), CharPointer_UTF8(p + size2)); } fifo.finishedRead(size1 + size2); return result; } bool LogFifo::hasMessage() { return fifo.getNumReady() > 0; } void setupLogging(Logger* logger) { if (fifo == NULL) fifo = new LogFifo(); Logger::setCurrentLogger(logger, true); } void fifoLogMessage(const String& message) { if (fifo) fifo->logMessage(message); } void relayFifoLogMessages() { if (fifo) fifo->relayMessages(); } <commit_msg>More FIFO logging fixes.<commit_after>#include "SFZDebug.h" static LogFifo* fifo = NULL; LogFifo::LogFifo() : fifo(capacity) { } LogFifo::~LogFifo() { } void LogFifo::logMessage(const String& message) { const char* p; // Stupid String class doesn't really let us get number of bytes. const char* bytes = message.getCharPointer(); unsigned long msgSize = strlen(bytes); int totalSize = sizeof(unsigned long) + msgSize; int start1, size1, start2, size2; fifo.prepareToWrite(totalSize, start1, size1, start2, size2); int givenSize = size1 + size2; if (givenSize < totalSize) msgSize -= givenSize - totalSize; // Write the count. if (size1 >= sizeof(unsigned long)) { memcpy(&buffer[start1], &msgSize, sizeof(unsigned long)); size1 -= sizeof(unsigned long); start1 += sizeof(unsigned long); } else { p = (const char*) &msgSize; memcpy(&buffer[start1], p, size1); p += size1; size1 = 0; int bytesLeft = sizeof(unsigned long) - size1; memcpy(&buffer[start2], p, bytesLeft); start2 += bytesLeft; size2 -= bytesLeft; } // Write the string. p = bytes; if (size1 > 0) { memcpy(&buffer[start1], p, size1); p += size1; } if (size2 > 0) memcpy(&buffer[start2], p, size2); fifo.finishedWrite(givenSize); } void LogFifo::relayMessages() { while (hasMessage()) { String message = nextMessage(); Logger::writeToLog(message); } } String LogFifo::nextMessage() { // Read the count. unsigned long msgSize = 0; int start1, size1, start2, size2; fifo.prepareToRead(sizeof(unsigned long), start1, size1, start2, size2); char* p = (char*) &msgSize; if (size1 > 0) { memcpy(p, &buffer[start1], size1); p += size1; } if (size2 > 0) memcpy(p, &buffer[start2], size2); fifo.finishedRead(size1 + size2); // Read the string. String result; fifo.prepareToRead(msgSize, start1, size1, start2, size2); if (size1 > 0) { p = &buffer[start1]; result = String(CharPointer_UTF8(p), CharPointer_UTF8(p + size1)); } if (size2 > 0) { p = &buffer[start2]; result += String(CharPointer_UTF8(p), CharPointer_UTF8(p + size2)); } fifo.finishedRead(size1 + size2); return result; } bool LogFifo::hasMessage() { return fifo.getNumReady() > 0; } void setupLogging(Logger* logger) { if (fifo == NULL) fifo = new LogFifo(); Logger::setCurrentLogger(logger, true); } void fifoLogMessage(const String& message) { if (fifo) fifo->logMessage(message); } void relayFifoLogMessages() { if (fifo) fifo->relayMessages(); } <|endoftext|>