text
stringlengths
54
60.6k
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/usr/isteps/istep06list.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __ISTEPS_ISTEP6LIST_H #define __ISTEPS_ISTEP6LIST_H /** * @file istep06list.H * * @note IStep definition for Hostboot - Slave SBE * * IStep 06 Slave SBE * IPL FLow Doc v0.95 * * 06.1 host_bootloader * : Host Bootloader (non-executable istep) * 06.2 host_setup * : Setup host environment (non-executable istep) * 06.3 host_istep_enable * : Hostboot istep ready (non-executable istep) * 06.4 host_init_bmc_pcie * : Setup the PCIE to the BMC chip * 06.5 host_init_fsi * : Setup the FSI links to slave chips * 06.6 host_set_ipl_parms * : Build ipl parameters * 06.7 host_discover_targets * : Builds targeting * 06.8 host_update_master_tpm * : Update master TPM * 06.9 host_gard * : Do Gard * 06.10 proc_revert_sbe_mcs_setup * : Clean up MCS extent regs * 06.11 host_start_occ_xstop_handler * : Start OpenPOWER xstop * 06.12 host_setup_voltages * : Set correct chip voltage * */ #include <initservice/initsvcstructs.H> #include <initservice/initsvcreasoncodes.H> namespace ISTEP_06 { /** * @brief host_init_fsi Setup the FSI links to slave chips (istep 6.5) * * Call into the hwas platform-specific initHardware() function * to init the FSI hardware. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_init_fsi( void *io_pArgs ); /** * @brief host_set_ipl_parms Build ipl parameters (istep 6.6) * * TBD * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_set_ipl_parms( void *io_pArgs ); /** * @brief host_discover_targets Builds targeting (istep 6.7) * * This routine will walk through all the targets and initialize HWAS STATE * to a known default value. * * Currently everything is initialized to powered off, etc. * * Call into the hwas platform-specific presenceDetect() function to * read the hardware information, and apply it to the target states. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_discover_targets( void *io_pArgs ); /** * @brief call_host_update_master_tpm (istep 6.8) * * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_update_master_tpm( void *io_pArgs ); /** * @brief host_gard Do Gard (istep 6.9) * * Collect GARD information and apply it to the target states. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_gard( void *io_pArgs ); /** * @brief host_revert_sbe_mcs_setup (istep 6.10) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_revert_sbe_mcs_setup (void * io_pArgs); /** * @brief host_start_occ_xstop_handler (istep 6.11) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_start_occ_xstop_handler (void * io_pArgs); /** * @brief host_voltage_config (istep 6.12) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_voltage_config (void * io_pArgs); }; namespace INITSERVICE { const TaskInfo g_istep06[] = { { "", // dummy, index 0 NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,01,""), // not used. host bootloader NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,02,""), // not used. host setup NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,03,""), // not used. host istep enable NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,04,""), // No support for now. init bmc pcie NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,05,"host_init_fsi"), ISTEP_06::host_init_fsi, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false, BASE_INITIALIZATION } }, { ISTEPNAME(06,06,"host_set_ipl_parms"), ISTEP_06::host_set_ipl_parms, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,07,"host_discover_targets"), ISTEP_06::host_discover_targets, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,08,"host_update_master_tpm"), ISTEP_06::call_host_update_master_tpm, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,09, "host_gard"), ISTEP_06::host_gard, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,10,"host_revert_sbe_mcs_setup"), ISTEP_06::call_host_revert_sbe_mcs_setup, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, { ISTEPNAME(06,11,"host_start_occ_xstop_handler"), ISTEP_06::host_start_occ_xstop_handler, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, { ISTEPNAME(06,12,"host_voltage_config"), ISTEP_06::call_host_voltage_config, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, }; const DepModInfo g_istep06Dependancies = { { DEP_LIB(libistep06.so), #ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS DEP_LIB(libocc.so), #endif NULL } }; const ExtTaskInfo g_istep06TaskList = { &(g_istep06[0]), ( sizeof(g_istep06)/sizeof(TaskInfo) ), &(g_istep06Dependancies), }; }; // end namespace #endif <commit_msg>Minor comment updates for v0.95 IPL Flow<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/usr/isteps/istep06list.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __ISTEPS_ISTEP6LIST_H #define __ISTEPS_ISTEP6LIST_H /** * @file istep06list.H * * @note IStep definition for Hostboot - Slave SBE * * IStep 06 Slave SBE * IPL FLow Doc v0.95 * * 06.1 host_bootloader * : Host Bootloader (non-executable istep) * 06.2 host_setup * : Setup host environment (non-executable istep) * 06.3 host_istep_enable * : Hostboot istep ready (non-executable istep) * 06.4 host_init_bmc_pcie * : Setup the PCIE to the BMC chip * 06.5 host_init_fsi * : Setup the FSI links to slave chips * 06.6 host_set_ipl_parms * : Build ipl parameters * 06.7 host_discover_targets * : Builds targeting * 06.8 host_update_master_tpm * : Update master TPM * 06.9 host_gard * : Do Gard * 06.10 host_revert_sbe_mcs_setup * : Clean up MCS extent regs * 06.11 host_start_occ_xstop_handler * : Start OpenPOWER xstop * 06.12 host_voltage_config * : Calculate correct chip voltage * */ #include <initservice/initsvcstructs.H> #include <initservice/initsvcreasoncodes.H> namespace ISTEP_06 { /** * @brief host_init_fsi Setup the FSI links to slave chips (istep 6.5) * * Call into the hwas platform-specific initHardware() function * to init the FSI hardware. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_init_fsi( void *io_pArgs ); /** * @brief host_set_ipl_parms Build ipl parameters (istep 6.6) * * TBD * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_set_ipl_parms( void *io_pArgs ); /** * @brief host_discover_targets Builds targeting (istep 6.7) * * This routine will walk through all the targets and initialize HWAS STATE * to a known default value. * * Currently everything is initialized to powered off, etc. * * Call into the hwas platform-specific presenceDetect() function to * read the hardware information, and apply it to the target states. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_discover_targets( void *io_pArgs ); /** * @brief call_host_update_master_tpm (istep 6.8) * * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_update_master_tpm( void *io_pArgs ); /** * @brief host_gard Do Gard (istep 6.9) * * Collect GARD information and apply it to the target states. * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_gard( void *io_pArgs ); /** * @brief host_revert_sbe_mcs_setup (istep 6.10) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_revert_sbe_mcs_setup (void * io_pArgs); /** * @brief host_start_occ_xstop_handler (istep 6.11) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* host_start_occ_xstop_handler (void * io_pArgs); /** * @brief host_voltage_config (istep 6.12) * * param[in,out] io_pArgs - (normally) a pointer to a TaskArgs struct, * or NULL. * return any error logs to istep */ void* call_host_voltage_config (void * io_pArgs); }; namespace INITSERVICE { const TaskInfo g_istep06[] = { { "", // dummy, index 0 NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,01,""), // not used. host bootloader NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,02,""), // not used. host setup NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,03,""), // not used. host istep enable NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,04,""), // No support for now. init bmc pcie NULL, { NONE, EXT_IMAGE, IPL_NOOP, false } }, { ISTEPNAME(06,05,"host_init_fsi"), ISTEP_06::host_init_fsi, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false, BASE_INITIALIZATION } }, { ISTEPNAME(06,06,"host_set_ipl_parms"), ISTEP_06::host_set_ipl_parms, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,07,"host_discover_targets"), ISTEP_06::host_discover_targets, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,08,"host_update_master_tpm"), ISTEP_06::call_host_update_master_tpm, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,09, "host_gard"), ISTEP_06::host_gard, { START_FN, EXT_IMAGE, NORMAL_IPL_OP | MPIPL_OP, false } }, { ISTEPNAME(06,10,"host_revert_sbe_mcs_setup"), ISTEP_06::call_host_revert_sbe_mcs_setup, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, { ISTEPNAME(06,11,"host_start_occ_xstop_handler"), ISTEP_06::host_start_occ_xstop_handler, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, { ISTEPNAME(06,12,"host_voltage_config"), ISTEP_06::call_host_voltage_config, { START_FN, EXT_IMAGE, NORMAL_IPL_OP, false } }, }; const DepModInfo g_istep06Dependancies = { { DEP_LIB(libistep06.so), #ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS DEP_LIB(libocc.so), #endif NULL } }; const ExtTaskInfo g_istep06TaskList = { &(g_istep06[0]), ( sizeof(g_istep06)/sizeof(TaskInfo) ), &(g_istep06Dependancies), }; }; // end namespace #endif <|endoftext|>
<commit_before>/* Contains code taken from libuv and node.js */ /* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "stdafx.h" #include "luanode.h" #include "luanode_hrtime.h" #undef NANOSEC #define NANOSEC 1000000000 static const char HRTIME_MT[] = "luanode_hrtime_mt"; #if defined (_WIN32) /* The resolution of the high-resolution clock. */ static boost::uint64_t uv_hrtime_frequency_ = 0; class hrtime_init { public: hrtime_init() { LARGE_INTEGER frequency; if (!::QueryPerformanceFrequency(&frequency)) { uv_hrtime_frequency_ = 0; return; } uv_hrtime_frequency_ = frequency.QuadPart; } }; hrtime_init init; #else # include <time.h> # define __STDC_FORMAT_MACROS # include <inttypes.h> #endif // used in GetHighresTime () below #define NANOS_PER_SEC 1000000000 #if defined (_WIN32) boost::uint64_t LuaNode::HighresTime::Get () { LARGE_INTEGER counter; /* If the performance frequency is zero, there's no support. */ if (!uv_hrtime_frequency_) { /* uv__set_sys_error(loop, ERROR_NOT_SUPPORTED); */ return 0; } if (!::QueryPerformanceCounter(&counter)) { /* uv__set_sys_error(loop, GetLastError()); */ return 0; } /* Because we have no guarantee about the order of magnitude of the */ /* performance counter frequency, and there may not be much headroom to */ /* multiply by NANOSEC without overflowing, we use 128-bit math instead. */ return ((boost::uint64_t) counter.LowPart * NANOSEC / uv_hrtime_frequency_) + (((boost::uint64_t) counter.HighPart * NANOSEC / uv_hrtime_frequency_) << 32); } #else boost::uint64_t LuaNode::HighresTime::Get () { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (ts.tv_sec * NANOSEC + ts.tv_nsec); } #endif ////////////////////////////////////////////////////////////////////////// /// Metamethods for some arithmetic operations static int substract (lua_State* L) { boost::uint64_t t1 = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); boost::uint64_t t2 = *(boost::uint64_t*)luaL_checkudata(L, 2, HRTIME_MT); boost::uint64_t* result = (boost::uint64_t*)lua_newuserdata(L, sizeof(boost::uint64_t)); *result = t1 - t2; luaL_newmetatable(L, HRTIME_MT); lua_setmetatable(L, -2); return 1; } static int less_than (lua_State* L) { boost::uint64_t t1 = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); boost::uint64_t t2 = *(boost::uint64_t*)luaL_checkudata(L, 2, HRTIME_MT); lua_pushboolean(L, (t1 < t2)); return 1; } ////////////////////////////////////////////////////////////////////////// /// Converts the time to a string representation (value in nanoseconds). static int tostring (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); char buffer[32]; #if defined (_WIN32) sprintf(buffer, "%I64u", time); #else sprintf(buffer, "%"PRId64, time); #endif lua_pushstring(L, buffer); return 1; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns its seconds part and its nanoseconds part. int split (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / NANOS_PER_SEC)); lua_pushnumber(L, (lua_Number)(time % NANOS_PER_SEC)); return 2; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns the number of microseconds in it. /// It is safe to return the value as a Lua number since we have enough precision now. /// (2^52) microseconds = 142.713509 years int as_microseconds (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / 1000)); return 1; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns the number of milliseconds in it. /// It is safe to return the value as a Lua number since we have enough precision now. /// (2^52) milliseconds = 142 713.509 years int as_milliseconds (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / 1000000)); return 1; } ////////////////////////////////////////////////////////////////////////// /// The value returned by uv_hrtime() is a 64-bit int representing nanoseconds, /// so this function instead returns a userdata large enought to hold a 64 bit number in it. /// Pass in a userdata from a previous hrtime() call to instead get a time diff. /// int LuaNode::HighresTime::Get (lua_State* L) { boost::uint64_t time = Get(); if(lua_isuserdata(L, 1)) { // Return a timediff userdata boost::uint64_t* start = (boost::uint64_t*)lua_touserdata(L, 1); time -= *start; } boost::uint64_t* result = (boost::uint64_t*)lua_newuserdata(L, sizeof(boost::uint64_t)); *result = time; int pos = lua_gettop(L); if(luaL_newmetatable(L, HRTIME_MT) == 1) { // If the metatable has been created, fill it with our metamethods. int mt = lua_gettop(L); lua_pushcfunction(L, substract); lua_setfield(L, mt, "__sub"); lua_pushcfunction(L, less_than); lua_setfield(L, mt, "__lt"); lua_pushcfunction(L, tostring); lua_setfield(L, mt, "__tostring"); lua_pushcfunction(L, split); lua_setfield(L, mt, "split"); lua_pushcfunction(L, as_microseconds); lua_setfield(L, mt, "us"); lua_pushcfunction(L, as_milliseconds); lua_setfield(L, mt, "ms"); lua_pushvalue(L, mt); lua_setfield(L, mt, "__index"); } lua_setmetatable(L, pos); return 1; } <commit_msg>make NANOSEC a 64 bits unsigned int.<commit_after>/* Contains code taken from libuv and node.js */ /* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "stdafx.h" #include "luanode.h" #include "luanode_hrtime.h" #undef NANOSEC #define NANOSEC ((boost::uint64_t) 1e9) static const char HRTIME_MT[] = "luanode_hrtime_mt"; #if defined (_WIN32) /* The resolution of the high-resolution clock. */ static boost::uint64_t uv_hrtime_frequency_ = 0; class hrtime_init { public: hrtime_init() { LARGE_INTEGER frequency; if (!::QueryPerformanceFrequency(&frequency)) { uv_hrtime_frequency_ = 0; return; } uv_hrtime_frequency_ = frequency.QuadPart; } }; hrtime_init init; #else # include <time.h> # define __STDC_FORMAT_MACROS # include <inttypes.h> #endif // used in GetHighresTime () below #define NANOS_PER_SEC 1000000000 #if defined (_WIN32) boost::uint64_t LuaNode::HighresTime::Get () { LARGE_INTEGER counter; /* If the performance frequency is zero, there's no support. */ if (!uv_hrtime_frequency_) { /* uv__set_sys_error(loop, ERROR_NOT_SUPPORTED); */ return 0; } if (!::QueryPerformanceCounter(&counter)) { /* uv__set_sys_error(loop, GetLastError()); */ return 0; } /* Because we have no guarantee about the order of magnitude of the */ /* performance counter frequency, and there may not be much headroom to */ /* multiply by NANOSEC without overflowing, we use 128-bit math instead. */ return ((boost::uint64_t) counter.LowPart * NANOSEC / uv_hrtime_frequency_) + (((boost::uint64_t) counter.HighPart * NANOSEC / uv_hrtime_frequency_) << 32); } #else boost::uint64_t LuaNode::HighresTime::Get () { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (ts.tv_sec * NANOSEC + ts.tv_nsec); } #endif ////////////////////////////////////////////////////////////////////////// /// Metamethods for some arithmetic operations static int substract (lua_State* L) { boost::uint64_t t1 = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); boost::uint64_t t2 = *(boost::uint64_t*)luaL_checkudata(L, 2, HRTIME_MT); boost::uint64_t* result = (boost::uint64_t*)lua_newuserdata(L, sizeof(boost::uint64_t)); *result = t1 - t2; luaL_newmetatable(L, HRTIME_MT); lua_setmetatable(L, -2); return 1; } static int less_than (lua_State* L) { boost::uint64_t t1 = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); boost::uint64_t t2 = *(boost::uint64_t*)luaL_checkudata(L, 2, HRTIME_MT); lua_pushboolean(L, (t1 < t2)); return 1; } ////////////////////////////////////////////////////////////////////////// /// Converts the time to a string representation (value in nanoseconds). static int tostring (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); char buffer[32]; #if defined (_WIN32) sprintf(buffer, "%I64u", time); #else sprintf(buffer, "%"PRId64, time); #endif lua_pushstring(L, buffer); return 1; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns its seconds part and its nanoseconds part. int split (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / NANOS_PER_SEC)); lua_pushnumber(L, (lua_Number)(time % NANOS_PER_SEC)); return 2; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns the number of microseconds in it. /// It is safe to return the value as a Lua number since we have enough precision now. /// (2^52) microseconds = 142.713509 years int as_microseconds (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / 1000)); return 1; } ////////////////////////////////////////////////////////////////////////// /// Takes a time and returns the number of milliseconds in it. /// It is safe to return the value as a Lua number since we have enough precision now. /// (2^52) milliseconds = 142 713.509 years int as_milliseconds (lua_State* L) { boost::uint64_t time = *(boost::uint64_t*)luaL_checkudata(L, 1, HRTIME_MT); lua_pushnumber(L, (lua_Number)(time / 1000000)); return 1; } ////////////////////////////////////////////////////////////////////////// /// The value returned by uv_hrtime() is a 64-bit int representing nanoseconds, /// so this function instead returns a userdata large enought to hold a 64 bit number in it. /// Pass in a userdata from a previous hrtime() call to instead get a time diff. /// int LuaNode::HighresTime::Get (lua_State* L) { boost::uint64_t time = Get(); if(lua_isuserdata(L, 1)) { // Return a timediff userdata boost::uint64_t* start = (boost::uint64_t*)lua_touserdata(L, 1); time -= *start; } boost::uint64_t* result = (boost::uint64_t*)lua_newuserdata(L, sizeof(boost::uint64_t)); *result = time; int pos = lua_gettop(L); if(luaL_newmetatable(L, HRTIME_MT) == 1) { // If the metatable has been created, fill it with our metamethods. int mt = lua_gettop(L); lua_pushcfunction(L, substract); lua_setfield(L, mt, "__sub"); lua_pushcfunction(L, less_than); lua_setfield(L, mt, "__lt"); lua_pushcfunction(L, tostring); lua_setfield(L, mt, "__tostring"); lua_pushcfunction(L, split); lua_setfield(L, mt, "split"); lua_pushcfunction(L, as_microseconds); lua_setfield(L, mt, "us"); lua_pushcfunction(L, as_milliseconds); lua_setfield(L, mt, "ms"); lua_pushvalue(L, mt); lua_setfield(L, mt, "__index"); } lua_setmetatable(L, pos); return 1; } <|endoftext|>
<commit_before>/** * \file * \brief SignalInformationQueue class implementation * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/internal/synchronization/SignalInformationQueue.hpp" #include "distortos/SignalSet.hpp" namespace distortos { namespace internal { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ SignalInformationQueue::SignalInformationQueue(StorageUniquePointer&& storageUniquePointer, const size_t maxElements) : storageUniquePointer_{std::move(storageUniquePointer)}, signalInformationList_{}, freeSignalInformationList_{} { for (size_t i {}; i < maxElements; ++i) { auto& element = *new (&storageUniquePointer_[i]) QueueNode{{}, {{}, {}, {}}}; freeSignalInformationList_.push_front(element); } } SignalInformationQueue::~SignalInformationQueue() { } std::pair<int, SignalInformation> SignalInformationQueue::acceptQueuedSignal(const uint8_t signalNumber) { auto it = signalInformationList_.before_begin(); auto next = signalInformationList_.begin(); const auto last = signalInformationList_.end(); while (next != last) { if (next->signalInformation.getSignalNumber() == signalNumber) { const auto signalInformation = next->signalInformation; List::splice_after(freeSignalInformationList_.before_begin(), it); return {{}, signalInformation}; } it = next; ++next; } return {EAGAIN, {{}, {}, {}}}; } SignalSet SignalInformationQueue::getQueuedSignalSet() const { SignalSet queuedSignalSet {SignalSet::empty}; for (const auto& node : signalInformationList_) queuedSignalSet.add(node.signalInformation.getSignalNumber()); return queuedSignalSet; } int SignalInformationQueue::queueSignal(const uint8_t signalNumber, const sigval value) { if (signalNumber >= SignalSet::Bitset{}.size()) return EINVAL; if (freeSignalInformationList_.empty() == true) return EAGAIN; auto it = signalInformationList_.before_begin(); auto next = signalInformationList_.begin(); const auto last = signalInformationList_.end(); while (next != last) // find the iterator to the last element on the list ("before end") { it = next; ++next; } freeSignalInformationList_.front().signalInformation = {signalNumber, SignalInformation::Code::Queued, value}; signalInformationList_.splice_after(it, freeSignalInformationList_.before_begin()); return 0; } } // namespace internal } // namespace distortos <commit_msg>SignalInformationQueue: add missing <cerrno> include header<commit_after>/** * \file * \brief SignalInformationQueue class implementation * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/internal/synchronization/SignalInformationQueue.hpp" #include "distortos/SignalSet.hpp" #include <cerrno> namespace distortos { namespace internal { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ SignalInformationQueue::SignalInformationQueue(StorageUniquePointer&& storageUniquePointer, const size_t maxElements) : storageUniquePointer_{std::move(storageUniquePointer)}, signalInformationList_{}, freeSignalInformationList_{} { for (size_t i {}; i < maxElements; ++i) { auto& element = *new (&storageUniquePointer_[i]) QueueNode{{}, {{}, {}, {}}}; freeSignalInformationList_.push_front(element); } } SignalInformationQueue::~SignalInformationQueue() { } std::pair<int, SignalInformation> SignalInformationQueue::acceptQueuedSignal(const uint8_t signalNumber) { auto it = signalInformationList_.before_begin(); auto next = signalInformationList_.begin(); const auto last = signalInformationList_.end(); while (next != last) { if (next->signalInformation.getSignalNumber() == signalNumber) { const auto signalInformation = next->signalInformation; List::splice_after(freeSignalInformationList_.before_begin(), it); return {{}, signalInformation}; } it = next; ++next; } return {EAGAIN, {{}, {}, {}}}; } SignalSet SignalInformationQueue::getQueuedSignalSet() const { SignalSet queuedSignalSet {SignalSet::empty}; for (const auto& node : signalInformationList_) queuedSignalSet.add(node.signalInformation.getSignalNumber()); return queuedSignalSet; } int SignalInformationQueue::queueSignal(const uint8_t signalNumber, const sigval value) { if (signalNumber >= SignalSet::Bitset{}.size()) return EINVAL; if (freeSignalInformationList_.empty() == true) return EAGAIN; auto it = signalInformationList_.before_begin(); auto next = signalInformationList_.begin(); const auto last = signalInformationList_.end(); while (next != last) // find the iterator to the last element on the list ("before end") { it = next; ++next; } freeSignalInformationList_.front().signalInformation = {signalNumber, SignalInformation::Code::Queued, value}; signalInformationList_.splice_after(it, freeSignalInformationList_.before_begin()); return 0; } } // namespace internal } // namespace distortos <|endoftext|>
<commit_before>/* Copyright 2014 DataStax 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. */ #ifndef __CASS_ROUND_ROBIN_POLICY_HPP_INCLUDED__ #define __CASS_ROUND_ROBIN_POLICY_HPP_INCLUDED__ #include "cassandra.h" #include "copy_on_write_ptr.hpp" #include "load_balancing.hpp" #include "host.hpp" #include <algorithm> namespace cass { class RoundRobinPolicy : public LoadBalancingPolicy { public: RoundRobinPolicy() : live_host_addresses_(new AddressVec) , index_(0) {} virtual void init(const HostMap& hosts) { live_host_addresses_->reserve(hosts.size()); for (HostMap::const_iterator it = hosts.begin(), end = hosts.end(); it != end; ++it) { live_host_addresses_->push_back(it->second->address()); } } virtual CassHostDistance distance(const SharedRefPtr<Host>& host) { return CASS_HOST_DISTANCE_LOCAL; } virtual QueryPlan* new_query_plan() { return new RoundRobinQueryPlan(live_host_addresses_, index_++); } virtual void on_add(SharedRefPtr<Host> host) { on_up(host); } virtual void on_remove(SharedRefPtr<Host> host) { on_down(host); } virtual void on_up(SharedRefPtr<Host> host) { AddressVec::iterator it = std::find(live_host_addresses_->begin(), live_host_addresses_->end(), host->address()); if (it == live_host_addresses_->end()) { live_host_addresses_->push_back(host->address()); } } virtual void on_down(SharedRefPtr<Host> host) { AddressVec::iterator it = std::find(live_host_addresses_->begin(), live_host_addresses_->end(), host->address()); if (it != live_host_addresses_->end()) { live_host_addresses_->erase(it); } } virtual LoadBalancingPolicy* new_instance() { return new RoundRobinPolicy(); } private: class RoundRobinQueryPlan : public QueryPlan { public: RoundRobinQueryPlan(const CopyOnWritePtr<AddressVec>& hosts, size_t start_index) : host_addresses_(hosts) , index_(start_index) , remaining_(hosts->size()) {} bool compute_next(Address* address) { if (remaining_ == 0) { return false; } remaining_--; *address = (*host_addresses_)[index_++ % host_addresses_->size()]; return true; } private: const CopyOnWritePtr<AddressVec> host_addresses_; size_t index_; size_t remaining_; }; CopyOnWritePtr<AddressVec> live_host_addresses_; size_t index_; private: DISALLOW_COPY_AND_ASSIGN(RoundRobinPolicy); }; } // namespace cass #endif <commit_msg>Change RR LB to use Host ptr, use state in query plan<commit_after>/* Copyright 2014 DataStax 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. */ #ifndef __CASS_ROUND_ROBIN_POLICY_HPP_INCLUDED__ #define __CASS_ROUND_ROBIN_POLICY_HPP_INCLUDED__ #include "cassandra.h" #include "copy_on_write_ptr.hpp" #include "load_balancing.hpp" #include "host.hpp" #include <algorithm> namespace cass { class RoundRobinPolicy : public LoadBalancingPolicy { public: RoundRobinPolicy() : hosts_(new HostVec) , index_(0) {} virtual void init(const HostMap& hosts) { hosts_->reserve(hosts.size()); for (HostMap::const_iterator it = hosts.begin(), end = hosts.end(); it != end; ++it) { hosts_->push_back(it->second); } } virtual CassHostDistance distance(const SharedRefPtr<Host>& host) { return CASS_HOST_DISTANCE_LOCAL; } virtual QueryPlan* new_query_plan() { return new RoundRobinQueryPlan(hosts_, index_++); } virtual void on_add(SharedRefPtr<Host> host) { HostVec::iterator it; for (it = hosts_->begin(); it != hosts_->end(); ++it) { if ((*it)->address() == host->address()) { (*it) = host; break; } } if (it == hosts_->end()) { hosts_->push_back(host); } } virtual void on_remove(SharedRefPtr<Host> host) { for (HostVec::iterator it = hosts_->begin(); it != hosts_->end(); ++it) { if ((*it)->address() == host->address()) { hosts_->erase(it); break; } } } // up/down Host state managed through session virtual void on_up(SharedRefPtr<Host> host) {} virtual void on_down(SharedRefPtr<Host> host) {} virtual LoadBalancingPolicy* new_instance() { return new RoundRobinPolicy(); } private: class RoundRobinQueryPlan : public QueryPlan { public: RoundRobinQueryPlan(const CopyOnWritePtr<HostVec>& hosts, size_t start_index) : hosts_(hosts) , index_(start_index) , remaining_(hosts->size()) {} bool compute_next(Address* address) { while (remaining_ > 0) { --remaining_; const SharedRefPtr<Host>& host((*hosts_)[index_++ % hosts_->size()]); if (host->is_up()) { *address = host->address(); return true; } if (!observed_down_.insert(host->address()).second) { ++remaining_;// don't count same host against this plan } index_ += rand()%remaining_;// hot-spot mitigation for small clusters } return false; } private: const CopyOnWritePtr<HostVec> hosts_; size_t index_; size_t remaining_; std::set<Address> observed_down_; }; CopyOnWritePtr<HostVec> hosts_; size_t index_; private: DISALLOW_COPY_AND_ASSIGN(RoundRobinPolicy); }; } // namespace cass #endif <|endoftext|>
<commit_before>/* * sim900_Suli.cpp * A library for SeeedStudio seeeduino GPRS shield * * Copyright (c) 2014 seeed technology inc. * Website : www.seeed.cc * Author : lawliet zou * Create Time: April 2015 * Change Log : * * The MIT License (MIT) * * 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 "sim900_Suli.h" SoftwareSerial *serialSIM900 = NULL; void sim900_init(void * uart_device, int16 uart_num, uint32 baud) { serialSIM900 = (SoftwareSerial*)uart_device; suli_uart_init(uart_device, uart_num, baud); } char sim900_read_byte(void) { return suli_uart_read_byte(serialSIM900,-1); } int sim900_check_readable() { return suli_uart_readable(serialSIM900,-1); } //Just in case, you need to used UNSIGNED LONG not to have problems after 51 days) //Also you need one variable less int sim900_wait_readable (int wait_time) { unsigned long timerStart; //,timerEnd; int dataLen = 0; timerStart = suli_millis(); //timerEnd = 1000*wait_time + timerStart; while((unsigned long) (suli_millis() - timerStart) > wait_time * 1000UL) { suli_delay_ms(500); dataLen = suli_uart_readable(serialSIM900,-1); if(dataLen > 0){ break; } } return dataLen; } void sim900_flush_serial() { while(suli_uart_readable(serialSIM900,-1)){ char c = suli_uart_read_byte(serialSIM900,-1); } } //Just in case, you need to used UNSIGNED LONG not to have problems after 51 days) //Also you need one variable less // CHANGE 1. Not to wait always full DEFAULT_TIMEOUT int sim900_read_buffer(char *buffer,int count, unsigned int timeout, unsigned int chartimeout) { int i = 0; unsigned long timerStart, prevChar; //,timerEnd; timerStart = suli_millis(); prevChar = 0; //timerEnd = 1000*timeOut + timerStart; while(1) { #if false //23/03/2015 WHY CAN YOU USE THIS IF IN sim900_wait_for_resp ARE YOU USING IT ? while (suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); prevChar = suli_millis(); buffer[i++] = c; if(i >= count)break; } if(i >= count)break; //if(millis() > timerEnd) { // break; //} if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { break; } //If interchar Timeout => return FALSE. So we can return sooner from this function. Not DO it if we dont recieve at least one char (prevChar <> 0) if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { break; } #else /** Anyway, Suli is not quickly enough to fetch data from buffer, so we have to fetch our data like this.*/ //23/03/2015 WHY THIS IF IN sim900_wait_for_resp ARE YOU USING IT ? while (serialSIM900->available()) { char c = serialSIM900->read(); prevChar = suli_millis(); buffer[i++] = c; if(i >= count)break; } if(i >= count)break; //if(millis() > timerEnd) { // break; //} if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { break; } //If interchar Timeout => return FALSE. So we can return sooner from this function. if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { break; } #endif } return 0; } void sim900_clean_buffer(char *buffer, int count) { for(int i=0; i < count; i++) { buffer[i] = '\0'; } //en una prueba para un buffer de 32 characteres, repetido 1000 veces, sim900_clean_buffer tarda 236 milisegundos, y // memset(gprsBuffer,'\0',32); tarda 107 milisegundos solo. } void sim900_send_cmd(const char* cmd) { suli_uart_send(serialSIM900, -1, (uint8_t*)cmd, strlen(cmd)); } // New functions to use F() void sim900_send_cmd(const __FlashStringHelper* cmd) { int i = 0; const char *ptr = (const char *) cmd; while (pgm_read_byte(ptr + i) != 0x00) { suli_uart_send_byte(serialSIM900, -1, pgm_read_byte(ptr + i++)); } } // New functions to use PROGMEM strings void sim900_send_cmd_P(const char* cmd) { while (pgm_read_byte(cmd) != 0x00) suli_uart_send_byte(serialSIM900, -1, pgm_read_byte(cmd++)); } // New functions to use CHARs void sim900_send_char(const char c) { suli_uart_send_byte(serialSIM900, -1, c); } void sim900_send_AT(void) { sim900_check_with_cmd("AT\r\n","OK",CMD); } /* NOT USED bool sim900_response_cmp(uint8_t* resp, unsigned int len, unsigned int timeout) { int sum=0; unsigned long timerStart,timerEnd; timerStart = suli_millis(); timerEnd = 1000*timeout + timerStart; while(1) { if(suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); sum = (c==resp[sum]) ? sum+1 : 0; if(sum == len)break; } if(suli_millis() > timerEnd) { return false; } } return true; } */ //Just in case, you need to used UNSIGNED LONG not to have problems after 51 days) //Also you need one variable less // CHANGE 1. Not to wait always full DEFAULT_TIMEOUT int sim900_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout) { int len = strlen(resp); int sum = 0; //unsigned long timerStart,timerEnd, prevChar; //prevChar is the time when the previous Char has been read. unsigned long timerStart, prevChar; //prevChar is the time when the previous Char has been read. timerStart = suli_millis(); prevChar = 0; // timerEnd = 1000*timeout + timerStart; while(1) { if(suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); prevChar = suli_millis(); sum = (c==resp[sum]) ? sum+1 : 0; if(sum == len)break; } if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { //if(suli_millis() > timerEnd) { return -1; } //If interchar Timeout => return FALSE. So we can return sooner from this function. if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { return -2; } } //If is a CMD, we will finish to read buffer. if(type == CMD) sim900_flush_serial(); return 0; } void sim900_send_End_Mark(void) { suli_uart_send_byte(serialSIM900,-1,(char)26); } // CHANGE 1. Not to wait always full DEFAULT_TIMEOUT int sim900_check_with_cmd(const char* cmd, const char *resp, DataType type, unsigned int timeout, unsigned int chartimeout) { sim900_send_cmd(cmd); return sim900_wait_for_resp(resp,type,timeout,chartimeout); } //FUTURE esto vale para algo en cadenas de texto tan cortas ??? /*int sim900_check_with_cmd(const __FlashStringHelper* cmd, const char *resp, unsigned timeout, DataType type) { sim900_send_cmd(cmd); return sim900_wait_for_resp(resp,timeout,type); }*/ <commit_msg>Version 0.7<commit_after>/* * sim900_Suli.cpp * A library for SeeedStudio seeeduino GPRS shield * * Copyright (c) 2014 seeed technology inc. * Website : www.seeed.cc * Author : lawliet zou * Create Time: April 2015 * Change Log : * * The MIT License (MIT) * * 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 "sim900_Suli.h" SoftwareSerial *serialSIM900 = NULL; void sim900_init(void * uart_device, int16 uart_num, uint32 baud) { serialSIM900 = (SoftwareSerial*)uart_device; suli_uart_init(uart_device, uart_num, baud); } char sim900_read_byte(void) { return suli_uart_read_byte(serialSIM900,-1); } int sim900_check_readable() { return suli_uart_readable(serialSIM900,-1); } int sim900_wait_readable (int wait_time) { unsigned long timerStart; //,timerEnd; int dataLen = 0; timerStart = suli_millis(); //timerEnd = 1000*wait_time + timerStart; while((unsigned long) (suli_millis() - timerStart) > wait_time * 1000UL) { suli_delay_ms(500); dataLen = suli_uart_readable(serialSIM900,-1); if(dataLen > 0){ break; } } return dataLen; } void sim900_flush_serial() { while(suli_uart_readable(serialSIM900,-1)){ char c = suli_uart_read_byte(serialSIM900,-1); } } int sim900_read_buffer(char *buffer,int count, unsigned int timeout, unsigned int chartimeout) { int i = 0; unsigned long timerStart, prevChar; //,timerEnd; timerStart = suli_millis(); prevChar = 0; //timerEnd = 1000*timeOut + timerStart; while(1) { #if false //23/03/2015 WHY CAN YOU USE THIS IF IN sim900_wait_for_resp ARE YOU USING IT ? while (suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); prevChar = suli_millis(); buffer[i++] = c; if(i >= count)break; } if(i >= count)break; //if(millis() > timerEnd) { // break; //} if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { break; } //If interchar Timeout => return FALSE. So we can return sooner from this function. Not DO it if we dont recieve at least one char (prevChar <> 0) if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { break; } #else /** Anyway, Suli is not quickly enough to fetch data from buffer, so we have to fetch our data like this.*/ //23/03/2015 WHY THIS IF IN sim900_wait_for_resp ARE YOU USING IT ? while (serialSIM900->available()) { char c = serialSIM900->read(); prevChar = suli_millis(); buffer[i++] = c; if(i >= count)break; } if(i >= count)break; //if(millis() > timerEnd) { // break; //} if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { break; } //If interchar Timeout => return FALSE. So we can return sooner from this function. if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { break; } #endif } return 0; } void sim900_clean_buffer(char *buffer, int count) { for(int i=0; i < count; i++) { buffer[i] = '\0'; } } void sim900_send_cmd(const char* cmd) { suli_uart_send(serialSIM900, -1, (uint8_t*)cmd, strlen(cmd)); } void sim900_send_cmd(const __FlashStringHelper* cmd) { int i = 0; const char *ptr = (const char *) cmd; while (pgm_read_byte(ptr + i) != 0x00) { suli_uart_send_byte(serialSIM900, -1, pgm_read_byte(ptr + i++)); } } void sim900_send_cmd_P(const char* cmd) { while (pgm_read_byte(cmd) != 0x00) suli_uart_send_byte(serialSIM900, -1, pgm_read_byte(cmd++)); } void sim900_send_char(const char c) { suli_uart_send_byte(serialSIM900, -1, c); } void sim900_send_AT(void) { sim900_check_with_cmd("AT\r\n","OK",CMD); } /* NOT USED bool sim900_response_cmp(uint8_t* resp, unsigned int len, unsigned int timeout) { int sum=0; unsigned long timerStart,timerEnd; timerStart = suli_millis(); timerEnd = 1000*timeout + timerStart; while(1) { if(suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); sum = (c==resp[sum]) ? sum+1 : 0; if(sum == len)break; } if(suli_millis() > timerEnd) { return false; } } return true; } */ int sim900_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout) { int len = strlen(resp); int sum = 0; //unsigned long timerStart,timerEnd, prevChar; //prevChar is the time when the previous Char has been read. unsigned long timerStart, prevChar; //prevChar is the time when the previous Char has been read. timerStart = suli_millis(); prevChar = 0; // timerEnd = 1000*timeout + timerStart; while(1) { if(suli_uart_readable(serialSIM900,-1)) { char c = suli_uart_read_byte(serialSIM900,-1); prevChar = suli_millis(); sum = (c==resp[sum]) ? sum+1 : 0; if(sum == len)break; } if ((unsigned long) (suli_millis() - timerStart) > timeout * 1000UL) { //if(suli_millis() > timerEnd) { return -1; } //If interchar Timeout => return FALSE. So we can return sooner from this function. if (((unsigned long) (suli_millis() - prevChar) > chartimeout) && (prevChar != 0)) { return -2; } } //If is a CMD, we will finish to read buffer. if(type == CMD) sim900_flush_serial(); return 0; } void sim900_send_End_Mark(void) { suli_uart_send_byte(serialSIM900,-1,(char)26); } int sim900_check_with_cmd(const char* cmd, const char *resp, DataType type, unsigned int timeout, unsigned int chartimeout) { sim900_send_cmd(cmd); return sim900_wait_for_resp(resp,type,timeout,chartimeout); } //FUTURE esto vale para algo en cadenas de texto tan cortas ??? /*int sim900_check_with_cmd(const __FlashStringHelper* cmd, const char *resp, unsigned timeout, DataType type) { sim900_send_cmd(cmd); return sim900_wait_for_resp(resp,timeout,type); }*/ <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- crypto/task.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 <config-kleopatra.h> #include "task.h" #include <utils/exception.h> #include <utils/gnupg-helper.h> #include <gpgme++/exception.h> #include <gpg-error.h> #include <KIconLoader> #include <KLocale> #include <QString> #include <boost/bind.hpp> using namespace Kleo; using namespace Kleo::Crypto; using namespace boost; using namespace GpgME; namespace { class ErrorResult : public Task::Result { public: ErrorResult( int code, const QString & details ) : Task::Result(), m_code( code ), m_details( details ) {} /* reimp */ QString overview() const { return makeSimpleOverview( m_details, Error ); } /* reimp */ QString details() const { return QString(); } /* reimp */ int errorCode() const { return m_code; } /* reimp */ QString errorString() const { return m_details; } private: int m_code; QString m_details; }; } class Task::Private { friend class ::Kleo::Crypto::Task; Task * const q; public: explicit Private( Task * qq ); private: QString m_progressLabel; int m_processedSize; int m_totalSize; }; Task::Private::Private( Task * qq ) : q( qq ), m_progressLabel(), m_processedSize( 0 ), m_totalSize( 0 ) { } Task::Task( QObject * p ) : QObject( p ), d( new Private( this ) ) { } Task::~Task() {} int Task::processedSize() const { return d->m_processedSize; } int Task::totalSize() const { return d->m_totalSize; } QString Task::progressLabel() const { d->m_progressLabel; } void Task::setProgress( const QString & label, int processed, int total ) { if ( processed == d->m_processedSize && total == d->m_totalSize && d->m_progressLabel == label ) return; d->m_processedSize = processed; d->m_totalSize == total; d->m_progressLabel = label; emit progress( label, processed, total ); } void Task::start() { try { doStart(); } catch ( const Kleo::Exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, e.error().encodedError() ), Q_ARG( QString, e.message() ) ); } catch ( const GpgME::Exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, e.error().encodedError() ), Q_ARG( QString, QString::fromLocal8Bit( e.what() ) ) ); } catch ( const std::exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, makeGnuPGError( GPG_ERR_UNEXPECTED ) ), Q_ARG( QString, QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, makeGnuPGError( GPG_ERR_UNEXPECTED ) ), Q_ARG( QString, i18n( "Unknown exception in Task::start()") ) ); } emit started(); } void Task::emitError( int errCode, const QString& details ) { emit result( makeErrorResult( errCode, details ) ); } boost::shared_ptr<Task::Result> Task::makeErrorResult( int errCode, const QString& details ) { return boost::shared_ptr<Task::Result>( new ErrorResult( errCode, details ) ); } static QString makeNonce() { // ### make better return QString::number( qrand(), 16 ); } Task::Result::Result() : m_nonce( makeNonce() ) {} Task::Result::~Result() {} QString Task::Result::formatKeyLink( const char * fpr, const QString & content ) const { return "<a href=\"key:" + m_nonce + ':' + fpr + "\">" + content + "</a>"; } bool Task::Result::hasError() const { return errorCode() != 0; } static QString image( const char* img ) { // ### escape? return KIconLoader::global()->iconPath( img, KIconLoader::Small ); } QString Task::Result::makeSimpleOverview( const QString& desc, ErrorLevel level ) { QString img; switch ( level ) { case Error: img = image( "dialog-error" ); break; case NoError: img = image( "dialog-ok" ); break; case Warning: img = image( "dialog-warning" ); break; } return QString( "<img src=\"%1\"/><b>%2</b>" ).arg( img, desc ); } #include "moc_task.cpp" <commit_msg>Make it compile<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- crypto/task.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 <config-kleopatra.h> #include "task.h" #include <utils/exception.h> #include <utils/gnupg-helper.h> #include <gpgme++/exception.h> #include <gpg-error.h> #include <KIconLoader> #include <KLocale> #include <QString> #include <boost/bind.hpp> using namespace Kleo; using namespace Kleo::Crypto; using namespace boost; using namespace GpgME; namespace { class ErrorResult : public Task::Result { public: ErrorResult( int code, const QString & details ) : Task::Result(), m_code( code ), m_details( details ) {} /* reimp */ QString overview() const { return makeSimpleOverview( m_details, Error ); } /* reimp */ QString details() const { return QString(); } /* reimp */ int errorCode() const { return m_code; } /* reimp */ QString errorString() const { return m_details; } private: int m_code; QString m_details; }; } class Task::Private { friend class ::Kleo::Crypto::Task; Task * const q; public: explicit Private( Task * qq ); private: QString m_progressLabel; int m_processedSize; int m_totalSize; }; Task::Private::Private( Task * qq ) : q( qq ), m_progressLabel(), m_processedSize( 0 ), m_totalSize( 0 ) { } Task::Task( QObject * p ) : QObject( p ), d( new Private( this ) ) { } Task::~Task() {} int Task::processedSize() const { return d->m_processedSize; } int Task::totalSize() const { return d->m_totalSize; } QString Task::progressLabel() const { return d->m_progressLabel; } void Task::setProgress( const QString & label, int processed, int total ) { if ( processed == d->m_processedSize && total == d->m_totalSize && d->m_progressLabel == label ) return; d->m_processedSize = processed; d->m_totalSize == total; d->m_progressLabel = label; emit progress( label, processed, total ); } void Task::start() { try { doStart(); } catch ( const Kleo::Exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, e.error().encodedError() ), Q_ARG( QString, e.message() ) ); } catch ( const GpgME::Exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, e.error().encodedError() ), Q_ARG( QString, QString::fromLocal8Bit( e.what() ) ) ); } catch ( const std::exception & e ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, makeGnuPGError( GPG_ERR_UNEXPECTED ) ), Q_ARG( QString, QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { QMetaObject::invokeMethod( this, "emitError", Qt::QueuedConnection, Q_ARG( int, makeGnuPGError( GPG_ERR_UNEXPECTED ) ), Q_ARG( QString, i18n( "Unknown exception in Task::start()") ) ); } emit started(); } void Task::emitError( int errCode, const QString& details ) { emit result( makeErrorResult( errCode, details ) ); } boost::shared_ptr<Task::Result> Task::makeErrorResult( int errCode, const QString& details ) { return boost::shared_ptr<Task::Result>( new ErrorResult( errCode, details ) ); } static QString makeNonce() { // ### make better return QString::number( qrand(), 16 ); } Task::Result::Result() : m_nonce( makeNonce() ) {} Task::Result::~Result() {} QString Task::Result::formatKeyLink( const char * fpr, const QString & content ) const { return "<a href=\"key:" + m_nonce + ':' + fpr + "\">" + content + "</a>"; } bool Task::Result::hasError() const { return errorCode() != 0; } static QString image( const char* img ) { // ### escape? return KIconLoader::global()->iconPath( img, KIconLoader::Small ); } QString Task::Result::makeSimpleOverview( const QString& desc, ErrorLevel level ) { QString img; switch ( level ) { case Error: img = image( "dialog-error" ); break; case NoError: img = image( "dialog-ok" ); break; case Warning: img = image( "dialog-warning" ); break; } return QString( "<img src=\"%1\"/><b>%2</b>" ).arg( img, desc ); } #include "moc_task.cpp" <|endoftext|>
<commit_before>#include <stdexcept> #include "FractalGenerator.h" #include "math_utils.h" /* * Public member functions */ FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate, void (*doneCallback)(v8::Isolate *isolate, v8::Local<v8::Object> nodeBuffer, bool halted, void *doneCallbackData), v8::Local<v8::Object> buf, void *doneCallbackData, int width, int height, double fractalWidth, double fractalHeight, double fracgtalX, double fractalY, int iterations) : id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width( width), height(height), fractalWidth(fractalWidth), fractalHeight( fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations( iterations) { if (node::Buffer::Length(buf) < (width * height * 4)) { throw new std::invalid_argument( "node::Buffer::Length(buf) < (width * height * 4)"); } nodeBuffer = new v8::Global<v8::Object>; nodeBuffer->Reset(isolate, buf); buffer = node::Buffer::Data(buf); doneAsync = new uv_async_t; doneAsync->data = this; uv_loop_t *loop = uv_default_loop(); uv_async_init(loop, doneAsync, doneAsyncCallback); } FractalGenerator::~FractalGenerator() { nodeBuffer->Reset(); delete nodeBuffer; delete doneAsync; } void FractalGenerator::start() { thread = new std::thread(&FractalGenerator::threadFunction, this); } void FractalGenerator::halt() { halting.store(true); } int FractalGenerator::getProgress() { return progress.load(); } bool FractalGenerator::isGenerating() { return generating.load(); } /* * Private member functions */ void FractalGenerator::doneAsyncCallback(uv_async_t *handle) { FractalGenerator *self = ((FractalGenerator *) handle->data); v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); (*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate), self->halting.load(), self->doneCallbackData); self->nodeBuffer->Reset(); } void FractalGenerator::threadFunction() { // build fractal here and call uv_async_send when done generating.store(true); progress.store(0); // does this make things faster or is this redundant with g++ optimization? float fx, fy, a, b, aa, bb, twoab; int x, y, i, n; RGBData color; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { if (halting.load()) { generating.store(false); uv_async_send(doneAsync); return; } // get buffer index i = x + y * width; // pixel value generation fx = x * fractalWidth / width + fractalX; fy = y * fractalHeight / height + fractalY; // z = (a + bi) a = fx; b = fy; for (n = 0; n < iterations; n++) { // z = z * z aa = a * a; bb = b * b; twoab = 2.0f * a * b; a = aa - bb + fx; b = twoab + fy; // if old sqrt(a * a + b * b) > 4 // z is outside a circle with radius 4 in the complex plane if (aa + bb > 16) { break; } } // pixel coloring if (n < iterations) { // magic numbers color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f, mod2(n * 16.0f, 0, 256.0f) / 256.0f); buffer[i] = color.r; buffer[i + 1] = color.g; buffer[i + 2] = color.b; buffer[i + 3] = 0xFF; } else { buffer[i] = 0x00; buffer[i + 1] = 0x00; buffer[i + 2] = 0x00; buffer[i + 3] = 0xFF; } progress++; } } // set status generating.store(false); // send callback uv_async_send(doneAsync); } <commit_msg>Buffer is re-created if invalid<commit_after>#include <stdexcept> #include "FractalGenerator.h" #include "math_utils.h" /* * Public member functions */ FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate, void (*doneCallback)(v8::Isolate *isolate, v8::Local<v8::Object> nodeBuffer, bool halted, void *doneCallbackData), v8::Local<v8::Object> buf, void *doneCallbackData, int width, int height, double fractalWidth, double fractalHeight, double fracgtalX, double fractalY, int iterations) : id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width( width), height(height), fractalWidth(fractalWidth), fractalHeight( fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations( iterations) { if (buf->IsNull() || buf->IsUndefined() || node::Buffer::Length(buf) < (width * height * 4)) { buf = Nan::NewBuffer(width * height * 4); } nodeBuffer = new v8::Global<v8::Object>; nodeBuffer->Reset(isolate, buf); buffer = node::Buffer::Data(buf); doneAsync = new uv_async_t; doneAsync->data = this; uv_loop_t *loop = uv_default_loop(); uv_async_init(loop, doneAsync, doneAsyncCallback); } FractalGenerator::~FractalGenerator() { nodeBuffer->Reset(); delete nodeBuffer; delete doneAsync; } void FractalGenerator::start() { thread = new std::thread(&FractalGenerator::threadFunction, this); } void FractalGenerator::halt() { halting.store(true); } int FractalGenerator::getProgress() { return progress.load(); } bool FractalGenerator::isGenerating() { return generating.load(); } /* * Private member functions */ void FractalGenerator::doneAsyncCallback(uv_async_t *handle) { FractalGenerator *self = ((FractalGenerator *) handle->data); v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); (*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate), self->halting.load(), self->doneCallbackData); self->nodeBuffer->Reset(); } void FractalGenerator::threadFunction() { // build fractal here and call uv_async_send when done generating.store(true); progress.store(0); // does this make things faster or is this redundant with g++ optimization? float fx, fy, a, b, aa, bb, twoab; int x, y, i, n; RGBData color; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { if (halting.load()) { generating.store(false); uv_async_send(doneAsync); return; } // get buffer index i = x + y * width; // pixel value generation fx = x * fractalWidth / width + fractalX; fy = y * fractalHeight / height + fractalY; // z = (a + bi) a = fx; b = fy; for (n = 0; n < iterations; n++) { // z = z * z aa = a * a; bb = b * b; twoab = 2.0f * a * b; a = aa - bb + fx; b = twoab + fy; // if old sqrt(a * a + b * b) > 4 // z is outside a circle with radius 4 in the complex plane if (aa + bb > 16) { break; } } // pixel coloring if (n < iterations) { // magic numbers color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f, mod2(n * 16.0f, 0, 256.0f) / 256.0f); buffer[i] = color.r; buffer[i + 1] = color.g; buffer[i + 2] = color.b; buffer[i + 3] = 0xFF; } else { buffer[i] = 0x00; buffer[i + 1] = 0x00; buffer[i + 2] = 0x00; buffer[i + 3] = 0xFF; } progress++; } } // set status generating.store(false); // send callback uv_async_send(doneAsync); } <|endoftext|>
<commit_before>#include "main.h" #include "config.h" #include "mainframe_impl.h" #include "aboutdlg_impl.h" #include "serverdlg_impl.h" #include "updatingdlg_impl.h" #include "listserverhandler.h" #include "serverping.h" static int SortHelper(int res, bool reverse=false) { if(res==0) return res; if(reverse) return res*(-1); return res; } static int wxCALLBACK ServerSortCallback(long item1, long item2, long col) { Server* s1 = reinterpret_cast<Server*>(item1); Server* s2 = reinterpret_cast<Server*>(item2); // Make sure fav's are placed at the top, no matter what if(s1->favorite && !s2->favorite) return -1; if(s2->favorite && !s1->favorite) return 1; bool ascending = (col<0); col = abs(col); switch(col) { case 1: // ServerHostPort return SortHelper(s1->serverHostPort.CmpNoCase(s2->serverHostPort),ascending); break; case 2: // Name return SortHelper(s1->name.CmpNoCase(s2->name),ascending); break; case 3: // Type return SortHelper(s1->GetType().CmpNoCase(s2->GetType()),ascending); break; case 4: // Players { int r=0; if(s1->GetPlayerCount() < s2->GetPlayerCount()) r = -1; else if(s1->GetPlayerCount() > s2->GetPlayerCount()) r = 1; return SortHelper(r,ascending); } break; case 5: // Ping { int r = 0; if(s1->ping.getDuration() < s2->ping.getDuration()) r = -1; else if(s1->ping.getDuration() > s2->ping.getDuration()) r = -1; return SortHelper(r,ascending); } break; default: return 0; break; } return -1; } MainFrameImpl::MainFrameImpl( wxWindow* parent ) : MainFrame( parent ), initialLoadTimer(this) { ServerPingTracker::receiver = this; this->toolBar->SetToolBitmapSize(wxSize(32,32)); this->toolBar->Realize(); this->SetSize(this->DetermineFrameSize()); this->SetupColumns(); this->m_currentSortMode = appConfig.getSortMode(); this->favoriteServers = appConfig.getFavorites(); this->serverList->SetFocus(); this->Connect( this->initialLoadTimer.GetId(), wxEVT_TIMER, wxTimerEventHandler(MainFrameImpl::EventTimer)); this->Connect( wxID_ANY, wxEVT_PING_CHANGED, wxCommandEventHandler(MainFrameImpl::EventPingChanged)); this->initialLoadTimer.Start(300,true); this->pingTimer.Start(10); } MainFrameImpl::~MainFrameImpl() { for(int col = 0; col < Config::COL_COUNT; col++) appConfig.setColumnWidth(Config::ColType(col), this->serverList->GetColumnWidth(col)); appConfig.setFavorites(this->favoriteServers); appConfig.setWindowDimensions(GetRect()); appConfig.setSortMode(this->m_currentSortMode); } void MainFrameImpl::SetupColumns() { wxString names[] = { _("Server"), _("Name"), _("Type"), _("#"), _("Ping"), _("Fav") }; for(int col = 0; col < Config::COL_COUNT; col++) { this->serverList->InsertColumn(col,names[col]); this->serverList->SetColumnWidth(col,appConfig.getColumnWidth(Config::ColType(col))); } } wxRect MainFrameImpl::DetermineFrameSize() const { const int minFrameW = 300; const int minFrameH = 300; wxSize scr = wxGetDisplaySize(); wxRect wanted = appConfig.getWindowDimensions(); // Check values wanted.x = wxMin(abs(wanted.x), scr.x - minFrameW); wanted.y = wxMin(abs(wanted.y), scr.y - minFrameH); wanted.height = wxMax(wanted.height, minFrameH); wanted.height = wxMin(wanted.height, scr.x - wanted.x); wanted.width = wxMax(wanted.width, minFrameW); wanted.width = wxMin(wanted.width, scr.y - wanted.y); return wanted; } void MainFrameImpl::SetStatusText(const wxString& t) { this->statusBar->SetStatusText(t); } void MainFrameImpl::EventRefresh(wxCommandEvent&) { this->RefreshServerGrid(); } void MainFrameImpl::RefreshServerGrid() { UpdatingDlgImpl dlg(this); dlg.Show(); BZLauncherApp& app = wxGetApp(); app.RefreshServerList(); wxListCtrl* list = this->serverList; list->DeleteAllItems(); // Content ServerList::iterator i; int idx = 0; for(i = app.listServerHandler.serverList.begin(); i != app.listServerHandler.serverList.end(); ++i) { dlg.Pulse(); Server* current = *i; // Check if its a favorite current->favorite = (this->favoriteServers.Index(current->serverHostPort) != wxNOT_FOUND); // Server list->InsertItem(idx, current->serverHostPort); list->SetItemPtrData(idx,reinterpret_cast<wxUIntPtr>(current)); // Name list->SetItem(idx, 1, current->name); // Type list->SetItem(idx, 2, current->GetType()); // Player Count list->SetItem(idx, 3, wxString::Format(_T("%d"), current->GetPlayerCount())); // Ping list->SetItem(idx, 4, _("n/a")); // Favorite this->UpdateServer(idx,current); idx++; } dlg.Pulse(); this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); dlg.Pulse(); } void MainFrameImpl::EventShowAbout(wxCommandEvent&) { AboutDlgImpl dlg(this); dlg.ShowModal(); } void MainFrameImpl::EventQuit(wxCommandEvent&) { this->Close(); } void MainFrameImpl::EventViewServer(wxCommandEvent&) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { ServerDlgImpl dlg(this, s); dlg.ShowModal(); } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::EventSelectServer(wxListEvent& event) { Server* srv = reinterpret_cast<Server*>(event.GetData()); const wxString s = srv->serverHostPort; wxGetApp().SetSelectedServer(s); } void MainFrameImpl::EventRightClick(wxListEvent& WXUNUSED(event)) { this->PopupMenu(this->serverMenu); } void MainFrameImpl::EventActivated(wxListEvent& WXUNUSED(event)) { this->LaunchGame(); } void MainFrameImpl::EventLaunch(wxCommandEvent& WXUNUSED(event)) { this->LaunchGame(); } void MainFrameImpl::LaunchGame() { BZLauncherApp& app = wxGetApp(); app.LaunchSelectedServer(this); } void MainFrameImpl::EventColClick(wxListEvent& event) { if(abs(this->m_currentSortMode) == (event.GetColumn()+1)) this->m_currentSortMode *= -1; else this->m_currentSortMode = event.GetColumn()+1; this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); } void MainFrameImpl::EventFavoriteToggle(wxCommandEvent& WXUNUSED(event)) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { if(s->favorite) { // Remove from favoriteServers s->favorite = false; this->favoriteServers.Remove(s->serverHostPort); } else { // Add to favoriteServers s->favorite = true; this->favoriteServers.Add(s->serverHostPort); } int idx = this->serverList->GetNextItem(-1,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED); if(idx==-1) { app.SetStatusText(_("Couldnt find row! :(")); } else { this->UpdateServer(idx,s); this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); } } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::UpdateServer(int idx, Server* s) { if(s->favorite) { this->serverList->SetItemFont(idx, wxFont( 8, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans") )); this->serverList->SetItem(idx, 5, _("Yes")); } else { this->serverList->SetItemFont(idx, wxFont( 8, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Sans") )); this->serverList->SetItem(idx, 5, _("No")); } if(s->ping.isOK()) { this->serverList->SetItem(idx, 4, wxString::Format(_T("%d"), s->ping.getDuration())); } else { this->serverList->SetItem(idx, 4, _("n/a")); } } void MainFrameImpl::EventPingServer(wxCommandEvent& WXUNUSED(event)) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { s->ping.ping(); } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::EventTimer(wxTimerEvent& WXUNUSED(event)) { this->RefreshServerGrid(); } void MainFrameImpl::EventPingChanged(wxCommandEvent& event) { wxIPV4address ip; long port = 5154; int pos; if((pos = event.GetString().Find(':',true)) != wxNOT_FOUND) { if(!event.GetString().Mid(pos+1).ToLong(&port)) port = 5154; ip.Hostname(event.GetString().Mid(0,pos)); } else { ip.Hostname(event.GetString()); } ip.Service(port); long item = -1; for ( ;; ) { item = this->serverList->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE); if(item == -1) break; Server* current = reinterpret_cast<Server*>(this->serverList->GetItemData(item)); if(current->ip.IPAddress() == ip.IPAddress() && current->ip.Service() && ip.Service()) { this->UpdateServer(item, current); } } } <commit_msg>Fixed ping-sorting<commit_after>#include "main.h" #include "config.h" #include "mainframe_impl.h" #include "aboutdlg_impl.h" #include "serverdlg_impl.h" #include "updatingdlg_impl.h" #include "listserverhandler.h" #include "serverping.h" static int SortHelper(int res, bool reverse=false) { if(res==0) return res; if(reverse) return res*(-1); return res; } static int wxCALLBACK ServerSortCallback(long item1, long item2, long col) { Server* s1 = reinterpret_cast<Server*>(item1); Server* s2 = reinterpret_cast<Server*>(item2); // Make sure fav's are placed at the top, no matter what if(s1->favorite && !s2->favorite) return -1; if(s2->favorite && !s1->favorite) return 1; bool ascending = (col<0); col = abs(col); switch(col) { case 1: // ServerHostPort return SortHelper(s1->serverHostPort.CmpNoCase(s2->serverHostPort),ascending); break; case 2: // Name return SortHelper(s1->name.CmpNoCase(s2->name),ascending); break; case 3: // Type return SortHelper(s1->GetType().CmpNoCase(s2->GetType()),ascending); break; case 4: // Players { int r=0; if(s1->GetPlayerCount() < s2->GetPlayerCount()) r = -1; else if(s1->GetPlayerCount() > s2->GetPlayerCount()) r = 1; return SortHelper(r,ascending); } break; case 5: // Ping { int r = 0; if(s1->ping.getDuration() < s2->ping.getDuration()) r = -1; else if(s1->ping.getDuration() > s2->ping.getDuration()) r = 1; return SortHelper(r,ascending); } break; default: return 0; break; } return -1; } MainFrameImpl::MainFrameImpl( wxWindow* parent ) : MainFrame( parent ), initialLoadTimer(this) { ServerPingTracker::receiver = this; this->toolBar->SetToolBitmapSize(wxSize(32,32)); this->toolBar->Realize(); this->SetSize(this->DetermineFrameSize()); this->SetupColumns(); this->m_currentSortMode = appConfig.getSortMode(); this->favoriteServers = appConfig.getFavorites(); this->serverList->SetFocus(); this->Connect( this->initialLoadTimer.GetId(), wxEVT_TIMER, wxTimerEventHandler(MainFrameImpl::EventTimer)); this->Connect( wxID_ANY, wxEVT_PING_CHANGED, wxCommandEventHandler(MainFrameImpl::EventPingChanged)); this->initialLoadTimer.Start(300,true); this->pingTimer.Start(10); } MainFrameImpl::~MainFrameImpl() { for(int col = 0; col < Config::COL_COUNT; col++) appConfig.setColumnWidth(Config::ColType(col), this->serverList->GetColumnWidth(col)); appConfig.setFavorites(this->favoriteServers); appConfig.setWindowDimensions(GetRect()); appConfig.setSortMode(this->m_currentSortMode); } void MainFrameImpl::SetupColumns() { wxString names[] = { _("Server"), _("Name"), _("Type"), _("#"), _("Ping"), _("Fav") }; for(int col = 0; col < Config::COL_COUNT; col++) { this->serverList->InsertColumn(col,names[col]); this->serverList->SetColumnWidth(col,appConfig.getColumnWidth(Config::ColType(col))); } } wxRect MainFrameImpl::DetermineFrameSize() const { const int minFrameW = 300; const int minFrameH = 300; wxSize scr = wxGetDisplaySize(); wxRect wanted = appConfig.getWindowDimensions(); // Check values wanted.x = wxMin(abs(wanted.x), scr.x - minFrameW); wanted.y = wxMin(abs(wanted.y), scr.y - minFrameH); wanted.height = wxMax(wanted.height, minFrameH); wanted.height = wxMin(wanted.height, scr.x - wanted.x); wanted.width = wxMax(wanted.width, minFrameW); wanted.width = wxMin(wanted.width, scr.y - wanted.y); return wanted; } void MainFrameImpl::SetStatusText(const wxString& t) { this->statusBar->SetStatusText(t); } void MainFrameImpl::EventRefresh(wxCommandEvent&) { this->RefreshServerGrid(); } void MainFrameImpl::RefreshServerGrid() { UpdatingDlgImpl dlg(this); dlg.Show(); BZLauncherApp& app = wxGetApp(); app.RefreshServerList(); wxListCtrl* list = this->serverList; list->DeleteAllItems(); // Content ServerList::iterator i; int idx = 0; for(i = app.listServerHandler.serverList.begin(); i != app.listServerHandler.serverList.end(); ++i) { dlg.Pulse(); Server* current = *i; // Check if its a favorite current->favorite = (this->favoriteServers.Index(current->serverHostPort) != wxNOT_FOUND); // Server list->InsertItem(idx, current->serverHostPort); list->SetItemPtrData(idx,reinterpret_cast<wxUIntPtr>(current)); // Name list->SetItem(idx, 1, current->name); // Type list->SetItem(idx, 2, current->GetType()); // Player Count list->SetItem(idx, 3, wxString::Format(_T("%d"), current->GetPlayerCount())); // Ping list->SetItem(idx, 4, _("n/a")); // Favorite this->UpdateServer(idx,current); idx++; } dlg.Pulse(); this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); dlg.Pulse(); } void MainFrameImpl::EventShowAbout(wxCommandEvent&) { AboutDlgImpl dlg(this); dlg.ShowModal(); } void MainFrameImpl::EventQuit(wxCommandEvent&) { this->Close(); } void MainFrameImpl::EventViewServer(wxCommandEvent&) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { ServerDlgImpl dlg(this, s); dlg.ShowModal(); } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::EventSelectServer(wxListEvent& event) { Server* srv = reinterpret_cast<Server*>(event.GetData()); const wxString s = srv->serverHostPort; wxGetApp().SetSelectedServer(s); } void MainFrameImpl::EventRightClick(wxListEvent& WXUNUSED(event)) { this->PopupMenu(this->serverMenu); } void MainFrameImpl::EventActivated(wxListEvent& WXUNUSED(event)) { this->LaunchGame(); } void MainFrameImpl::EventLaunch(wxCommandEvent& WXUNUSED(event)) { this->LaunchGame(); } void MainFrameImpl::LaunchGame() { BZLauncherApp& app = wxGetApp(); app.LaunchSelectedServer(this); } void MainFrameImpl::EventColClick(wxListEvent& event) { if(abs(this->m_currentSortMode) == (event.GetColumn()+1)) this->m_currentSortMode *= -1; else this->m_currentSortMode = event.GetColumn()+1; this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); } void MainFrameImpl::EventFavoriteToggle(wxCommandEvent& WXUNUSED(event)) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { if(s->favorite) { // Remove from favoriteServers s->favorite = false; this->favoriteServers.Remove(s->serverHostPort); } else { // Add to favoriteServers s->favorite = true; this->favoriteServers.Add(s->serverHostPort); } int idx = this->serverList->GetNextItem(-1,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED); if(idx==-1) { app.SetStatusText(_("Couldnt find row! :(")); } else { this->UpdateServer(idx,s); this->serverList->SortItems(ServerSortCallback, this->m_currentSortMode); } } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::UpdateServer(int idx, Server* s) { if(s->favorite) { this->serverList->SetItemFont(idx, wxFont( 8, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans") )); this->serverList->SetItem(idx, 5, _("Yes")); } else { this->serverList->SetItemFont(idx, wxFont( 8, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Sans") )); this->serverList->SetItem(idx, 5, _("No")); } if(s->ping.isOK()) { this->serverList->SetItem(idx, 4, wxString::Format(_T("%d"), s->ping.getDuration())); } else { this->serverList->SetItem(idx, 4, _("n/a")); } } void MainFrameImpl::EventPingServer(wxCommandEvent& WXUNUSED(event)) { BZLauncherApp& app = wxGetApp(); Server* s = app.listServerHandler.FindByName(app.GetSelectedServer()); if(s) { s->ping.ping(); } else { app.SetStatusText(_("No server selected")); } } void MainFrameImpl::EventTimer(wxTimerEvent& WXUNUSED(event)) { this->RefreshServerGrid(); } void MainFrameImpl::EventPingChanged(wxCommandEvent& event) { wxIPV4address ip; long port = 5154; int pos; if((pos = event.GetString().Find(':',true)) != wxNOT_FOUND) { if(!event.GetString().Mid(pos+1).ToLong(&port)) port = 5154; ip.Hostname(event.GetString().Mid(0,pos)); } else { ip.Hostname(event.GetString()); } ip.Service(port); long item = -1; for ( ;; ) { item = this->serverList->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE); if(item == -1) break; Server* current = reinterpret_cast<Server*>(this->serverList->GetItemData(item)); if(current->ip.IPAddress() == ip.IPAddress() && current->ip.Service() && ip.Service()) { this->UpdateServer(item, current); } } } <|endoftext|>
<commit_before><commit_msg>Gui: [skip ci] automatically save & load settings of PrefFontBox widgets<commit_after><|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 "IECore/ChannelOp.h" #include "IECore/TypeTraits.h" #include "IECore/DespatchTypedData.h" #include "IECore/CompoundParameter.h" #include "boost/format.hpp" using namespace IECore; using namespace std; using namespace boost; ChannelOp::ChannelOp( const std::string &name, const std::string &description ) : ImagePrimitiveOp( name, description ) { StringVectorDataPtr defaultChannels = new StringVectorData; defaultChannels->writable().push_back( "R" ); defaultChannels->writable().push_back( "G" ); defaultChannels->writable().push_back( "B" ); m_channelNamesParameter = new StringVectorParameter( "channels", "The names of the channels to modify.", defaultChannels ); parameters()->addParameter( m_channelNamesParameter ); } ChannelOp::~ChannelOp() { } StringVectorParameterPtr ChannelOp::channelNamesParameter() { return m_channelNamesParameter; } ConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const { return m_channelNamesParameter; } void ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands ) { if( image->getDataWindow().isEmpty() ) { return; } ChannelVector channels; /// \todo Just use ImagePrimitive::channelValid. We don't want to do that right now /// as it imposes loose restrictions on the channel datatype - in the future it should perhaps /// impose the restrictions we have here (float, int or half vector data). size_t numPixels = image->variableSize( PrimitiveVariable::Vertex ); const vector<string> channelNames = channelNamesParameter()->getTypedValue(); for( unsigned i=0; i<channelNames.size(); i++ ) { PrimitiveVariableMap::iterator it = image->variables.find( channelNames[i] ); if( it==image->variables.end() ) { throw Exception( str( format( "Channel \"%s\" does not exist." ) % channelNames[i] ) ); } if( it->second.interpolation!=PrimitiveVariable::Vertex && it->second.interpolation!=PrimitiveVariable::Varying && it->second.interpolation!=PrimitiveVariable::FaceVarying ) { throw Exception( str( format( "Primitive variable \"%s\" has inappropriate interpolation." ) % channelNames[i] ) ); } if( !it->second.data ) { throw Exception( str( format( "Primitive variable \"%s\" has no data." ) % channelNames[i] ) ); } if( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) && !it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) && !it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) ) { throw Exception( str( format( "Primitive variable \"%s\" has inappropriate type." ) % channelNames[i] ) ); } size_t size = despatchTypedData<TypedDataSize>( it->second.data ); if( size!=numPixels ) { throw Exception( str( format( "Primitive variable \"%s\" has wrong size (%d but should be %d)." ) % channelNames[i] % size % numPixels ) ); } channels.push_back( it->second.data ); } modifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels ); assert( image->arePrimitiveVariablesValid() ); } <commit_msg>Removed assert<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 "IECore/ChannelOp.h" #include "IECore/TypeTraits.h" #include "IECore/DespatchTypedData.h" #include "IECore/CompoundParameter.h" #include "boost/format.hpp" using namespace IECore; using namespace std; using namespace boost; ChannelOp::ChannelOp( const std::string &name, const std::string &description ) : ImagePrimitiveOp( name, description ) { StringVectorDataPtr defaultChannels = new StringVectorData; defaultChannels->writable().push_back( "R" ); defaultChannels->writable().push_back( "G" ); defaultChannels->writable().push_back( "B" ); m_channelNamesParameter = new StringVectorParameter( "channels", "The names of the channels to modify.", defaultChannels ); parameters()->addParameter( m_channelNamesParameter ); } ChannelOp::~ChannelOp() { } StringVectorParameterPtr ChannelOp::channelNamesParameter() { return m_channelNamesParameter; } ConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const { return m_channelNamesParameter; } void ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands ) { if( image->getDataWindow().isEmpty() ) { return; } ChannelVector channels; /// \todo Just use ImagePrimitive::channelValid. We don't want to do that right now /// as it imposes loose restrictions on the channel datatype - in the future it should perhaps /// impose the restrictions we have here (float, int or half vector data). size_t numPixels = image->variableSize( PrimitiveVariable::Vertex ); const vector<string> channelNames = channelNamesParameter()->getTypedValue(); for( unsigned i=0; i<channelNames.size(); i++ ) { PrimitiveVariableMap::iterator it = image->variables.find( channelNames[i] ); if( it==image->variables.end() ) { throw Exception( str( format( "Channel \"%s\" does not exist." ) % channelNames[i] ) ); } if( it->second.interpolation!=PrimitiveVariable::Vertex && it->second.interpolation!=PrimitiveVariable::Varying && it->second.interpolation!=PrimitiveVariable::FaceVarying ) { throw Exception( str( format( "Primitive variable \"%s\" has inappropriate interpolation." ) % channelNames[i] ) ); } if( !it->second.data ) { throw Exception( str( format( "Primitive variable \"%s\" has no data." ) % channelNames[i] ) ); } if( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) && !it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) && !it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) ) { throw Exception( str( format( "Primitive variable \"%s\" has inappropriate type." ) % channelNames[i] ) ); } size_t size = despatchTypedData<TypedDataSize>( it->second.data ); if( size!=numPixels ) { throw Exception( str( format( "Primitive variable \"%s\" has wrong size (%d but should be %d)." ) % channelNames[i] % size % numPixels ) ); } channels.push_back( it->second.data ); } modifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels ); } <|endoftext|>
<commit_before>#include "InlineReductions.h" #include "Func.h" #include "Scope.h" #include "IRPrinter.h" #include "IROperator.h" namespace Halide { using std::string; using std::vector; using std::ostringstream; namespace Internal { class FindFreeVars : public IRVisitor { public: vector<Var> free_vars; RDom rdom; private: Scope<int> internal; using IRVisitor::visit; void visit(const Let *op) { op->value.accept(this); internal.push(op->name, 0); op->body.accept(this); internal.pop(op->name); } void visit(const Variable *v) { if (internal.contains(v->name)) { // Don't capture internally defined vars return; } if (starts_with(v->name, "iv.")) { // Don't capture implicit vars return; } if (v->reduction_domain.defined()) { rdom = RDom(v->reduction_domain); return; } if (v->param.defined()) { // Skip parameters return; } for (size_t i = 0; i < free_vars.size(); i++) { if (v->name == free_vars[i].name()) return; } free_vars.push_back(Var(v->name)); } }; } Expr sum(Expr e) { return sum(e, "sum"); } Expr product(Expr e) { return product(e, "product"); } Expr maximum(Expr e) { return maximum(e, "maximum"); } Expr minimum(Expr e) { return minimum(e, "minimum"); } Expr sum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); f(v.free_vars) += e; return f(v.free_vars); } Expr product(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); f(v.free_vars) *= e; return f(v.free_vars); } Expr maximum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); f(v.free_vars) = e.type().min(); f(v.free_vars) = max(f(v.free_vars), e); return f(v.free_vars); } Expr minimum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); f(v.free_vars) = e.type().max(); f(v.free_vars) = min(f(v.free_vars), e); return f(v.free_vars); } Tuple argmax(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); assert(v.rdom.defined()); Tuple initial_tup(vector<Expr>(v.rdom.dimensions()+1)); Tuple update_tup(vector<Expr>(v.rdom.dimensions()+1)); for (int i = 0; i < v.rdom.dimensions(); i++) { initial_tup[i] = 0; update_tup[i] = v.rdom[i]; } int value_index = (int)initial_tup.size()-1; initial_tup[value_index] = e.type().min(); update_tup[value_index] = e; f(v.free_vars) = initial_tup; Expr better = e > f(v.free_vars)[value_index]; Tuple update = tuple_select(better, update_tup, f(v.free_vars)); f(v.free_vars) = update; return f(v.free_vars); } Tuple argmin(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); Tuple initial_tup(vector<Expr>(v.rdom.dimensions()+1)); Tuple update_tup(vector<Expr>(v.rdom.dimensions()+1)); for (int i = 0; i < v.rdom.dimensions(); i++) { initial_tup[i] = 0; update_tup[i] = v.rdom[i]; } int value_index = (int)initial_tup.size()-1; initial_tup[value_index] = e.type().max(); update_tup[value_index] = e; f(v.free_vars) = initial_tup; Expr better = e < f(v.free_vars)[value_index]; f(v.free_vars) = tuple_select(better, update_tup, f(v.free_vars)); return f(v.free_vars); } Tuple argmin(Expr e) { return argmin(e, "argmin"); } Tuple argmax(Expr e) { return argmax(e, "argmax"); } } <commit_msg>inline reductions explicitly check for a reduction domain<commit_after>#include "InlineReductions.h" #include "Func.h" #include "Scope.h" #include "IRPrinter.h" #include "IROperator.h" namespace Halide { using std::string; using std::vector; using std::ostringstream; namespace Internal { class FindFreeVars : public IRVisitor { public: vector<Var> free_vars; RDom rdom; private: Scope<int> internal; using IRVisitor::visit; void visit(const Let *op) { op->value.accept(this); internal.push(op->name, 0); op->body.accept(this); internal.pop(op->name); } void visit(const Variable *v) { if (internal.contains(v->name)) { // Don't capture internally defined vars return; } if (starts_with(v->name, "iv.")) { // Don't capture implicit vars return; } if (v->reduction_domain.defined()) { rdom = RDom(v->reduction_domain); return; } if (v->param.defined()) { // Skip parameters return; } for (size_t i = 0; i < free_vars.size(); i++) { if (v->name == free_vars[i].name()) return; } free_vars.push_back(Var(v->name)); } }; } Expr sum(Expr e) { return sum(e, "sum"); } Expr product(Expr e) { return product(e, "product"); } Expr maximum(Expr e) { return maximum(e, "maximum"); } Expr minimum(Expr e) { return minimum(e, "minimum"); } Expr sum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); assert(v.rdom.defined() && "Expression passed to sum must reference a reduction domain"); Func f(name); f(v.free_vars) += e; return f(v.free_vars); } Expr product(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); assert(v.rdom.defined() && "Expression passed to product must reference a reduction domain"); Func f(name); f(v.free_vars) *= e; return f(v.free_vars); } Expr maximum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); assert(v.rdom.defined() && "Expression passed to maximum must reference a reduction domain"); Func f(name); f(v.free_vars) = e.type().min(); f(v.free_vars) = max(f(v.free_vars), e); return f(v.free_vars); } Expr minimum(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); assert(v.rdom.defined() && "Expression passed to minimum must reference a reduction domain"); Func f(name); f(v.free_vars) = e.type().max(); f(v.free_vars) = min(f(v.free_vars), e); return f(v.free_vars); } Tuple argmax(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); assert(v.rdom.defined() && "Expression passed to argmax must reference a reduction domain"); Tuple initial_tup(vector<Expr>(v.rdom.dimensions()+1)); Tuple update_tup(vector<Expr>(v.rdom.dimensions()+1)); for (int i = 0; i < v.rdom.dimensions(); i++) { initial_tup[i] = 0; update_tup[i] = v.rdom[i]; } int value_index = (int)initial_tup.size()-1; initial_tup[value_index] = e.type().min(); update_tup[value_index] = e; f(v.free_vars) = initial_tup; Expr better = e > f(v.free_vars)[value_index]; Tuple update = tuple_select(better, update_tup, f(v.free_vars)); f(v.free_vars) = update; return f(v.free_vars); } Tuple argmin(Expr e, const std::string &name) { Internal::FindFreeVars v; e.accept(&v); Func f(name); assert(v.rdom.defined() && "Expression passed to argmin must reference a reduction domain"); Tuple initial_tup(vector<Expr>(v.rdom.dimensions()+1)); Tuple update_tup(vector<Expr>(v.rdom.dimensions()+1)); for (int i = 0; i < v.rdom.dimensions(); i++) { initial_tup[i] = 0; update_tup[i] = v.rdom[i]; } int value_index = (int)initial_tup.size()-1; initial_tup[value_index] = e.type().max(); update_tup[value_index] = e; f(v.free_vars) = initial_tup; Expr better = e < f(v.free_vars)[value_index]; f(v.free_vars) = tuple_select(better, update_tup, f(v.free_vars)); return f(v.free_vars); } Tuple argmin(Expr e) { return argmin(e, "argmin"); } Tuple argmax(Expr e) { return argmax(e, "argmax"); } } <|endoftext|>
<commit_before>#include "GeometryObject.h" #include <cassert> #include "../lib/EasyBMP_1.06/EasyBMP.h" GeometryObject::GeometryObject() { } GeometryObject::GeometryObject(const Material & material, const std::vector<Point3D>& vertices, const std::vector<RGBColor>& colors, const std::vector<Vector2D>& texture_coords, const std::vector<uint32_t>& indices, const std::string texture_file) : m_material(material), m_vertices(vertices), m_indices(indices), m_colors(colors), m_texture_coords(texture_coords){ loadTexture(texture_file); } GeometryObject::~GeometryObject() { } const std::vector<Triangle3D> GeometryObject::triangulate() const { assert(m_indices.size() % 3 == 0 && "Indices array must be made up of triangles"); assert((m_colors.size() == 0 || m_vertices.size() == m_colors.size()) && "Vertices size and colors size should match"); assert((m_texture_coords.size() == 0 || m_vertices.size() == m_texture_coords.size()) && "Vertices size and texture coordinates size should match"); std::vector<Triangle3D> triangles; for (int i = 0; i < m_indices.size(); i+=3) { const Triangle3D triangle = Triangle3D( build_vertex(m_indices[i]), build_vertex(m_indices[i + 1]), build_vertex(m_indices[i + 2]) ); triangles.push_back(triangle); } return triangles; } const Vertex3D GeometryObject::build_vertex(const uint32_t vertex_index) const { Vertex3D v; v.position = m_vertices[vertex_index]; v.color = (m_colors.size() > 1) ? m_colors[vertex_index] : RGBColor(); v.texture_coords = (m_texture_coords.size() > 1) ? m_texture_coords[vertex_index] : Vector2D(); return v; } void GeometryObject::loadTexture(const std::string import_path) { if (import_path != "") { BMP image; image.ReadFromFile(import_path.c_str()); m_texture_width = image.TellWidth(); m_texture_height = image.TellHeight(); if (m_texture_width > 1 && m_texture_height > 1) { m_texture.reserve(m_texture_width * m_texture_height); for (int x = 0; x < m_texture_width; ++x) { for (int y = 0; y < m_texture_height; ++y) { RGBApixel pixel = image.GetPixel(x, y); RGBColor color(pixel.Red / 255.0, pixel.Green / 255.0, pixel.Blue / 255.0); m_texture.push_back(color); } } } } } const RGBColor GeometryObject::getTextureColor(const Vector2D& text_coords) const { // Convert from (0,0) at left-bottom to (0,0) at left-top const Vector2D text_coords_image ( 1 - std::min(text_coords.y, 1.0), std::min(text_coords.x, 1.0) ); // Scale to texture size const int x = text_coords_image.x * (m_texture_width - 1); const int y = text_coords_image.y * (m_texture_height - 1); const int index = y * m_texture_width + x; return m_texture[index]; } <commit_msg>Modified texture color to support texture repeating<commit_after>#include "GeometryObject.h" #include <cassert> #include "../lib/EasyBMP_1.06/EasyBMP.h" #include <math.h> /* fmod */ GeometryObject::GeometryObject() { } GeometryObject::GeometryObject(const Material & material, const std::vector<Point3D>& vertices, const std::vector<RGBColor>& colors, const std::vector<Vector2D>& texture_coords, const std::vector<uint32_t>& indices, const std::string texture_file) : m_material(material), m_vertices(vertices), m_indices(indices), m_colors(colors), m_texture_coords(texture_coords){ loadTexture(texture_file); } GeometryObject::~GeometryObject() { } const std::vector<Triangle3D> GeometryObject::triangulate() const { assert(m_indices.size() % 3 == 0 && "Indices array must be made up of triangles"); assert((m_colors.size() == 0 || m_vertices.size() == m_colors.size()) && "Vertices size and colors size should match"); assert((m_texture_coords.size() == 0 || m_vertices.size() == m_texture_coords.size()) && "Vertices size and texture coordinates size should match"); std::vector<Triangle3D> triangles; for (int i = 0; i < m_indices.size(); i+=3) { const Triangle3D triangle = Triangle3D( build_vertex(m_indices[i]), build_vertex(m_indices[i + 1]), build_vertex(m_indices[i + 2]) ); triangles.push_back(triangle); } return triangles; } const Vertex3D GeometryObject::build_vertex(const uint32_t vertex_index) const { Vertex3D v; v.position = m_vertices[vertex_index]; v.color = (m_colors.size() > 1) ? m_colors[vertex_index] : RGBColor(); v.texture_coords = (m_texture_coords.size() > 1) ? m_texture_coords[vertex_index] : Vector2D(); return v; } void GeometryObject::loadTexture(const std::string import_path) { if (import_path != "") { BMP image; image.ReadFromFile(import_path.c_str()); m_texture_width = image.TellWidth(); m_texture_height = image.TellHeight(); if (m_texture_width > 1 && m_texture_height > 1) { m_texture.reserve(m_texture_width * m_texture_height); for (int x = 0; x < m_texture_width; ++x) { for (int y = 0; y < m_texture_height; ++y) { RGBApixel pixel = image.GetPixel(x, y); RGBColor color(pixel.Red / 255.0, pixel.Green / 255.0, pixel.Blue / 255.0); m_texture.push_back(color); } } } } } const RGBColor GeometryObject::getTextureColor(const Vector2D& text_coords) const { // Convert from (0,0) at left-bottom to (0,0) at left-top const Vector2D text_coords_image ( 1 - std::min(fmod(text_coords.y, 1), 1.0), std::min(fmod(text_coords.x, 1), 1.0) ); // Scale to texture size const int x = text_coords_image.x * (m_texture_width - 1); const int y = text_coords_image.y * (m_texture_height - 1); const int index = y * m_texture_width + x; return m_texture[index]; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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 author 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 "libtorrent/pch.hpp" #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #ifdef TORRENT_DEBUG o->m_in_constructor = false; #endif return o; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << "] failed to " "allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) m_results.resize(100); } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << "] WARNING: " "node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end()); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } namespace { bool bitwise_nand(unsigned char lhs, unsigned char rhs) { return (lhs & rhs) == 0; } } void traversal_algorithm::add_requests() { int results_target = m_node.m_table.bucket_size(); // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { if ((*i)->flags & observer::flag_queried) continue; ++l.nodes_left; } } } } // namespace libtorrent::dht <commit_msg>dht assert fix<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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 author 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 "libtorrent/pch.hpp" #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #ifdef TORRENT_DEBUG o->m_in_constructor = false; #endif return o; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << "] failed to " "allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) m_results.resize(100); } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << "] WARNING: " "node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } namespace { bool bitwise_nand(unsigned char lhs, unsigned char rhs) { return (lhs & rhs) == 0; } } void traversal_algorithm::add_requests() { int results_target = m_node.m_table.bucket_size(); // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { if ((*i)->flags & observer::flag_queried) continue; ++l.nodes_left; } } } } // namespace libtorrent::dht <|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 <algorithm> #include <iostream> #include <iterator> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <boost/algorithm/string/predicate.hpp> #include <boost/optional/optional.hpp> #include <gflags/gflags_declare.h> #include <glog/logging.h> #include "kudu/common/common.pb.h" #include "kudu/common/wire_protocol.h" #include "kudu/common/wire_protocol.pb.h" #include "kudu/consensus/metadata.pb.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/strings/join.h" #include "kudu/gutil/strings/split.h" #include "kudu/gutil/strings/stringpiece.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/master/master.h" #include "kudu/master/master.pb.h" #include "kudu/master/master.proxy.h" #include "kudu/rpc/rpc_controller.h" #include "kudu/tools/tool_action.h" #include "kudu/tools/tool_action_common.h" #include "kudu/util/monotime.h" #include "kudu/util/status.h" DECLARE_bool(force); DECLARE_int64(timeout_ms); DECLARE_string(columns); using kudu::master::ConnectToMasterRequestPB; using kudu::master::ConnectToMasterResponsePB; using kudu::master::ListMastersRequestPB; using kudu::master::ListMastersResponsePB; using kudu::master::Master; using kudu::master::MasterServiceProxy; using kudu::master::MasterServiceProxy; using kudu::master::ResetAuthzCacheRequestPB; using kudu::master::ResetAuthzCacheResponsePB; using kudu::consensus::RaftPeerPB; using kudu::rpc::RpcController; using std::cout; using std::map; using std::set; using std::string; using std::unique_ptr; using std::vector; using strings::Substitute; namespace kudu { namespace tools { namespace { const char* const kMasterAddressArg = "master_address"; const char* const kMasterAddressDesc = "Address of a Kudu Master of form " "'hostname:port'. Port may be omitted if the Master is bound to the " "default port."; const char* const kFlagArg = "flag"; const char* const kValueArg = "value"; Status MasterGetFlags(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerFlags(address, Master::kDefaultPort); } Status MasterSetFlag(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); const string& flag = FindOrDie(context.required_args, kFlagArg); const string& value = FindOrDie(context.required_args, kValueArg); return SetServerFlag(address, Master::kDefaultPort, flag, value); } Status MasterStatus(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerStatus(address, Master::kDefaultPort); } Status MasterTimestamp(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerTimestamp(address, Master::kDefaultPort); } Status ListMasters(const RunnerContext& context) { LeaderMasterProxy proxy; RETURN_NOT_OK(proxy.Init(context)); ListMastersRequestPB req; ListMastersResponsePB resp; proxy.SyncRpc<ListMastersRequestPB, ListMastersResponsePB>( req, &resp, "ListMasters", &MasterServiceProxy::ListMastersAsync); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } DataTable table({}); vector<ServerEntryPB> masters; std::copy_if(resp.masters().begin(), resp.masters().end(), std::back_inserter(masters), [](const ServerEntryPB& master) { if (master.has_error()) { LOG(WARNING) << "Failed to retrieve info for master: " << StatusFromPB(master.error()).ToString(); return false; } return true; }); auto hostport_to_string = [] (const HostPortPB& hostport) { return Substitute("$0:$1", hostport.host(), hostport.port()); }; for (const auto& column : strings::Split(FLAGS_columns, ",", strings::SkipEmpty())) { vector<string> values; if (boost::iequals(column, "uuid")) { for (const auto& master : masters) { values.push_back(master.instance_id().permanent_uuid()); } } else if (boost::iequals(column, "seqno")) { for (const auto& master : masters) { values.push_back(std::to_string(master.instance_id().instance_seqno())); } } else if (boost::iequals(column, "rpc-addresses") || boost::iequals(column, "rpc_addresses")) { for (const auto& master : masters) { values.push_back(JoinMapped(master.registration().rpc_addresses(), hostport_to_string, ",")); } } else if (boost::iequals(column, "http-addresses") || boost::iequals(column, "http_addresses")) { for (const auto& master : masters) { values.push_back(JoinMapped(master.registration().http_addresses(), hostport_to_string, ",")); } } else if (boost::iequals(column, "version")) { for (const auto& master : masters) { values.push_back(master.registration().software_version()); } } else if (boost::iequals(column, "start_time")) { for (const auto& master : masters) { values.emplace_back(StartTimeToString(master.registration())); } } else if (boost::iequals(column, "role")) { for (const auto& master : masters) { values.emplace_back(RaftPeerPB::Role_Name(master.role())); } } else { return Status::InvalidArgument("unknown column (--columns)", column); } table.AddColumn(column.ToString(), std::move(values)); } RETURN_NOT_OK(table.PrintTo(cout)); return Status::OK(); } Status MasterDumpMemTrackers(const RunnerContext& context) { const auto& address = FindOrDie(context.required_args, kMasterAddressArg); return DumpMemTrackers(address, Master::kDefaultPort); } // Make sure the list of master addresses specified in 'master_addresses' // corresponds to the actual list of masters addresses in the cluster, // as reported in ConnectToMasterResponsePB::master_addrs. Status VerifyMasterAddressList(const vector<string>& master_addresses) { map<string, set<string>> addresses_per_master; for (const auto& address : master_addresses) { unique_ptr<MasterServiceProxy> proxy; RETURN_NOT_OK(BuildProxy(address, Master::kDefaultPort, &proxy)); RpcController ctl; ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms)); ConnectToMasterRequestPB req; ConnectToMasterResponsePB resp; RETURN_NOT_OK(proxy->ConnectToMaster(req, &resp, &ctl)); const auto& resp_master_addrs = resp.master_addrs(); if (resp_master_addrs.size() != master_addresses.size()) { const auto addresses_provided = JoinStrings(master_addresses, ","); const auto addresses_cluster_config = JoinMapped( resp_master_addrs, [](const HostPortPB& pb) { return Substitute("$0:$1", pb.host(), pb.port()); }, ","); return Status::InvalidArgument(Substitute( "list of master addresses provided ($0) " "does not match the actual cluster configuration ($1) ", addresses_provided, addresses_cluster_config)); } set<string> addr_set; for (const auto& hp : resp_master_addrs) { addr_set.emplace(Substitute("$0:$1", hp.host(), hp.port())); } addresses_per_master.emplace(address, std::move(addr_set)); } bool mismatch = false; if (addresses_per_master.size() > 1) { const auto it_0 = addresses_per_master.cbegin(); auto it_1 = addresses_per_master.begin(); ++it_1; for (auto it = it_1; it != addresses_per_master.end(); ++it) { if (it->second != it_0->second) { mismatch = true; break; } } } if (mismatch) { string err_msg = Substitute("specified: ($0);", JoinStrings(master_addresses, ",")); for (const auto& e : addresses_per_master) { err_msg += Substitute(" from master $0: ($1);", e.first, JoinStrings(e.second, ",")); } return Status::ConfigurationError( Substitute("master address lists mismatch: $0", err_msg)); } return Status::OK(); } Status ResetAuthzCacheAtMaster(const string& master_address) { unique_ptr<MasterServiceProxy> proxy; RETURN_NOT_OK(BuildProxy(master_address, Master::kDefaultPort, &proxy)); RpcController ctl; ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms)); ResetAuthzCacheRequestPB req; ResetAuthzCacheResponsePB resp; RETURN_NOT_OK(proxy->ResetAuthzCache(req, &resp, &ctl)); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } return Status::OK(); } Status ResetAuthzCache(const RunnerContext& context) { vector<string> master_addresses; RETURN_NOT_OK(ParseMasterAddresses(context, &master_addresses)); if (!FLAGS_force) { // Make sure the list of master addresses specified for the command // matches the actual list of masters in the cluster. RETURN_NOT_OK(VerifyMasterAddressList(master_addresses)); } // It makes sense to reset privileges cache at every master in the cluster. // Otherwise, SentryAuthzProvider might return inconsistent results for authz // requests upon master leadership change. vector<Status> statuses; statuses.reserve(master_addresses.size()); for (const auto& address : master_addresses) { auto status = ResetAuthzCacheAtMaster(address); statuses.emplace_back(std::move(status)); } DCHECK_EQ(master_addresses.size(), statuses.size()); string err_str; for (auto i = 0; i < statuses.size(); ++i) { const auto& s = statuses[i]; if (s.ok()) { continue; } err_str += Substitute(" error from master at $0: $1", master_addresses[i], s.ToString()); } if (err_str.empty()) { return Status::OK(); } return Status::Incomplete(err_str); } } // anonymous namespace unique_ptr<Mode> BuildMasterMode() { ModeBuilder builder("master"); builder.Description("Operate on a Kudu Master"); { unique_ptr<Action> action_reset = ActionBuilder("reset", &ResetAuthzCache) .Description("Reset the privileges cache") .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc }) .AddOptionalParameter( "force", boost::none, string("Ignore mismatches of the specified and the actual lists " "of master addresses in the cluster")) .Build(); unique_ptr<Mode> mode_authz_cache = ModeBuilder("authz_cache") .Description("Operate on the authz cache of a Kudu Master") .AddAction(std::move(action_reset)) .Build(); builder.AddMode(std::move(mode_authz_cache)); } { unique_ptr<Action> dump_memtrackers = ActionBuilder("dump_memtrackers", &MasterDumpMemTrackers) .Description("Dump the memtrackers from a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddOptionalParameter("format") .AddOptionalParameter("memtracker_output") .AddOptionalParameter("timeout_ms") .Build(); builder.AddAction(std::move(dump_memtrackers)); } { unique_ptr<Action> get_flags = ActionBuilder("get_flags", &MasterGetFlags) .Description("Get the gflags for a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddOptionalParameter("all_flags") .AddOptionalParameter("flag_tags") .Build(); builder.AddAction(std::move(get_flags)); } { unique_ptr<Action> set_flag = ActionBuilder("set_flag", &MasterSetFlag) .Description("Change a gflag value on a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddRequiredParameter({ kFlagArg, "Name of the gflag" }) .AddRequiredParameter({ kValueArg, "New value for the gflag" }) .AddOptionalParameter("force") .Build(); builder.AddAction(std::move(set_flag)); } { unique_ptr<Action> status = ActionBuilder("status", &MasterStatus) .Description("Get the status of a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .Build(); builder.AddAction(std::move(status)); } { unique_ptr<Action> timestamp = ActionBuilder("timestamp", &MasterTimestamp) .Description("Get the current timestamp of a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .Build(); builder.AddAction(std::move(timestamp)); } { unique_ptr<Action> list_masters = ActionBuilder("list", &ListMasters) .Description("List masters in a Kudu cluster") .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc }) .AddOptionalParameter( "columns", string("uuid,rpc-addresses,role"), string("Comma-separated list of master info fields to " "include in output.\nPossible values: uuid, " "rpc-addresses, http-addresses, version, seqno, " "start_time and role")) .AddOptionalParameter("format") .AddOptionalParameter("timeout_ms") .Build(); builder.AddAction(std::move(list_masters)); } return builder.Build(); } } // namespace tools } // namespace kudu <commit_msg>Remove redundant references of MasterServiceProxy<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 <algorithm> #include <iostream> #include <iterator> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <boost/algorithm/string/predicate.hpp> #include <boost/optional/optional.hpp> #include <gflags/gflags_declare.h> #include <glog/logging.h> #include "kudu/common/common.pb.h" #include "kudu/common/wire_protocol.h" #include "kudu/common/wire_protocol.pb.h" #include "kudu/consensus/metadata.pb.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/strings/join.h" #include "kudu/gutil/strings/split.h" #include "kudu/gutil/strings/stringpiece.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/master/master.h" #include "kudu/master/master.pb.h" #include "kudu/master/master.proxy.h" #include "kudu/rpc/rpc_controller.h" #include "kudu/tools/tool_action.h" #include "kudu/tools/tool_action_common.h" #include "kudu/util/monotime.h" #include "kudu/util/status.h" DECLARE_bool(force); DECLARE_int64(timeout_ms); DECLARE_string(columns); using kudu::master::ConnectToMasterRequestPB; using kudu::master::ConnectToMasterResponsePB; using kudu::master::ListMastersRequestPB; using kudu::master::ListMastersResponsePB; using kudu::master::Master; using kudu::master::MasterServiceProxy; using kudu::master::ResetAuthzCacheRequestPB; using kudu::master::ResetAuthzCacheResponsePB; using kudu::consensus::RaftPeerPB; using kudu::rpc::RpcController; using std::cout; using std::map; using std::set; using std::string; using std::unique_ptr; using std::vector; using strings::Substitute; namespace kudu { namespace tools { namespace { const char* const kMasterAddressArg = "master_address"; const char* const kMasterAddressDesc = "Address of a Kudu Master of form " "'hostname:port'. Port may be omitted if the Master is bound to the " "default port."; const char* const kFlagArg = "flag"; const char* const kValueArg = "value"; Status MasterGetFlags(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerFlags(address, Master::kDefaultPort); } Status MasterSetFlag(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); const string& flag = FindOrDie(context.required_args, kFlagArg); const string& value = FindOrDie(context.required_args, kValueArg); return SetServerFlag(address, Master::kDefaultPort, flag, value); } Status MasterStatus(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerStatus(address, Master::kDefaultPort); } Status MasterTimestamp(const RunnerContext& context) { const string& address = FindOrDie(context.required_args, kMasterAddressArg); return PrintServerTimestamp(address, Master::kDefaultPort); } Status ListMasters(const RunnerContext& context) { LeaderMasterProxy proxy; RETURN_NOT_OK(proxy.Init(context)); ListMastersRequestPB req; ListMastersResponsePB resp; proxy.SyncRpc<ListMastersRequestPB, ListMastersResponsePB>( req, &resp, "ListMasters", &MasterServiceProxy::ListMastersAsync); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } DataTable table({}); vector<ServerEntryPB> masters; std::copy_if(resp.masters().begin(), resp.masters().end(), std::back_inserter(masters), [](const ServerEntryPB& master) { if (master.has_error()) { LOG(WARNING) << "Failed to retrieve info for master: " << StatusFromPB(master.error()).ToString(); return false; } return true; }); auto hostport_to_string = [] (const HostPortPB& hostport) { return Substitute("$0:$1", hostport.host(), hostport.port()); }; for (const auto& column : strings::Split(FLAGS_columns, ",", strings::SkipEmpty())) { vector<string> values; if (boost::iequals(column, "uuid")) { for (const auto& master : masters) { values.push_back(master.instance_id().permanent_uuid()); } } else if (boost::iequals(column, "seqno")) { for (const auto& master : masters) { values.push_back(std::to_string(master.instance_id().instance_seqno())); } } else if (boost::iequals(column, "rpc-addresses") || boost::iequals(column, "rpc_addresses")) { for (const auto& master : masters) { values.push_back(JoinMapped(master.registration().rpc_addresses(), hostport_to_string, ",")); } } else if (boost::iequals(column, "http-addresses") || boost::iequals(column, "http_addresses")) { for (const auto& master : masters) { values.push_back(JoinMapped(master.registration().http_addresses(), hostport_to_string, ",")); } } else if (boost::iequals(column, "version")) { for (const auto& master : masters) { values.push_back(master.registration().software_version()); } } else if (boost::iequals(column, "start_time")) { for (const auto& master : masters) { values.emplace_back(StartTimeToString(master.registration())); } } else if (boost::iequals(column, "role")) { for (const auto& master : masters) { values.emplace_back(RaftPeerPB::Role_Name(master.role())); } } else { return Status::InvalidArgument("unknown column (--columns)", column); } table.AddColumn(column.ToString(), std::move(values)); } RETURN_NOT_OK(table.PrintTo(cout)); return Status::OK(); } Status MasterDumpMemTrackers(const RunnerContext& context) { const auto& address = FindOrDie(context.required_args, kMasterAddressArg); return DumpMemTrackers(address, Master::kDefaultPort); } // Make sure the list of master addresses specified in 'master_addresses' // corresponds to the actual list of masters addresses in the cluster, // as reported in ConnectToMasterResponsePB::master_addrs. Status VerifyMasterAddressList(const vector<string>& master_addresses) { map<string, set<string>> addresses_per_master; for (const auto& address : master_addresses) { unique_ptr<MasterServiceProxy> proxy; RETURN_NOT_OK(BuildProxy(address, Master::kDefaultPort, &proxy)); RpcController ctl; ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms)); ConnectToMasterRequestPB req; ConnectToMasterResponsePB resp; RETURN_NOT_OK(proxy->ConnectToMaster(req, &resp, &ctl)); const auto& resp_master_addrs = resp.master_addrs(); if (resp_master_addrs.size() != master_addresses.size()) { const auto addresses_provided = JoinStrings(master_addresses, ","); const auto addresses_cluster_config = JoinMapped( resp_master_addrs, [](const HostPortPB& pb) { return Substitute("$0:$1", pb.host(), pb.port()); }, ","); return Status::InvalidArgument(Substitute( "list of master addresses provided ($0) " "does not match the actual cluster configuration ($1) ", addresses_provided, addresses_cluster_config)); } set<string> addr_set; for (const auto& hp : resp_master_addrs) { addr_set.emplace(Substitute("$0:$1", hp.host(), hp.port())); } addresses_per_master.emplace(address, std::move(addr_set)); } bool mismatch = false; if (addresses_per_master.size() > 1) { const auto it_0 = addresses_per_master.cbegin(); auto it_1 = addresses_per_master.begin(); ++it_1; for (auto it = it_1; it != addresses_per_master.end(); ++it) { if (it->second != it_0->second) { mismatch = true; break; } } } if (mismatch) { string err_msg = Substitute("specified: ($0);", JoinStrings(master_addresses, ",")); for (const auto& e : addresses_per_master) { err_msg += Substitute(" from master $0: ($1);", e.first, JoinStrings(e.second, ",")); } return Status::ConfigurationError( Substitute("master address lists mismatch: $0", err_msg)); } return Status::OK(); } Status ResetAuthzCacheAtMaster(const string& master_address) { unique_ptr<MasterServiceProxy> proxy; RETURN_NOT_OK(BuildProxy(master_address, Master::kDefaultPort, &proxy)); RpcController ctl; ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms)); ResetAuthzCacheRequestPB req; ResetAuthzCacheResponsePB resp; RETURN_NOT_OK(proxy->ResetAuthzCache(req, &resp, &ctl)); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } return Status::OK(); } Status ResetAuthzCache(const RunnerContext& context) { vector<string> master_addresses; RETURN_NOT_OK(ParseMasterAddresses(context, &master_addresses)); if (!FLAGS_force) { // Make sure the list of master addresses specified for the command // matches the actual list of masters in the cluster. RETURN_NOT_OK(VerifyMasterAddressList(master_addresses)); } // It makes sense to reset privileges cache at every master in the cluster. // Otherwise, SentryAuthzProvider might return inconsistent results for authz // requests upon master leadership change. vector<Status> statuses; statuses.reserve(master_addresses.size()); for (const auto& address : master_addresses) { auto status = ResetAuthzCacheAtMaster(address); statuses.emplace_back(std::move(status)); } DCHECK_EQ(master_addresses.size(), statuses.size()); string err_str; for (auto i = 0; i < statuses.size(); ++i) { const auto& s = statuses[i]; if (s.ok()) { continue; } err_str += Substitute(" error from master at $0: $1", master_addresses[i], s.ToString()); } if (err_str.empty()) { return Status::OK(); } return Status::Incomplete(err_str); } } // anonymous namespace unique_ptr<Mode> BuildMasterMode() { ModeBuilder builder("master"); builder.Description("Operate on a Kudu Master"); { unique_ptr<Action> action_reset = ActionBuilder("reset", &ResetAuthzCache) .Description("Reset the privileges cache") .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc }) .AddOptionalParameter( "force", boost::none, string("Ignore mismatches of the specified and the actual lists " "of master addresses in the cluster")) .Build(); unique_ptr<Mode> mode_authz_cache = ModeBuilder("authz_cache") .Description("Operate on the authz cache of a Kudu Master") .AddAction(std::move(action_reset)) .Build(); builder.AddMode(std::move(mode_authz_cache)); } { unique_ptr<Action> dump_memtrackers = ActionBuilder("dump_memtrackers", &MasterDumpMemTrackers) .Description("Dump the memtrackers from a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddOptionalParameter("format") .AddOptionalParameter("memtracker_output") .AddOptionalParameter("timeout_ms") .Build(); builder.AddAction(std::move(dump_memtrackers)); } { unique_ptr<Action> get_flags = ActionBuilder("get_flags", &MasterGetFlags) .Description("Get the gflags for a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddOptionalParameter("all_flags") .AddOptionalParameter("flag_tags") .Build(); builder.AddAction(std::move(get_flags)); } { unique_ptr<Action> set_flag = ActionBuilder("set_flag", &MasterSetFlag) .Description("Change a gflag value on a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .AddRequiredParameter({ kFlagArg, "Name of the gflag" }) .AddRequiredParameter({ kValueArg, "New value for the gflag" }) .AddOptionalParameter("force") .Build(); builder.AddAction(std::move(set_flag)); } { unique_ptr<Action> status = ActionBuilder("status", &MasterStatus) .Description("Get the status of a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .Build(); builder.AddAction(std::move(status)); } { unique_ptr<Action> timestamp = ActionBuilder("timestamp", &MasterTimestamp) .Description("Get the current timestamp of a Kudu Master") .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc }) .Build(); builder.AddAction(std::move(timestamp)); } { unique_ptr<Action> list_masters = ActionBuilder("list", &ListMasters) .Description("List masters in a Kudu cluster") .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc }) .AddOptionalParameter( "columns", string("uuid,rpc-addresses,role"), string("Comma-separated list of master info fields to " "include in output.\nPossible values: uuid, " "rpc-addresses, http-addresses, version, seqno, " "start_time and role")) .AddOptionalParameter("format") .AddOptionalParameter("timeout_ms") .Build(); builder.AddAction(std::move(list_masters)); } return builder.Build(); } } // namespace tools } // namespace kudu <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include <AST.h> #include <ASTVisitor.h> #include <Control.h> #include <Scope.h> #include <Semantic.h> #include <TranslationUnit.h> #include <PrettyPrinter.h> #include <QFile> #include <QList> #include <QCoreApplication> #include <QStringList> #include <QFileInfo> #include <QtDebug> #include <cstdio> #include <cstdlib> #include <iostream> #include <sstream> CPLUSPLUS_USE_NAMESPACE class Rewrite { QMultiMap<unsigned, QByteArray> _insertBefore; QMultiMap<unsigned, QByteArray> _insertAfter; QSet<unsigned> _removed; public: void remove(unsigned index) { remove(index, index + 1); } void remove(unsigned first, unsigned last) { Q_ASSERT(first < last); for (; first != last; ++first) _removed.insert(first); } void insertTextBefore(unsigned index, const QByteArray &text) { _insertBefore.insert(index, text); } void insertTextAfter(unsigned index, const QByteArray &text) { _insertAfter.insert(index, text); } void rewrite(const TranslationUnit *unit, const QByteArray &contents, QByteArray *out) { _source = contents; const char *source = contents.constData(); unsigned previousTokenEndPosition = 0; for (unsigned i = 0; i < unit->tokenCount(); ++i) { const Token &tk = unit->tokenAt(i); if (previousTokenEndPosition != tk.begin()) { Q_ASSERT(previousTokenEndPosition < tk.begin()); out->append(source + previousTokenEndPosition, tk.begin() - previousTokenEndPosition); } QMultiMap<unsigned, QByteArray>::const_iterator it; it = _insertBefore.constFind(i); for (; it != _insertBefore.constEnd() && it.key() == i; ++it) { out->append(it.value()); } if (! _removed.contains(i)) out->append(source + tk.begin(), tk.length); it = _insertAfter.constFind(i); for (; it != _insertAfter.constEnd() && it.key() == i; ++it) { out->append(it.value()); } previousTokenEndPosition = tk.end(); } } protected: QByteArray _source; }; class SimpleRefactor: protected ASTVisitor, Rewrite { public: SimpleRefactor(Control *control) : ASTVisitor(control) { } void operator()(const TranslationUnit *unit, const QByteArray &source, QByteArray *out) { accept(unit->ast()); rewrite(unit, source, out); } protected: bool isEnumOrTypedefEnum(SpecifierAST *spec) { if (! spec) return false; if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) { if (tokenKind(simpleSpec->specifier_token) == T_TYPEDEF) return isEnumOrTypedefEnum(spec->next); } return spec->asEnumSpecifier() != 0; } virtual bool visit(SimpleDeclarationAST *ast) { if (isEnumOrTypedefEnum(ast->decl_specifier_seq)) { //remove(ast->firstToken(), ast->lastToken()); insertTextBefore(ast->firstToken(), "/* #REF# removed "); insertTextAfter(ast->lastToken() - 1, "*/"); return true; } return true; } virtual bool visit(AccessDeclarationAST *ast) { if (tokenKind(ast->access_specifier_token) == T_PRIVATE) { // change visibility from `private' to `public'. remove(ast->access_specifier_token); insertTextAfter(ast->access_specifier_token, "public /* #REF# private->public */"); } return true; } virtual bool visit(FunctionDefinitionAST *ast) { bool isInline = false; for (SpecifierAST *spec = ast->decl_specifier_seq; spec; spec = spec->next) { if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) { if (tokenKind(simpleSpec->specifier_token) == T_INLINE) { isInline = true; break; } } } // force the `inline' specifier. if (! isInline) insertTextBefore(ast->firstToken(), "inline /* #REF# made inline */ "); return true; } virtual bool visit(ClassSpecifierAST *ast) { // export/import the class using the macro MY_EXPORT. if (ast->name) insertTextBefore(ast->name->firstToken(), "MY_EXPORT "); // add QObject to the base clause. if (ast->colon_token) insertTextAfter(ast->colon_token, " public QObject,"); else if (ast->lbrace_token) insertTextBefore(ast->lbrace_token, ": public QObject "); // mark the class as Q_OBJECT. if (ast->lbrace_token) insertTextAfter(ast->lbrace_token, " Q_OBJECT\n"); for (DeclarationAST *it = ast->member_specifiers; it; it = it->next) { accept(it); } return false; } virtual bool visit(CppCastExpressionAST *ast) { // Replace the C++ cast expression (e.g. static_cast<foo>(a)) with // the one generated by the pretty printer. std::ostringstream o; PrettyPrinter pp(control(), o); pp(ast, _source); remove(ast->firstToken(), ast->lastToken()); const std::string str = o.str(); insertTextBefore(ast->firstToken(), str.c_str()); insertTextBefore(ast->firstToken(), "/* #REF# beautiful cast */ "); return false; } }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); const QString appName = args.first(); args.removeFirst(); bool test_rewriter = false; bool test_pretty_printer = false; foreach (QString arg, args) { if (arg == QLatin1String("--test-rewriter")) test_rewriter = true; else if (arg == QLatin1String("--test-pretty-printer")) test_pretty_printer = true; else if (arg == QLatin1String("--help")) { const QFileInfo appInfo(appName); const QByteArray appFileName = QFile::encodeName(appInfo.fileName()); printf("Usage: %s [options]\n" " --help Display this information\n" " --test-rewriter Test the tree rewriter\n" " --test-pretty-printer Test the pretty printer\n", appFileName.constData()); return EXIT_SUCCESS; } } QFile in; if (! in.open(stdin, QFile::ReadOnly)) return EXIT_FAILURE; const QByteArray source = in.readAll(); Control control; StringLiteral *fileId = control.findOrInsertFileName("<stdin>"); TranslationUnit unit(&control, fileId); unit.setObjCEnabled(true); unit.setSource(source.constData(), source.size()); unit.parse(); if (! unit.ast()) return EXIT_FAILURE; TranslationUnitAST *ast = unit.ast()->asTranslationUnit(); Q_ASSERT(ast != 0); Scope globalScope; Semantic sem(&control); for (DeclarationAST *decl = ast->declarations; decl; decl = decl->next) { sem.check(decl, &globalScope); } // test the rewriter if (test_rewriter) { QByteArray out; SimpleRefactor refactor(&control); refactor(&unit, source, &out); printf("%s\n", out.constData()); } else if (test_pretty_printer) { PrettyPrinter pp(&control, std::cout); pp(unit.ast(), source); } return EXIT_SUCCESS; } <commit_msg>A simple generator for the clone methods.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include <AST.h> #include <ASTVisitor.h> #include <Control.h> #include <Scope.h> #include <Semantic.h> #include <TranslationUnit.h> #include <PrettyPrinter.h> #include <Literals.h> #include <Symbols.h> #include <Names.h> #include <CoreTypes.h> #include <QFile> #include <QList> #include <QCoreApplication> #include <QStringList> #include <QFileInfo> #include <QTime> #include <QtDebug> #include <cstdio> #include <cstdlib> #include <iostream> #include <sstream> CPLUSPLUS_USE_NAMESPACE class Rewrite { QMultiMap<unsigned, QByteArray> _insertBefore; QMultiMap<unsigned, QByteArray> _insertAfter; QSet<unsigned> _removed; public: void remove(unsigned index) { remove(index, index + 1); } void remove(unsigned first, unsigned last) { Q_ASSERT(first < last); for (; first != last; ++first) _removed.insert(first); } void insertTextBefore(unsigned index, const QByteArray &text) { _insertBefore.insert(index, text); } void insertTextAfter(unsigned index, const QByteArray &text) { _insertAfter.insert(index, text); } void rewrite(const TranslationUnit *unit, const QByteArray &contents, QByteArray *out) { _source = contents; const char *source = contents.constData(); unsigned previousTokenEndPosition = 0; for (unsigned i = 0; i < unit->tokenCount(); ++i) { const Token &tk = unit->tokenAt(i); if (previousTokenEndPosition != tk.begin()) { Q_ASSERT(previousTokenEndPosition < tk.begin()); out->append(source + previousTokenEndPosition, tk.begin() - previousTokenEndPosition); } QMultiMap<unsigned, QByteArray>::const_iterator it; it = _insertBefore.constFind(i); for (; it != _insertBefore.constEnd() && it.key() == i; ++it) { out->append(it.value()); } if (! _removed.contains(i)) out->append(source + tk.begin(), tk.length); it = _insertAfter.constFind(i); for (; it != _insertAfter.constEnd() && it.key() == i; ++it) { out->append(it.value()); } previousTokenEndPosition = tk.end(); } } protected: QByteArray _source; }; class SimpleRefactor: protected ASTVisitor, Rewrite { public: SimpleRefactor(Control *control) : ASTVisitor(control) { } void operator()(const TranslationUnit *unit, const QByteArray &source, QByteArray *out) { accept(unit->ast()); rewrite(unit, source, out); } protected: bool isEnumOrTypedefEnum(SpecifierAST *spec) { if (! spec) return false; if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) { if (tokenKind(simpleSpec->specifier_token) == T_TYPEDEF) return isEnumOrTypedefEnum(spec->next); } return spec->asEnumSpecifier() != 0; } virtual bool visit(SimpleDeclarationAST *ast) { if (isEnumOrTypedefEnum(ast->decl_specifier_seq)) { //remove(ast->firstToken(), ast->lastToken()); insertTextBefore(ast->firstToken(), "/* #REF# removed "); insertTextAfter(ast->lastToken() - 1, "*/"); return true; } return true; } virtual bool visit(AccessDeclarationAST *ast) { if (tokenKind(ast->access_specifier_token) == T_PRIVATE) { // change visibility from `private' to `public'. remove(ast->access_specifier_token); insertTextAfter(ast->access_specifier_token, "public /* #REF# private->public */"); } return true; } virtual bool visit(FunctionDefinitionAST *ast) { bool isInline = false; for (SpecifierAST *spec = ast->decl_specifier_seq; spec; spec = spec->next) { if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) { if (tokenKind(simpleSpec->specifier_token) == T_INLINE) { isInline = true; break; } } } // force the `inline' specifier. if (! isInline) insertTextBefore(ast->firstToken(), "inline /* #REF# made inline */ "); return true; } virtual bool visit(ClassSpecifierAST *ast) { // export/import the class using the macro MY_EXPORT. if (ast->name) insertTextBefore(ast->name->firstToken(), "MY_EXPORT "); // add QObject to the base clause. if (ast->colon_token) insertTextAfter(ast->colon_token, " public QObject,"); else if (ast->lbrace_token) insertTextBefore(ast->lbrace_token, ": public QObject "); // mark the class as Q_OBJECT. if (ast->lbrace_token) insertTextAfter(ast->lbrace_token, " Q_OBJECT\n"); for (DeclarationAST *it = ast->member_specifiers; it; it = it->next) { accept(it); } return false; } virtual bool visit(CppCastExpressionAST *ast) { // Replace the C++ cast expression (e.g. static_cast<foo>(a)) with // the one generated by the pretty printer. std::ostringstream o; PrettyPrinter pp(control(), o); pp(ast, _source); remove(ast->firstToken(), ast->lastToken()); const std::string str = o.str(); insertTextBefore(ast->firstToken(), str.c_str()); insertTextBefore(ast->firstToken(), "/* #REF# beautiful cast */ "); return false; } }; class CloneCG: protected ASTVisitor { public: CloneCG(Control *control) : ASTVisitor(control) { } void operator()(AST *ast) { std::cout << "/**************************************************************************\n" "**\n" "** This file is part of Qt Creator\n" "**\n" "** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\n" "**\n" "** Contact: Qt Software Information (qt-info@nokia.com)\n" "**\n" "** Commercial Usage\n" "**\n" "** Licensees holding valid Qt Commercial licenses may use this file in\n" "** accordance with the Qt Commercial License Agreement provided with the\n" "** Software or, alternatively, in accordance with the terms contained in\n" "** a written agreement between you and Nokia.\n" "**\n" "** GNU Lesser General Public License Usage\n" "**\n" "** Alternatively, this file may be used under the terms of the GNU Lesser\n" "** General Public License version 2.1 as published by the Free Software\n" "** Foundation and appearing in the file LICENSE.LGPL included in the\n" "** packaging of this file. Please review the following information to\n" "** ensure the GNU Lesser General Public License version 2.1 requirements\n" "** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n" "**\n" "** If you are unsure which license is appropriate for your use, please\n" "** contact the sales department at qt-sales@nokia.com.\n" "**\n" "**************************************************************************/\n" "\n" "#include \"AST.h\"\n" "\n" "CPLUSPLUS_BEGIN_NAMESPACE\n" << std::endl; accept(ast); std::cout << "CPLUSPLUS_END_NAMESPACE" << std::endl; } protected: using ASTVisitor::visit; QMap<QByteArray, ClassSpecifierAST *> classMap; QByteArray id_cast(NameAST *name) { if (! name) return QByteArray(); Identifier *id = identifier(name->asSimpleName()->identifier_token); return QByteArray::fromRawData(id->chars(), id->size()); } void copyMembers(Class *klass) { for (unsigned i = 0; i < klass->baseClassCount(); ++i) { const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars(); if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) { copyMembers(baseClassSpec->symbol); } } const QByteArray className = klass->name()->identifier()->chars(); std::cout << " // copy " << className.constData() << std::endl; for (unsigned i = 0; i < klass->memberCount(); ++i) { Symbol *member = klass->memberAt(i); Identifier *id = member->name()->identifier(); if (! id) continue; const QByteArray memberName = QByteArray::fromRawData(id->chars(), id->size()); if (member->type().isUnsigned() && memberName.endsWith("_token")) { std::cout << " ast->" << id->chars() << " = " << id->chars() << ";" << std::endl; } else if (PointerType *ptrTy = member->type()->asPointerType()) { if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) { QByteArray typeName = namedTy->name()->identifier()->chars(); if (typeName.endsWith("AST")) { std::cout << " if (" << memberName.constData() << ") ast->" << memberName.constData() << " = " << memberName.constData() << "->clone(pool);" << std::endl; } } } } } virtual bool visit(ClassSpecifierAST *ast) { Class *klass = ast->symbol; const QByteArray className = id_cast(ast->name); classMap.insert(className, ast); Identifier *clone_id = control()->findOrInsertIdentifier("clone"); if (! klass->members()->lookat(clone_id)) return true; std::cout << className.constData() << " *" << className.constData() << "::clone(MemoryPool *pool) const" << std::endl << "{" << std::endl; std::cout << " " << className.constData() << " *ast = new (pool) " << className.constData() << ";" << std::endl; copyMembers(klass); std::cout << " return ast;" << std::endl << "}" << std::endl << std::endl; return true; } }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); const QString appName = args.first(); args.removeFirst(); bool test_rewriter = false; bool test_pretty_printer = false; foreach (QString arg, args) { if (arg == QLatin1String("--test-rewriter")) test_rewriter = true; else if (arg == QLatin1String("--test-pretty-printer")) test_pretty_printer = true; else if (arg == QLatin1String("--help")) { const QFileInfo appInfo(appName); const QByteArray appFileName = QFile::encodeName(appInfo.fileName()); printf("Usage: %s [options]\n" " --help Display this information\n" " --test-rewriter Test the tree rewriter\n" " --test-pretty-printer Test the pretty printer\n", appFileName.constData()); return EXIT_SUCCESS; } } QFile in; if (! in.open(stdin, QFile::ReadOnly)) return EXIT_FAILURE; const QByteArray source = in.readAll(); Control control; StringLiteral *fileId = control.findOrInsertFileName("<stdin>"); TranslationUnit unit(&control, fileId); unit.setObjCEnabled(true); unit.setSource(source.constData(), source.size()); unit.parse(); if (! unit.ast()) return EXIT_FAILURE; TranslationUnitAST *ast = unit.ast()->asTranslationUnit(); Q_ASSERT(ast != 0); Scope globalScope; Semantic sem(&control); for (DeclarationAST *decl = ast->declarations; decl; decl = decl->next) { sem.check(decl, &globalScope); } // test the rewriter if (test_rewriter) { QByteArray out; SimpleRefactor refactor(&control); refactor(&unit, source, &out); printf("%s\n", out.constData()); } else if (test_pretty_printer) { MemoryPool pool2; TranslationUnitAST *other = unit.ast()->clone(&pool2)->asTranslationUnit(); PrettyPrinter pp(&control, std::cout); pp(other, source); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -Xclang -verify 2>&1 | FileCheck %s #include "cling/Interpreter/RuntimePrintValue.h" struct Trigger { } trgr // CHECK: (struct Trigger &) @0x{{.*}} .undo struct Trigger2 { } trgr // CHECK-NEXT: (struct Trigger2 &) @0x{{.*}} .undo .undo // #include "cling/Interpreter/RuntimePrintValue.h" struct Trigger3 { } trgr // CHECK-NEXT: (struct Trigger3 &) @0x{{.*}} // expected-no-diagnostics .q <commit_msg>Fixes for CERN/master.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -Xclang -verify 2>&1 | FileCheck %s #include "cling/Interpreter/RuntimePrintValue.h" struct Trigger { } trgr // CHECK: (struct Trigger &) @0x{{.*}} .undo struct Trigger2 { } trgr // CHECK-NEXT: (struct Trigger2 &) @0x{{.*}} .undo // expected-no-diagnostics .q <|endoftext|>
<commit_before>#include "shepards.h" using std::cout; using std::endl; namespace scenarios { shepards::shepards(const boost::property_tree::ptree& config) : scenario<shepards>(config) { assert(config.get<std::string>("type") == "shepards"); for(auto& point : config.get_child("curve.points")) { std::vector<float> p; for(auto& pi : point.second) p.push_back(pi.second.get<float>("")); if(p.size() != 2) throw std::runtime_error("shepards - only 2D points are supported at the moment."); m_leading_curve.add_point(Imath::Vec2<float>(p[0], p[1])); } m_sampling = config.get("curve.sampling", 0.05); m_power = config.get("power", -2); const unsigned sample_count = (unsigned)round(1.0f / m_sampling); for(unsigned s=0; s<=sample_count; ++s) { const float t = (float)s / (float)sample_count; m_samples.push_back(std::make_pair(m_leading_curve[t], m_leading_curve.normdiff(t))); } } const bezier<Imath::Vec2<float>>& shepards::leading_curve() const { return m_leading_curve; } float shepards::sampling() const { return m_sampling; } std::string shepards::type() { return "shepards"; } Imath::Vec2<float> shepards::sample(const Imath::Vec2<float>& pos) const { Imath::Vec2<float> value(0.0f, 0.0f); float norm = 0.0f; for(auto& p : m_samples) { const float weight = pow((pos - p.first).length(), m_power); // if there is a division by zero, we've hit precisely a point in the source curve // -> just return its value and be done if(std::isinf(weight)) return p.second; norm += weight; value += p.second * weight; } return value / norm; } agents shepards::apply(const agents& source) const { // get the heading line / direction line l = source.heading(); // normalize the direction vector - we'll need to use it to compute acos l.direction.normalize(); // and compute the angle to the world axes const float lAngle = atan2(l.direction.y, l.direction.x); agents result(source); for(unsigned agentId = 0; agentId < source.agent_count(); ++agentId) { auto& agent = source[agentId]; for(unsigned frameId = 0; frameId < agent.size(); ++frameId) { // evaluate the shepard's function at a local point const Imath::Vec2<float> s = sample(result[agentId][std::max((int)frameId-1, 0)].position); // and compute its angle to world axes const float sAngle = atan2(s.y, s.x); // the full angle is the difference const float angle = sAngle - lAngle; const float cs = cos(angle); const float sn = sin(angle); // update the position, except first frame (there we keep the original) if(frameId > 0) { Imath::Vec2<float> diff = agent[frameId].position - agent[frameId-1].position; result[agentId][frameId].position = result[agentId][frameId-1].position + Imath::Vec2<float>( diff.x * cs - diff.y * sn, diff.y * cs + diff.x * sn ); } // and update the direction auto& dir = result[agentId][frameId].direction; dir = Imath::Vec2<float>( dir.x * cs - dir.y * sn, dir.y * cs + dir.x * sn ); } } return result; } } <commit_msg>Adjusted first frame positions to be based on local coordinate frame of the start of the curve<commit_after>#include "shepards.h" using std::cout; using std::endl; namespace scenarios { shepards::shepards(const boost::property_tree::ptree& config) : scenario<shepards>(config) { assert(config.get<std::string>("type") == "shepards"); for(auto& point : config.get_child("curve.points")) { std::vector<float> p; for(auto& pi : point.second) p.push_back(pi.second.get<float>("")); if(p.size() != 2) throw std::runtime_error("shepards - only 2D points are supported at the moment."); m_leading_curve.add_point(Imath::Vec2<float>(p[0], p[1])); } m_sampling = config.get("curve.sampling", 0.05); m_power = config.get("power", -2); const unsigned sample_count = (unsigned)round(1.0f / m_sampling); for(unsigned s=0; s<=sample_count; ++s) { const float t = (float)s / (float)sample_count; m_samples.push_back(std::make_pair(m_leading_curve[t], m_leading_curve.normdiff(t))); } } const bezier<Imath::Vec2<float>>& shepards::leading_curve() const { return m_leading_curve; } float shepards::sampling() const { return m_sampling; } std::string shepards::type() { return "shepards"; } Imath::Vec2<float> shepards::sample(const Imath::Vec2<float>& pos) const { Imath::Vec2<float> value(0.0f, 0.0f); float norm = 0.0f; for(auto& p : m_samples) { const float weight = pow((pos - p.first).length(), m_power); // if there is a division by zero, we've hit precisely a point in the source curve // -> just return its value and be done if(std::isinf(weight)) return p.second; norm += weight; value += p.second * weight; } return value / norm; } agents shepards::apply(const agents& source) const { // get the heading line / direction line l = source.heading(); // normalize the direction vector - we'll need to use it to compute acos l.direction.normalize(); // and compute the angle to the world axes const float lAngle = atan2(l.direction.y, l.direction.x); agents result(source); for(unsigned agentId = 0; agentId < source.agent_count(); ++agentId) { auto& agent = source[agentId]; // first frame's positions should be adjusted to the local axes { // compute the angular difference between line's direction and curve's beginning const Imath::Vec2<float> s = m_leading_curve.normdiff(0.0f); // and compute its angle to world axes const float sAngle = atan2(s.y, s.x); // the full angle is the difference const float angle = sAngle - lAngle; const float cs = cos(angle); const float sn = sin(angle); // make a vector from line origin to trajectory start const Imath::Vec2<float> d = agent[0].position - l.origin; // rotate it to match local coord system, relative to leading curve's start point result[agentId][0].position = m_leading_curve[0] + Imath::Vec2<float>( d.x * cs - d.y * sn, d.y * cs + d.x * sn ); // and rotate direction in the same manner const Imath::Vec2<float>& dir = agent[0].direction; result[agentId][0].direction = Imath::Vec2<float>( dir.x * cs - dir.y * sn, dir.y * cs + dir.x * sn ); } for(unsigned frameId = 0; frameId < agent.size(); ++frameId) { // evaluate the shepard's function at a local point const Imath::Vec2<float> s = sample(result[agentId][std::max((int)frameId-1, 0)].position); // and compute its angle to world axes const float sAngle = atan2(s.y, s.x); // the full angle is the difference const float angle = sAngle - lAngle; const float cs = cos(angle); const float sn = sin(angle); // update the position, except first frame (there we keep the original) if(frameId > 0) { Imath::Vec2<float> diff = agent[frameId].position - agent[frameId-1].position; result[agentId][frameId].position = result[agentId][frameId-1].position + Imath::Vec2<float>( diff.x * cs - diff.y * sn, diff.y * cs + diff.x * sn ); } // and update the direction auto& dir = result[agentId][frameId].direction; dir = Imath::Vec2<float>( dir.x * cs - dir.y * sn, dir.y * cs + dir.x * sn ); } } return result; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include "tests/cql_test_env.hh" #include "tests/perf/perf.hh" #include <seastar/core/app-template.hh> #include "schema_builder.hh" static const sstring table_name = "cf"; static bytes make_key(uint64_t sequence) { bytes b(bytes::initialized_later(), sizeof(sequence)); auto i = b.begin(); write<uint64_t>(i, sequence); return b; }; static auto execute_update_for_key(cql_test_env& env, const bytes& key) { return env.execute_cql(sprint("UPDATE cf SET " "\"C0\" = 0x8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a," "\"C1\" = 0xa8761a2127160003033a8f4f3d1069b7833ebe24ef56b3beee728c2b686ca516fa51," "\"C2\" = 0x583449ce81bfebc2e1a695eb59aad5fcc74d6d7311fc6197b10693e1a161ca2e1c64," "\"C3\" = 0x62bcb1dbc0ff953abc703bcb63ea954f437064c0c45366799658bd6b91d0f92908d7," "\"C4\" = 0x222fcbe31ffa1e689540e1499b87fa3f9c781065fccd10e4772b4c7039c2efd0fb27 " "WHERE \"KEY\"= 0x%s;", to_hex(key))).discard_result(); }; static auto execute_counter_update_for_key(cql_test_env& env, const bytes& key) { return env.execute_cql(sprint("UPDATE cf SET " "\"C0\" = \"C0\" + 1," "\"C1\" = \"C1\" + 2," "\"C2\" = \"C2\" + 3," "\"C3\" = \"C3\" + 4," "\"C4\" = \"C4\" + 5 " "WHERE \"KEY\"= 0x%s;", to_hex(key))).discard_result(); }; struct test_config { enum class run_mode { read, write, del }; run_mode mode; unsigned partitions; unsigned concurrency; bool query_single_key; unsigned duration_in_seconds; bool counters; unsigned operations_per_shard = 0; }; std::ostream& operator<<(std::ostream& os, const test_config::run_mode& m) { switch (m) { case test_config::run_mode::write: return os << "write"; case test_config::run_mode::read: return os << "read"; case test_config::run_mode::del: return os << "delete"; } abort(); } std::ostream& operator<<(std::ostream& os, const test_config& cfg) { return os << "{partitions=" << cfg.partitions << ", concurrency=" << cfg.concurrency << ", mode=" << cfg.mode << ", query_single_key=" << (cfg.query_single_key ? "yes" : "no") << ", counters=" << (cfg.counters ? "yes" : "no") << "}"; } future<> create_partitions(cql_test_env& env, test_config& cfg) { std::cout << "Creating " << cfg.partitions << " partitions..." << std::endl; auto partitions = boost::irange(0, (int)cfg.partitions); return do_for_each(partitions.begin(), partitions.end(), [&] (int sequence) { if (cfg.counters) { return execute_counter_update_for_key(env, make_key(sequence)); } return execute_update_for_key(env, make_key(sequence)); }); } future<std::vector<double>> test_read(cql_test_env& env, test_config& cfg) { return create_partitions(env, cfg).then([&env] { return env.prepare("select \"C0\", \"C1\", \"C2\", \"C3\", \"C4\" from cf where \"KEY\" = ?"); }).then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_write(cql_test_env& env, test_config& cfg) { return env.prepare("UPDATE cf SET " "\"C0\" = 0x8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a," "\"C1\" = 0xa8761a2127160003033a8f4f3d1069b7833ebe24ef56b3beee728c2b686ca516fa51," "\"C2\" = 0x583449ce81bfebc2e1a695eb59aad5fcc74d6d7311fc6197b10693e1a161ca2e1c64," "\"C3\" = 0x62bcb1dbc0ff953abc703bcb63ea954f437064c0c45366799658bd6b91d0f92908d7," "\"C4\" = 0x222fcbe31ffa1e689540e1499b87fa3f9c781065fccd10e4772b4c7039c2efd0fb27 " "WHERE \"KEY\" = ?;") .then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_delete(cql_test_env& env, test_config& cfg) { return create_partitions(env, cfg).then([&env] { return env.prepare("DELETE \"C0\", \"C1\", \"C2\", \"C3\", \"C4\" FROM cf WHERE \"KEY\" = ?"); }).then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_counter_update(cql_test_env& env, test_config& cfg) { return env.prepare("UPDATE cf SET " "\"C0\" = \"C0\" + 1," "\"C1\" = \"C1\" + 2," "\"C2\" = \"C2\" + 3," "\"C3\" = \"C3\" + 4," "\"C4\" = \"C4\" + 5 " "WHERE \"KEY\" = ?;") .then([&env, &cfg] (auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } schema_ptr make_counter_schema(const sstring& ks_name) { return schema_builder(ks_name, "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", counter_type) .with_column("C1", counter_type) .with_column("C2", counter_type) .with_column("C3", counter_type) .with_column("C4", counter_type) .build(); } future<std::vector<double>> do_test(cql_test_env& env, test_config& cfg) { std::cout << "Running test with config: " << cfg << std::endl; return env.create_table([&cfg] (auto ks_name) { if (cfg.counters) { return *make_counter_schema(ks_name); } return schema({}, ks_name, "cf", {{"KEY", bytes_type}}, {}, {{"C0", bytes_type}, {"C1", bytes_type}, {"C2", bytes_type}, {"C3", bytes_type}, {"C4", bytes_type}}, {}, utf8_type); }).then([&env, &cfg] { switch (cfg.mode) { case test_config::run_mode::read: return test_read(env, cfg); case test_config::run_mode::write: if (cfg.counters) { return test_counter_update(env, cfg); } else { return test_write(env, cfg); } case test_config::run_mode::del: return test_delete(env, cfg); }; abort(); }); } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("partitions", bpo::value<unsigned>()->default_value(10000), "number of partitions") ("write", "test write path instead of read path") ("delete", "test delete path instead of read path") ("duration", bpo::value<unsigned>()->default_value(5), "test duration in seconds") ("query-single-key", "test reading with a single key instead of random keys") ("concurrency", bpo::value<unsigned>()->default_value(100), "workers per core") ("operations-per-shard", bpo::value<unsigned>(), "run this many operations per shard (overrides duration)") ("counters", "test counters"); return app.run(argc, argv, [&app] { return do_with_cql_env([&app] (auto&& env) { auto cfg = test_config(); cfg.partitions = app.configuration()["partitions"].as<unsigned>(); cfg.duration_in_seconds = app.configuration()["duration"].as<unsigned>(); cfg.concurrency = app.configuration()["concurrency"].as<unsigned>(); cfg.query_single_key = app.configuration().count("query-single-key"); cfg.counters = app.configuration().count("counters"); if (app.configuration().count("write")) { cfg.mode = test_config::run_mode::write; } else if (app.configuration().count("delete")) { cfg.mode = test_config::run_mode::del; } else { cfg.mode = test_config::run_mode::read; }; if (app.configuration().count("operations-per-shard")) { cfg.operations_per_shard = app.configuration()["operations-per-shard"].as<unsigned>(); } do_test(env, cfg).get(); return make_ready_future<>(); }); }); } <commit_msg>perf_simple_query: calculate and print statistics<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include "tests/cql_test_env.hh" #include "tests/perf/perf.hh" #include <seastar/core/app-template.hh> #include "schema_builder.hh" static const sstring table_name = "cf"; static bytes make_key(uint64_t sequence) { bytes b(bytes::initialized_later(), sizeof(sequence)); auto i = b.begin(); write<uint64_t>(i, sequence); return b; }; static auto execute_update_for_key(cql_test_env& env, const bytes& key) { return env.execute_cql(sprint("UPDATE cf SET " "\"C0\" = 0x8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a," "\"C1\" = 0xa8761a2127160003033a8f4f3d1069b7833ebe24ef56b3beee728c2b686ca516fa51," "\"C2\" = 0x583449ce81bfebc2e1a695eb59aad5fcc74d6d7311fc6197b10693e1a161ca2e1c64," "\"C3\" = 0x62bcb1dbc0ff953abc703bcb63ea954f437064c0c45366799658bd6b91d0f92908d7," "\"C4\" = 0x222fcbe31ffa1e689540e1499b87fa3f9c781065fccd10e4772b4c7039c2efd0fb27 " "WHERE \"KEY\"= 0x%s;", to_hex(key))).discard_result(); }; static auto execute_counter_update_for_key(cql_test_env& env, const bytes& key) { return env.execute_cql(sprint("UPDATE cf SET " "\"C0\" = \"C0\" + 1," "\"C1\" = \"C1\" + 2," "\"C2\" = \"C2\" + 3," "\"C3\" = \"C3\" + 4," "\"C4\" = \"C4\" + 5 " "WHERE \"KEY\"= 0x%s;", to_hex(key))).discard_result(); }; struct test_config { enum class run_mode { read, write, del }; run_mode mode; unsigned partitions; unsigned concurrency; bool query_single_key; unsigned duration_in_seconds; bool counters; unsigned operations_per_shard = 0; }; std::ostream& operator<<(std::ostream& os, const test_config::run_mode& m) { switch (m) { case test_config::run_mode::write: return os << "write"; case test_config::run_mode::read: return os << "read"; case test_config::run_mode::del: return os << "delete"; } abort(); } std::ostream& operator<<(std::ostream& os, const test_config& cfg) { return os << "{partitions=" << cfg.partitions << ", concurrency=" << cfg.concurrency << ", mode=" << cfg.mode << ", query_single_key=" << (cfg.query_single_key ? "yes" : "no") << ", counters=" << (cfg.counters ? "yes" : "no") << "}"; } future<> create_partitions(cql_test_env& env, test_config& cfg) { std::cout << "Creating " << cfg.partitions << " partitions..." << std::endl; auto partitions = boost::irange(0, (int)cfg.partitions); return do_for_each(partitions.begin(), partitions.end(), [&] (int sequence) { if (cfg.counters) { return execute_counter_update_for_key(env, make_key(sequence)); } return execute_update_for_key(env, make_key(sequence)); }); } future<std::vector<double>> test_read(cql_test_env& env, test_config& cfg) { return create_partitions(env, cfg).then([&env] { return env.prepare("select \"C0\", \"C1\", \"C2\", \"C3\", \"C4\" from cf where \"KEY\" = ?"); }).then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_write(cql_test_env& env, test_config& cfg) { return env.prepare("UPDATE cf SET " "\"C0\" = 0x8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a," "\"C1\" = 0xa8761a2127160003033a8f4f3d1069b7833ebe24ef56b3beee728c2b686ca516fa51," "\"C2\" = 0x583449ce81bfebc2e1a695eb59aad5fcc74d6d7311fc6197b10693e1a161ca2e1c64," "\"C3\" = 0x62bcb1dbc0ff953abc703bcb63ea954f437064c0c45366799658bd6b91d0f92908d7," "\"C4\" = 0x222fcbe31ffa1e689540e1499b87fa3f9c781065fccd10e4772b4c7039c2efd0fb27 " "WHERE \"KEY\" = ?;") .then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_delete(cql_test_env& env, test_config& cfg) { return create_partitions(env, cfg).then([&env] { return env.prepare("DELETE \"C0\", \"C1\", \"C2\", \"C3\", \"C4\" FROM cf WHERE \"KEY\" = ?"); }).then([&env, &cfg](auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } future<std::vector<double>> test_counter_update(cql_test_env& env, test_config& cfg) { return env.prepare("UPDATE cf SET " "\"C0\" = \"C0\" + 1," "\"C1\" = \"C1\" + 2," "\"C2\" = \"C2\" + 3," "\"C3\" = \"C3\" + 4," "\"C4\" = \"C4\" + 5 " "WHERE \"KEY\" = ?;") .then([&env, &cfg] (auto id) { return time_parallel([&env, &cfg, id] { bytes key = make_key(cfg.query_single_key ? 0 : std::rand() % cfg.partitions); return env.execute_prepared(id, {{cql3::raw_value::make_value(std::move(key))}}).discard_result(); }, cfg.concurrency, cfg.duration_in_seconds, cfg.operations_per_shard); }); } schema_ptr make_counter_schema(const sstring& ks_name) { return schema_builder(ks_name, "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", counter_type) .with_column("C1", counter_type) .with_column("C2", counter_type) .with_column("C3", counter_type) .with_column("C4", counter_type) .build(); } future<std::vector<double>> do_test(cql_test_env& env, test_config& cfg) { std::cout << "Running test with config: " << cfg << std::endl; return env.create_table([&cfg] (auto ks_name) { if (cfg.counters) { return *make_counter_schema(ks_name); } return schema({}, ks_name, "cf", {{"KEY", bytes_type}}, {}, {{"C0", bytes_type}, {"C1", bytes_type}, {"C2", bytes_type}, {"C3", bytes_type}, {"C4", bytes_type}}, {}, utf8_type); }).then([&env, &cfg] { switch (cfg.mode) { case test_config::run_mode::read: return test_read(env, cfg); case test_config::run_mode::write: if (cfg.counters) { return test_counter_update(env, cfg); } else { return test_write(env, cfg); } case test_config::run_mode::del: return test_delete(env, cfg); }; abort(); }); } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("partitions", bpo::value<unsigned>()->default_value(10000), "number of partitions") ("write", "test write path instead of read path") ("delete", "test delete path instead of read path") ("duration", bpo::value<unsigned>()->default_value(5), "test duration in seconds") ("query-single-key", "test reading with a single key instead of random keys") ("concurrency", bpo::value<unsigned>()->default_value(100), "workers per core") ("operations-per-shard", bpo::value<unsigned>(), "run this many operations per shard (overrides duration)") ("counters", "test counters"); return app.run(argc, argv, [&app] { return do_with_cql_env([&app] (auto&& env) { auto cfg = test_config(); cfg.partitions = app.configuration()["partitions"].as<unsigned>(); cfg.duration_in_seconds = app.configuration()["duration"].as<unsigned>(); cfg.concurrency = app.configuration()["concurrency"].as<unsigned>(); cfg.query_single_key = app.configuration().count("query-single-key"); cfg.counters = app.configuration().count("counters"); if (app.configuration().count("write")) { cfg.mode = test_config::run_mode::write; } else if (app.configuration().count("delete")) { cfg.mode = test_config::run_mode::del; } else { cfg.mode = test_config::run_mode::read; }; if (app.configuration().count("operations-per-shard")) { cfg.operations_per_shard = app.configuration()["operations-per-shard"].as<unsigned>(); } auto results = do_test(env, cfg).get0(); std::sort(results.begin(), results.end()); auto median = results[results.size() / 2]; auto min = results[0]; auto max = results[results.size() - 1]; for (auto& r : results) { r = abs(r - median); } std::sort(results.begin(), results.end()); auto mad = results[results.size() / 2]; std::cout << format("\nmedian {:.2f}\nmedian absolute deviation: {:.2f}\nmaximum: {:.2f}\nminimum: {:.2f}\n", median, mad, max, min); return make_ready_future<>(); }); }); } <|endoftext|>
<commit_before>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <cassert> #include <cstdlib> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include "kernel/userver.hh" #include "object/urbi-exception.hh" #include "scheduler/scheduler.hh" #include "scheduler/job.hh" namespace scheduler { // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job (void* job) { static_cast<Job*>(job)->run(); } void Scheduler::add_job (Job* job) { assert (job); assert (!libport::has (jobs_, job)); jobs_.push_back (job); jobs_to_start_ = true; } libport::utime_t Scheduler::work () { ++cycle_; ECHO ("======================================================== cycle " << cycle_); libport::utime_t deadline = execute_round (false); // If some jobs need to be stopped, do it as soon as possible. deadline = std::min (deadline, check_for_stopped_tags (deadline)); #ifdef ENABLE_DEBUG_TRACES if (deadline) ECHO ("Scheduler asking to be woken up in " << (deadline - ::urbiserver->getTime ()) / 1000000L << " seconds"); else ECHO ("Scheduler asking to be woken up ASAP"); #endif return deadline; } libport::utime_t Scheduler::execute_round (bool blocked_only) { // Run all the jobs in the run queue once. If any job declares upon entry or // return that it is not side-effect free, we remember that for the next // cycle. pending_.clear (); std::swap (pending_, jobs_); // By default, wake us up after one hour and consider that we have no // new job to start. Also, run waiting jobs only if the previous round // may have add a side effect and reset this indication for the current // job. libport::utime_t deadline = ::urbiserver->getTime () + 3600000000LL; jobs_to_start_ = false; bool start_waiting = possible_side_effect_; possible_side_effect_ = false; ECHO (pending_.size() << " jobs in the queue for this round"); foreach (Job* job, pending_) { // Kill a job if needed. See explanation in job.hh. to_kill_ = 0; assert (job); assert (!job->terminated ()); // Should the job be started? bool start = false; ECHO ("Considering " << *job << " in state " << state_name (job->state_get ())); switch (job->state_get ()) { case to_start: // New job. Start its coroutine but do not start the job as it would be queued // twice otherwise. It will start doing real work at the next cycle, so set // deadline to 0. Note that we use "continue" here to avoid having the job // requeued because it hasn't been started by setting "start". ECHO ("Starting job " << *job); current_job_ = job; Coro_startCoro_ (coro_, job->coro_get(), job, run_job); current_job_ = 0; ECHO ("Job " << *job << " has been started"); assert (job->state_get () != to_start); deadline = 0; continue; case zombie: assert (false); break; case running: start = !blocked_only || job->blocked (); break; case sleeping: { libport::utime_t job_deadline = job->deadline_get (); if (job_deadline <= ::urbiserver->getTime ()) start = true; else deadline = std::min (deadline, job_deadline); } break; case waiting: // Since jobs keep their orders in the queue, start waiting jobs if // previous jobs in the run have had a possible side effect or if // the previous run may have had some. Without it, we may miss some // changes if the watching job is after the modifying job in the queue // and the watched condition gets true for only one cycle. start = start_waiting | possible_side_effect_; break; case joining: break; } if (start) { ECHO ("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); possible_side_effect_ |= !job->side_effect_free_get (); assert (!current_job_); Coro_switchTo_ (coro_, job->coro_get ()); assert (!current_job_); possible_side_effect_ |= !job->side_effect_free_get (); ECHO ("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); switch (job->state_get ()) { case running: deadline = 0; break; case sleeping: deadline = std::min (deadline, job->deadline_get ()); break; default: break; } } else jobs_.push_back (job); // Job not started, keep it in queue } // Kill a job if needed. See explanation in job.hh. to_kill_ = 0; /// If during this cycle a new job has been created by an existing job, /// start it. if (jobs_to_start_) deadline = 0; return deadline; } libport::utime_t Scheduler::check_for_stopped_tags (libport::utime_t old_deadline) { bool blocked_job = false; // If we have had no stopped tag, return immediately. if (stopped_tags_.empty ()) return old_deadline; // If some jobs have been blocked, mark them as running so that they will // handle the condition when they are resumed. foreach (Job* job, jobs_) if (job->blocked ()) { job->state_set (running); blocked_job = true; } // Wake up blocked jobs. libport::utime_t deadline = execute_round (true); // Reset tags to their real blocked value and reset the list. foreach (tag_state_type t, stopped_tags_) t.first->set_blocked (t.second); stopped_tags_.clear (); return deadline; } void Scheduler::switch_back (Job* job) { // Switch back to the scheduler. assert (current_job_ == job); current_job_ = 0; Coro_switchTo_ (job->coro_get (), coro_); // We regained control, we are again in the context of the job. assert (!current_job_); current_job_ = job; ECHO ("job " << *job << " resumed"); // Check that we are not near exhausting the stack space. job->check_stack_space (); // Execute a deferred exception if any job->check_for_pending_exception (); // If we are in frozen state, let's requeue ourselves waiting // for something to change. And let's mark us side-effect // free during this time so that we won't cause other jobs // to be scheduled. Of course, we have to check for pending // exceptions each time we are woken up. if (job->frozen ()) { bool side_effect_free_save = job->side_effect_free_get (); do { job->side_effect_free_set (true); job->yield_until_things_changed (); job->side_effect_free_set (side_effect_free_save); // Execute a deferred exception if any job->check_for_pending_exception (); } while (job->frozen ()); } } void Scheduler::resume_scheduler (Job* job) { // If the job has not terminated and is side-effect free, then we // assume it will not take a long time as we are probably evaluating // a condition. In order to reduce the number of cycles spent to evaluate // the condition, continue until it asks to be suspended in another // way or until it is no longer side-effect free. if (!job->terminated ()) { if (job->state_get () == running && job->side_effect_free_get ()) return; else jobs_.push_back (job); } ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated\n\t" << "state: " << state_name (job->state_get ())); switch_back (job); } void Scheduler::killall_jobs () { ECHO ("killing all jobs!"); foreach (Job* job, jobs_) kill_job (job); foreach (Job* job, pending_) kill_job (job); } void Scheduler::unschedule_job (Job* job) { assert (job); assert (job != current_job_); ECHO ("unscheduling job " << *job); // Remove the job from the queue. jobs_.remove (job); // Remove it from live queues as well if the job is destroyed. pending_.remove (job); } void Scheduler::kill_job (Job* job) { KillException ke; job->async_throw (ke); } void Scheduler::signal_stop (rTag t) { bool previous_state = t->own_blocked (); t->set_blocked (true); stopped_tags_.push_back (std::make_pair(t, previous_state)); } } // namespace scheduler <commit_msg>Do not test the job state twice in a row<commit_after>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <cassert> #include <cstdlib> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include "kernel/userver.hh" #include "object/urbi-exception.hh" #include "scheduler/scheduler.hh" #include "scheduler/job.hh" namespace scheduler { // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job (void* job) { static_cast<Job*>(job)->run(); } void Scheduler::add_job (Job* job) { assert (job); assert (!libport::has (jobs_, job)); jobs_.push_back (job); jobs_to_start_ = true; } libport::utime_t Scheduler::work () { ++cycle_; ECHO ("======================================================== cycle " << cycle_); libport::utime_t deadline = execute_round (false); // If some jobs need to be stopped, do it as soon as possible. deadline = std::min (deadline, check_for_stopped_tags (deadline)); #ifdef ENABLE_DEBUG_TRACES if (deadline) ECHO ("Scheduler asking to be woken up in " << (deadline - ::urbiserver->getTime ()) / 1000000L << " seconds"); else ECHO ("Scheduler asking to be woken up ASAP"); #endif return deadline; } libport::utime_t Scheduler::execute_round (bool blocked_only) { // Run all the jobs in the run queue once. If any job declares upon entry or // return that it is not side-effect free, we remember that for the next // cycle. pending_.clear (); std::swap (pending_, jobs_); // By default, wake us up after one hour and consider that we have no // new job to start. Also, run waiting jobs only if the previous round // may have add a side effect and reset this indication for the current // job. libport::utime_t deadline = ::urbiserver->getTime () + 3600000000LL; jobs_to_start_ = false; bool start_waiting = possible_side_effect_; possible_side_effect_ = false; ECHO (pending_.size() << " jobs in the queue for this round"); foreach (Job* job, pending_) { // Kill a job if needed. See explanation in job.hh. to_kill_ = 0; assert (job); assert (!job->terminated ()); // Should the job be started? bool start = false; ECHO ("Considering " << *job << " in state " << state_name (job->state_get ())); switch (job->state_get ()) { case to_start: // New job. Start its coroutine but do not start the job as it would be queued // twice otherwise. It will start doing real work at the next cycle, so set // deadline to 0. Note that we use "continue" here to avoid having the job // requeued because it hasn't been started by setting "start". ECHO ("Starting job " << *job); current_job_ = job; Coro_startCoro_ (coro_, job->coro_get(), job, run_job); current_job_ = 0; ECHO ("Job " << *job << " has been started"); assert (job->state_get () != to_start); deadline = 0; continue; case zombie: assert (false); break; case running: start = !blocked_only || job->blocked (); break; case sleeping: { libport::utime_t job_deadline = job->deadline_get (); if (job_deadline <= ::urbiserver->getTime ()) start = true; else deadline = std::min (deadline, job_deadline); } break; case waiting: // Since jobs keep their orders in the queue, start waiting jobs if // previous jobs in the run have had a possible side effect or if // the previous run may have had some. Without it, we may miss some // changes if the watching job is after the modifying job in the queue // and the watched condition gets true for only one cycle. start = start_waiting | possible_side_effect_; break; case joining: break; } if (start) { ECHO ("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); possible_side_effect_ |= !job->side_effect_free_get (); assert (!current_job_); Coro_switchTo_ (coro_, job->coro_get ()); assert (!current_job_); possible_side_effect_ |= !job->side_effect_free_get (); ECHO ("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); switch (job->state_get ()) { case running: deadline = 0; break; case sleeping: deadline = std::min (deadline, job->deadline_get ()); break; default: break; } } else jobs_.push_back (job); // Job not started, keep it in queue } // Kill a job if needed. See explanation in job.hh. to_kill_ = 0; /// If during this cycle a new job has been created by an existing job, /// start it. if (jobs_to_start_) deadline = 0; return deadline; } libport::utime_t Scheduler::check_for_stopped_tags (libport::utime_t old_deadline) { bool blocked_job = false; // If we have had no stopped tag, return immediately. if (stopped_tags_.empty ()) return old_deadline; // If some jobs have been blocked, mark them as running so that they will // handle the condition when they are resumed. foreach (Job* job, jobs_) if (job->blocked ()) { job->state_set (running); blocked_job = true; } // Wake up blocked jobs. libport::utime_t deadline = execute_round (true); // Reset tags to their real blocked value and reset the list. foreach (tag_state_type t, stopped_tags_) t.first->set_blocked (t.second); stopped_tags_.clear (); return deadline; } void Scheduler::switch_back (Job* job) { // Switch back to the scheduler. assert (current_job_ == job); current_job_ = 0; Coro_switchTo_ (job->coro_get (), coro_); // We regained control, we are again in the context of the job. assert (!current_job_); current_job_ = job; ECHO ("job " << *job << " resumed"); // Check that we are not near exhausting the stack space. job->check_stack_space (); // Execute a deferred exception if any job->check_for_pending_exception (); // If we are in frozen state, let's requeue ourselves waiting // for something to change. And let's mark us side-effect // free during this time so that we won't cause other jobs // to be scheduled. Of course, we have to check for pending // exceptions each time we are woken up. if (job->frozen ()) { bool side_effect_free_save = job->side_effect_free_get (); do { job->side_effect_free_set (true); job->yield_until_things_changed (); job->side_effect_free_set (side_effect_free_save); // Execute a deferred exception if any job->check_for_pending_exception (); } while (job->frozen ()); } } void Scheduler::resume_scheduler (Job* job) { // If the job has not terminated and is side-effect free, then we // assume it will not take a long time as we are probably evaluating // a condition. In order to reduce the number of cycles spent to evaluate // the condition, continue until it asks to be suspended in another // way or until it is no longer side-effect free. if (job->state_get () == running && job->side_effect_free_get ()) return; else jobs_.push_back (job); ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated\n\t" << "state: " << state_name (job->state_get ())); switch_back (job); } void Scheduler::killall_jobs () { ECHO ("killing all jobs!"); foreach (Job* job, jobs_) kill_job (job); foreach (Job* job, pending_) kill_job (job); } void Scheduler::unschedule_job (Job* job) { assert (job); assert (job != current_job_); ECHO ("unscheduling job " << *job); // Remove the job from the queue. jobs_.remove (job); // Remove it from live queues as well if the job is destroyed. pending_.remove (job); } void Scheduler::kill_job (Job* job) { KillException ke; job->async_throw (ke); } void Scheduler::signal_stop (rTag t) { bool previous_state = t->own_blocked (); t->set_blocked (true); stopped_tags_.push_back (std::make_pair(t, previous_state)); } } // namespace scheduler <|endoftext|>
<commit_before>#include <sys/types.h> #include <signal.h> #include <QThread> #include "debug.h" #include <QModelIndex> #include <QFile> #include <QDir> #include <QSet> #include <QTimer> #include "global.h" #include "rootitem.h" #include "repository.h" #include "jsonreader.h" #include "settingsmodel.h" //TODO: Should it be faster? RootItem::RootItem(TreeModel* parentModel): RootItem(Constants::DEFAULT_USERNAME, Constants::DEFAULT_PASSWORD, Constants::DEFAULT_PORT, parentModel) { } RootItem::RootItem(const QString& username, const QString& password, unsigned port, TreeModel* parentModel): QObject(), TreeItem("[DBG] Root Item"), initializing_(true), parent_(parentModel), username_(username), password_(password), port_(port) { initSync(); Global::btsync = sync_; DBG << "initBtsync completed"; JsonReader::fillEverything(this); DBG << "readJson completed"; connect(sync_, SIGNAL(initCompleted()), this, SLOT(removeOrphans())); initializing_ = false; Global::workerThread->start(); } RootItem::~RootItem() { DBG; for (Repository* repo : childItems()) { delete repo; } Global::workerThread->quit(); Global::workerThread->wait(3000); DBG << "Shutdown2"; sync_->shutdown2(); DBG << "Btsync destruction"; delete sync_; } //Removes btsync dirs which //are not represented in this program. void RootItem::removeOrphans() { QSet<QString> keys; for (const Repository* repository : childItems()) { for (const Mod* mod : repository->mods()) { DBG << "Processing mod =" << mod->name() << " key =" << mod->key() << " repository=" << repository->name(); keys.insert(mod->key()); } } for (const QString& key : sync_->getFolderKeys()) { if (!keys.contains(key)) { //Not found DBG << "Deleting folder with key:" << key; sync_->removeFolder2(key); } } DBG << "remove orhpans completed"; } void RootItem::processCompletion() { DBG << "Started"; for (Repository* repo : childItems()) { repo->processCompletion(); } DBG << "Finished"; } void RootItem::resetSyncSettings() { DBG; sync_->shutdown2(); for (Repository* repo : childItems()) { if (repo->checked()) { repo->checkboxClicked(true); repo->updateView(this); } } //Brute way to avoid "file in use" while btsync is shutting down. QDir dir(Constants::BTSYNC_SETTINGS_PATH); int attempts = 0; while ( dir.exists() && attempts < 100 ) { dir.removeRecursively(); //It's rape time. DBG << "Failure to delete BtSync Storage... retrying path=" << dir.currentPath() << " attempts =" << attempts; QThread::sleep(1); ++attempts; } dir.mkpath("."); sync_->restart2(); } QList<Repository*> RootItem::childItems() { QList<Repository*> rVal; for (TreeItem* item : TreeItem::childItems()) { rVal.append(static_cast<Repository*>(item)); } return rVal; } void RootItem::updateView(TreeItem* item, int row) { if (initializing_) { //Wait for repos to load return; } //DBG << "Updating row=" << row->row(); parent_->updateView(item, row); } BtsApi2* RootItem::btsync() const { return sync_; } void RootItem::enableRepositories() { DBG; for (Repository* repo : childItems()) { if (!repo->checked()) { repo->checkboxClicked(); } repo->enableMods(); } } QString RootItem::defaultter(const QString& value, const QString& defaultValue) { if (value == "") { return defaultValue; } return value; } void RootItem::initSync() { sync_ = new BtsApi2(username_, password_, port_); updateTimer_.setInterval(1000); DBG << "Setting up speed updates"; QObject::connect(&updateTimer_, SIGNAL(timeout()), sync_, SLOT(getSpeed())); QObject::connect(sync_, SIGNAL(getSpeedResult(qint64,qint64)), parent_, SLOT(updateSpeed(qint64,qint64))); QObject::connect(sync_, SIGNAL(initCompleted()), &updateTimer_, SLOT(start())); } <commit_msg>Fixed: Crashing when AFISync is loaded and BtSync connection has not been established.<commit_after>#include <sys/types.h> #include <signal.h> #include <QThread> #include "debug.h" #include <QModelIndex> #include <QFile> #include <QDir> #include <QSet> #include <QTimer> #include "global.h" #include "rootitem.h" #include "repository.h" #include "jsonreader.h" #include "settingsmodel.h" //TODO: Should it be faster? RootItem::RootItem(TreeModel* parentModel): RootItem(Constants::DEFAULT_USERNAME, Constants::DEFAULT_PASSWORD, Constants::DEFAULT_PORT, parentModel) { } RootItem::RootItem(const QString& username, const QString& password, unsigned port, TreeModel* parentModel): QObject(), TreeItem("[DBG] Root Item"), initializing_(true), parent_(parentModel), username_(username), password_(password), port_(port) { initSync(); Global::btsync = sync_; DBG << "initBtsync completed"; JsonReader::fillEverything(this); DBG << "readJson completed"; connect(sync_, SIGNAL(initCompleted()), this, SLOT(removeOrphans())); initializing_ = false; Global::workerThread->start(); } RootItem::~RootItem() { DBG; for (Repository* repo : childItems()) { delete repo; } Global::workerThread->quit(); Global::workerThread->wait(3000); DBG << "Shutdown2"; sync_->shutdown2(); //Causes chrashes if BtSync connection is unestablished. //delete sync_; } //Removes btsync dirs which //are not represented in this program. void RootItem::removeOrphans() { QSet<QString> keys; for (const Repository* repository : childItems()) { for (const Mod* mod : repository->mods()) { DBG << "Processing mod =" << mod->name() << " key =" << mod->key() << " repository=" << repository->name(); keys.insert(mod->key()); } } for (const QString& key : sync_->getFolderKeys()) { if (!keys.contains(key)) { //Not found DBG << "Deleting folder with key:" << key; sync_->removeFolder2(key); } } DBG << "remove orhpans completed"; } void RootItem::processCompletion() { DBG << "Started"; for (Repository* repo : childItems()) { repo->processCompletion(); } DBG << "Finished"; } void RootItem::resetSyncSettings() { DBG; sync_->shutdown2(); for (Repository* repo : childItems()) { if (repo->checked()) { repo->checkboxClicked(true); repo->updateView(this); } } //Brute way to avoid "file in use" while btsync is shutting down. QDir dir(Constants::BTSYNC_SETTINGS_PATH); int attempts = 0; while ( dir.exists() && attempts < 100 ) { dir.removeRecursively(); //It's rape time. DBG << "Failure to delete BtSync Storage... retrying path=" << dir.currentPath() << " attempts =" << attempts; QThread::sleep(1); ++attempts; } dir.mkpath("."); sync_->restart2(); } QList<Repository*> RootItem::childItems() { QList<Repository*> rVal; for (TreeItem* item : TreeItem::childItems()) { rVal.append(static_cast<Repository*>(item)); } return rVal; } void RootItem::updateView(TreeItem* item, int row) { if (initializing_) { //Wait for repos to load return; } //DBG << "Updating row=" << row->row(); parent_->updateView(item, row); } BtsApi2* RootItem::btsync() const { return sync_; } void RootItem::enableRepositories() { DBG; for (Repository* repo : childItems()) { if (!repo->checked()) { repo->checkboxClicked(); } repo->enableMods(); } } QString RootItem::defaultter(const QString& value, const QString& defaultValue) { if (value == "") { return defaultValue; } return value; } void RootItem::initSync() { sync_ = new BtsApi2(username_, password_, port_); updateTimer_.setInterval(1000); DBG << "Setting up speed updates"; QObject::connect(&updateTimer_, SIGNAL(timeout()), sync_, SLOT(getSpeed())); QObject::connect(sync_, SIGNAL(getSpeedResult(qint64,qint64)), parent_, SLOT(updateSpeed(qint64,qint64))); QObject::connect(sync_, SIGNAL(initCompleted()), &updateTimer_, SLOT(start())); } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "library/trace.h" #include "library/vm/vm_list.h" #include "library/tactic/tactic_state.h" namespace lean { expr revert(environment const & env, options const & opts, metavar_context & mctx, expr const & mvar, buffer<expr> & locals, bool preserve_locals_order) { optional<metavar_decl> g = mctx.find_metavar_decl(mvar); lean_assert(g); type_context ctx = mk_type_context_for(env, opts, mctx, g->get_context(), transparency_mode::All); expr val = ctx.revert(locals, mvar, preserve_locals_order); expr new_g = get_app_fn(val); mctx = ctx.mctx(); return new_g; } tactic_state revert(buffer<expr> & locals, tactic_state const & s, bool preserve_locals_order) { lean_assert(s.goals()); metavar_context mctx = s.mctx(); expr new_g = revert(s.env(), s.get_options(), mctx, head(s.goals()), locals, preserve_locals_order); return set_mctx_goals(s, mctx, cons(new_g, tail(s.goals()))); } vm_obj revert(list<expr> const & ls, tactic_state const & s, bool preserve_locals_order) { optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); local_context lctx = g->get_context(); buffer<expr> locals; for (expr const & l : ls) { if (lctx.find_local_decl(l)) { locals.push_back(l); } else { return tactic::mk_exception(sstream() << "revert tactic failed, unknown '" << mlocal_pp_name(l) << "' hypothesis", s); } } tactic_state new_s = revert(locals, s, preserve_locals_order); return tactic::mk_success(mk_vm_nat(locals.size()), new_s); } vm_obj tactic_revert_lst(vm_obj const & ns, vm_obj const & s) { bool preserve_locals_order = false; return revert(to_list_expr(ns), tactic::to_state(s), preserve_locals_order); } void initialize_revert_tactic() { DECLARE_VM_BUILTIN(name({"tactic", "revert_lst"}), tactic_revert_lst); } void finalize_revert_tactic() { } } <commit_msg>fix(library/tactic/revert_tactic): missing `catch`<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "library/trace.h" #include "library/vm/vm_list.h" #include "library/tactic/tactic_state.h" namespace lean { expr revert(environment const & env, options const & opts, metavar_context & mctx, expr const & mvar, buffer<expr> & locals, bool preserve_locals_order) { optional<metavar_decl> g = mctx.find_metavar_decl(mvar); lean_assert(g); type_context ctx = mk_type_context_for(env, opts, mctx, g->get_context(), transparency_mode::All); expr val = ctx.revert(locals, mvar, preserve_locals_order); expr new_g = get_app_fn(val); mctx = ctx.mctx(); return new_g; } tactic_state revert(buffer<expr> & locals, tactic_state const & s, bool preserve_locals_order) { lean_assert(s.goals()); metavar_context mctx = s.mctx(); expr new_g = revert(s.env(), s.get_options(), mctx, head(s.goals()), locals, preserve_locals_order); return set_mctx_goals(s, mctx, cons(new_g, tail(s.goals()))); } vm_obj revert(list<expr> const & ls, tactic_state const & s, bool preserve_locals_order) { try { optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); local_context lctx = g->get_context(); buffer<expr> locals; for (expr const & l : ls) { if (lctx.find_local_decl(l)) { locals.push_back(l); } else { return tactic::mk_exception(sstream() << "revert tactic failed, unknown '" << mlocal_pp_name(l) << "' hypothesis", s); } } tactic_state new_s = revert(locals, s, preserve_locals_order); return tactic::mk_success(mk_vm_nat(locals.size()), new_s); } catch (exception & ex) { return tactic::mk_exception(ex, s); } } vm_obj tactic_revert_lst(vm_obj const & ns, vm_obj const & s) { bool preserve_locals_order = false; return revert(to_list_expr(ns), tactic::to_state(s), preserve_locals_order); } void initialize_revert_tactic() { DECLARE_VM_BUILTIN(name({"tactic", "revert_lst"}), tactic_revert_lst); } void finalize_revert_tactic() { } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_GP_EXP_QUAD_COV_HPP #define STAN_MATH_PRIM_MAT_FUN_GP_EXP_QUAD_COV_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/divide.hpp> #include <stan/math/prim/mat/fun/divide_columns.hpp> #include <stan/math/prim/mat/fun/squared_distance.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/fun/divide.hpp> #include <stan/math/prim/scal/fun/exp.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/opencl/gp_exp_quad_cov.hpp> #include <cmath> #include <vector> namespace stan { namespace math { /** * Returns a squared exponential kernel. * * @tparam T_x type for each scalar * @tparam T_sigma type of parameter sigma * @tparam T_l type of parameter length scale * * @param x std::vector of scalars that can be used in square distance. * This function assumes each element of x is the same size. * @param sigma marginal standard deviation or magnitude * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<T_x> &x, const T_sigma &sigma, const T_l &length_scale) { using std::exp; check_positive("gp_exp_quad_cov", "magnitude", sigma); check_positive("gp_exp_quad_cov", "length scale", length_scale); size_t x_size = x.size(); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; for (size_t n = 0; n < x.size(); ++n) check_not_nan("gp_exp_quad_cov", "x", x[n]); #ifdef STAN_OPENCL if(is_constant_struct<T_x>::value && is_constant_struct<T_sigma>::value && is_constant_struct<T_l>::value) { matrix_cl x_gpu(x); matrix_cl cov_gpu = gp_exp_quad_cov(x_gpu, sigma, length_scale); copy(cov, cov_gpu); } else { #endif T_sigma sigma_sq = square(sigma); T_l neg_half_inv_l_sq = -0.5 / square(length_scale); for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(squared_distance(x[i], x[j]) * neg_half_inv_l_sq); cov(j, i) = cov(i, j); } } #ifdef STAN_OPENCL } #endif return cov; } /** * Returns a squared exponential kernel. * * @tparam T_x type for each scalar * @tparam T_sigma type of parameter sigma * @tparam T_l type of each length scale parameter * * @param x std::vector of Eigen vectors of scalars. * @param sigma marginal standard deviation or magnitude * @param length_scale std::vector length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x, const T_sigma &sigma, const std::vector<T_l> &length_scale) { using std::exp; check_positive_finite("gp_exp_quad_cov", "magnitude", sigma); check_positive_finite("gp_exp_quad_cov", "length scale", length_scale); size_t x_size = x.size(); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; size_t l_size = length_scale.size(); check_size_match("gp_exp_quad_cov", "x dimension", x[0].size(), "number of length scales", l_size); T_sigma sigma_sq = square(sigma); std::vector< Eigen::Matrix<typename return_type<T_x, T_l>::type, Eigen::Dynamic, 1>> x_new = divide_columns(x, length_scale); for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(-0.5 * squared_distance(x_new[i], x_new[j])); cov(j, i) = cov(i, j); } } return cov; } /** * Returns a squared exponential kernel. * * This function is for the cross covariance matrix * needed to compute posterior predictive density. * * @tparam T_x1 type of first std::vector of scalars * @tparam T_x2 type of second std::vector of scalars * This function assumes each element of x1 and x2 are the same size. * @tparam T_sigma type of sigma * @tparam T_l type of of length scale * * @param x1 std::vector of elements that can be used in square distance * @param x2 std::vector of elements that can be used in square distance * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x1, typename T_x2, typename T_sigma, typename T_l> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma, const T_l &length_scale) { using std::exp; const char *function_name = "gp_exp_quad_cov"; check_positive(function_name, "magnitude", sigma); check_positive(function_name, "length scale", length_scale); size_t x1_size = x1.size(); size_t x2_size = x2.size(); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; for (size_t i = 0; i < x1_size; ++i) check_not_nan(function_name, "x1", x1[i]); for (size_t i = 0; i < x2_size; ++i) check_not_nan(function_name, "x2", x2[i]); #ifdef STAN_OPENCL if(is_constant_struct<T_x1>::value && is_constant_struct<T_x2>::value && is_constant_struct<T_sigma>::value && is_constant_struct<T_l>::value) { matrix_cl x1_gpu(x1); matrix_cl x2_gpu(x2); matrix_cl cov_gpu = gp_exp_quad_cov(x1_gpu, x2_gpu, sigma, length_scale); copy(cov, cov_gpu); } else { #endif T_sigma sigma_sq = square(sigma); T_l neg_half_inv_l_sq = -0.5 / square(length_scale); for (size_t i = 0; i < x1.size(); ++i) { for (size_t j = 0; j < x2.size(); ++j) { cov(i, j) = sigma_sq * exp(squared_distance(x1[i], x2[j]) * neg_half_inv_l_sq); } } #ifdef STAN_OPENCL } #endif return cov; } /** * Returns a squared exponential kernel. * * This function is for the cross covariance * matrix needed to compute the posterior predictive density. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_s type of sigma * @tparam T_l type of length scale * * @param x1 std::vector of Eigen vectors of scalars. * @param x2 std::vector of Eigen vectors of scalars. * @param sigma standard deviation * @param length_scale std::vector of length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x1, typename T_x2, typename T_s, typename T_l> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_s, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1, const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2, const T_s &sigma, const std::vector<T_l> &length_scale) { using std::exp; size_t x1_size = x1.size(); size_t x2_size = x2.size(); size_t l_size = length_scale.size(); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_s, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; const char *function_name = "gp_exp_quad_cov"; for (size_t i = 0; i < x1_size; ++i) check_not_nan(function_name, "x1", x1[i]); for (size_t i = 0; i < x2_size; ++i) check_not_nan(function_name, "x2", x2[i]); check_positive_finite(function_name, "magnitude", sigma); check_positive_finite(function_name, "length scale", length_scale); check_size_match(function_name, "x dimension", x1[0].size(), "number of length scales", l_size); check_size_match(function_name, "x dimension", x2[0].size(), "number of length scales", l_size); T_s sigma_sq = square(sigma); std::vector<Eigen::Matrix<typename return_type<T_x1, T_l, T_s>::type, Eigen::Dynamic, 1>> x1_new = divide_columns(x1, length_scale); std::vector<Eigen::Matrix<typename return_type<T_x2, T_l, T_s>::type, Eigen::Dynamic, 1>> x2_new = divide_columns(x2, length_scale); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq * exp(-0.5 * squared_distance(x1_new[i], x2_new[j])); } } return cov; } } // namespace math } // namespace stan #endif <commit_msg>gpu gp_exp_quad_cov vector length_scale cases implemented<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_GP_EXP_QUAD_COV_HPP #define STAN_MATH_PRIM_MAT_FUN_GP_EXP_QUAD_COV_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/divide.hpp> #include <stan/math/prim/mat/fun/divide_columns.hpp> #include <stan/math/prim/mat/fun/squared_distance.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/fun/divide.hpp> #include <stan/math/prim/scal/fun/exp.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/opencl/gp_exp_quad_cov.hpp> #include <cmath> #include <vector> namespace stan { namespace math { /** * Returns a squared exponential kernel. * * @tparam T_x type for each scalar * @tparam T_sigma type of parameter sigma * @tparam T_l type of parameter length scale * * @param x std::vector of scalars that can be used in square distance. * This function assumes each element of x is the same size. * @param sigma marginal standard deviation or magnitude * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<T_x> &x, const T_sigma &sigma, const T_l &length_scale) { using std::exp; check_positive("gp_exp_quad_cov", "magnitude", sigma); check_positive("gp_exp_quad_cov", "length scale", length_scale); size_t x_size = x.size(); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; for (size_t n = 0; n < x.size(); ++n) check_not_nan("gp_exp_quad_cov", "x", x[n]); #ifdef STAN_OPENCL if(is_constant_struct<T_x>::value && is_constant_struct<T_sigma>::value && is_constant_struct<T_l>::value) { matrix_cl x_gpu(x); matrix_cl cov_gpu = gp_exp_quad_cov(x_gpu, sigma, length_scale); copy(cov, cov_gpu); } else { #endif T_sigma sigma_sq = square(sigma); T_l neg_half_inv_l_sq = -0.5 / square(length_scale); for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(squared_distance(x[i], x[j]) * neg_half_inv_l_sq); cov(j, i) = cov(i, j); } } #ifdef STAN_OPENCL } #endif return cov; } /** * Returns a squared exponential kernel. * * @tparam T_x type for each scalar * @tparam T_sigma type of parameter sigma * @tparam T_l type of each length scale parameter * * @param x std::vector of Eigen vectors of scalars. * @param sigma marginal standard deviation or magnitude * @param length_scale std::vector length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x, typename T_sigma, typename T_l> inline typename Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<Eigen::Matrix<T_x, Eigen::Dynamic, 1>> &x, const T_sigma &sigma, const std::vector<T_l> &length_scale) { using std::exp; check_positive_finite("gp_exp_quad_cov", "magnitude", sigma); check_positive_finite("gp_exp_quad_cov", "length scale", length_scale); size_t x_size = x.size(); Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x_size, x_size); if (x_size == 0) return cov; size_t l_size = length_scale.size(); check_size_match("gp_exp_quad_cov", "x dimension", x[0].size(), "number of length scales", l_size); std::vector< Eigen::Matrix<typename return_type<T_x, T_l>::type, Eigen::Dynamic, 1>> x_new = divide_columns(x, length_scale); #ifdef STAN_OPENCL if(is_constant_struct<T_x>::value && is_constant_struct<T_sigma>::value && is_constant_struct<T_l>::value) { matrix_cl x_gpu(x_new); matrix_cl cov_gpu = gp_exp_quad_cov(x_gpu, sigma, 1); copy(cov, cov_gpu); } else { #endif T_sigma sigma_sq = square(sigma); for (size_t j = 0; j < x_size; ++j) { cov(j, j) = sigma_sq; for (size_t i = j + 1; i < x_size; ++i) { cov(i, j) = sigma_sq * exp(-0.5 * squared_distance(x_new[i], x_new[j])); cov(j, i) = cov(i, j); } } #ifdef STAN_OPENCL } #endif return cov; } /** * Returns a squared exponential kernel. * * This function is for the cross covariance matrix * needed to compute posterior predictive density. * * @tparam T_x1 type of first std::vector of scalars * @tparam T_x2 type of second std::vector of scalars * This function assumes each element of x1 and x2 are the same size. * @tparam T_sigma type of sigma * @tparam T_l type of of length scale * * @param x1 std::vector of elements that can be used in square distance * @param x2 std::vector of elements that can be used in square distance * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x1, typename T_x2, typename T_sigma, typename T_l> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<T_x1> &x1, const std::vector<T_x2> &x2, const T_sigma &sigma, const T_l &length_scale) { using std::exp; const char *function_name = "gp_exp_quad_cov"; check_positive(function_name, "magnitude", sigma); check_positive(function_name, "length scale", length_scale); size_t x1_size = x1.size(); size_t x2_size = x2.size(); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; for (size_t i = 0; i < x1_size; ++i) check_not_nan(function_name, "x1", x1[i]); for (size_t i = 0; i < x2_size; ++i) check_not_nan(function_name, "x2", x2[i]); #ifdef STAN_OPENCL if(is_constant_struct<T_x1>::value && is_constant_struct<T_x2>::value && is_constant_struct<T_sigma>::value && is_constant_struct<T_l>::value) { matrix_cl x1_gpu(x1); matrix_cl x2_gpu(x2); matrix_cl cov_gpu = gp_exp_quad_cov(x1_gpu, x2_gpu, sigma, length_scale); copy(cov, cov_gpu); } else { #endif T_sigma sigma_sq = square(sigma); T_l neg_half_inv_l_sq = -0.5 / square(length_scale); for (size_t i = 0; i < x1.size(); ++i) { for (size_t j = 0; j < x2.size(); ++j) { cov(i, j) = sigma_sq * exp(squared_distance(x1[i], x2[j]) * neg_half_inv_l_sq); } } #ifdef STAN_OPENCL } #endif return cov; } /** * Returns a squared exponential kernel. * * This function is for the cross covariance * matrix needed to compute the posterior predictive density. * * @tparam T_x1 type of first std::vector of elements * @tparam T_x2 type of second std::vector of elements * @tparam T_s type of sigma * @tparam T_l type of length scale * * @param x1 std::vector of Eigen vectors of scalars. * @param x2 std::vector of Eigen vectors of scalars. * @param sigma standard deviation * @param length_scale std::vector of length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x1, typename T_x2, typename T_s, typename T_l> inline typename Eigen::Matrix< typename stan::return_type<T_x1, T_x2, T_s, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> gp_exp_quad_cov(const std::vector<Eigen::Matrix<T_x1, Eigen::Dynamic, 1>> &x1, const std::vector<Eigen::Matrix<T_x2, Eigen::Dynamic, 1>> &x2, const T_s &sigma, const std::vector<T_l> &length_scale) { using std::exp; size_t x1_size = x1.size(); size_t x2_size = x2.size(); size_t l_size = length_scale.size(); Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_s, T_l>::type, Eigen::Dynamic, Eigen::Dynamic> cov(x1_size, x2_size); if (x1_size == 0 || x2_size == 0) return cov; const char *function_name = "gp_exp_quad_cov"; for (size_t i = 0; i < x1_size; ++i) check_not_nan(function_name, "x1", x1[i]); for (size_t i = 0; i < x2_size; ++i) check_not_nan(function_name, "x2", x2[i]); check_positive_finite(function_name, "magnitude", sigma); check_positive_finite(function_name, "length scale", length_scale); check_size_match(function_name, "x dimension", x1[0].size(), "number of length scales", l_size); check_size_match(function_name, "x dimension", x2[0].size(), "number of length scales", l_size); std::vector<Eigen::Matrix<typename return_type<T_x1, T_l, T_s>::type, Eigen::Dynamic, 1>> x1_new = divide_columns(x1, length_scale); std::vector<Eigen::Matrix<typename return_type<T_x2, T_l, T_s>::type, Eigen::Dynamic, 1>> x2_new = divide_columns(x2, length_scale); #ifdef STAN_OPENCL if(is_constant_struct<T_x1>::value && is_constant_struct<T_x2>::value && is_constant_struct<T_s>::value && is_constant_struct<T_l>::value) { matrix_cl x1_gpu(x1_new); matrix_cl x2_gpu(x2_new); matrix_cl cov_gpu = gp_exp_quad_cov(x1_gpu, x2_gpu, sigma, 1); copy(cov, cov_gpu); } else { #endif T_s sigma_sq = square(sigma); for (size_t i = 0; i < x1_size; ++i) { for (size_t j = 0; j < x2_size; ++j) { cov(i, j) = sigma_sq * exp(-0.5 * squared_distance(x1_new[i], x2_new[j])); } } #ifdef STAN_OPENCL } #endif return cov; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef OPTIMIZER_HPP #define OPTIMIZER_HPP #include <utility> #include <tuple> #include <array> #include <cmath> #include <functional> #include <limits> #include <cassert> namespace Slic3r { namespace opt { // A type to hold the complete result of the optimization. template<size_t N> struct Result { int resultcode; // Method dependent std::array<double, N> optimum; double score; }; // An interval of possible input values for optimization class Bound { double m_min, m_max; public: Bound(double min = std::numeric_limits<double>::min(), double max = std::numeric_limits<double>::max()) : m_min(min), m_max(max) {} double min() const noexcept { return m_min; } double max() const noexcept { return m_max; } }; // Helper types for optimization function input and bounds template<size_t N> using Input = std::array<double, N>; template<size_t N> using Bounds = std::array<Bound, N>; // A type for specifying the stop criteria. Setter methods can be concatenated class StopCriteria { // If the absolute value difference between two scores. double m_abs_score_diff = std::nan(""); // If the relative value difference between two scores. double m_rel_score_diff = std::nan(""); // Stop if this value or better is found. double m_stop_score = std::nan(""); // A predicate that if evaluates to true, the optimization should terminate // and the best result found prior to termination should be returned. std::function<bool()> m_stop_condition = [] { return false; }; // The max allowed number of iterations. unsigned m_max_iterations = 0; public: StopCriteria & abs_score_diff(double val) { m_abs_score_diff = val; return *this; } double abs_score_diff() const { return m_abs_score_diff; } StopCriteria & rel_score_diff(double val) { m_rel_score_diff = val; return *this; } double rel_score_diff() const { return m_rel_score_diff; } StopCriteria & stop_score(double val) { m_stop_score = val; return *this; } double stop_score() const { return m_stop_score; } StopCriteria & max_iterations(double val) { m_max_iterations = val; return *this; } double max_iterations() const { return m_max_iterations; } template<class Fn> StopCriteria & stop_condition(Fn &&cond) { m_stop_condition = cond; return *this; } bool stop_condition() { return m_stop_condition(); } }; // Helper class to use optimization methods involving gradient. template<size_t N> struct ScoreGradient { double score; std::optional<std::array<double, N>> gradient; ScoreGradient(double s, const std::array<double, N> &grad) : score{s}, gradient{grad} {} }; // Helper to be used in static_assert. template<class T> struct always_false { enum { value = false }; }; // Basic interface to optimizer object template<class Method, class Enable = void> class Optimizer { public: Optimizer(const StopCriteria &) { static_assert (always_false<Method>::value, "Optimizer unimplemented for given method!"); } // Switch optimization towards function minimum Optimizer &to_min() { return *this; } // Switch optimization towards function maximum Optimizer &to_max() { return *this; } // Set criteria for successive optimizations Optimizer &set_criteria(const StopCriteria &) { return *this; } // Get current criteria StopCriteria get_criteria() const { return {}; }; // Find function minimum or maximum for Func which has has signature: // double(const Input<N> &input) and input with dimension N // // Initial starting point can be given as the second parameter. // // For each dimension an interval (Bound) has to be given marking the bounds // for that dimension. // // initvals have to be within the specified bounds, otherwise its undefined // behavior. // // Func can return a score of type double or optionally a ScoreGradient // class to indicate the function gradient for a optimization methods that // make use of the gradient. template<class Func, size_t N> Result<N> optimize(Func&& /*func*/, const Input<N> &/*initvals*/, const Bounds<N>& /*bounds*/) { return {}; } // optional for randomized methods: void seed(long /*s*/) {} }; namespace detail { // Helper to convert C style array to std::array. The copy should be optimized // away with modern compilers. template<size_t N, class T> auto to_arr(const T *a) { std::array<T, N> r; std::copy(a, a + N, std::begin(r)); return r; } template<size_t N, class T> auto to_arr(const T (&a) [N]) { return to_arr<N>(static_cast<const T *>(a)); } } // namespace detail // Helper functions to create bounds, initial value template<size_t N> Bounds<N> bounds(const Bound (&b) [N]) { return detail::to_arr(b); } template<size_t N> Input<N> initvals(const double (&a) [N]) { return detail::to_arr(a); } template<size_t N> auto score_gradient(double s, const double (&grad)[N]) { return ScoreGradient<N>(s, detail::to_arr(grad)); } }} // namespace Slic3r::opt #endif // OPTIMIZER_HPP <commit_msg>Added missing include (GCC 11.1)<commit_after>#ifndef OPTIMIZER_HPP #define OPTIMIZER_HPP #include <utility> #include <tuple> #include <array> #include <cmath> #include <functional> #include <limits> #include <cassert> #include <optional> namespace Slic3r { namespace opt { // A type to hold the complete result of the optimization. template<size_t N> struct Result { int resultcode; // Method dependent std::array<double, N> optimum; double score; }; // An interval of possible input values for optimization class Bound { double m_min, m_max; public: Bound(double min = std::numeric_limits<double>::min(), double max = std::numeric_limits<double>::max()) : m_min(min), m_max(max) {} double min() const noexcept { return m_min; } double max() const noexcept { return m_max; } }; // Helper types for optimization function input and bounds template<size_t N> using Input = std::array<double, N>; template<size_t N> using Bounds = std::array<Bound, N>; // A type for specifying the stop criteria. Setter methods can be concatenated class StopCriteria { // If the absolute value difference between two scores. double m_abs_score_diff = std::nan(""); // If the relative value difference between two scores. double m_rel_score_diff = std::nan(""); // Stop if this value or better is found. double m_stop_score = std::nan(""); // A predicate that if evaluates to true, the optimization should terminate // and the best result found prior to termination should be returned. std::function<bool()> m_stop_condition = [] { return false; }; // The max allowed number of iterations. unsigned m_max_iterations = 0; public: StopCriteria & abs_score_diff(double val) { m_abs_score_diff = val; return *this; } double abs_score_diff() const { return m_abs_score_diff; } StopCriteria & rel_score_diff(double val) { m_rel_score_diff = val; return *this; } double rel_score_diff() const { return m_rel_score_diff; } StopCriteria & stop_score(double val) { m_stop_score = val; return *this; } double stop_score() const { return m_stop_score; } StopCriteria & max_iterations(double val) { m_max_iterations = val; return *this; } double max_iterations() const { return m_max_iterations; } template<class Fn> StopCriteria & stop_condition(Fn &&cond) { m_stop_condition = cond; return *this; } bool stop_condition() { return m_stop_condition(); } }; // Helper class to use optimization methods involving gradient. template<size_t N> struct ScoreGradient { double score; std::optional<std::array<double, N>> gradient; ScoreGradient(double s, const std::array<double, N> &grad) : score{s}, gradient{grad} {} }; // Helper to be used in static_assert. template<class T> struct always_false { enum { value = false }; }; // Basic interface to optimizer object template<class Method, class Enable = void> class Optimizer { public: Optimizer(const StopCriteria &) { static_assert (always_false<Method>::value, "Optimizer unimplemented for given method!"); } // Switch optimization towards function minimum Optimizer &to_min() { return *this; } // Switch optimization towards function maximum Optimizer &to_max() { return *this; } // Set criteria for successive optimizations Optimizer &set_criteria(const StopCriteria &) { return *this; } // Get current criteria StopCriteria get_criteria() const { return {}; }; // Find function minimum or maximum for Func which has has signature: // double(const Input<N> &input) and input with dimension N // // Initial starting point can be given as the second parameter. // // For each dimension an interval (Bound) has to be given marking the bounds // for that dimension. // // initvals have to be within the specified bounds, otherwise its undefined // behavior. // // Func can return a score of type double or optionally a ScoreGradient // class to indicate the function gradient for a optimization methods that // make use of the gradient. template<class Func, size_t N> Result<N> optimize(Func&& /*func*/, const Input<N> &/*initvals*/, const Bounds<N>& /*bounds*/) { return {}; } // optional for randomized methods: void seed(long /*s*/) {} }; namespace detail { // Helper to convert C style array to std::array. The copy should be optimized // away with modern compilers. template<size_t N, class T> auto to_arr(const T *a) { std::array<T, N> r; std::copy(a, a + N, std::begin(r)); return r; } template<size_t N, class T> auto to_arr(const T (&a) [N]) { return to_arr<N>(static_cast<const T *>(a)); } } // namespace detail // Helper functions to create bounds, initial value template<size_t N> Bounds<N> bounds(const Bound (&b) [N]) { return detail::to_arr(b); } template<size_t N> Input<N> initvals(const double (&a) [N]) { return detail::to_arr(a); } template<size_t N> auto score_gradient(double s, const double (&grad)[N]) { return ScoreGradient<N>(s, detail::to_arr(grad)); } }} // namespace Slic3r::opt #endif // OPTIMIZER_HPP <|endoftext|>
<commit_before>/* This file is part of the Rendering library. Copyright (C) 2014 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef RENDERING_HAS_LIB_OPENCL #include "Context.h" #include "Platform.h" #include "Device.h" #include "CLUtils.h" #include <Rendering/Helper.h> #include <Util/Macros.h> #include <CL/cl.hpp> #if defined __APPLE__ || defined(MACOSX) #else #if defined WIN32 #else //needed for context sharing functions #include <GL/glx.h> #endif #endif namespace Rendering { namespace CL { void* getCurrentContext() { #if defined (__APPLE__) || defined(MACOSX) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); return reinterpret_cast<void*>(kCGLShareGroup); #else #if defined WIN32 // Win32 return reinterpret_cast<void*>(wglGetCurrentContext()); #else return reinterpret_cast<void*>(glXGetCurrentContext()); #endif #endif } void* getCurrentDisplay() { #if defined (__APPLE__) || defined(MACOSX) return nullptr; #else #if defined WIN32 // Win32 return reinterpret_cast<void*>(wglGetCurrentDC()); #else return reinterpret_cast<void*>(glXGetCurrentDisplay()); #endif #endif } std::vector<cl_context_properties> getContextProperties(const cl::Platform& platform, bool shareGLContext) { if(shareGLContext) { #if defined (__APPLE__) || defined(MACOSX) return { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, reinterpret_cast<cl_context_properties>(getCurrentContext()), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0 }; #else #if defined WIN32 // Win32 return { CL_GL_CONTEXT_KHR, (cl_context_properties)getCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties)getCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties)(platform()), 0 }; #else return { CL_GL_CONTEXT_KHR, (cl_context_properties)getCurrentContext(), CL_GLX_DISPLAY_KHR, (cl_context_properties)getCurrentDisplay(), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0 }; #endif #endif } else { return {CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0}; } } Context::Context(Platform* platform, uint32_t device_type, bool shareGLContext /*= false*/) : platform(platform), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); context.reset(new cl::Context(static_cast<cl_device_type>(device_type), cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::~Context() = default; Context::Context(Platform* platform, const std::vector<DeviceRef>& devices, bool shareGLContext /*= false*/) : platform(platform), devices(devices), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); std::vector<cl::Device> cl_devices; for(auto device : devices) cl_devices.push_back(*device->_internal()); context.reset(new cl::Context(cl_devices, cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::Context(Platform* platform, Device* device, bool shareGLContext /*= false*/) : platform(platform), devices(std::vector<DeviceRef>{device}), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); std::vector<cl::Device> cl_devices; context.reset(new cl::Context({*device->_internal()}, cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::Context(const Context& context) : context(new cl::Context(*context.context.get())), platform(context.platform), devices(context.devices), glInterop(context.glInterop) { } //Context::Context(Context&& context) = default; // //Context& Context::operator=(Context&&) = default; std::vector<intptr_t> Context::getProperties() const { return context->getInfo<CL_CONTEXT_PROPERTIES>(); } std::vector<DeviceRef> Context::getDevices() { if(devices.empty()) { std::vector<cl::Device> cl_devices = context->getInfo<CL_CONTEXT_DEVICES>(); for(auto device : cl_devices) devices.push_back(new Device(&device)); } return devices; } } /* namespace CL */ } /* namespace Rendering */ #endif /* RENDERING_HAS_LIB_OPENCL */ <commit_msg>removed getCurrentContext and getCurrentDisplay (directly using glXGetCurrentContext or wglGetCurrentContext)<commit_after>/* This file is part of the Rendering library. Copyright (C) 2014 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef RENDERING_HAS_LIB_OPENCL #include "Context.h" #include "Platform.h" #include "Device.h" #include "CLUtils.h" #include <Rendering/Helper.h> #include <Util/Macros.h> #include <CL/cl.hpp> #if defined __APPLE__ || defined(MACOSX) #else #if defined WIN32 #else //needed for context sharing functions #include <GL/glx.h> #endif #endif namespace Rendering { namespace CL { std::vector<cl_context_properties> getContextProperties(const cl::Platform& platform, bool shareGLContext) { if(shareGLContext) { #if defined (__APPLE__) || defined(MACOSX) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); return { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, reinterpret_cast<cl_context_properties>(kCGLShareGroup), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0 }; #else #if defined WIN32 // Win32 return { CL_GL_CONTEXT_KHR, reinterpret_cast<cl_context_properties>(wglGetCurrentContext()), CL_WGL_HDC_KHR, reinterpret_cast<cl_context_properties>(wglGetCurrentDC()), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0 }; #else return { CL_GL_CONTEXT_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentContext()), CL_GLX_DISPLAY_KHR, reinterpret_cast<cl_context_properties>(glXGetCurrentDisplay()), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0 }; #endif #endif } else { return {CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform()), 0}; } } Context::Context(Platform* platform, uint32_t device_type, bool shareGLContext /*= false*/) : platform(platform), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); context.reset(new cl::Context(static_cast<cl_device_type>(device_type), cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::~Context() = default; Context::Context(Platform* platform, const std::vector<DeviceRef>& devices, bool shareGLContext /*= false*/) : platform(platform), devices(devices), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); std::vector<cl::Device> cl_devices; for(auto device : devices) cl_devices.push_back(*device->_internal()); context.reset(new cl::Context(cl_devices, cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::Context(Platform* platform, Device* device, bool shareGLContext /*= false*/) : platform(platform), devices(std::vector<DeviceRef>{device}), glInterop(shareGLContext) { cl_int err; auto cprops = getContextProperties(*platform->_internal(), shareGLContext); std::vector<cl::Device> cl_devices; context.reset(new cl::Context({*device->_internal()}, cprops.data(), nullptr, nullptr, &err)); if(err != CL_SUCCESS) WARN("Could not create context (" + getErrorString(err) + ")"); FAIL_IF(err != CL_SUCCESS); } Context::Context(const Context& context) : context(new cl::Context(*context.context.get())), platform(context.platform), devices(context.devices), glInterop(context.glInterop) { } //Context::Context(Context&& context) = default; // //Context& Context::operator=(Context&&) = default; std::vector<intptr_t> Context::getProperties() const { return context->getInfo<CL_CONTEXT_PROPERTIES>(); } std::vector<DeviceRef> Context::getDevices() { if(devices.empty()) { std::vector<cl::Device> cl_devices = context->getInfo<CL_CONTEXT_DEVICES>(); for(auto device : cl_devices) devices.push_back(new Device(&device)); } return devices; } } /* namespace CL */ } /* namespace Rendering */ #endif /* RENDERING_HAS_LIB_OPENCL */ <|endoftext|>
<commit_before>#include "dsa_common.h" #include "variant.h" #include <msgpack.h> namespace dsa { struct MsgpackMemPool { msgpack_zone zone; MsgpackMemPool() { msgpack_zone_init(&zone, 2048); } ~MsgpackMemPool() { msgpack_zone_destroy(&zone); } }; thread_local msgpack_packer pk; struct MsgpackSbuffer : public msgpack_sbuffer { MsgpackSbuffer() { msgpack_sbuffer_init(this); msgpack_packer_init(&pk, this, msgpack_sbuffer_write); } ~MsgpackSbuffer() { if (data != nullptr) free(data); } }; thread_local MsgpackSbuffer sbuf; Var Var::to_variant(const msgpack_object &obj) { switch (obj.type) { case MSGPACK_OBJECT_MAP: { auto map = new VarMap(); struct msgpack_object_kv *p = obj.via.map.ptr; for (size_t i = 0; i < obj.via.map.size; ++i, ++p) { // ignore the key if not string if (p->key.type == MSGPACK_OBJECT_STR) { (*map)[string_(p->key.via.str.ptr, p->key.via.str.size)] = to_variant(p->val); } } return Var(map); } case MSGPACK_OBJECT_ARRAY: { auto array = new VarArray(); array->reserve(obj.via.array.size); struct msgpack_object *p = obj.via.array.ptr; for (size_t i = 0; i < obj.via.array.size; ++i, ++p) { array->push_back(to_variant(*p)); } return Var(array); } case MSGPACK_OBJECT_STR: return Var(obj.via.str.ptr, obj.via.str.size); case MSGPACK_OBJECT_POSITIVE_INTEGER: return Var(static_cast<int64_t>(obj.via.u64)); case MSGPACK_OBJECT_NEGATIVE_INTEGER: return Var(obj.via.i64); case MSGPACK_OBJECT_FLOAT64: return Var(obj.via.f64); case MSGPACK_OBJECT_BOOLEAN: return Var(obj.via.boolean); case MSGPACK_OBJECT_BIN: return Var(reinterpret_cast<const uint8_t *>(obj.via.bin.ptr), obj.via.bin.size); default: // return null // ignore extension return Var(); } } Var Var::from_msgpack(const uint8_t *data, size_t size) { MsgpackMemPool mempool; msgpack_object obj; auto result = msgpack_unpack(reinterpret_cast<const char *>(data), size, NULL, &mempool.zone, &obj); if (result == MSGPACK_UNPACK_SUCCESS || result == MSGPACK_UNPACK_EXTRA_BYTES) { return Var(to_variant(obj)); } else { return Var(); } } bool msgpack_pack(msgpack_packer *pk, const Var &v) { bool rc = true; if (v.is_double()) { msgpack_pack_double(pk, v.get_double()); } else if (v.is_int()) { msgpack_pack_int64(pk, v.get_int()); } else if (v.is_bool()) { v.get_bool() ? msgpack_pack_true(pk) : msgpack_pack_false(pk); } else if (v.is_string()) { const string_ &str = v.get_string(); size_t str_length = str.length(); msgpack_pack_str(pk, str_length); msgpack_pack_str_body(pk, str.c_str(), str_length); } else if (v.is_binary()) { const std::vector<uint8_t> &bin = v.get_binary(); size_t bin_size = bin.size(); uint8_t *buf = new uint8_t[bin_size]; std::copy(bin.begin(), bin.end(), buf); msgpack_pack_bin(pk, bin_size); msgpack_pack_bin_body(pk, buf, bin_size); delete[] buf; } else if (v.is_null()) { msgpack_pack_nil(pk); } else if (v.is_array()) { VarArray &array = v.get_array(); msgpack_pack_array(pk, array.size()); for (auto &it : array) { msgpack_pack(pk, it); } } else if (v.is_map()) { VarMap &map = v.get_map(); msgpack_pack_map(pk, map.size()); for (auto &it : map) { string_ key = it.first; size_t key_size = key.size(); msgpack_pack_str(pk, key_size); msgpack_pack_str_body(pk, key.c_str(), key_size); msgpack_pack(pk, it.second); } } else { rc = false; } return rc; } std::vector<uint8_t> Var::to_msgpack() const throw(const EncodingError &) { sbuf; if (msgpack_pack(&pk, *this)) { size_t sbuf_size = sbuf.size; sbuf.size = 0; if (sbuf.alloc >= 0x100000) { std::vector<uint8_t> v(&sbuf.data[0], &sbuf.data[sbuf_size]); free(sbuf.data); sbuf.data = nullptr; sbuf.alloc = 0; return std::move(v); } return std::vector<uint8_t>(&sbuf.data[0], &sbuf.data[sbuf_size]); } throw EncodingError("Failed to pack Var to msgpack"); } Var Var::from_msgpack_pages(std::vector<BytesRef> &pages, const uint8_t *extra_first_page, size_t first_size) { size_t len = first_size; for (auto &page : pages) { len += page->size(); } std::vector<uint8_t> data; data.reserve(len); if (first_size) { data.assign(extra_first_page, extra_first_page + first_size); } for (auto &page : pages) { data.insert(data.end(), page->begin(), page->end()); } return Var::from_msgpack(data.data(), data.size()); } std::vector<BytesRef> Var::to_msgpack_pages(size_t first_page_size) const throw(const EncodingError &) { std::vector<uint8_t> data = to_msgpack(); if (data.size() <= first_page_size) { std::vector<BytesRef> result; result.emplace_back(make_ref_<RefCountBytes>(std::move(data))); return std::move(result); } else { return split_pages(data); } } std::vector<BytesRef> Var::split_pages(const std::vector<uint8_t> &data, size_t first_page_size) { std::vector<BytesRef> result; size_t remain_size = data.size(); const uint8_t *pdata = data.data(); if (first_page_size < MAX_PAGE_BODY_SIZE) { // first page might need to save some space for message metadata result.emplace_back( make_ref_<RefCountBytes>(pdata, pdata + first_page_size)); remain_size -= first_page_size; pdata += first_page_size; } while (remain_size > MAX_PAGE_BODY_SIZE) { result.emplace_back( make_ref_<RefCountBytes>(pdata, pdata + MAX_PAGE_BODY_SIZE)); remain_size -= MAX_PAGE_BODY_SIZE; pdata += MAX_PAGE_BODY_SIZE; } // remain_size won't be 0 result.emplace_back(make_ref_<RefCountBytes>(pdata, pdata + remain_size)); return std::move(result); } } // namespace dsa <commit_msg>don't use thread local in mingw<commit_after>#include "dsa_common.h" #include "variant.h" #include <msgpack.h> namespace dsa { struct MsgpackMemPool { msgpack_zone zone; MsgpackMemPool() { msgpack_zone_init(&zone, 2048); } ~MsgpackMemPool() { msgpack_zone_destroy(&zone); } }; thread_local msgpack_packer pk; struct MsgpackSbuffer : public msgpack_sbuffer { MsgpackSbuffer() { msgpack_sbuffer_init(this); msgpack_packer_init(&pk, this, msgpack_sbuffer_write); } ~MsgpackSbuffer() { try { if (data != nullptr) free(data); } catch (std::exception &e) { } } }; #ifndef __MINGW32__ // mingw's thread_local is buggy thread_local MsgpackSbuffer sbuf; #endif Var Var::to_variant(const msgpack_object &obj) { switch (obj.type) { case MSGPACK_OBJECT_MAP: { auto map = new VarMap(); struct msgpack_object_kv *p = obj.via.map.ptr; for (size_t i = 0; i < obj.via.map.size; ++i, ++p) { // ignore the key if not string if (p->key.type == MSGPACK_OBJECT_STR) { (*map)[string_(p->key.via.str.ptr, p->key.via.str.size)] = to_variant(p->val); } } return Var(map); } case MSGPACK_OBJECT_ARRAY: { auto array = new VarArray(); array->reserve(obj.via.array.size); struct msgpack_object *p = obj.via.array.ptr; for (size_t i = 0; i < obj.via.array.size; ++i, ++p) { array->push_back(to_variant(*p)); } return Var(array); } case MSGPACK_OBJECT_STR: return Var(obj.via.str.ptr, obj.via.str.size); case MSGPACK_OBJECT_POSITIVE_INTEGER: return Var(static_cast<int64_t>(obj.via.u64)); case MSGPACK_OBJECT_NEGATIVE_INTEGER: return Var(obj.via.i64); case MSGPACK_OBJECT_FLOAT64: return Var(obj.via.f64); case MSGPACK_OBJECT_BOOLEAN: return Var(obj.via.boolean); case MSGPACK_OBJECT_BIN: return Var(reinterpret_cast<const uint8_t *>(obj.via.bin.ptr), obj.via.bin.size); default: // return null // ignore extension return Var(); } } Var Var::from_msgpack(const uint8_t *data, size_t size) { MsgpackMemPool mempool; msgpack_object obj; auto result = msgpack_unpack(reinterpret_cast<const char *>(data), size, NULL, &mempool.zone, &obj); if (result == MSGPACK_UNPACK_SUCCESS || result == MSGPACK_UNPACK_EXTRA_BYTES) { return Var(to_variant(obj)); } else { return Var(); } } bool msgpack_pack(msgpack_packer *pk, const Var &v) { bool rc = true; if (v.is_double()) { msgpack_pack_double(pk, v.get_double()); } else if (v.is_int()) { msgpack_pack_int64(pk, v.get_int()); } else if (v.is_bool()) { v.get_bool() ? msgpack_pack_true(pk) : msgpack_pack_false(pk); } else if (v.is_string()) { const string_ &str = v.get_string(); size_t str_length = str.length(); msgpack_pack_str(pk, str_length); msgpack_pack_str_body(pk, str.c_str(), str_length); } else if (v.is_binary()) { const std::vector<uint8_t> &bin = v.get_binary(); size_t bin_size = bin.size(); uint8_t *buf = new uint8_t[bin_size]; std::copy(bin.begin(), bin.end(), buf); msgpack_pack_bin(pk, bin_size); msgpack_pack_bin_body(pk, buf, bin_size); delete[] buf; } else if (v.is_null()) { msgpack_pack_nil(pk); } else if (v.is_array()) { VarArray &array = v.get_array(); msgpack_pack_array(pk, array.size()); for (auto &it : array) { msgpack_pack(pk, it); } } else if (v.is_map()) { VarMap &map = v.get_map(); msgpack_pack_map(pk, map.size()); for (auto &it : map) { string_ key = it.first; size_t key_size = key.size(); msgpack_pack_str(pk, key_size); msgpack_pack_str_body(pk, key.c_str(), key_size); msgpack_pack(pk, it.second); } } else { rc = false; } return rc; } std::vector<uint8_t> Var::to_msgpack() const throw(const EncodingError &) { #ifdef __MINGW32__ // mingw's thread_local is buggy MsgpackSbuffer sbuf; #else sbuf; #endif if (msgpack_pack(&pk, *this)) { size_t sbuf_size = sbuf.size; sbuf.size = 0; if (sbuf.alloc >= 0x100000) { std::vector<uint8_t> v(&sbuf.data[0], &sbuf.data[sbuf_size]); free(sbuf.data); sbuf.data = nullptr; sbuf.alloc = 0; return std::move(v); } return std::vector<uint8_t>(&sbuf.data[0], &sbuf.data[sbuf_size]); } throw EncodingError("Failed to pack Var to msgpack"); } Var Var::from_msgpack_pages(std::vector<BytesRef> &pages, const uint8_t *extra_first_page, size_t first_size) { size_t len = first_size; for (auto &page : pages) { len += page->size(); } std::vector<uint8_t> data; data.reserve(len); if (first_size) { data.assign(extra_first_page, extra_first_page + first_size); } for (auto &page : pages) { data.insert(data.end(), page->begin(), page->end()); } return Var::from_msgpack(data.data(), data.size()); } std::vector<BytesRef> Var::to_msgpack_pages(size_t first_page_size) const throw(const EncodingError &) { std::vector<uint8_t> data = to_msgpack(); if (data.size() <= first_page_size) { std::vector<BytesRef> result; result.emplace_back(make_ref_<RefCountBytes>(std::move(data))); return std::move(result); } else { return split_pages(data); } } std::vector<BytesRef> Var::split_pages(const std::vector<uint8_t> &data, size_t first_page_size) { std::vector<BytesRef> result; size_t remain_size = data.size(); const uint8_t *pdata = data.data(); if (first_page_size < MAX_PAGE_BODY_SIZE) { // first page might need to save some space for message metadata result.emplace_back( make_ref_<RefCountBytes>(pdata, pdata + first_page_size)); remain_size -= first_page_size; pdata += first_page_size; } while (remain_size > MAX_PAGE_BODY_SIZE) { result.emplace_back( make_ref_<RefCountBytes>(pdata, pdata + MAX_PAGE_BODY_SIZE)); remain_size -= MAX_PAGE_BODY_SIZE; pdata += MAX_PAGE_BODY_SIZE; } // remain_size won't be 0 result.emplace_back(make_ref_<RefCountBytes>(pdata, pdata + remain_size)); return std::move(result); } } // namespace dsa <|endoftext|>
<commit_before>// Check that we can turn a function id to a function address, and also get the // maximum function id for the current binary. // // RUN: %clangxx_xray -std=c++11 %s -o %t // RUN: XRAY_OPTIONS="patch_premain=false xray_naive_log=false" %run %t // FIXME: When we know why this fails in ppc, un-xfail it. // XFAIL: powerpc64le #include "xray/xray_interface.h" #include <algorithm> #include <cassert> #include <cstdio> #include <iterator> #include <set> [[clang::xray_always_instrument]] void bar(){} [[clang::xray_always_instrument]] void foo() { bar(); } [[clang::xray_always_instrument]] int main(int argc, char *argv[]) { assert(__xray_max_function_id() != 0 && "we need xray instrumentation!"); std::set<void *> must_be_instrumented = {reinterpret_cast<void *>(&foo), reinterpret_cast<void *>(&bar), reinterpret_cast<void *>(&main)}; std::set<void *> all_instrumented; for (auto i = __xray_max_function_id(); i != 0; --i) { auto addr = __xray_function_address(i); all_instrumented.insert(reinterpret_cast<void *>(addr)); } assert(all_instrumented.size() == __xray_max_function_id() && "each function id must be assigned to a unique function"); std::set<void *> common; std::set_intersection(all_instrumented.begin(), all_instrumented.end(), must_be_instrumented.begin(), must_be_instrumented.end(), std::inserter(common, common.begin())); assert( common == must_be_instrumented && "we should see all explicitly instrumented functions with function ids"); return common == must_be_instrumented ? 0 : 1; } <commit_msg>[XRay] Fix the test func-id-utils.cc on PPC.<commit_after>// Check that we can turn a function id to a function address, and also get the // maximum function id for the current binary. // // RUN: %clangxx_xray -std=c++11 %s -o %t // RUN: XRAY_OPTIONS="patch_premain=false xray_naive_log=false" %run %t #include "xray/xray_interface.h" #include <algorithm> #include <cassert> #include <cstdio> #include <iterator> #include <set> [[clang::xray_always_instrument]] void bar(){} [[clang::xray_always_instrument]] void foo() { bar(); } [[clang::xray_always_instrument]] int main(int argc, char *argv[]) { assert(__xray_max_function_id() != 0 && "we need xray instrumentation!"); std::set<void *> must_be_instrumented = {reinterpret_cast<void *>(&foo), reinterpret_cast<void *>(&bar), reinterpret_cast<void *>(&main)}; std::set<void *> all_instrumented; for (auto i = __xray_max_function_id(); i != 0; --i) { auto addr = __xray_function_address(i); all_instrumented.insert(reinterpret_cast<void *>(addr)); } assert(all_instrumented.size() == __xray_max_function_id() && "each function id must be assigned to a unique function"); std::set<void *> not_instrumented; const auto comp = [](void *lhs, void *rhs) { #ifdef __PPC__ return reinterpret_cast<uintptr_t>(lhs) + 8 < reinterpret_cast<uintptr_t>(rhs); #else return lhs < rhs; #endif }; std::set_difference(must_be_instrumented.begin(), must_be_instrumented.end(), all_instrumented.begin(), all_instrumented.end(), std::inserter(not_instrumented, not_instrumented.begin()), comp); assert( not_instrumented.empty() && "we should see all explicitly instrumented functions with function ids"); return not_instrumented.empty() ? 0 : 1; } <|endoftext|>
<commit_before>/* * * Copyright 2018 gRPC authors. * * 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 "src/core/lib/iomgr/port.h" // This test won't work except with posix sockets enabled #ifdef GRPC_POSIX_SOCKET_TCP #include <arpa/inet.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <string> #include "absl/strings/str_cat.h" #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/load_file.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem" #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key" #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem" // Simple gRPC server. This listens until client_handshake_complete occurs. static gpr_event client_handshake_complete; static void server_thread(void* arg) { const int port = *static_cast<int*>(arg); // Load key pair and establish server SSL credentials. grpc_ssl_pem_key_cert_pair pem_key_cert_pair; grpc_slice ca_slice, cert_slice, key_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CA_PATH, 1, &ca_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_KEY_PATH, 1, &key_slice))); const char* ca_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice); pem_key_cert_pair.private_key = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice); pem_key_cert_pair.cert_chain = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create( ca_cert, &pem_key_cert_pair, 1, 0, nullptr); // Start server listening on local port. std::string addr = absl::StrCat("127.0.0.1:", port); grpc_server* server = grpc_server_create(nullptr, nullptr); GPR_ASSERT( grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds)); grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_server_register_completion_queue(server, cq, nullptr); grpc_server_start(server); // Wait a bounded number of time until client_handshake_complete is set, // sleeping between polls. The total time spent (deadline * retries) // should be strictly greater than the client retry limit so that the // client will always timeout first. int retries = 60; while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) { const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT); } gpr_log(GPR_INFO, "Shutting down server"); grpc_server_shutdown_and_notify(server, cq, nullptr); grpc_server_cancel_all_calls(server); grpc_completion_queue_shutdown(cq); const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(60); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); grpc_server_destroy(server); grpc_completion_queue_destroy(cq); grpc_server_credentials_release(ssl_creds); grpc_slice_unref(cert_slice); grpc_slice_unref(key_slice); grpc_slice_unref(ca_slice); } // This test launches a minimal TLS grpc server on a separate thread and then // establishes a TLS handshake via the core library to the server. The client // uses the supplied verify options. static bool verify_peer_options_test(verify_peer_options* verify_options) { bool success = true; grpc_init(); int port = grpc_pick_unused_port_or_die(); gpr_event_init(&client_handshake_complete); // Load key pair and establish client SSL credentials. // NOTE: we intentionally load the credential files before starting // the server thread because grpc_load_file can experience trouble // when two threads attempt to load the same file concurrently // and server thread also reads the same files as soon as it starts. // See https://github.com/grpc/grpc/issues/23503 for details. grpc_ssl_pem_key_cert_pair pem_key_cert_pair; grpc_slice ca_slice, cert_slice, key_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CA_PATH, 1, &ca_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_KEY_PATH, 1, &key_slice))); const char* ca_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice); pem_key_cert_pair.private_key = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice); pem_key_cert_pair.cert_chain = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create( ca_cert, &pem_key_cert_pair, verify_options, nullptr); // Launch the gRPC server thread. bool ok; grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &port, &ok); GPR_ASSERT(ok); thd.Start(); // Establish a channel pointing at the TLS server. Since the gRPC runtime is // lazy, this won't necessarily establish a connection yet. std::string target = absl::StrCat("127.0.0.1:", port); grpc_arg ssl_name_override = { GRPC_ARG_STRING, const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG), {const_cast<char*>("foo.test.google.fr")}}; grpc_channel_args grpc_args; grpc_args.num_args = 1; grpc_args.args = &ssl_name_override; grpc_channel* channel = grpc_secure_channel_create(ssl_creds, target.c_str(), &grpc_args, nullptr); GPR_ASSERT(channel); // Initially the channel will be idle, the // grpc_channel_check_connectivity_state triggers an attempt to connect. GPR_ASSERT(grpc_channel_check_connectivity_state( channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE); // Wait a bounded number of times for the channel to be ready. When the // channel is ready, the initial TLS handshake will have successfully // completed. The total time spent on the client side (retries * deadline) // should be greater than the server side time limit. int retries = 10; grpc_connectivity_state state = GRPC_CHANNEL_IDLE; grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); while (state != GRPC_CHANNEL_READY && retries-- > 0) { grpc_channel_watch_connectivity_state( channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr); gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); state = grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */); } grpc_completion_queue_destroy(cq); if (retries < 0) { success = false; } grpc_channel_destroy(channel); grpc_channel_credentials_release(ssl_creds); grpc_slice_unref(cert_slice); grpc_slice_unref(key_slice); grpc_slice_unref(ca_slice); // Now that the client is completely cleaned up, trigger the server to // shutdown gpr_event_set(&client_handshake_complete, &client_handshake_complete); // Wait for the server to completely shutdown thd.Join(); grpc_shutdown(); return success; } static int callback_return_value = 0; static char callback_target_host[4096]; static char callback_target_pem[4096]; static void* callback_userdata = nullptr; static void* destruct_userdata = nullptr; static int verify_callback(const char* target_host, const char* target_pem, void* userdata) { if (target_host != nullptr) { snprintf(callback_target_host, sizeof(callback_target_host), "%s", target_host); } else { callback_target_host[0] = '\0'; } if (target_pem != nullptr) { snprintf(callback_target_pem, sizeof(callback_target_pem), "%s", target_pem); } else { callback_target_pem[0] = '\0'; } callback_userdata = userdata; return callback_return_value; } static void verify_destruct(void* userdata) { destruct_userdata = userdata; } int main(int argc, char* argv[]) { grpc::testing::TestEnvironment env(argc, argv); int userdata = 42; verify_peer_options verify_options; // Load the server's cert so that we can assert it gets passed to the callback grpc_slice cert_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); const char* server_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); // Running with all-null values should have no effect verify_options.verify_peer_callback = nullptr; verify_options.verify_peer_callback_userdata = nullptr; verify_options.verify_peer_destruct = nullptr; GPR_ASSERT(verify_peer_options_test(&verify_options)); GPR_ASSERT(strlen(callback_target_host) == 0); GPR_ASSERT(strlen(callback_target_pem) == 0); GPR_ASSERT(callback_userdata == nullptr); GPR_ASSERT(destruct_userdata == nullptr); // Running with the callbacks and verify we get the expected values verify_options.verify_peer_callback = verify_callback; verify_options.verify_peer_callback_userdata = static_cast<void*>(&userdata); verify_options.verify_peer_destruct = verify_destruct; GPR_ASSERT(verify_peer_options_test(&verify_options)); GPR_ASSERT(strcmp(callback_target_host, "foo.test.google.fr") == 0); GPR_ASSERT(strcmp(callback_target_pem, server_cert) == 0); GPR_ASSERT(callback_userdata == static_cast<void*>(&userdata)); GPR_ASSERT(destruct_userdata == static_cast<void*>(&userdata)); // If the callback returns non-zero, initializing the channel should fail. callback_return_value = 1; GPR_ASSERT(!verify_peer_options_test(&verify_options)); grpc_slice_unref(cert_slice); return 0; } #else /* GRPC_POSIX_SOCKET_TCP */ int main(int argc, char** argv) { return 1; } #endif /* GRPC_POSIX_SOCKET_TCP */ <commit_msg>Add init and shutdown to verify_peer_options<commit_after>/* * * Copyright 2018 gRPC authors. * * 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 "src/core/lib/iomgr/port.h" // This test won't work except with posix sockets enabled #ifdef GRPC_POSIX_SOCKET_TCP #include <arpa/inet.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <string> #include "absl/strings/str_cat.h" #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/load_file.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem" #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key" #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem" // Simple gRPC server. This listens until client_handshake_complete occurs. static gpr_event client_handshake_complete; static void server_thread(void* arg) { const int port = *static_cast<int*>(arg); // Load key pair and establish server SSL credentials. grpc_ssl_pem_key_cert_pair pem_key_cert_pair; grpc_slice ca_slice, cert_slice, key_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CA_PATH, 1, &ca_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_KEY_PATH, 1, &key_slice))); const char* ca_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice); pem_key_cert_pair.private_key = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice); pem_key_cert_pair.cert_chain = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create( ca_cert, &pem_key_cert_pair, 1, 0, nullptr); // Start server listening on local port. std::string addr = absl::StrCat("127.0.0.1:", port); grpc_server* server = grpc_server_create(nullptr, nullptr); GPR_ASSERT( grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds)); grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_server_register_completion_queue(server, cq, nullptr); grpc_server_start(server); // Wait a bounded number of time until client_handshake_complete is set, // sleeping between polls. The total time spent (deadline * retries) // should be strictly greater than the client retry limit so that the // client will always timeout first. int retries = 60; while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) { const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT); } gpr_log(GPR_INFO, "Shutting down server"); grpc_server_shutdown_and_notify(server, cq, nullptr); grpc_server_cancel_all_calls(server); grpc_completion_queue_shutdown(cq); const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(60); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); grpc_server_destroy(server); grpc_completion_queue_destroy(cq); grpc_server_credentials_release(ssl_creds); grpc_slice_unref(cert_slice); grpc_slice_unref(key_slice); grpc_slice_unref(ca_slice); } // This test launches a minimal TLS grpc server on a separate thread and then // establishes a TLS handshake via the core library to the server. The client // uses the supplied verify options. static bool verify_peer_options_test(verify_peer_options* verify_options) { bool success = true; grpc_init(); int port = grpc_pick_unused_port_or_die(); gpr_event_init(&client_handshake_complete); // Load key pair and establish client SSL credentials. // NOTE: we intentionally load the credential files before starting // the server thread because grpc_load_file can experience trouble // when two threads attempt to load the same file concurrently // and server thread also reads the same files as soon as it starts. // See https://github.com/grpc/grpc/issues/23503 for details. grpc_ssl_pem_key_cert_pair pem_key_cert_pair; grpc_slice ca_slice, cert_slice, key_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CA_PATH, 1, &ca_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_KEY_PATH, 1, &key_slice))); const char* ca_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice); pem_key_cert_pair.private_key = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice); pem_key_cert_pair.cert_chain = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create( ca_cert, &pem_key_cert_pair, verify_options, nullptr); // Launch the gRPC server thread. bool ok; grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &port, &ok); GPR_ASSERT(ok); thd.Start(); // Establish a channel pointing at the TLS server. Since the gRPC runtime is // lazy, this won't necessarily establish a connection yet. std::string target = absl::StrCat("127.0.0.1:", port); grpc_arg ssl_name_override = { GRPC_ARG_STRING, const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG), {const_cast<char*>("foo.test.google.fr")}}; grpc_channel_args grpc_args; grpc_args.num_args = 1; grpc_args.args = &ssl_name_override; grpc_channel* channel = grpc_secure_channel_create(ssl_creds, target.c_str(), &grpc_args, nullptr); GPR_ASSERT(channel); // Initially the channel will be idle, the // grpc_channel_check_connectivity_state triggers an attempt to connect. GPR_ASSERT(grpc_channel_check_connectivity_state( channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE); // Wait a bounded number of times for the channel to be ready. When the // channel is ready, the initial TLS handshake will have successfully // completed. The total time spent on the client side (retries * deadline) // should be greater than the server side time limit. int retries = 10; grpc_connectivity_state state = GRPC_CHANNEL_IDLE; grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); while (state != GRPC_CHANNEL_READY && retries-- > 0) { grpc_channel_watch_connectivity_state( channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr); gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5); grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); state = grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */); } grpc_completion_queue_destroy(cq); if (retries < 0) { success = false; } grpc_channel_destroy(channel); grpc_channel_credentials_release(ssl_creds); grpc_slice_unref(cert_slice); grpc_slice_unref(key_slice); grpc_slice_unref(ca_slice); // Now that the client is completely cleaned up, trigger the server to // shutdown gpr_event_set(&client_handshake_complete, &client_handshake_complete); // Wait for the server to completely shutdown thd.Join(); grpc_shutdown(); return success; } static int callback_return_value = 0; static char callback_target_host[4096]; static char callback_target_pem[4096]; static void* callback_userdata = nullptr; static void* destruct_userdata = nullptr; static int verify_callback(const char* target_host, const char* target_pem, void* userdata) { if (target_host != nullptr) { snprintf(callback_target_host, sizeof(callback_target_host), "%s", target_host); } else { callback_target_host[0] = '\0'; } if (target_pem != nullptr) { snprintf(callback_target_pem, sizeof(callback_target_pem), "%s", target_pem); } else { callback_target_pem[0] = '\0'; } callback_userdata = userdata; return callback_return_value; } static void verify_destruct(void* userdata) { destruct_userdata = userdata; } int main(int argc, char* argv[]) { grpc::testing::TestEnvironment env(argc, argv); grpc_init(); int userdata = 42; verify_peer_options verify_options; // Load the server's cert so that we can assert it gets passed to the callback grpc_slice cert_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(SSL_CERT_PATH, 1, &cert_slice))); const char* server_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice); // Running with all-null values should have no effect verify_options.verify_peer_callback = nullptr; verify_options.verify_peer_callback_userdata = nullptr; verify_options.verify_peer_destruct = nullptr; GPR_ASSERT(verify_peer_options_test(&verify_options)); GPR_ASSERT(strlen(callback_target_host) == 0); GPR_ASSERT(strlen(callback_target_pem) == 0); GPR_ASSERT(callback_userdata == nullptr); GPR_ASSERT(destruct_userdata == nullptr); // Running with the callbacks and verify we get the expected values verify_options.verify_peer_callback = verify_callback; verify_options.verify_peer_callback_userdata = static_cast<void*>(&userdata); verify_options.verify_peer_destruct = verify_destruct; GPR_ASSERT(verify_peer_options_test(&verify_options)); GPR_ASSERT(strcmp(callback_target_host, "foo.test.google.fr") == 0); GPR_ASSERT(strcmp(callback_target_pem, server_cert) == 0); GPR_ASSERT(callback_userdata == static_cast<void*>(&userdata)); GPR_ASSERT(destruct_userdata == static_cast<void*>(&userdata)); // If the callback returns non-zero, initializing the channel should fail. callback_return_value = 1; GPR_ASSERT(!verify_peer_options_test(&verify_options)); grpc_slice_unref(cert_slice); grpc_shutdown(); return 0; } #else /* GRPC_POSIX_SOCKET_TCP */ int main(int argc, char** argv) { return 1; } #endif /* GRPC_POSIX_SOCKET_TCP */ <|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 // C++ includes #include <fstream> #include <cstring> // Local includes #include "exodusII_io.h" #include "boundary_info.h" #include "mesh_base.h" #include "enum_elem_type.h" #include "elem.h" #include "system.h" #include "numeric_vector.h" #include "exodusII_io_helper.h" // ------------------------------------------------------------ // ExodusII_IO class members ExodusII_IO::ExodusII_IO (MeshBase& mesh) : MeshInput<MeshBase> (mesh), MeshOutput<MeshBase> (mesh), _timestep(1), _verbose (false) { } ExodusII_IO::~ExodusII_IO () { #ifndef LIBMESH_HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); #else if(libMesh::processor_id() == 0) exio_helper.close(); #endif } void ExodusII_IO::verbose (bool set_verbosity) { _verbose = set_verbosity; #ifdef LIBMESH_HAVE_EXODUS_API // Set the verbose flag in the helper object // as well. exio_helper.verbose(_verbose); #endif } void ExodusII_IO::read (const std::string& fname) { // This is a serial-only process for now; // the Mesh should be read on processor 0 and // broadcast later libmesh_assert(libMesh::processor_id() == 0); #ifndef LIBMESH_HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << "Input file " << fname << " cannot be read" << std::endl; libmesh_error(); #else // Get a reference to the mesh we are reading MeshBase& mesh = MeshInput<MeshBase>::mesh(); // Clear any existing mesh data mesh.clear(); if (mesh.mesh_dimension() == 1) // No support for 1D ExodusII meshes libmesh_not_implemented(); #ifdef DEBUG this->verbose(true); #endif ExodusII_IO_Helper::ElementMaps em; // Instantiate the ElementMaps interface exio_helper.open(fname.c_str()); // Open the exodus file, if possible exio_helper.read_header(); // Get header information from exodus file exio_helper.print_header(); // Print header information libmesh_assert(static_cast<unsigned int>(exio_helper.get_num_dim()) == mesh.mesh_dimension()); // Be sure number of dimensions // is equal to the number of // dimensions in the mesh supplied. exio_helper.read_nodes(); // Read nodes from the exodus file mesh.reserve_nodes(exio_helper.get_num_nodes()); // Reserve space for the nodes. // Loop over the nodes, create Nodes with local processor_id 0. for (int i=0; i<exio_helper.get_num_nodes(); i++) mesh.add_point (Point(exio_helper.get_x(i), exio_helper.get_y(i), exio_helper.get_z(i)), i); libmesh_assert (static_cast<unsigned int>(exio_helper.get_num_nodes()) == mesh.n_nodes()); exio_helper.read_block_info(); // Get information about all the blocks mesh.reserve_elem(exio_helper.get_num_elem()); // Reserve space for the elements // Read in the element connectivity for each block. int nelem_last_block = 0; // Loop over all the blocks for (int i=0; i<exio_helper.get_num_elem_blk(); i++) { // Read the information for block i exio_helper.read_elem_in_block (i); int subdomain_id = exio_helper.get_block_id(i); // Set any relevant node/edge maps for this element const std::string type_str (exio_helper.get_elem_type()); const ExodusII_IO_Helper::Conversion conv = em.assign_conversion(type_str); //if (_verbose) //std::cout << "Reading a block of " << type_str << " elements." << std::endl; // Loop over all the faces in this block int jmax = nelem_last_block+exio_helper.get_num_elem_this_blk(); for (int j=nelem_last_block; j<jmax; j++) { Elem* elem = Elem::build (conv.get_canonical_type()).release(); libmesh_assert (elem); elem->subdomain_id() = subdomain_id; //elem->set_id(j);// Don't try to second guess the Element ID setting scheme! elem = mesh.add_elem (elem); // Catch the Elem pointer that the Mesh throws back // Set all the nodes for this element for (int k=0; k<exio_helper.get_num_nodes_per_elem(); k++) { int gi = (j-nelem_last_block)*exio_helper.get_num_nodes_per_elem() + conv.get_node_map(k); // global index int node_number = exio_helper.get_connect(gi); // Global node number (1-based) elem->set_node(k) = mesh.node_ptr((node_number-1)); // Set node number // Subtract 1 since // exodus is internally 1-based } } // running sum of # of elements per block, // (should equal total number of elements in the end) nelem_last_block += exio_helper.get_num_elem_this_blk(); } libmesh_assert (static_cast<unsigned int>(nelem_last_block) == mesh.n_elem()); // Read in sideset information -- this is useful for applying boundary conditions { exio_helper.read_sideset_info(); // Get basic information about ALL sidesets int offset=0; for (int i=0; i<exio_helper.get_num_side_sets(); i++) { offset += (i > 0 ? exio_helper.get_num_sides_per_set(i-1) : 0); // Compute new offset exio_helper.read_sideset (i, offset); } const std::vector<int>& elem_list = exio_helper.get_elem_list(); const std::vector<int>& side_list = exio_helper.get_side_list(); const std::vector<int>& id_list = exio_helper.get_id_list(); for (unsigned int e=0; e<elem_list.size(); e++) { // Set any relevant node/edge maps for this element const ExodusII_IO_Helper::Conversion conv = em.assign_conversion(mesh.elem(elem_list[e]-1)->type()); mesh.boundary_info->add_side (elem_list[e]-1, conv.get_side_map(side_list[e]-1), id_list[e]); } } #endif } #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::copy_nodal_solution(System& , std::string) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::copy_nodal_solution(System& system, std::string nodal_var_name, unsigned int timestep) { // FIXME: Do we need to call get_time_steps() at all? /*const std::vector<double>& time_steps = */ exio_helper.get_time_steps(); const std::vector<double> & nodal_values = exio_helper.get_nodal_var_values(nodal_var_name,timestep); //const DofMap & dof_map = system.get_dof_map(); const unsigned int var_num = system.variable_number(nodal_var_name); for (unsigned int i=0; i<nodal_values.size(); ++i) { const unsigned int dof_index = MeshInput<MeshBase>::mesh().node_ptr(i)->dof_number(system.number(),var_num,0); // If the dof_index is local to this processor, set the value if ((dof_index >= system.solution->first_local_index()) && (dof_index < system.solution->last_local_index())) system.solution->set (dof_index, nodal_values[i]); } system.update(); } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write_nodal_data (const std::string& , const std::vector<Number>& , const std::vector<std::string>& ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write_nodal_data (const std::string& fname, const std::vector<Number>& soln, const std::vector<std::string>& names) { if (libMesh::processor_id() == 0) { const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); int num_vars = names.size(); int num_nodes = mesh.n_nodes(); // FIXME: Will we ever _not_ need to do this? // DRG: Yes... when writing multiple timesteps to the same file. if (!exio_helper.created()) { exio_helper.create(fname); exio_helper.initialize(fname,mesh); exio_helper.write_nodal_coordinates(mesh); exio_helper.write_elements(mesh); exio_helper.write_sidesets(mesh); exio_helper.initialize_nodal_variables(names); } for (int c=0; c<num_vars; c++) { std::vector<Number> cur_soln(num_nodes); //Copy out this variable's solution for(int i=0; i<num_nodes; i++) cur_soln[i] = soln[i*num_vars + c];//c*num_nodes+i]; exio_helper.write_nodal_values(c+1,cur_soln,_timestep); } } } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write_timestep (const std::string& , const EquationSystems& , const int , const double ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write_timestep (const std::string& fname, const EquationSystems& es, const int timestep, const double time) { _timestep=timestep; write_equation_systems(fname,es); if (libMesh::processor_id() == 0) exio_helper.write_timestep(timestep, time); } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write (const std::string& ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write (const std::string& fname) { if (libMesh::processor_id() == 0) { const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); libmesh_assert( !exio_helper.created() ); exio_helper.create(fname); exio_helper.initialize(fname,mesh); exio_helper.write_nodal_coordinates(mesh); exio_helper.write_elements(mesh); exio_helper.write_sidesets(mesh); // Note: the file is closed automatically by the ExodusII_IO destructor. } } #endif <commit_msg>fix exodus reading with parallel mesh<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 // C++ includes #include <fstream> #include <cstring> // Local includes #include "exodusII_io.h" #include "boundary_info.h" #include "mesh_base.h" #include "enum_elem_type.h" #include "elem.h" #include "system.h" #include "numeric_vector.h" #include "exodusII_io_helper.h" // ------------------------------------------------------------ // ExodusII_IO class members ExodusII_IO::ExodusII_IO (MeshBase& mesh) : MeshInput<MeshBase> (mesh), MeshOutput<MeshBase> (mesh), _timestep(1), _verbose (false) { } ExodusII_IO::~ExodusII_IO () { #ifndef LIBMESH_HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); #else if(libMesh::processor_id() == 0) exio_helper.close(); #endif } void ExodusII_IO::verbose (bool set_verbosity) { _verbose = set_verbosity; #ifdef LIBMESH_HAVE_EXODUS_API // Set the verbose flag in the helper object // as well. exio_helper.verbose(_verbose); #endif } void ExodusII_IO::read (const std::string& fname) { // This is a serial-only process for now; // the Mesh should be read on processor 0 and // broadcast later libmesh_assert(libMesh::processor_id() == 0); #ifndef LIBMESH_HAVE_EXODUS_API std::cerr << "ERROR, ExodusII API is not defined.\n" << "Input file " << fname << " cannot be read" << std::endl; libmesh_error(); #else // Get a reference to the mesh we are reading MeshBase& mesh = MeshInput<MeshBase>::mesh(); // Clear any existing mesh data mesh.clear(); if (mesh.mesh_dimension() == 1) // No support for 1D ExodusII meshes libmesh_not_implemented(); #ifdef DEBUG this->verbose(true); #endif ExodusII_IO_Helper::ElementMaps em; // Instantiate the ElementMaps interface exio_helper.open(fname.c_str()); // Open the exodus file, if possible exio_helper.read_header(); // Get header information from exodus file exio_helper.print_header(); // Print header information libmesh_assert(static_cast<unsigned int>(exio_helper.get_num_dim()) == mesh.mesh_dimension()); // Be sure number of dimensions // is equal to the number of // dimensions in the mesh supplied. exio_helper.read_nodes(); // Read nodes from the exodus file mesh.reserve_nodes(exio_helper.get_num_nodes()); // Reserve space for the nodes. // Loop over the nodes, create Nodes with local processor_id 0. for (int i=0; i<exio_helper.get_num_nodes(); i++) mesh.add_point (Point(exio_helper.get_x(i), exio_helper.get_y(i), exio_helper.get_z(i)), i); libmesh_assert (static_cast<unsigned int>(exio_helper.get_num_nodes()) == mesh.n_nodes()); exio_helper.read_block_info(); // Get information about all the blocks mesh.reserve_elem(exio_helper.get_num_elem()); // Reserve space for the elements // Read in the element connectivity for each block. int nelem_last_block = 0; std::map<int, unsigned int> exodus_id_to_mesh_id; // Loop over all the blocks for (int i=0; i<exio_helper.get_num_elem_blk(); i++) { // Read the information for block i exio_helper.read_elem_in_block (i); int subdomain_id = exio_helper.get_block_id(i); // Set any relevant node/edge maps for this element const std::string type_str (exio_helper.get_elem_type()); const ExodusII_IO_Helper::Conversion conv = em.assign_conversion(type_str); //if (_verbose) //std::cout << "Reading a block of " << type_str << " elements." << std::endl; // Loop over all the faces in this block int jmax = nelem_last_block+exio_helper.get_num_elem_this_blk(); for (int j=nelem_last_block; j<jmax; j++) { Elem* elem = Elem::build (conv.get_canonical_type()).release(); libmesh_assert (elem); elem->subdomain_id() = subdomain_id; //elem->set_id(j);// Don't try to second guess the Element ID setting scheme! elem = mesh.add_elem (elem); // Catch the Elem pointer that the Mesh throws back exodus_id_to_mesh_id[j+1] = elem->id(); // Set all the nodes for this element for (int k=0; k<exio_helper.get_num_nodes_per_elem(); k++) { int gi = (j-nelem_last_block)*exio_helper.get_num_nodes_per_elem() + conv.get_node_map(k); // global index int node_number = exio_helper.get_connect(gi); // Global node number (1-based) elem->set_node(k) = mesh.node_ptr((node_number-1)); // Set node number // Subtract 1 since // exodus is internally 1-based } } // running sum of # of elements per block, // (should equal total number of elements in the end) nelem_last_block += exio_helper.get_num_elem_this_blk(); } libmesh_assert (static_cast<unsigned int>(nelem_last_block) == mesh.n_elem()); // Read in sideset information -- this is useful for applying boundary conditions { exio_helper.read_sideset_info(); // Get basic information about ALL sidesets int offset=0; for (int i=0; i<exio_helper.get_num_side_sets(); i++) { offset += (i > 0 ? exio_helper.get_num_sides_per_set(i-1) : 0); // Compute new offset exio_helper.read_sideset (i, offset); } const std::vector<int>& elem_list = exio_helper.get_elem_list(); const std::vector<int>& side_list = exio_helper.get_side_list(); const std::vector<int>& id_list = exio_helper.get_id_list(); for (unsigned int e=0; e<elem_list.size(); e++) { // Set any relevant node/edge maps for this element Elem * elem = mesh.elem(exodus_id_to_mesh_id[elem_list[e]]); const ExodusII_IO_Helper::Conversion conv = em.assign_conversion(elem->type()); mesh.boundary_info->add_side (exodus_id_to_mesh_id[elem_list[e]], conv.get_side_map(side_list[e]-1), id_list[e]); } } #endif } #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::copy_nodal_solution(System& , std::string) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::copy_nodal_solution(System& system, std::string nodal_var_name, unsigned int timestep) { // FIXME: Do we need to call get_time_steps() at all? /*const std::vector<double>& time_steps = */ exio_helper.get_time_steps(); const std::vector<double> & nodal_values = exio_helper.get_nodal_var_values(nodal_var_name,timestep); //const DofMap & dof_map = system.get_dof_map(); const unsigned int var_num = system.variable_number(nodal_var_name); for (unsigned int i=0; i<nodal_values.size(); ++i) { const unsigned int dof_index = MeshInput<MeshBase>::mesh().node_ptr(i)->dof_number(system.number(),var_num,0); // If the dof_index is local to this processor, set the value if ((dof_index >= system.solution->first_local_index()) && (dof_index < system.solution->last_local_index())) system.solution->set (dof_index, nodal_values[i]); } system.update(); } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write_nodal_data (const std::string& , const std::vector<Number>& , const std::vector<std::string>& ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write_nodal_data (const std::string& fname, const std::vector<Number>& soln, const std::vector<std::string>& names) { if (libMesh::processor_id() == 0) { const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); int num_vars = names.size(); int num_nodes = mesh.n_nodes(); // FIXME: Will we ever _not_ need to do this? // DRG: Yes... when writing multiple timesteps to the same file. if (!exio_helper.created()) { exio_helper.create(fname); exio_helper.initialize(fname,mesh); exio_helper.write_nodal_coordinates(mesh); exio_helper.write_elements(mesh); exio_helper.write_sidesets(mesh); exio_helper.initialize_nodal_variables(names); } for (int c=0; c<num_vars; c++) { std::vector<Number> cur_soln(num_nodes); //Copy out this variable's solution for(int i=0; i<num_nodes; i++) cur_soln[i] = soln[i*num_vars + c];//c*num_nodes+i]; exio_helper.write_nodal_values(c+1,cur_soln,_timestep); } } } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write_timestep (const std::string& , const EquationSystems& , const int , const double ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write_timestep (const std::string& fname, const EquationSystems& es, const int timestep, const double time) { _timestep=timestep; write_equation_systems(fname,es); if (libMesh::processor_id() == 0) exio_helper.write_timestep(timestep, time); } #endif #ifndef LIBMESH_HAVE_EXODUS_API void ExodusII_IO::write (const std::string& ) { std::cerr << "ERROR, ExodusII API is not defined.\n" << std::endl; libmesh_error(); } #else void ExodusII_IO::write (const std::string& fname) { if (libMesh::processor_id() == 0) { const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); libmesh_assert( !exio_helper.created() ); exio_helper.create(fname); exio_helper.initialize(fname,mesh); exio_helper.write_nodal_coordinates(mesh); exio_helper.write_elements(mesh); exio_helper.write_sidesets(mesh); // Note: the file is closed automatically by the ExodusII_IO destructor. } } #endif <|endoftext|>
<commit_before>#include "sevensegment.h" #include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <stdexcept> namespace sevensegment { using digit = std::vector<std::string>; using digit_vector = std::vector<digit>; const digit_vector digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const digit minus_sign { " ", " ", " - ", " ", " " }; // - std::string stretchDigitLine(const std::string& line, const unsigned scale_factor) { std::string stretched_line(scale_factor+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } digit_vector split_digits(const int i, digit_vector& vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } digit_vector split_digits(int i) { digit_vector vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const digit_vector& vector, const unsigned line_nr, const unsigned scale_factor){ std::string line {}; unsigned digit_nr { 0 }; const auto number_of_digits = vector.size(); for(digit d : vector){ line.append(stretchDigitLine(d[line_nr], scale_factor)); // between digits (not at the end) if (++digit_nr != number_of_digits) line.append(scale_factor/2, ' '); // letter spacing for readability } return line; } constexpr unsigned display_size { 8 }; void printDigitSequence(const digit_vector vector, std::ostream& out, const unsigned scale_factor){ if (scale_factor<1) throw std::range_error { "invalid scale" }; if (vector.size() > display_size) throw std::overflow_error { "too many digits" }; std::ostream_iterator<std::string> out_it(out, "\n"); // iterate through lines, not digits // OPTIMIZE: transpose vector first for(int line_nr { 0 }; line_nr < 5; ++line_nr) { if (line_nr == 1 || line_nr == 3) { const auto line = lineOfLargeDigits(vector, line_nr, scale_factor); std::generate_n(out_it, scale_factor, [&](){return line;}); } else { out << lineOfLargeDigits(vector, line_nr, scale_factor) << '\n'; } } } // Requested for the assignment. Used nowhere but in the tests. void printLargeDigit(const unsigned i, std::ostream& out, const unsigned scale_factor) { const auto d = digits.at(i); const digit_vector single_digit_vector { d }; printDigitSequence(single_digit_vector, out, scale_factor); } void printLargeNumber(const int i, std::ostream& out, const unsigned scale_factor) { printDigitSequence(split_digits(i), out, scale_factor); } const digit_vector error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |" " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; void printLargeError(std::ostream& out, const unsigned scale_factor) { printDigitSequence(error, out, scale_factor); } } <commit_msg>partially revert 6b36e840 to fix weird bug in tests<commit_after>#include "sevensegment.h" #include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <stdexcept> namespace sevensegment { using digit = std::vector<std::string>; using digit_vector = std::vector<digit>; const digit_vector digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const digit minus_sign { " ", " ", " - ", " ", " " }; // - std::string stretchDigitLine(const std::string& line, const unsigned scale_factor) { std::string stretched_line(scale_factor+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } digit_vector split_digits(const int i, digit_vector& vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } digit_vector split_digits(int i) { digit_vector vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const digit_vector& vector, const unsigned line_nr, const unsigned scale_factor){ std::string line {}; unsigned digit_nr { 0 }; const auto number_of_digits = vector.size(); for(digit d : vector){ line.append(stretchDigitLine(d[line_nr], scale_factor)); // between digits (not at the end) if (++digit_nr != number_of_digits) line.append(scale_factor/2, ' '); // letter spacing for readability } return line; } constexpr unsigned display_size { 8 }; void printDigitSequence(const digit_vector vector, std::ostream& out, const unsigned scale_factor){ if (scale_factor<1) throw std::range_error { "invalid scale" }; if (vector.size() > display_size) throw std::overflow_error { "too many digits" }; std::ostream_iterator<std::string> out_it(out, "\n"); // iterate through lines, not digits // OPTIMIZE: transpose vector first for(int line_nr { 0 }; line_nr < 5; ++line_nr) { if (line_nr == 1 || line_nr == 3) { const auto line = lineOfLargeDigits(vector, line_nr, scale_factor); std::generate_n(out_it, scale_factor, [&](){return line;}); } else { out << lineOfLargeDigits(vector, line_nr, scale_factor) << '\n'; } } } // Requested for the assignment. Used nowhere but in the tests. void printLargeDigit(const unsigned i, std::ostream& out, const unsigned scale_factor) { const auto d = digits.at(i); const digit_vector single_digit_vector { d }; printDigitSequence(single_digit_vector, out, scale_factor); } void printLargeNumber(const int i, std::ostream& out, const unsigned scale_factor) { printDigitSequence(split_digits(i), out, scale_factor); } const digit_vector error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |", " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; void printLargeError(std::ostream& out, const unsigned scale_factor) { printDigitSequence(error, out, scale_factor); } } <|endoftext|>
<commit_before>#include <cstring> #include "message.hpp" #include "identity_message.hpp" #include "ping_pong_message.hpp" #include "suspect_message.hpp" /** * A message header has 4 fields: * - type (1 byte) * - flags (1 byte) * - id (8 bytes) * - length (4 bytes) * Total: 14 bytes */ #define MSG_HEADER_SIZE 14 int Message :: pack(uint8_t* dest, int dest_len) { int length = body_size(); if (dest_len < length+MSG_HEADER_SIZE) { return -1; } write8be(type, dest); dest++; dest_len--; write8be(flags, dest); dest++; dest_len--; write64be(id, dest); dest += 8; dest_len -= 8; write32be(length, dest); dest += 4; dest_len -= 4; int status = pack_body(dest, dest_len); if (status < 0) { return -2; } return MSG_HEADER_SIZE+length; } int Message :: unpack(uint8_t* src, int src_len) { if (src_len < MSG_HEADER_SIZE) { return -1; } type = read8be(src); src++; flags = read8be(src); src++; id = read64be(src); src += 8; uint32_t length = read32be(src); src += 4; if (src_len - MSG_HEADER_SIZE < length) { return -2; } unpack_body(src, length); return 0; } int decode_message(std::unique_ptr<Message>& m, uint8_t* src, int src_len) { assert(src_len > 0); // Peek at the message type switch (src[0]) { case MSG_PING: m = std::make_unique<PingMessage>(); break; case MSG_PONG: m = std::make_unique<PongMessage>(); break; case MSG_IDENT_REQUEST: m = std::make_unique<IdentityRequest>(); break; case MSG_IDENT: m = std::make_unique<IdentityMessage>(); break; case MSG_SUSPECT: m = std::make_unique<SuspectMessage>(); break; case MSG_STILL_ALIVE: m = std::make_unique<StillAliveMessage>(); break; default: return -1; } return m->unpack(src, src_len); } #undef MSG_HEADER_SIZE <commit_msg>add <memory> to message.cc<commit_after>#include <memory> #include <cstring> #include "message.hpp" #include "identity_message.hpp" #include "ping_pong_message.hpp" #include "suspect_message.hpp" /** * A message header has 4 fields: * - type (1 byte) * - flags (1 byte) * - id (8 bytes) * - length (4 bytes) * Total: 14 bytes */ #define MSG_HEADER_SIZE 14 int Message :: pack(uint8_t* dest, int dest_len) { int length = body_size(); if (dest_len < length+MSG_HEADER_SIZE) { return -1; } write8be(type, dest); dest++; dest_len--; write8be(flags, dest); dest++; dest_len--; write64be(id, dest); dest += 8; dest_len -= 8; write32be(length, dest); dest += 4; dest_len -= 4; int status = pack_body(dest, dest_len); if (status < 0) { return -2; } return MSG_HEADER_SIZE+length; } int Message :: unpack(uint8_t* src, int src_len) { if (src_len < MSG_HEADER_SIZE) { return -1; } type = read8be(src); src++; flags = read8be(src); src++; id = read64be(src); src += 8; uint32_t length = read32be(src); src += 4; if (src_len - MSG_HEADER_SIZE < length) { return -2; } unpack_body(src, length); return 0; } int decode_message(std::unique_ptr<Message>& m, uint8_t* src, int src_len) { assert(src_len > 0); // Peek at the message type switch (src[0]) { case MSG_PING: m = std::make_unique<PingMessage>(); break; case MSG_PONG: m = std::make_unique<PongMessage>(); break; case MSG_IDENT_REQUEST: m = std::make_unique<IdentityRequest>(); break; case MSG_IDENT: m = std::make_unique<IdentityMessage>(); break; case MSG_SUSPECT: m = std::make_unique<SuspectMessage>(); break; case MSG_STILL_ALIVE: m = std::make_unique<StillAliveMessage>(); break; default: return -1; } return m->unpack(src, src_len); } #undef MSG_HEADER_SIZE <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include <iostream> #include <hdf5.h> #include <hdf5_hl.h> namespace FrameSimulatorTest { class HDF5FrameTest { public: HDF5FrameTest() { const int master_argc = boost::unit_test::framework::master_test_suite().argc; if (master_argc > 1) { std::string config_file = boost::unit_test::framework::master_test_suite().argv[1]; boost::property_tree::ini_parser::read_ini(config_file, ptree); file_id = H5Fopen(ptree.get<std::string>("Test.output_file").c_str(), H5F_ACC_SWMR_READ, H5P_DEFAULT); dataset = H5Dopen(file_id, "/data", H5P_DEFAULT); } else { throw std::runtime_error("HDF5FrameTest: ini file not specified!"); }; } hid_t file_id, dataset; boost::property_tree::ptree ptree; }; BOOST_FIXTURE_TEST_SUITE(HDF5FrameUnitTest, HDF5FrameTest); BOOST_AUTO_TEST_CASE(HDF5Frame_size) { hid_t filetype = H5Dget_type(dataset); hid_t space = H5Dget_space(dataset); const int ndims = H5Sget_simple_extent_ndims(space); hsize_t dims[ndims]; int ndms = H5Sget_simple_extent_dims(space, dims, NULL); BOOST_CHECK_EQUAL(ndims, ptree.get<int>("Test.dimensions")); BOOST_CHECK_EQUAL(dims[0], ptree.get<int>("Test.frames")); BOOST_CHECK_EQUAL(dims[1], ptree.get<int>("Test.width")); BOOST_CHECK_EQUAL(dims[2], ptree.get<int>("Test.height")); }; BOOST_AUTO_TEST_SUITE_END(); } <commit_msg>allow enviroment variables in test config<commit_after>#include <boost/test/unit_test.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include "PropertyTreeUtility.h" #include <iostream> #include <hdf5.h> #include <hdf5_hl.h> namespace FrameSimulatorTest { class HDF5FrameTest { public: HDF5FrameTest() { const int master_argc = boost::unit_test::framework::master_test_suite().argc; if (master_argc > 1) { std::string config_file = boost::unit_test::framework::master_test_suite().argv[1]; boost::property_tree::ini_parser::read_ini(config_file, ptree); // Get path to hdf5 file std::string output_file = ptree.get<std::string>("Test.output_file"); PropertyTreeUtility::expandEnvVars(output_file); file_id = H5Fopen(output_file.c_str(), H5F_ACC_SWMR_READ, H5P_DEFAULT); dataset = H5Dopen(file_id, "/data", H5P_DEFAULT); } else { throw std::runtime_error("HDF5FrameTest: ini file not specified!"); }; } hid_t file_id, dataset; boost::property_tree::ptree ptree; }; BOOST_FIXTURE_TEST_SUITE(HDF5FrameUnitTest, HDF5FrameTest); BOOST_AUTO_TEST_CASE(HDF5Frame_size) { hid_t filetype = H5Dget_type(dataset); hid_t space = H5Dget_space(dataset); const int ndims = H5Sget_simple_extent_ndims(space); hsize_t dims[ndims]; int ndms = H5Sget_simple_extent_dims(space, dims, NULL); BOOST_CHECK_EQUAL(ndims, ptree.get<int>("Test.dimensions")); BOOST_CHECK_EQUAL(dims[0], ptree.get<int>("Test.frames")); BOOST_CHECK_EQUAL(dims[1], ptree.get<int>("Test.width")); BOOST_CHECK_EQUAL(dims[2], ptree.get<int>("Test.height")); }; BOOST_AUTO_TEST_SUITE_END(); } <|endoftext|>
<commit_before>#include "arrowhead/config.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/bind.hpp> #include "coap/coap.h" #include "arrowhead/coap.hpp" /* Ugly global state because of libcoap limitations (no opaque pointer in base * coap context struct) */ int count = 0; /* * The resource handler */ static void hello_handler(coap_context_t *ctx, struct coap_resource_t *resource, const coap_endpoint_t *local_interface, coap_address_t *peer, coap_pdu_t *request, str *token, coap_pdu_t *response) { (void)ctx; (void)resource; unsigned char buf[3]; response->hdr->code = COAP_RESPONSE_CODE(205); coap_add_option(response, COAP_OPTION_CONTENT_TYPE, coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); std::ostringstream os; os << count << " seconds since start"; std::string str(os.str()); // coap_add_data must be the last operation on the PDU. coap_add_data(response, str.length(), reinterpret_cast<const unsigned char *>(str.c_str())); } void print(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* tim, int* count) { std::cout << *count << std::endl; ++(*count); tim->expires_at(tim->expires_at() + boost::posix_time::seconds(1)); tim->async_wait(boost::bind(print, boost::asio::placeholders::error, tim, count)); } int main(int argc, char* argv[]) { boost::asio::io_service io_service; Arrowhead::CoAPResource hello("hello"); hello.register_handler(COAP_REQUEST_GET, hello_handler); Arrowhead::CoAPContext server(io_service, 13131); server.add_resource(hello); boost::asio::deadline_timer tim(io_service, boost::posix_time::seconds(1)); tim.async_wait(boost::bind(print, boost::asio::placeholders::error, &tim, &count)); io_service.run(); return 0; } <commit_msg>coap-server: Add serviceregistry registration during startup<commit_after>#include "arrowhead/config.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/bind.hpp> #include "coap/coap.h" #include "arrowhead/coap.hpp" #include "arrowhead/core_services/serviceregistry.hpp" /* Ugly global state because of libcoap limitations (no opaque pointer in base * coap context struct) */ int count = 0; /* * The resource handler */ static void hello_handler(coap_context_t *ctx, struct coap_resource_t *resource, const coap_endpoint_t *local_interface, coap_address_t *peer, coap_pdu_t *request, str *token, coap_pdu_t *response) { (void)ctx; (void)resource; unsigned char buf[3]; response->hdr->code = COAP_RESPONSE_CODE(205); coap_add_option(response, COAP_OPTION_CONTENT_TYPE, coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); std::ostringstream os; os << count << " seconds since start"; std::string str(os.str()); // coap_add_data must be the last operation on the PDU. coap_add_data(response, str.length(), reinterpret_cast<const unsigned char *>(str.c_str())); } void print(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* tim, int* count) { std::cout << *count << std::endl; ++(*count); tim->expires_at(tim->expires_at() + boost::posix_time::seconds(1)); tim->async_wait(boost::bind(print, boost::asio::placeholders::error, tim, count)); } int main(int argc, char* argv[]) { boost::asio::io_service io_service; Arrowhead::CoAPResource hello("hello"); hello.register_handler(COAP_REQUEST_GET, hello_handler); Arrowhead::CoAPContext server(io_service, 13131); server.add_resource(hello); boost::asio::deadline_timer tim(io_service, boost::posix_time::seconds(1)); tim.async_wait(boost::bind(print, boost::asio::placeholders::error, &tim, &count)); Arrowhead::ServiceRegistryHTTP servicereg("http://localhost:8045/servicediscovery"); Arrowhead::ServiceDescription srv; srv.name = argv[0]; srv.type = "example-server.arrowhead.cpp"; srv.host = "localhost"; srv.port = 13131; srv.properties["version"] = "0.1"; srv.properties["path"] = "/hello"; servicereg.publish(srv); io_service.run(); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** ** Copyright (C) 2010 Nokia Corporation. ** ** ** ** Author: Simo Piiroinen <simo.piiroinen@nokia.com> ** ** ** ** This file is part of Timed ** ** ** ** Timed 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. ** ** ** ** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ ** ** ** ***************************************************************************/ #include "credentials.h" #include "log.h" #include <sys/creds.h> #include <stdlib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <dbus/dbus.h> #define CS(s) (s).toLocal8Bit().constData() #define US(s) (s).toUtf8().constData() #define BOINK() log_warning("!!! %s:%d: BOINK\n", __FILE__,__LINE__) #define SEPARATOR " " /* ------------------------------------------------------------------------- * * get_owner_pid * ------------------------------------------------------------------------- */ static pid_t get_owner_pid(QDBusConnection &bus, const char *name) { /* FIXME: this makes a synchronous roundtrip to dbus daemon * and back during which time the timed process will be blocked. * * Note: We can't really handle this asynchronously without * handling the whole add_event asynchronously and this would * require modifications to the timed event state machine and * delaying sending add_event replies from QDBusAbstractAdaptor. * At the moment I do not know how to handle either of those ... */ pid_t result = -1; QString service = "org.freedesktop.DBus"; QString path = "/org/freedesktop/DBus"; QString interface = "org.freedesktop.DBus"; QString method = "GetConnectionUnixProcessID"; QDBusMessage req = QDBusMessage::createMethodCall(service, path, interface, method); req << QString(name); QDBusMessage rsp = bus.call(req); if( rsp.type() == QDBusMessage::ReplyMessage ) { QList<QVariant> args = rsp.arguments(); if( !args.isEmpty() ) { bool ok = false; int reply = rsp.arguments().first().toInt(&ok); log_warning("@@@ rsp.ok = %d, rsp.reply = %d", ok, reply); if( ok ) result = reply; } } log_warning("@@@ owner pid = %d", (int)result); return result; } /* ------------------------------------------------------------------------- * * xrealloc * ------------------------------------------------------------------------- */ static bool xrealloc(void *pptr, size_t size) { // *pptr is not changed if false is returned bool res = true; void *prev = *(void **)pptr; void *curr = 0; // if malloc(0) does (and it can) return non-NULL // values, realloc(NULL, 0) will too -> explicitly // handle new size of 0 as free ... if( size == 0 ) { free(prev); } else if( (curr = realloc(prev, size)) == 0 ) { res = false, curr = prev; } *(void **)pptr = curr; return true; } /* ------------------------------------------------------------------------- * * xappend * ------------------------------------------------------------------------- */ static bool xappend(char **pstr, const char *add) { // *pstr is not changed if false is returned char *res = 0; char *cur = *pstr; size_t a = cur ? strlen(cur) : 0; size_t b = add ? strlen(add) : 0; if( (res = (char *)malloc(a + b + 1)) == 0 ) { goto cleanup; } memcpy(res+0, cur, a); memcpy(res+a, add, b); res[a+b] = 0; *pstr = res; cleanup: return (res != 0); } /* ------------------------------------------------------------------------- * * credentials_to_string * ------------------------------------------------------------------------- */ static char * credentials_to_string(creds_t creds) { bool success = false; char *result = 0; creds_type_t cr_type = CREDS_BAD; creds_value_t cr_val = CREDS_BAD; char *cr_str = 0; size_t cr_len = 32; int i,rc; if( (cr_str = (char *)malloc(cr_len)) == 0 ) { goto cleanup; } for( i = 0; (cr_type = creds_list(creds, i, &cr_val)) != CREDS_BAD ; ++i ) { if( (rc = creds_creds2str(cr_type, cr_val, cr_str, cr_len)) < 0 ) { BOINK(); continue; } if( (size_t)rc >= cr_len ) { cr_len = (size_t)rc + 1; if( !xrealloc(&cr_str, cr_len) ) { goto cleanup; } if( creds_creds2str(cr_type, cr_val, cr_str, cr_len) != rc ) { BOINK(); goto cleanup; } } if( result != 0 && !xappend(&result, SEPARATOR) ) { goto cleanup; } if( !xappend(&result, cr_str) ) { goto cleanup; } } success = true; cleanup: if( !success ) { // all or nothing free(result), result = 0; } free(cr_str); return result; } /* ------------------------------------------------------------------------- * * credentials_from_string * ------------------------------------------------------------------------- */ static creds_t credentials_from_string(const char *input) { creds_t creds = creds_init(); char *work = strdup(input); char *now; char *zen; for( now = work; now; now = zen ) { creds_type_t c_type = CREDS_BAD; creds_value_t c_val = CREDS_BAD; if( (zen = strstr(now, SEPARATOR)) != 0 ) { *zen++ = 0; } if( (c_type = creds_str2creds(now, &c_val)) == CREDS_BAD ) { BOINK(); continue; } if( c_val == CREDS_BAD ) { BOINK(); continue; } if( creds_add(&creds, c_type, c_val) == -1 ) { BOINK(); } } free(work); return creds; } /* ------------------------------------------------------------------------- * * credentials_get_from_pid * ------------------------------------------------------------------------- */ static QString credentials_get_from_pid(pid_t pid) { QString result; // assume null string creds_t creds = 0; char *text = 0; if( (creds = creds_gettask(pid)) == 0 ) { BOINK(); goto cleanup; } if( (text = credentials_to_string(creds)) == 0 ) { BOINK(); goto cleanup; } result = QString::fromUtf8(text); cleanup: free(text); creds_free(creds); log_warning("@@@ pid=%d -> creds=%s", pid, CS(result)); return result; } /* ------------------------------------------------------------------------- * * credentials_get_from_dbus * ------------------------------------------------------------------------- */ QString credentials_get_from_dbus(QDBusConnection &bus, const QDBusMessage &msg) { QString result; // assume null string pid_t owner = -1; QString sender = msg.service(); /* returns "sender" on inbound messages * and "service" on outbound messages * which saves one QString object and * confuses at least me ... */ log_warning("@@@ service/sender = '%s'", CS(sender)); if( (owner = get_owner_pid(bus, sender.toUtf8().constData())) == -1 ) { goto cleanup; } result = credentials_get_from_pid(owner); cleanup: return result; } /* ------------------------------------------------------------------------- * * credentials_set * ------------------------------------------------------------------------- */ bool credentials_set(QString credentials) { bool success = false; creds_t cr_want = 0; creds_t cr_have = 0; creds_type_t cr_type = CREDS_BAD; creds_value_t cr_val = CREDS_BAD; if( credentials.isEmpty() ) // null string is also empty { BOINK(); goto cleanup; } cr_want = credentials_from_string(credentials.toUtf8().constData()); if( cr_want == 0 ) { BOINK(); goto cleanup; } if( creds_set(cr_want) < 0 ) { BOINK(); goto cleanup; } if( (cr_have = creds_gettask(0)) == 0 ) { BOINK(); goto cleanup; } // assume success at this point success = true; int i; for( i = 0; (cr_type = creds_list(cr_want, i, &cr_val)) != CREDS_BAD ; ++i ) { if( creds_have_p(cr_have, cr_type, cr_val) ) { creds_sub(cr_have, cr_type, cr_val); } else { // missing a required credential BOINK(); success = false; } } if( (cr_type = creds_list(cr_want, 0, &cr_val)) != CREDS_BAD ) { // other than asked for credentials left BOINK(); success = false; } cleanup: creds_free(cr_want); creds_free(cr_have); return success; } <commit_msg>Oops. Tested in the wrong set<commit_after>/*************************************************************************** ** ** ** Copyright (C) 2010 Nokia Corporation. ** ** ** ** Author: Simo Piiroinen <simo.piiroinen@nokia.com> ** ** ** ** This file is part of Timed ** ** ** ** Timed 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. ** ** ** ** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ ** ** ** ***************************************************************************/ #include "credentials.h" #include "log.h" #include <sys/creds.h> #include <stdlib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <dbus/dbus.h> #define CS(s) (s).toLocal8Bit().constData() #define US(s) (s).toUtf8().constData() #define BOINK() log_warning("!!! %s:%d: BOINK\n", __FILE__,__LINE__) #define SEPARATOR " " /* ------------------------------------------------------------------------- * * get_owner_pid * ------------------------------------------------------------------------- */ static pid_t get_owner_pid(QDBusConnection &bus, const char *name) { /* FIXME: this makes a synchronous roundtrip to dbus daemon * and back during which time the timed process will be blocked. * * Note: We can't really handle this asynchronously without * handling the whole add_event asynchronously and this would * require modifications to the timed event state machine and * delaying sending add_event replies from QDBusAbstractAdaptor. * At the moment I do not know how to handle either of those ... */ pid_t result = -1; QString service = "org.freedesktop.DBus"; QString path = "/org/freedesktop/DBus"; QString interface = "org.freedesktop.DBus"; QString method = "GetConnectionUnixProcessID"; QDBusMessage req = QDBusMessage::createMethodCall(service, path, interface, method); req << QString(name); QDBusMessage rsp = bus.call(req); if( rsp.type() == QDBusMessage::ReplyMessage ) { QList<QVariant> args = rsp.arguments(); if( !args.isEmpty() ) { bool ok = false; int reply = rsp.arguments().first().toInt(&ok); log_warning("@@@ rsp.ok = %d, rsp.reply = %d", ok, reply); if( ok ) result = reply; } } log_warning("@@@ owner pid = %d", (int)result); return result; } /* ------------------------------------------------------------------------- * * xrealloc * ------------------------------------------------------------------------- */ static bool xrealloc(void *pptr, size_t size) { // *pptr is not changed if false is returned bool res = true; void *prev = *(void **)pptr; void *curr = 0; // if malloc(0) does (and it can) return non-NULL // values, realloc(NULL, 0) will too -> explicitly // handle new size of 0 as free ... if( size == 0 ) { free(prev); } else if( (curr = realloc(prev, size)) == 0 ) { res = false, curr = prev; } *(void **)pptr = curr; return true; } /* ------------------------------------------------------------------------- * * xappend * ------------------------------------------------------------------------- */ static bool xappend(char **pstr, const char *add) { // *pstr is not changed if false is returned char *res = 0; char *cur = *pstr; size_t a = cur ? strlen(cur) : 0; size_t b = add ? strlen(add) : 0; if( (res = (char *)malloc(a + b + 1)) == 0 ) { goto cleanup; } memcpy(res+0, cur, a); memcpy(res+a, add, b); res[a+b] = 0; *pstr = res; cleanup: return (res != 0); } /* ------------------------------------------------------------------------- * * credentials_to_string * ------------------------------------------------------------------------- */ static char * credentials_to_string(creds_t creds) { bool success = false; char *result = 0; creds_type_t cr_type = CREDS_BAD; creds_value_t cr_val = CREDS_BAD; char *cr_str = 0; size_t cr_len = 32; int i,rc; if( (cr_str = (char *)malloc(cr_len)) == 0 ) { goto cleanup; } for( i = 0; (cr_type = creds_list(creds, i, &cr_val)) != CREDS_BAD ; ++i ) { if( (rc = creds_creds2str(cr_type, cr_val, cr_str, cr_len)) < 0 ) { BOINK(); continue; } if( (size_t)rc >= cr_len ) { cr_len = (size_t)rc + 1; if( !xrealloc(&cr_str, cr_len) ) { goto cleanup; } if( creds_creds2str(cr_type, cr_val, cr_str, cr_len) != rc ) { BOINK(); goto cleanup; } } if( result != 0 && !xappend(&result, SEPARATOR) ) { goto cleanup; } if( !xappend(&result, cr_str) ) { goto cleanup; } } success = true; cleanup: if( !success ) { // all or nothing free(result), result = 0; } free(cr_str); return result; } /* ------------------------------------------------------------------------- * * credentials_from_string * ------------------------------------------------------------------------- */ static creds_t credentials_from_string(const char *input) { creds_t creds = creds_init(); char *work = strdup(input); char *now; char *zen; for( now = work; now; now = zen ) { creds_type_t c_type = CREDS_BAD; creds_value_t c_val = CREDS_BAD; if( (zen = strstr(now, SEPARATOR)) != 0 ) { *zen++ = 0; } if( (c_type = creds_str2creds(now, &c_val)) == CREDS_BAD ) { BOINK(); continue; } if( c_val == CREDS_BAD ) { BOINK(); continue; } if( creds_add(&creds, c_type, c_val) == -1 ) { BOINK(); } } free(work); return creds; } /* ------------------------------------------------------------------------- * * credentials_get_from_pid * ------------------------------------------------------------------------- */ static QString credentials_get_from_pid(pid_t pid) { QString result; // assume null string creds_t creds = 0; char *text = 0; if( (creds = creds_gettask(pid)) == 0 ) { BOINK(); goto cleanup; } if( (text = credentials_to_string(creds)) == 0 ) { BOINK(); goto cleanup; } result = QString::fromUtf8(text); cleanup: free(text); creds_free(creds); log_warning("@@@ pid=%d -> creds=%s", pid, CS(result)); return result; } /* ------------------------------------------------------------------------- * * credentials_get_from_dbus * ------------------------------------------------------------------------- */ QString credentials_get_from_dbus(QDBusConnection &bus, const QDBusMessage &msg) { QString result; // assume null string pid_t owner = -1; QString sender = msg.service(); /* returns "sender" on inbound messages * and "service" on outbound messages * which saves one QString object and * confuses at least me ... */ log_warning("@@@ service/sender = '%s'", CS(sender)); if( (owner = get_owner_pid(bus, sender.toUtf8().constData())) == -1 ) { goto cleanup; } result = credentials_get_from_pid(owner); cleanup: return result; } /* ------------------------------------------------------------------------- * * credentials_set * ------------------------------------------------------------------------- */ bool credentials_set(QString credentials) { bool success = false; creds_t cr_want = 0; creds_t cr_have = 0; creds_type_t cr_type = CREDS_BAD; creds_value_t cr_val = CREDS_BAD; if( credentials.isEmpty() ) // null string is also empty { BOINK(); goto cleanup; } cr_want = credentials_from_string(credentials.toUtf8().constData()); if( cr_want == 0 ) { BOINK(); goto cleanup; } if( creds_set(cr_want) < 0 ) { BOINK(); goto cleanup; } if( (cr_have = creds_gettask(0)) == 0 ) { BOINK(); goto cleanup; } // assume success at this point success = true; int i; for( i = 0; (cr_type = creds_list(cr_want, i, &cr_val)) != CREDS_BAD ; ++i ) { if( creds_have_p(cr_have, cr_type, cr_val) ) { creds_sub(cr_have, cr_type, cr_val); } else { // missing a required credential BOINK(); success = false; } } if( (cr_type = creds_list(cr_have, 0, &cr_val)) != CREDS_BAD ) { // other than asked for credentials left BOINK(); success = false; } cleanup: creds_free(cr_want); creds_free(cr_have); return success; } <|endoftext|>
<commit_before>#include "command.hh" #include "store-api.hh" #include "progress-bar.hh" #include "fs-accessor.hh" #include <queue> using namespace nix; static std::string hilite(const std::string & s, size_t pos, size_t len, const std::string & colour = ANSI_RED) { return std::string(s, 0, pos) + colour + std::string(s, pos, len) + ANSI_NORMAL + std::string(s, pos + len); } static std::string filterPrintable(const std::string & s) { std::string res; for (char c : s) res += isprint(c) ? c : '.'; return res; } struct CmdWhyDepends : SourceExprCommand { std::string _package, _dependency; bool all = false; CmdWhyDepends() { expectArg("package", &_package); expectArg("dependency", &_dependency); mkFlag() .longName("all") .shortName('a') .description("show all edges in the dependency graph leading from 'package' to 'dependency', rather than just a shortest path") .set(&all, true); } std::string name() override { return "why-depends"; } std::string description() override { return "show why a package has another package in its closure"; } Examples examples() override { return { Example{ "To show one path through the dependency graph leading from Hello to Glibc:", "nix why-depends nixpkgs.hello nixpkgs.glibc" }, Example{ "To show all files and paths in the dependency graph leading from Thunderbird to libX11:", "nix why-depends --all nixpkgs.thunderbird nixpkgs.xorg.libX11" }, Example{ "To show why Glibc depends on itself:", "nix why-depends nixpkgs.glibc nixpkgs.glibc" }, }; } void run(ref<Store> store) override { auto package = parseInstallable(*this, store, _package, false); auto packagePath = toStorePath(store, Build, package); auto dependency = parseInstallable(*this, store, _dependency, false); auto dependencyPath = toStorePath(store, NoBuild, dependency); auto dependencyPathHash = storePathToHash(dependencyPath); PathSet closure; store->computeFSClosure({packagePath}, closure, false, false); if (!closure.count(dependencyPath)) { printError("'%s' does not depend on '%s'", package->what(), dependency->what()); return; } stopProgressBar(); // FIXME auto accessor = store->getFSAccessor(); auto const inf = std::numeric_limits<size_t>::max(); struct Node { Path path; PathSet refs; PathSet rrefs; size_t dist = inf; Node * prev = nullptr; bool queued = false; bool visited = false; }; std::map<Path, Node> graph; for (auto & path : closure) graph.emplace(path, Node{path, store->queryPathInfo(path)->references}); // Transpose the graph. for (auto & node : graph) for (auto & ref : node.second.refs) graph[ref].rrefs.insert(node.first); /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */ graph[dependencyPath].dist = 0; std::priority_queue<Node *> queue; queue.push(&graph.at(dependencyPath)); while (!queue.empty()) { auto & node = *queue.top(); queue.pop(); for (auto & rref : node.rrefs) { auto & node2 = graph.at(rref); auto dist = node.dist + 1; if (dist < node2.dist) { node2.dist = dist; node2.prev = &node; if (!node2.queued) { node2.queued = true; queue.push(&node2); } } } } /* Print the subgraph of nodes that have 'dependency' in their closure (i.e., that have a non-infinite distance to 'dependency'). Print every edge on a path between `package` and `dependency`. */ std::function<void(Node &, const string &, const string &)> printNode; const string treeConn = "╠═══"; const string treeLast = "╚═══"; const string treeLine = "║ "; const string treeNull = " "; struct BailOut { }; printNode = [&](Node & node, const string & firstPad, const string & tailPad) { assert(node.dist != inf); std::cout << fmt("%s%s%s%s" ANSI_NORMAL "\n", firstPad, node.visited ? "\e[38;5;244m" : "", firstPad != "" ? "=> " : "", node.path); if (node.path == dependencyPath && !all && packagePath != dependencyPath) throw BailOut(); if (node.visited) return; node.visited = true; /* Sort the references by distance to `dependency` to ensure that the shortest path is printed first. */ std::multimap<size_t, Node *> refs; std::set<std::string> hashes; for (auto & ref : node.refs) { if (ref == node.path && packagePath != dependencyPath) continue; auto & node2 = graph.at(ref); if (node2.dist == inf) continue; refs.emplace(node2.dist, &node2); hashes.insert(storePathToHash(node2.path)); } /* For each reference, find the files and symlinks that contain the reference. */ std::map<std::string, Strings> hits; std::function<void(const Path &)> visitPath; visitPath = [&](const Path & p) { auto st = accessor->stat(p); auto p2 = p == node.path ? "/" : std::string(p, node.path.size() + 1); auto getColour = [&](const std::string & hash) { return hash == dependencyPathHash ? ANSI_GREEN : ANSI_BLUE; }; if (st.type == FSAccessor::Type::tDirectory) { auto names = accessor->readDirectory(p); for (auto & name : names) visitPath(p + "/" + name); } else if (st.type == FSAccessor::Type::tRegular) { auto contents = accessor->readFile(p); for (auto & hash : hashes) { auto pos = contents.find(hash); if (pos != std::string::npos) { size_t margin = 32; auto pos2 = pos >= margin ? pos - margin : 0; hits[hash].emplace_back(fmt("%s: …%s…\n", p2, hilite(filterPrintable( std::string(contents, pos2, pos - pos2 + hash.size() + margin)), pos - pos2, storePathHashLen, getColour(hash)))); } } } else if (st.type == FSAccessor::Type::tSymlink) { auto target = accessor->readLink(p); for (auto & hash : hashes) { auto pos = target.find(hash); if (pos != std::string::npos) hits[hash].emplace_back(fmt("%s -> %s\n", p2, hilite(target, pos, storePathHashLen, getColour(hash)))); } } }; // FIXME: should use scanForReferences(). visitPath(node.path); for (auto & ref : refs) { auto hash = storePathToHash(ref.second->path); bool last = all ? ref == *refs.rbegin() : true; for (auto & hit : hits[hash]) { bool first = hit == *hits[hash].begin(); std::cout << tailPad << (first ? (last ? treeLast : treeConn) : (last ? treeNull : treeLine)) << hit; if (!all) break; } printNode(*ref.second, tailPad + (last ? treeNull : treeLine), tailPad + (last ? treeNull : treeLine)); } }; try { printNode(graph.at(packagePath), "", ""); } catch (BailOut & ) { } } }; static RegisterCommand r1(make_ref<CmdWhyDepends>()); <commit_msg>nix why-depends: render output into $PAGER<commit_after>#include "command.hh" #include "store-api.hh" #include "progress-bar.hh" #include "fs-accessor.hh" #include "shared.hh" #include <queue> using namespace nix; static std::string hilite(const std::string & s, size_t pos, size_t len, const std::string & colour = ANSI_RED) { return std::string(s, 0, pos) + colour + std::string(s, pos, len) + ANSI_NORMAL + std::string(s, pos + len); } static std::string filterPrintable(const std::string & s) { std::string res; for (char c : s) res += isprint(c) ? c : '.'; return res; } struct CmdWhyDepends : SourceExprCommand { std::string _package, _dependency; bool all = false; CmdWhyDepends() { expectArg("package", &_package); expectArg("dependency", &_dependency); mkFlag() .longName("all") .shortName('a') .description("show all edges in the dependency graph leading from 'package' to 'dependency', rather than just a shortest path") .set(&all, true); } std::string name() override { return "why-depends"; } std::string description() override { return "show why a package has another package in its closure"; } Examples examples() override { return { Example{ "To show one path through the dependency graph leading from Hello to Glibc:", "nix why-depends nixpkgs.hello nixpkgs.glibc" }, Example{ "To show all files and paths in the dependency graph leading from Thunderbird to libX11:", "nix why-depends --all nixpkgs.thunderbird nixpkgs.xorg.libX11" }, Example{ "To show why Glibc depends on itself:", "nix why-depends nixpkgs.glibc nixpkgs.glibc" }, }; } void run(ref<Store> store) override { auto package = parseInstallable(*this, store, _package, false); auto packagePath = toStorePath(store, Build, package); auto dependency = parseInstallable(*this, store, _dependency, false); auto dependencyPath = toStorePath(store, NoBuild, dependency); auto dependencyPathHash = storePathToHash(dependencyPath); PathSet closure; store->computeFSClosure({packagePath}, closure, false, false); if (!closure.count(dependencyPath)) { printError("'%s' does not depend on '%s'", package->what(), dependency->what()); return; } stopProgressBar(); // FIXME auto accessor = store->getFSAccessor(); auto const inf = std::numeric_limits<size_t>::max(); struct Node { Path path; PathSet refs; PathSet rrefs; size_t dist = inf; Node * prev = nullptr; bool queued = false; bool visited = false; }; std::map<Path, Node> graph; for (auto & path : closure) graph.emplace(path, Node{path, store->queryPathInfo(path)->references}); // Transpose the graph. for (auto & node : graph) for (auto & ref : node.second.refs) graph[ref].rrefs.insert(node.first); /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */ graph[dependencyPath].dist = 0; std::priority_queue<Node *> queue; queue.push(&graph.at(dependencyPath)); while (!queue.empty()) { auto & node = *queue.top(); queue.pop(); for (auto & rref : node.rrefs) { auto & node2 = graph.at(rref); auto dist = node.dist + 1; if (dist < node2.dist) { node2.dist = dist; node2.prev = &node; if (!node2.queued) { node2.queued = true; queue.push(&node2); } } } } /* Print the subgraph of nodes that have 'dependency' in their closure (i.e., that have a non-infinite distance to 'dependency'). Print every edge on a path between `package` and `dependency`. */ std::function<void(Node &, const string &, const string &)> printNode; const string treeConn = "╠═══"; const string treeLast = "╚═══"; const string treeLine = "║ "; const string treeNull = " "; struct BailOut { }; printNode = [&](Node & node, const string & firstPad, const string & tailPad) { assert(node.dist != inf); std::cout << fmt("%s%s%s%s" ANSI_NORMAL "\n", firstPad, node.visited ? "\e[38;5;244m" : "", firstPad != "" ? "=> " : "", node.path); if (node.path == dependencyPath && !all && packagePath != dependencyPath) throw BailOut(); if (node.visited) return; node.visited = true; /* Sort the references by distance to `dependency` to ensure that the shortest path is printed first. */ std::multimap<size_t, Node *> refs; std::set<std::string> hashes; for (auto & ref : node.refs) { if (ref == node.path && packagePath != dependencyPath) continue; auto & node2 = graph.at(ref); if (node2.dist == inf) continue; refs.emplace(node2.dist, &node2); hashes.insert(storePathToHash(node2.path)); } /* For each reference, find the files and symlinks that contain the reference. */ std::map<std::string, Strings> hits; std::function<void(const Path &)> visitPath; visitPath = [&](const Path & p) { auto st = accessor->stat(p); auto p2 = p == node.path ? "/" : std::string(p, node.path.size() + 1); auto getColour = [&](const std::string & hash) { return hash == dependencyPathHash ? ANSI_GREEN : ANSI_BLUE; }; if (st.type == FSAccessor::Type::tDirectory) { auto names = accessor->readDirectory(p); for (auto & name : names) visitPath(p + "/" + name); } else if (st.type == FSAccessor::Type::tRegular) { auto contents = accessor->readFile(p); for (auto & hash : hashes) { auto pos = contents.find(hash); if (pos != std::string::npos) { size_t margin = 32; auto pos2 = pos >= margin ? pos - margin : 0; hits[hash].emplace_back(fmt("%s: …%s…\n", p2, hilite(filterPrintable( std::string(contents, pos2, pos - pos2 + hash.size() + margin)), pos - pos2, storePathHashLen, getColour(hash)))); } } } else if (st.type == FSAccessor::Type::tSymlink) { auto target = accessor->readLink(p); for (auto & hash : hashes) { auto pos = target.find(hash); if (pos != std::string::npos) hits[hash].emplace_back(fmt("%s -> %s\n", p2, hilite(target, pos, storePathHashLen, getColour(hash)))); } } }; // FIXME: should use scanForReferences(). visitPath(node.path); RunPager pager; for (auto & ref : refs) { auto hash = storePathToHash(ref.second->path); bool last = all ? ref == *refs.rbegin() : true; for (auto & hit : hits[hash]) { bool first = hit == *hits[hash].begin(); std::cout << tailPad << (first ? (last ? treeLast : treeConn) : (last ? treeNull : treeLine)) << hit; if (!all) break; } printNode(*ref.second, tailPad + (last ? treeNull : treeLine), tailPad + (last ? treeNull : treeLine)); } }; try { printNode(graph.at(packagePath), "", ""); } catch (BailOut & ) { } } }; static RegisterCommand r1(make_ref<CmdWhyDepends>()); <|endoftext|>
<commit_before>#include <common/list.h> #include <common/log.h> #include <user_cmd/pertypes.h> #include <user_cmd/per.lex.h> #include <user_cmd/per.tab.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdio.h> /* macros */ /** * \brief remove leading and trailing spaces * * \param s string to be updated * \param o index of the first non-blank */ #define skip_blank(s, o) { \ unsigned int i; \ \ \ o = 0; \ while(s[o] != 0 && s[o] == ' ') o++; \ i = strlen(s) - 1; \ while(i > 0 && s[i] == ' ') i--; \ s[i + 1] = 0; \ } /* global functions */ int main(int argc, char** argv){ int retval = 1; unsigned int sec_off, reg_off, bit_off; FILE *per, *header; per_section_t *rlst, *sec; per_range_t *range; per_register_t* reg; per_bits_t* bits; /* init */ if(argc < 3){ printf("usage: %s <per-file> <header-file>\n", argv[0]); goto e0; } if(log::init("/proc/self/fd/1", LOG_LEVEL) != 0) goto e0; per = fopen(argv[1], "r"); if(per == 0){ USER("error: unable to open file \"%s\" - %s\n", argv[1], strerror(errno)); goto e1; } header = fopen(argv[2], "w"); if(header == 0){ USER("error: unable to open file \"%s\" - %s\n", argv[2], strerror(errno)); goto e2; } /* parse peripheral file */ if(perparse(per, &rlst) != 0){ USER("error: parsing peripheral file failed\n"); goto e3; } /* generate header */ list_for_each(rlst, sec){ skip_blank(sec->name, sec_off); fprintf(header, "/* %s */\n", sec->name + sec_off); list_for_each(sec->ranges, range){ if(!range->name){ list_for_each(range->regs, reg){ if(reg->nbytes == 0) continue; skip_blank(reg->name, reg_off); fprintf(header, "// %s\n" "#define %s\t0x%lx\n\n" , reg->name + reg_off , reg->name + reg_off , (unsigned long int)range->base + reg->offset ); list_for_each(reg->bits, bits){ skip_blank(bits->name, bit_off); fprintf(header, "#define %s_%s\t%d\n", reg->name + reg_off, bits->name + bit_off, bits->idx); } if(!list_empty(reg->bits)) fprintf(header, "\n"); } } } } retval = 0; /* cleanup */ e3: perlex_destroy(); e2: fclose(per); e1: log::cleanup(); e0: return retval; } <commit_msg>[tools: per2h]<commit_after>#include <common/list.h> #include <common/log.h> #include <user_cmd/pertypes.h> #include <user_cmd/per.lex.h> #include <user_cmd/per.tab.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdio.h> /* macros */ /** * \brief remove leading and trailing spaces * * \param s string to be updated * \param o index of the first non-blank */ #define skip_blank(s, o) { \ unsigned int i; \ \ \ o = 0; \ while(s[o] != 0 && s[o] == ' ') o++; \ i = strlen(s) - 1; \ while(i > 0 && s[i] == ' ') i--; \ s[i + 1] = 0; \ } /* global functions */ int main(int argc, char** argv){ int retval = 1; unsigned int sec_off, reg_off, bit_off; FILE *per, *header; per_section_t *rlst, *sec; per_range_t *range; per_register_t* reg; per_bits_t* bits; /* init */ if(argc < 3){ printf("usage: %s <per-file> <header-file>\n", argv[0]); goto e0; } if(log::init("/proc/self/fd/1", LOG_LEVEL) != 0) goto e0; per = fopen(argv[1], "r"); if(per == 0){ USER("error: unable to open file \"%s\" - %s\n", argv[1], strerror(errno)); goto e1; } header = fopen(argv[2], "w"); if(header == 0){ USER("error: unable to open file \"%s\" - %s\n", argv[2], strerror(errno)); goto e2; } /* parse peripheral file */ if(perparse(per, &rlst) != 0){ USER("error: parsing peripheral file failed\n"); goto e3; } /* generate header */ list_for_each(rlst, sec){ skip_blank(sec->name, sec_off); fprintf(header, "/* %s */\n", sec->name + sec_off); list_for_each(sec->ranges, range){ if(!range->name){ list_for_each(range->regs, reg){ if(reg->nbytes == 0) continue; skip_blank(reg->name, reg_off); fprintf(header, "/* %s */\n" "// register\n" "#define %s\t\t\t0x%lx\n\n" , reg->name + reg_off , reg->name + reg_off , (unsigned long int)range->base + reg->offset ); if(!list_empty(reg->bits)) fprintf(header, "// bits\n"); list_for_each(reg->bits, bits){ skip_blank(bits->name, bit_off); fprintf(header, "#define %s_%s\t\t%d\n", reg->name + reg_off, bits->name + bit_off, bits->idx); } if(!list_empty(reg->bits)) fprintf(header, "\n// masks\n"); list_for_each(reg->bits, bits) fprintf(header, "#define %s_%s_MASK\t0x%x\n", reg->name + reg_off, bits->name + bit_off, bits->mask); if(!list_empty(reg->bits)) fprintf(header, "\n"); } } } } retval = 0; /* cleanup */ e3: perlex_destroy(); e2: fclose(per); e1: log::cleanup(); e0: return retval; } <|endoftext|>
<commit_before><commit_msg>Using istream and ostream headers in preference to iostream<commit_after><|endoftext|>
<commit_before><commit_msg>Blackberry: Use the rotation matrix as the compass source<commit_after><|endoftext|>
<commit_before>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "JsonRpcHandler.hpp" #include "JsonRpcConstants.hpp" #define JSON_RPC_ERROR_INVALID_REQUEST "Invalid JSON-RPC request." namespace kurento { namespace JsonRpc { void Handler::addMethod (const std::string &name, Method method) { methods[name] = method; } bool Handler::checkProtocol (const Json::Value &msg, Json::Value &error) { Json::Value err; if (!msg.isObject() || !msg.isMember (JSON_RPC_PROTO) || msg[JSON_RPC_PROTO] != JSON_RPC_PROTO_VERSION) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } if (msg.isMember (JSON_RPC_ID) && (msg[JSON_RPC_ID].isArray() || msg[JSON_RPC_ID].isObject() ) ) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } if (!msg.isMember (JSON_RPC_METHOD) || !msg[JSON_RPC_METHOD].isString() ) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } return true; } bool Handler::process (const Json::Value &msg, Json::Value &_response) { Json::Value error; std::string methodName; if (!checkProtocol (msg, error) ) { _response = error; return false; } _response[JSON_RPC_ID] = msg.isMember (JSON_RPC_ID) ? msg[JSON_RPC_ID] : Json::Value::null; _response[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; methodName = msg[JSON_RPC_METHOD].asString(); if (methodName != "" && methods.find (methodName) != methods.end() ) { Method &method = methods[methodName]; Json::Value response; try { method (msg[JSON_RPC_PARAMS], response); if (!msg.isMember (JSON_RPC_ID) || msg[JSON_RPC_ID] == Json::Value::null) { if (response != Json::Value::null) { throw JsonRpc::CallException (ErrorCode::SERVER_ERROR_INIT, "Ignoring response because of a notification request", response); } _response = Json::Value::null; } else { _response[JSON_RPC_RESULT] = response; } return true; } catch (CallException &e) { Json::Value error; Json::Value data; error[JSON_RPC_ERROR_CODE] = e.getCode(); error[JSON_RPC_ERROR_MESSAGE] = e.getMessage(); data = e.getData(); if (data != Json::Value::null) { error[JSON_RPC_ERROR_DATA] = data; } _response[JSON_RPC_ERROR] = error; return false; } } error[JSON_RPC_ERROR_CODE] = METHOD_NOT_FOUND; error[JSON_RPC_ERROR_MESSAGE] = "Method not found."; _response[JSON_RPC_ERROR] = error; return false; } bool Handler::process (const std::string &msg, std::string &_responseMsg) { Json::Value response; Json::Value request; Json::Value error; bool parse = false; Json::Reader reader; Json::FastWriter writer; parse = reader.parse (msg, request); if (!parse) { response[JSON_RPC_ID] = Json::Value::null; response[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; error[JSON_RPC_ERROR_CODE] = PARSE_ERROR; error[JSON_RPC_ERROR_MESSAGE] = "Parse error."; response[JSON_RPC_ERROR] = error; _responseMsg = writer.write (response); return false; } if (request.isArray() ) { Json::Value::ArrayIndex i = 0; Json::Value::ArrayIndex j = 0; for (i = 0 ; i < request.size() ; i++) { Json::Value ret; process (request[i], ret); if (ret != Json::Value::null) { response[j] = ret; j++; } } if (response != Json::Value::null) { _responseMsg = writer.write (response); } return true; } else { bool ret; ret = process (request, response); if (response != Json::Value::null) { _responseMsg = writer.write (response); } return ret; } } } /* JsonRpc */ } /* kurento */ <commit_msg>Unify exception management on RpcHandler<commit_after>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "JsonRpcHandler.hpp" #include "JsonRpcConstants.hpp" #define JSON_RPC_ERROR_INVALID_REQUEST "Invalid JSON-RPC request." namespace kurento { namespace JsonRpc { void Handler::addMethod (const std::string &name, Method method) { methods[name] = method; } bool Handler::checkProtocol (const Json::Value &msg, Json::Value &error) { Json::Value err; if (!msg.isObject() || !msg.isMember (JSON_RPC_PROTO) || msg[JSON_RPC_PROTO] != JSON_RPC_PROTO_VERSION) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } if (msg.isMember (JSON_RPC_ID) && (msg[JSON_RPC_ID].isArray() || msg[JSON_RPC_ID].isObject() ) ) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } if (!msg.isMember (JSON_RPC_METHOD) || !msg[JSON_RPC_METHOD].isString() ) { error[JSON_RPC_ID] = Json::Value::null; error[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; err[JSON_RPC_ERROR_CODE] = INVALID_REQUEST; err[JSON_RPC_ERROR_MESSAGE] = JSON_RPC_ERROR_INVALID_REQUEST; error[JSON_RPC_ERROR] = err; return false; } return true; } bool Handler::process (const Json::Value &msg, Json::Value &_response) { Json::Value error; std::string methodName; if (!checkProtocol (msg, error) ) { _response = error; return false; } _response[JSON_RPC_ID] = msg.isMember (JSON_RPC_ID) ? msg[JSON_RPC_ID] : Json::Value::null; _response[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; methodName = msg[JSON_RPC_METHOD].asString(); if (methodName != "" && methods.find (methodName) != methods.end() ) { Method &method = methods[methodName]; Json::Value response; try { method (msg[JSON_RPC_PARAMS], response); if (!msg.isMember (JSON_RPC_ID) || msg[JSON_RPC_ID] == Json::Value::null) { if (response != Json::Value::null) { throw JsonRpc::CallException (ErrorCode::SERVER_ERROR_INIT, "Ignoring response because of a notification request", response); } _response = Json::Value::null; } else { _response[JSON_RPC_RESULT] = response; } return true; } catch (CallException &e) { Json::Value error; Json::Value data; error[JSON_RPC_ERROR_CODE] = e.getCode(); error[JSON_RPC_ERROR_MESSAGE] = e.getMessage(); data = e.getData(); if (data != Json::Value::null) { error[JSON_RPC_ERROR_DATA] = data; } _response[JSON_RPC_ERROR] = error; } catch (std::string &e) { Json::Value error; error[JSON_RPC_ERROR_CODE] = INTERNAL_ERROR; error[JSON_RPC_ERROR_MESSAGE] = std::string ("Unexpected error while processing method: ") + e; _response[JSON_RPC_ERROR] = error; } catch (std::exception &e) { Json::Value error; error[JSON_RPC_ERROR_CODE] = INTERNAL_ERROR; error[JSON_RPC_ERROR_MESSAGE] = std::string ("Unexpected error while processing method: ") + e.what(); _response[JSON_RPC_ERROR] = error; } catch (...) { Json::Value error; error[JSON_RPC_ERROR_CODE] = INTERNAL_ERROR; error[JSON_RPC_ERROR_MESSAGE] = "Unexpected error while processing method"; _response[JSON_RPC_ERROR] = error; } return false; } error[JSON_RPC_ERROR_CODE] = METHOD_NOT_FOUND; error[JSON_RPC_ERROR_MESSAGE] = "Method not found."; _response[JSON_RPC_ERROR] = error; return false; } bool Handler::process (const std::string &msg, std::string &_responseMsg) { Json::Value response; Json::Value request; Json::Value error; bool parse = false; Json::Reader reader; Json::FastWriter writer; parse = reader.parse (msg, request); if (!parse) { response[JSON_RPC_ID] = Json::Value::null; response[JSON_RPC_PROTO] = JSON_RPC_PROTO_VERSION; error[JSON_RPC_ERROR_CODE] = PARSE_ERROR; error[JSON_RPC_ERROR_MESSAGE] = "Parse error."; response[JSON_RPC_ERROR] = error; _responseMsg = writer.write (response); return false; } if (request.isArray() ) { Json::Value::ArrayIndex i = 0; Json::Value::ArrayIndex j = 0; for (i = 0 ; i < request.size() ; i++) { Json::Value ret; process (request[i], ret); if (ret != Json::Value::null) { response[j] = ret; j++; } } if (response != Json::Value::null) { _responseMsg = writer.write (response); } return true; } else { bool ret; ret = process (request, response); if (response != Json::Value::null) { _responseMsg = writer.write (response); } return ret; } } } /* JsonRpc */ } /* kurento */ <|endoftext|>
<commit_before>#include "value.h" #include "row.h" #include "schema.h" #include "table.h" namespace mdb { Row::~Row() { delete[] fixed_part_; if (schema_->var_size_cols_ > 0) { if (kind_ == DENSE) { delete[] dense_var_part_; delete[] dense_var_idx_; } else { verify(kind_ == SPARSE); delete[] sparse_var_; } } } void Row::make_sparse() { if (kind_ == SPARSE) { // already sparse data return; } kind_ = SPARSE; if (schema_->var_size_cols_ == 0) { // special case, no memory copying required return; } // save those 2 values to prevent overwriting (union type!) char* var_data = dense_var_part_; int* var_idx = dense_var_idx_; assert(schema_->var_size_cols_ > 0); sparse_var_ = new std::string[schema_->var_size_cols_]; sparse_var_[0] = std::string(var_data, var_idx[0]); for (int i = 1; i < schema_->var_size_cols_; i++) { int var_start = var_idx[i - 1]; int var_len = var_idx[i] - var_idx[i - 1]; sparse_var_[i] = std::string(&var_data[var_start], var_len); } delete[] var_data; delete[] var_idx; } Value Row::get_column(int column_id) const { Value v; const Schema::column_info* info = schema_->get_column_info(column_id); verify(info != nullptr); switch (info->type) { case Value::I32: v = Value(*((i32*) &fixed_part_[info->fixed_size_offst])); break; case Value::I64: v = Value(*((i64*) &fixed_part_[info->fixed_size_offst])); break; case Value::DOUBLE: v = Value(*((double*) &fixed_part_[info->fixed_size_offst])); break; case Value::STR: if (kind_ == DENSE) { int var_start = 0; int var_len = 0; if (info->var_size_idx == 0) { var_start = 0; var_len = dense_var_idx_[0]; } else { var_start = dense_var_idx_[info->var_size_idx - 1]; var_len = dense_var_idx_[info->var_size_idx] - dense_var_idx_[info->var_size_idx - 1]; } v = Value(std::string(&dense_var_part_[var_start], var_len)); } else { verify(kind_ == SPARSE); v = Value(sparse_var_[info->var_size_idx]); } break; default: Log::fatal("unexpected value type %d", info->type); verify(0); break; } return v; } MultiBlob Row::get_key() const { const std::vector<int>& key_cols = schema_->key_columns_id(); MultiBlob mb(key_cols.size()); for (int i = 0; i < mb.count(); i++) { mb[i] = this->get_blob(key_cols[i]); } return mb; } blob Row::get_blob(int column_id) const { blob b; const Schema::column_info* info = schema_->get_column_info(column_id); verify(info != nullptr); switch (info->type) { case Value::I32: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(i32); break; case Value::I64: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(i64); break; case Value::DOUBLE: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(double); break; case Value::STR: if (kind_ == DENSE) { int var_start = 0; int var_len = 0; if (info->var_size_idx == 0) { var_start = 0; var_len = dense_var_idx_[0]; } else { var_start = dense_var_idx_[info->var_size_idx - 1]; var_len = dense_var_idx_[info->var_size_idx] - dense_var_idx_[info->var_size_idx - 1]; } b.data = &dense_var_part_[var_start]; b.len = var_len; } else { verify(kind_ == SPARSE); b.data = &(sparse_var_[info->var_size_idx][0]); b.len = sparse_var_[info->var_size_idx].size(); } break; default: Log::fatal("unexpected value type %d", info->type); verify(0); break; } return b; } void Row::update_fixed(const Schema::column_info* col, void* ptr, int len) { // check if really updating (new data!), and if necessary to remove/insert into table bool re_insert = false; if (memcmp(&fixed_part_[col->fixed_size_offst], ptr, len) == 0) { // not really updating return; } if (col->key) { re_insert = true; } if (re_insert && tbl_ != nullptr) { tbl_->remove(this, false); } memcpy(&fixed_part_[col->fixed_size_offst], ptr, len); if (re_insert && tbl_ != nullptr) { tbl_->insert(this); } } void Row::update(int column_id, const std::string& v) { const Schema::column_info* col = schema_->get_column_info(column_id); verify(col->type == Value::STR); // check if really updating (new data!), and if necessary to remove/insert into table bool re_insert = false; if (kind_ == SPARSE) { if (this->sparse_var_[col->var_size_idx] == v) { return; } } else { verify(kind_ == DENSE); int var_start = 0; int var_len = 0; if (col->var_size_idx == 0) { var_start = 0; var_len = dense_var_idx_[0]; } else { var_start = dense_var_idx_[col->var_size_idx - 1]; var_len = dense_var_idx_[col->var_size_idx] - dense_var_idx_[col->var_size_idx - 1]; } if (memcmp(&dense_var_part_[var_start], &v[0], v.size()) == 0) { return; } } if (col->key) { re_insert = true; } if (re_insert && tbl_ != nullptr) { tbl_->remove(this, false); } this->make_sparse(); this->sparse_var_[col->var_size_idx] = v; if (re_insert && tbl_ != nullptr) { tbl_->insert(this); } } void Row::update(int column_id, const Value& v) { switch (v.get_kind()) { case Value::I32: this->update(column_id, v.get_i32()); break; case Value::I64: this->update(column_id, v.get_i64()); break; case Value::DOUBLE: this->update(column_id, v.get_double()); break; case Value::STR: this->update(column_id, v.get_str()); break; default: Log::fatal("unexpected value type %d", v.get_kind()); verify(0); break; } } Row* Row::create(Schema* schema, const std::map<std::string, Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr(values.size(), nullptr); for (auto& it: values) { int col_id = schema->get_column_id(it.first); verify(col_id >= 0); values_ptr[col_id] = &it.second; } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::unordered_map<std::string, Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr(values.size(), nullptr); for (auto& it: values) { int col_id = schema->get_column_id(it.first); verify(col_id >= 0); values_ptr[col_id] = &it.second; } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::vector<Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr; values_ptr.reserve(values.size()); for (auto& it: values) { values_ptr.push_back(&it); } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::vector<const Value*>& values) { Row* row = new Row; row->schema_ = schema; row->fixed_part_ = new char[schema->fixed_part_size_]; if (schema->var_size_cols_ > 0) { row->dense_var_idx_ = new int[schema->var_size_cols_]; } // 1st pass, write fixed part, and calculate var part size int var_part_size = 0; int fixed_pos = 0; for (auto& it: values) { switch (it->get_kind()) { case Value::I32: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(i32); break; case Value::I64: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(i64); break; case Value::DOUBLE: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(double); break; case Value::STR: var_part_size += it->get_str().size(); break; default: Log::fatal("unexpected value type %d", it->get_kind()); verify(0); break; } } verify(fixed_pos == schema->fixed_part_size_); if (schema->var_size_cols_ > 0) { // 2nd pass, write var part int var_counter = 0; int var_pos = 0; row->dense_var_part_ = new char[var_part_size]; for (auto& it: values) { if (it->get_kind() == Value::STR) { row->dense_var_idx_[var_counter] = it->get_str().size(); it->write_binary(&row->dense_var_part_[var_pos]); var_counter++; var_pos += it->get_str().size(); } } verify(var_part_size == var_pos); verify(var_counter == schema->var_size_cols_); } return row; } } // namespace mdb <commit_msg>code cleanup<commit_after>#include "value.h" #include "row.h" #include "schema.h" #include "table.h" namespace mdb { Row::~Row() { delete[] fixed_part_; if (schema_->var_size_cols_ > 0) { if (kind_ == DENSE) { delete[] dense_var_part_; delete[] dense_var_idx_; } else { verify(kind_ == SPARSE); delete[] sparse_var_; } } } void Row::make_sparse() { if (kind_ == SPARSE) { // already sparse data return; } kind_ = SPARSE; if (schema_->var_size_cols_ == 0) { // special case, no memory copying required return; } // save those 2 values to prevent overwriting (union type!) char* var_data = dense_var_part_; int* var_idx = dense_var_idx_; assert(schema_->var_size_cols_ > 0); sparse_var_ = new std::string[schema_->var_size_cols_]; sparse_var_[0] = std::string(var_data, var_idx[0]); for (int i = 1; i < schema_->var_size_cols_; i++) { int var_start = var_idx[i - 1]; int var_len = var_idx[i] - var_idx[i - 1]; sparse_var_[i] = std::string(&var_data[var_start], var_len); } delete[] var_data; delete[] var_idx; } Value Row::get_column(int column_id) const { Value v; const Schema::column_info* info = schema_->get_column_info(column_id); blob b = this->get_blob(column_id); verify(info != nullptr); switch (info->type) { case Value::I32: v = Value(*((i32*) b.data)); break; case Value::I64: v = Value(*((i64*) b.data)); break; case Value::DOUBLE: v = Value(*((double*) b.data)); break; case Value::STR: v = Value(std::string(b.data, b.len)); break; default: Log::fatal("unexpected value type %d", info->type); verify(0); break; } return v; } MultiBlob Row::get_key() const { const std::vector<int>& key_cols = schema_->key_columns_id(); MultiBlob mb(key_cols.size()); for (int i = 0; i < mb.count(); i++) { mb[i] = this->get_blob(key_cols[i]); } return mb; } blob Row::get_blob(int column_id) const { blob b; const Schema::column_info* info = schema_->get_column_info(column_id); verify(info != nullptr); switch (info->type) { case Value::I32: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(i32); break; case Value::I64: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(i64); break; case Value::DOUBLE: b.data = &fixed_part_[info->fixed_size_offst]; b.len = sizeof(double); break; case Value::STR: if (kind_ == DENSE) { int var_start = 0; int var_len = 0; if (info->var_size_idx == 0) { var_start = 0; var_len = dense_var_idx_[0]; } else { var_start = dense_var_idx_[info->var_size_idx - 1]; var_len = dense_var_idx_[info->var_size_idx] - dense_var_idx_[info->var_size_idx - 1]; } b.data = &dense_var_part_[var_start]; b.len = var_len; } else { verify(kind_ == SPARSE); b.data = &(sparse_var_[info->var_size_idx][0]); b.len = sparse_var_[info->var_size_idx].size(); } break; default: Log::fatal("unexpected value type %d", info->type); verify(0); break; } return b; } void Row::update_fixed(const Schema::column_info* col, void* ptr, int len) { // check if really updating (new data!), and if necessary to remove/insert into table bool re_insert = false; if (memcmp(&fixed_part_[col->fixed_size_offst], ptr, len) == 0) { // not really updating return; } if (col->key) { re_insert = true; } if (re_insert && tbl_ != nullptr) { tbl_->remove(this, false); } memcpy(&fixed_part_[col->fixed_size_offst], ptr, len); if (re_insert && tbl_ != nullptr) { tbl_->insert(this); } } void Row::update(int column_id, const std::string& v) { const Schema::column_info* col = schema_->get_column_info(column_id); verify(col->type == Value::STR); // check if really updating (new data!), and if necessary to remove/insert into table bool re_insert = false; if (kind_ == SPARSE) { if (this->sparse_var_[col->var_size_idx] == v) { return; } } else { verify(kind_ == DENSE); blob b = this->get_blob(column_id); if (b.len == v.size() && memcmp(b.data, &v[0], v.size()) == 0) { return; } } if (col->key) { re_insert = true; } if (re_insert && tbl_ != nullptr) { tbl_->remove(this, false); } this->make_sparse(); this->sparse_var_[col->var_size_idx] = v; if (re_insert && tbl_ != nullptr) { tbl_->insert(this); } } void Row::update(int column_id, const Value& v) { switch (v.get_kind()) { case Value::I32: this->update(column_id, v.get_i32()); break; case Value::I64: this->update(column_id, v.get_i64()); break; case Value::DOUBLE: this->update(column_id, v.get_double()); break; case Value::STR: this->update(column_id, v.get_str()); break; default: Log::fatal("unexpected value type %d", v.get_kind()); verify(0); break; } } Row* Row::create(Schema* schema, const std::map<std::string, Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr(values.size(), nullptr); for (auto& it: values) { int col_id = schema->get_column_id(it.first); verify(col_id >= 0); values_ptr[col_id] = &it.second; } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::unordered_map<std::string, Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr(values.size(), nullptr); for (auto& it: values) { int col_id = schema->get_column_id(it.first); verify(col_id >= 0); values_ptr[col_id] = &it.second; } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::vector<Value>& values) { verify(values.size() == schema->columns_count()); std::vector<const Value*> values_ptr; values_ptr.reserve(values.size()); for (auto& it: values) { values_ptr.push_back(&it); } return Row::create(schema, values_ptr); } Row* Row::create(Schema* schema, const std::vector<const Value*>& values) { Row* row = new Row; row->schema_ = schema; row->fixed_part_ = new char[schema->fixed_part_size_]; if (schema->var_size_cols_ > 0) { row->dense_var_idx_ = new int[schema->var_size_cols_]; } // 1st pass, write fixed part, and calculate var part size int var_part_size = 0; int fixed_pos = 0; for (auto& it: values) { switch (it->get_kind()) { case Value::I32: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(i32); break; case Value::I64: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(i64); break; case Value::DOUBLE: it->write_binary(&row->fixed_part_[fixed_pos]); fixed_pos += sizeof(double); break; case Value::STR: var_part_size += it->get_str().size(); break; default: Log::fatal("unexpected value type %d", it->get_kind()); verify(0); break; } } verify(fixed_pos == schema->fixed_part_size_); if (schema->var_size_cols_ > 0) { // 2nd pass, write var part int var_counter = 0; int var_pos = 0; row->dense_var_part_ = new char[var_part_size]; for (auto& it: values) { if (it->get_kind() == Value::STR) { row->dense_var_idx_[var_counter] = it->get_str().size(); it->write_binary(&row->dense_var_part_[var_pos]); var_counter++; var_pos += it->get_str().size(); } } verify(var_part_size == var_pos); verify(var_counter == schema->var_size_cols_); } return row; } } // namespace mdb <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_NETWORK_ABSTRACT_SOCKET_HPP_ #define POSEIDON_NETWORK_ABSTRACT_SOCKET_HPP_ #include "../fwd.hpp" #include "enums.hpp" namespace poseidon { class Abstract_Socket : public virtual ::asteria::Rcbase { friend Network_Driver; private: unique_posix_fd m_fd; public: explicit Abstract_Socket(unique_posix_fd&& fd) : m_fd(::std::move(fd)) { this->do_set_common_options(); } ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket); private: // Enables non-blocking mode, etc. void do_set_common_options(); protected: // The network driver notifies incoming data via this callback. // `lock` shall lock `*this` after the call if locking is supported. // `hint` points to a temporary buffer of `size` bytes that may be used by this // function for any purpose. // Please mind thread safety, as this function is called by the network thread. virtual IO_Result do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size) = 0; // This function shall return the number of bytes that are pending for writing. // `lock` shall lock `*this` after the call if locking is supported. virtual size_t do_write_queue_size(Si_Mutex::unique_lock& lock) const = 0; // The network driver notifies possibility of outgoing data via this callback. // `lock` shall lock `*this` after the call if locking is supported. // `hint` points to a temporary buffer of `size` bytes that may be used by this // function for any purpose. // Please mind thread safety, as this function is called by the network thread. virtual IO_Result do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* hint, size_t size) = 0; // The network driver notifies closure via this callback. // `err` is zero for graceful shutdown. // Please mind thread safety, as this function is called by the network thread. virtual void do_on_async_poll_shutdown(int err) = 0; public: // Returns the stream descriptor. // This is used to query and adjust stream flags. You shall not perform I/O // operations on it. ROCKET_PURE_FUNCTION int get_fd() const noexcept { return this->m_fd; } // Causes abnormal termination of this stream. // Any data that have not been delivered to the other peer are discarded. // The other peer is likely to see a 'connection reset by peer' error. void terminate() noexcept; // Gets the (bound) address of the local peer. Socket_Address get_local_address() const; // Gets the (connected) address of the remote peer. // This function throws an exception if no peer has connected. Socket_Address get_remote_address() const; }; } // namespace poseidon #endif <commit_msg>network/abstract_socket: Add `m_epoll_data`<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_NETWORK_ABSTRACT_SOCKET_HPP_ #define POSEIDON_NETWORK_ABSTRACT_SOCKET_HPP_ #include "../fwd.hpp" #include "enums.hpp" namespace poseidon { class Abstract_Socket : public virtual ::asteria::Rcbase { friend Network_Driver; private: uint64_t m_epoll_data = 123456789; // used by network driver for quick lookups unique_posix_fd m_fd; public: explicit Abstract_Socket(unique_posix_fd&& fd) : m_fd(::std::move(fd)) { this->do_set_common_options(); } ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket); private: // Enables non-blocking mode, etc. void do_set_common_options(); protected: // The network driver notifies incoming data via this callback. // `lock` shall lock `*this` after the call if locking is supported. // `hint` points to a temporary buffer of `size` bytes that may be used by this // function for any purpose. // Please mind thread safety, as this function is called by the network thread. virtual IO_Result do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size) = 0; // This function shall return the number of bytes that are pending for writing. // `lock` shall lock `*this` after the call if locking is supported. virtual size_t do_write_queue_size(Si_Mutex::unique_lock& lock) const = 0; // The network driver notifies possibility of outgoing data via this callback. // `lock` shall lock `*this` after the call if locking is supported. // `hint` points to a temporary buffer of `size` bytes that may be used by this // function for any purpose. // Please mind thread safety, as this function is called by the network thread. virtual IO_Result do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* hint, size_t size) = 0; // The network driver notifies closure via this callback. // `err` is zero for graceful shutdown. // Please mind thread safety, as this function is called by the network thread. virtual void do_on_async_poll_shutdown(int err) = 0; public: // Returns the stream descriptor. // This is used to query and adjust stream flags. You shall not perform I/O // operations on it. ROCKET_PURE_FUNCTION int get_fd() const noexcept { return this->m_fd; } // Causes abnormal termination of this stream. // Any data that have not been delivered to the other peer are discarded. // The other peer is likely to see a 'connection reset by peer' error. void terminate() noexcept; // Gets the (bound) address of the local peer. Socket_Address get_local_address() const; // Gets the (connected) address of the remote peer. // This function throws an exception if no peer has connected. Socket_Address get_remote_address() const; }; } // namespace poseidon #endif <|endoftext|>
<commit_before>#include <LD30/PlayState.hpp> #include <LD30/ResourceManager.hpp> #include <LD30/Engine.hpp> #include <LD30/Menu/BaseMenu.hpp> #include <SFML/Graphics/Texture.hpp> #include <SFML/Window.hpp> ld::PlayState::PlayState(sf::RenderWindow& window) : GameState(window), m_player(window) { } ld::PlayState::~PlayState() { } bool ld::PlayState::init() { //Player auto tex = ldResource.getTexture("assets/Graphics/Player and shield planets/Player_Base.png"); tex->setSmooth(true); m_player.setTexture(tex); m_player.setSize(sf::Vector2f(128.f,128.f)); m_player.setOrigin(m_player.getSize().x / 2, m_player.getSize().y / 2); tex = ldResource.getTexture("assets/Graphics/Player and shield planets/Shield.png"); tex->setSmooth(true); m_player.m_shield.setTexture(tex); m_player.m_shield.setSize(sf::Vector2f(128.f, 128.f)); m_player.m_shield.setOrigin(m_player.m_shield.getSize().x / 2, m_player.m_shield.getSize().y / 2); //Enemy addEnemy(); return true; } void ld::PlayState::update(const float delta) { m_player.update(delta); for (int i = 0; i < (int)m_enemies.size(); ++i) { m_enemies[i].setPlayer(m_player); m_enemies[i].update(delta); } m_spawnTime += delta; countTimeForEnemies(); if (m_Time > m_minTime) m_Time -= delta / 100; else m_Time = m_minTime; } void ld::PlayState::draw() { m_player.draw(); for (auto &i:m_enemies) { i.draw(); } } void ld::PlayState::addEnemy() { m_enemies.emplace_back(*m_window); auto& ref = m_enemies.back(); if (!easterEgg) { auto tex = ldResource.getTexture("assets/Graphics/Enemies/Alien_1_sheet.png"); Animation anim; anim.load(*tex, 3); anim.setChangeTime(0.5f); anim.start(); ref.setAnimation(anim); ref.setTexture(tex); tex->setSmooth(true); } else { auto tex = ldResource.getTexture("assets/Graphics/Enemies/space core.png"); Animation anim; anim.load(*tex, 1); anim.setChangeTime(1); anim.start(); ref.setTexture(tex); tex->setSmooth(true); ref.m_useAnim = false; easterEgg = false; } ref.setSize(sf::Vector2f(256.f, 148.f)); ref.setOrigin(ref.getSize().x / 2, ref.getSize().y / 2); ref.setPosition(getRandSpawnPos()); } void ld::PlayState::countTimeForEnemies() { if (m_Time <= m_spawnTime) { m_spawnTime = 0; addEnemy(); } } void ld::PlayState::setDifficulty(int dif) { switch (dif) { case 1: m_Time = 15.f; m_minTime = 7.f; startLives = 5; break; case 2: m_Time = 13.f; m_minTime = 6.f; startLives = 4; break; case 3: m_Time = 10.f; m_minTime = 5.f; startLives = 3; break; default: m_Time = 15.f; m_minTime = 7.f; startLives = 5; } } sf::Vector2f ld::PlayState::getRandSpawnPos() { auto &ref = m_window->getView(); int east = ld::Misc::getRandomInt(1, 999); if (east == 556) easterEgg = true; switch (ld::Misc::getRandomInt(1, 4)) { case 1: //Left return sf::Vector2f(-300,ld::Misc::getRandomFloat(0,ref.getSize().y)); break; case 2: //Right return sf::Vector2f(ref.getSize().x + 300, ld::Misc::getRandomFloat(0, ref.getSize().y)); break; case 3: //Top return sf::Vector2f(ld::Misc::getRandomFloat(0, ref.getSize().x), -ref.getSize().y - 300); break; case 4: //Bottom return sf::Vector2f(ld::Misc::getRandomFloat(0, ref.getSize().y), ref.getSize().y + 300); break; } return sf::Vector2f(0,0); } void ld::PlayState::collisionCheck() { for (auto &i : m_enemies) { if (ifCollide(m_player, i)) { //Do stuff (explosion and shit } if (ifCollide(m_player.m_shield, i)) { //Aliens explode } } } bool ld::PlayState::ifCollide(sf::RectangleShape A, sf::RectangleShape B) { float aRad = A.getGlobalBounds().height; float bRad = B.getGlobalBounds().height; float length = aRad + bRad; sf::Vector2f aPos = A.getPosition(); sf::Vector2f bPos = B.getPosition(); sf::Vector2f diff = aPos - bPos; float magn = diff.x*diff.x + diff.y*diff.y; return magn <= length; }<commit_msg>little fix<commit_after>#include <LD30/PlayState.hpp> #include <LD30/ResourceManager.hpp> #include <LD30/Engine.hpp> #include <LD30/Menu/BaseMenu.hpp> #include <SFML/Graphics/Texture.hpp> #include <SFML/Window.hpp> #include <iostream> ld::PlayState::PlayState(sf::RenderWindow& window) : GameState(window), m_player(window) { } ld::PlayState::~PlayState() { } bool ld::PlayState::init() { //Player auto tex = ldResource.getTexture("assets/Graphics/Player and shield planets/Player_Base.png"); tex->setSmooth(true); m_player.setTexture(tex); m_player.setSize(sf::Vector2f(128.f,128.f)); m_player.setOrigin(m_player.getSize().x / 2, m_player.getSize().y / 2); tex = ldResource.getTexture("assets/Graphics/Player and shield planets/Shield.png"); tex->setSmooth(true); m_player.m_shield.setTexture(tex); m_player.m_shield.setSize(sf::Vector2f(128.f, 128.f)); m_player.m_shield.setOrigin(m_player.m_shield.getSize().x / 2, m_player.m_shield.getSize().y / 2); //Enemy addEnemy(); return true; } void ld::PlayState::update(const float delta) { m_player.update(delta); collisionCheck(); for (int i = 0; i < (int)m_enemies.size(); ++i) { m_enemies[i].setPlayer(m_player); m_enemies[i].update(delta); } m_spawnTime += delta; countTimeForEnemies(); if (m_Time > m_minTime) m_Time -= delta / 100; else m_Time = m_minTime; } void ld::PlayState::draw() { m_player.draw(); for (auto &i:m_enemies) { i.draw(); } } void ld::PlayState::addEnemy() { m_enemies.emplace_back(*m_window); auto& ref = m_enemies.back(); if (!easterEgg) { auto tex = ldResource.getTexture("assets/Graphics/Enemies/Alien_1_sheet.png"); Animation anim; anim.load(*tex, 3); anim.setChangeTime(0.5f); anim.start(); ref.setAnimation(anim); ref.setTexture(tex); tex->setSmooth(true); } else { auto tex = ldResource.getTexture("assets/Graphics/Enemies/space core.png"); Animation anim; anim.load(*tex, 1); anim.setChangeTime(1); anim.start(); ref.setTexture(tex); tex->setSmooth(true); ref.m_useAnim = false; easterEgg = false; } ref.setSize(sf::Vector2f(256.f, 148.f)); ref.setOrigin(ref.getSize().x / 2, ref.getSize().y / 2); ref.setPosition(getRandSpawnPos()); } void ld::PlayState::countTimeForEnemies() { if (m_Time <= m_spawnTime) { m_spawnTime = 0; addEnemy(); } } void ld::PlayState::setDifficulty(int dif) { switch (dif) { case 1: m_Time = 15.f; m_minTime = 7.f; startLives = 5; break; case 2: m_Time = 13.f; m_minTime = 6.f; startLives = 4; break; case 3: m_Time = 10.f; m_minTime = 5.f; startLives = 3; break; default: m_Time = 15.f; m_minTime = 7.f; startLives = 5; } } sf::Vector2f ld::PlayState::getRandSpawnPos() { auto &ref = m_window->getView(); int east = ld::Misc::getRandomInt(1, 999); if (east == 556) easterEgg = true; switch (ld::Misc::getRandomInt(1, 4)) { case 1: //Left return sf::Vector2f(-300,ld::Misc::getRandomFloat(0,ref.getSize().y)); break; case 2: //Right return sf::Vector2f(ref.getSize().x + 300, ld::Misc::getRandomFloat(0, ref.getSize().y)); break; case 3: //Top return sf::Vector2f(ld::Misc::getRandomFloat(0, ref.getSize().x), -ref.getSize().y - 300); break; case 4: //Bottom return sf::Vector2f(ld::Misc::getRandomFloat(0, ref.getSize().y), ref.getSize().y + 300); break; } return sf::Vector2f(0,0); } void ld::PlayState::collisionCheck() { //for (auto &i : m_enemies) for (std::size_t i = 0; i < m_enemies.size(); ++i) { if (ifCollide(m_player, m_enemies[i])) { //Do stuff (explosion and shit std::cout << "OUCH" << std::endl; } if (ifCollide(m_player.m_shield, m_enemies[i])) { m_enemies.erase(m_enemies.begin() + i); --i; std::cout << "BANG" << std::endl; //Aliens explode } } } bool ld::PlayState::ifCollide(sf::RectangleShape A, sf::RectangleShape B) { float aRad = A.getGlobalBounds().height; float bRad = B.getGlobalBounds().height; float length = (aRad + bRad)/2.f; sf::Vector2f aPos = A.getPosition(); sf::Vector2f bPos = B.getPosition(); sf::Vector2f diff = aPos - bPos; float magn = sqrt(diff.x*diff.x + diff.y*diff.y); return magn <= length; }<|endoftext|>
<commit_before>#include "logger.h" #include "manager.h" #include <fstream> #include <sstream> #include <map> namespace nano { void opencl_manager_t::init() { const cl_int ret = cl::Platform::get(&m_platforms); if (m_platforms.empty() || ret != CL_SUCCESS) { log_error() << "cannot find any OpenCL platform!"; throw cl::Error(ret); } for (size_t i = 0; i < m_platforms.size(); ++ i) { const cl::Platform& platform = m_platforms[i]; std::stringstream ss; ss << "OpenCL platform [" << (i + 1) << "/" << m_platforms.size() << "]: "; const std::string base = ss.str(); log_info() << base << "CL_PLATFORM_NAME: " << platform.getInfo<CL_PLATFORM_NAME>(); log_info() << base << "CL_PLATFORM_VENDOR: " << platform.getInfo<CL_PLATFORM_NAME>(); log_info() << base << "CL_PLATFORM_VERSION: " << platform.getInfo<CL_PLATFORM_NAME>(); std::vector<cl::Device> devices; const cl_int ret = platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); if (devices.empty() || ret != CL_SUCCESS) { log_error() << "cannot find any OpenCL device for the current platform!"; throw cl::Error(ret); } m_devices.insert(m_devices.end(), devices.begin(), devices.end()); for (size_t j = 0; j < devices.size(); j ++) { const cl::Device& device = devices[j]; const std::string name = device.getInfo<CL_DEVICE_NAME>(); const std::string vendor = device.getInfo<CL_DEVICE_VENDOR>(); const std::string driver = device.getInfo<CL_DRIVER_VERSION>(); const std::string version = device.getInfo<CL_DEVICE_VERSION>(); const std::string type = device_type_string(device.getInfo<CL_DEVICE_TYPE>()); const size_t gmemsize = device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); const size_t lmemsize = device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>(); const size_t amemsize = device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); const size_t cmemsize = device.getInfo<CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE>(); const size_t maxcus = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>(); const size_t maxwgsize = device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>(); const size_t maxwidims = device.getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>(); const std::vector<size_t> maxwisizes = device.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>(); const size_t maxkparams = device.getInfo<CL_DEVICE_MAX_PARAMETER_SIZE>(); std::stringstream ss; ss << "-> OpenCL device [" << (j + 1) << "/" << devices.size() << "]: "; const std::string base = ss.str(); log_info() << base << "CL_DEVICE_NAME: " << name; log_info() << base << "CL_DEVICE_VENDOR:" << vendor; log_info() << base << "CL_DRIVER_VERSION: " << driver; log_info() << base << "CL_DEVICE_VERSION: " << version; log_info() << base << "CL_DEVICE_TYPE: " << type; log_info() << base << "CL_DEVICE_GLOBAL_MEM_SIZE: " << gmemsize << "B = " << (gmemsize / 1024) << "KB = " << (gmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_LOCAL_MEM_SIZE: " << lmemsize << "B = " << (lmemsize / 1024) << "KB = " << (lmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: " << cmemsize << "B = " << (cmemsize / 1024) << "KB = " << (cmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_MEM_ALLOC_SIZE: " << amemsize << "B = " << (amemsize / 1024) << "KB = " << (amemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_COMPUTE_UNITS: " << maxcus; log_info() << base << "CL_DEVICE_MAX_WORK_GROUP_SIZE: " << maxwgsize; log_info() << base << "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS: " << maxwidims; log_info() << base << "CL_DEVICE_MAX_WORK_ITEM_SIZES: " << (maxwisizes.size() > 0 ? maxwisizes[0] : 0) << " / " << (maxwisizes.size() > 1 ? maxwisizes[1] : 0) << " / " << (maxwisizes.size() > 2 ? maxwisizes[2] : 0); log_info() << base << "CL_DEVICE_MAX_PARAMETER_SIZE: " << maxkparams; } } } bool opencl_manager_t::select(const cl_device_type type) { // <number of compute units, index> std::map<size_t, size_t, std::greater<size_t>> cuByIndex; for (size_t i = 0; i < m_devices.size(); ++ i) { const cl::Device& device = m_devices[i]; cuByIndex[device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>()] = i; } // select the device with the maximum number of compute units and the given type (if possible) for (const auto& cu : cuByIndex) { const cl::Device& device = m_devices[cu.second]; if ( type == CL_DEVICE_TYPE_ALL || device.getInfo<CL_DEVICE_TYPE>() == type) { select(device); return true; } } if (!cuByIndex.empty()) { const auto& cu = *cuByIndex.begin(); select(m_devices[cu.second]); return true; } else { return false; } } void opencl_manager_t::select(const cl::Device& device) { log_info() << "selected OpenCL device " << device.getInfo<CL_DEVICE_NAME>() << " of type " << device_type_string(device.getInfo<CL_DEVICE_TYPE>()) << "."; m_device = device; m_context = cl::Context({m_device}); m_command_queue = cl::CommandQueue(m_context, m_device, 0); } cl::Program opencl_manager_t::make_program_from_file(const std::string& filepath) const { std::ifstream file(filepath, std::ios::in); if (file.is_open()) { std::ostringstream oss; oss << file.rdbuf(); return make_program_from_text(oss.str()); } else { return make_program_from_text("cannot load file!"); } } cl::Program opencl_manager_t::make_program_from_text(const std::string& source) const { cl::Program::Sources sources(1, source); cl::Program program = cl::Program(m_context, sources); try { program.build({m_device}, "-cl-mad-enable");//, "-cl-fast-relaxed-math"); } catch (cl::Error& e) { // load compilation errors log_error() << "OpenCL program build status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(m_device); log_error() << "OpenCL program build options: " << program.getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(m_device); log_error() << "OpenCL program build log: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device); // and re-throw the exception throw cl::Error(e.err()); } return program; } cl::Kernel opencl_manager_t::make_kernel(const cl::Program& program, const std::string& name) const { try { return cl::Kernel(program, name.c_str()); } catch (cl::Error& e) { // load kernel errors log_error() << "OpenCL kernel error: " << error_string(e.err()); // and re-throw the exception throw cl::Error(e.err()); } } cl::Buffer opencl_manager_t::make_buffer(const size_t bytesize, cl_mem_flags flags) const { return cl::Buffer(m_context, flags, bytesize); } const char* device_type_string(const cl_device_type type) { switch (type) { case CL_DEVICE_TYPE_DEFAULT: return "DEFAULT"; case CL_DEVICE_TYPE_CPU: return "CPU"; case CL_DEVICE_TYPE_GPU: return "GPU"; case CL_DEVICE_TYPE_ACCELERATOR:return "ACCELERATOR"; case CL_DEVICE_TYPE_ALL: return "ALL"; default: return "UNKNOWN"; } } const char* error_string(const cl_int error) { static const char* errorString[] = { "CL_SUCCESS", "CL_DEVICE_NOT_FOUND", "CL_DEVICE_NOT_AVAILABLE", "CL_COMPILER_NOT_AVAILABLE", "CL_MEM_OBJECT_ALLOCATION_FAILURE", "CL_OUT_OF_RESOURCES", "CL_OUT_OF_HOST_MEMORY", "CL_PROFILING_INFO_NOT_AVAILABLE", "CL_MEM_COPY_OVERLAP", "CL_IMAGE_FORMAT_MISMATCH", "CL_IMAGE_FORMAT_NOT_SUPPORTED", "CL_BUILD_PROGRAM_FAILURE", "CL_MAP_FAILURE", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "CL_INVALID_VALUE", "CL_INVALID_DEVICE_TYPE", "CL_INVALID_PLATFORM", "CL_INVALID_DEVICE", "CL_INVALID_CONTEXT", "CL_INVALID_QUEUE_PROPERTIES", "CL_INVALID_COMMAND_QUEUE", "CL_INVALID_HOST_PTR", "CL_INVALID_MEM_OBJECT", "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "CL_INVALID_IMAGE_SIZE", "CL_INVALID_SAMPLER", "CL_INVALID_BINARY", "CL_INVALID_BUILD_OPTIONS", "CL_INVALID_PROGRAM", "CL_INVALID_PROGRAM_EXECUTABLE", "CL_INVALID_KERNEL_NAME", "CL_INVALID_KERNEL_DEFINITION", "CL_INVALID_KERNEL", "CL_INVALID_ARG_INDEX", "CL_INVALID_ARG_VALUE", "CL_INVALID_ARG_SIZE", "CL_INVALID_KERNEL_ARGS", "CL_INVALID_WORK_DIMENSION", "CL_INVALID_WORK_GROUP_SIZE", "CL_INVALID_WORK_ITEM_SIZE", "CL_INVALID_GLOBAL_OFFSET", "CL_INVALID_EVENT_WAIT_LIST", "CL_INVALID_EVENT", "CL_INVALID_OPERATION", "CL_INVALID_GL_OBJECT", "CL_INVALID_BUFFER_SIZE", "CL_INVALID_MIP_LEVEL", "CL_INVALID_GLOBAL_WORK_SIZE", }; static const int errorCount = sizeof(errorString) / sizeof(errorString[0]); const int index = -error; return (index >= 0 && index < errorCount) ? errorString[index] : ""; } } <commit_msg>update mapping of OpenCL status codes to strings<commit_after>#include "logger.h" #include "manager.h" #include <fstream> #include <sstream> #include <map> namespace nano { void opencl_manager_t::init() { const cl_int ret = cl::Platform::get(&m_platforms); if (m_platforms.empty() || ret != CL_SUCCESS) { log_error() << "cannot find any OpenCL platform!"; throw cl::Error(ret); } for (size_t i = 0; i < m_platforms.size(); ++ i) { const cl::Platform& platform = m_platforms[i]; std::stringstream ss; ss << "OpenCL platform [" << (i + 1) << "/" << m_platforms.size() << "]: "; const std::string base = ss.str(); log_info() << base << "CL_PLATFORM_NAME: " << platform.getInfo<CL_PLATFORM_NAME>(); log_info() << base << "CL_PLATFORM_VENDOR: " << platform.getInfo<CL_PLATFORM_NAME>(); log_info() << base << "CL_PLATFORM_VERSION: " << platform.getInfo<CL_PLATFORM_NAME>(); std::vector<cl::Device> devices; const cl_int ret = platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); if (devices.empty() || ret != CL_SUCCESS) { log_error() << "cannot find any OpenCL device for the current platform!"; throw cl::Error(ret); } m_devices.insert(m_devices.end(), devices.begin(), devices.end()); for (size_t j = 0; j < devices.size(); j ++) { const cl::Device& device = devices[j]; const std::string name = device.getInfo<CL_DEVICE_NAME>(); const std::string vendor = device.getInfo<CL_DEVICE_VENDOR>(); const std::string driver = device.getInfo<CL_DRIVER_VERSION>(); const std::string version = device.getInfo<CL_DEVICE_VERSION>(); const std::string type = device_type_string(device.getInfo<CL_DEVICE_TYPE>()); const size_t gmemsize = device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); const size_t lmemsize = device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>(); const size_t amemsize = device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); const size_t cmemsize = device.getInfo<CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE>(); const size_t maxcus = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>(); const size_t maxwgsize = device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>(); const size_t maxwidims = device.getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>(); const std::vector<size_t> maxwisizes = device.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>(); const size_t maxkparams = device.getInfo<CL_DEVICE_MAX_PARAMETER_SIZE>(); std::stringstream ss; ss << "-> OpenCL device [" << (j + 1) << "/" << devices.size() << "]: "; const std::string base = ss.str(); log_info() << base << "CL_DEVICE_NAME: " << name; log_info() << base << "CL_DEVICE_VENDOR:" << vendor; log_info() << base << "CL_DRIVER_VERSION: " << driver; log_info() << base << "CL_DEVICE_VERSION: " << version; log_info() << base << "CL_DEVICE_TYPE: " << type; log_info() << base << "CL_DEVICE_GLOBAL_MEM_SIZE: " << gmemsize << "B = " << (gmemsize / 1024) << "KB = " << (gmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_LOCAL_MEM_SIZE: " << lmemsize << "B = " << (lmemsize / 1024) << "KB = " << (lmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: " << cmemsize << "B = " << (cmemsize / 1024) << "KB = " << (cmemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_MEM_ALLOC_SIZE: " << amemsize << "B = " << (amemsize / 1024) << "KB = " << (amemsize / 1024 / 1024) << "MB"; log_info() << base << "CL_DEVICE_MAX_COMPUTE_UNITS: " << maxcus; log_info() << base << "CL_DEVICE_MAX_WORK_GROUP_SIZE: " << maxwgsize; log_info() << base << "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS: " << maxwidims; log_info() << base << "CL_DEVICE_MAX_WORK_ITEM_SIZES: " << (maxwisizes.size() > 0 ? maxwisizes[0] : 0) << " / " << (maxwisizes.size() > 1 ? maxwisizes[1] : 0) << " / " << (maxwisizes.size() > 2 ? maxwisizes[2] : 0); log_info() << base << "CL_DEVICE_MAX_PARAMETER_SIZE: " << maxkparams; } } } bool opencl_manager_t::select(const cl_device_type type) { // <number of compute units, index> std::map<size_t, size_t, std::greater<size_t>> cuByIndex; for (size_t i = 0; i < m_devices.size(); ++ i) { const cl::Device& device = m_devices[i]; cuByIndex[device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>()] = i; } // select the device with the maximum number of compute units and the given type (if possible) for (const auto& cu : cuByIndex) { const cl::Device& device = m_devices[cu.second]; if ( type == CL_DEVICE_TYPE_ALL || device.getInfo<CL_DEVICE_TYPE>() == type) { select(device); return true; } } if (!cuByIndex.empty()) { const auto& cu = *cuByIndex.begin(); select(m_devices[cu.second]); return true; } else { return false; } } void opencl_manager_t::select(const cl::Device& device) { log_info() << "selected OpenCL device " << device.getInfo<CL_DEVICE_NAME>() << " of type " << device_type_string(device.getInfo<CL_DEVICE_TYPE>()) << "."; m_device = device; m_context = cl::Context({m_device}); m_command_queue = cl::CommandQueue(m_context, m_device, 0); } cl::Program opencl_manager_t::make_program_from_file(const std::string& filepath) const { std::ifstream file(filepath, std::ios::in); if (file.is_open()) { std::ostringstream oss; oss << file.rdbuf(); return make_program_from_text(oss.str()); } else { return make_program_from_text("cannot load file!"); } } cl::Program opencl_manager_t::make_program_from_text(const std::string& source) const { cl::Program::Sources sources(1, source); cl::Program program = cl::Program(m_context, sources); try { program.build({m_device}, "-cl-mad-enable");//, "-cl-fast-relaxed-math"); } catch (cl::Error& e) { // load compilation errors log_error() << "OpenCL program build status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(m_device); log_error() << "OpenCL program build options: " << program.getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(m_device); log_error() << "OpenCL program build log: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device); // and re-throw the exception throw cl::Error(e.err()); } return program; } cl::Kernel opencl_manager_t::make_kernel(const cl::Program& program, const std::string& name) const { try { return cl::Kernel(program, name.c_str()); } catch (cl::Error& e) { // load kernel errors log_error() << "OpenCL kernel error: " << error_string(e.err()); // and re-throw the exception throw cl::Error(e.err()); } } cl::Buffer opencl_manager_t::make_buffer(const size_t bytesize, cl_mem_flags flags) const { return cl::Buffer(m_context, flags, bytesize); } const char* device_type_string(const cl_device_type type) { switch (type) { case CL_DEVICE_TYPE_DEFAULT: return "DEFAULT"; case CL_DEVICE_TYPE_CPU: return "CPU"; case CL_DEVICE_TYPE_GPU: return "GPU"; case CL_DEVICE_TYPE_ACCELERATOR:return "ACCELERATOR"; case CL_DEVICE_TYPE_ALL: return "ALL"; default: return "UNKNOWN"; } } const char* error_string(const cl_int error) { static const char* errorString[] = { "CL_SUCCESS", // 0 "CL_DEVICE_NOT_FOUND", // -1 "CL_DEVICE_NOT_AVAILABLE", // -2 "CL_COMPILER_NOT_AVAILABLE", // -3 "CL_MEM_OBJECT_ALLOCATION_FAILURE", // -4 "CL_OUT_OF_RESOURCES", // -5 "CL_OUT_OF_HOST_MEMORY", // -6 "CL_PROFILING_INFO_NOT_AVAILABLE", // -7 "CL_MEM_COPY_OVERLAP", // -8 "CL_IMAGE_FORMAT_MISMATCH", // -9 "CL_IMAGE_FORMAT_NOT_SUPPORTED", // -10 "CL_BUILD_PROGRAM_FAILURE", // -11 "CL_MAP_FAILURE", // -12 "CL_MISALIGNED_SUB_BUFFER_OFFSET", // -13 "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST", // -14 "CL_COMPILE_PROGRAM_FAILURE", // -15 "CL_LINKER_NOT_AVAILABLE", // -16 "CL_LINK_PROGRAM_FAILURE", // -17 "CL_DEVICE_PARTITION_FAILED", // -18 "CL_KERNEL_ARG_INFO_NOT_AVAILABLE", // -19 "", "", "", "", "", "", "", "", "", "", "CL_INVALID_VALUE", // -30 "CL_INVALID_DEVICE_TYPE", // -31 "CL_INVALID_PLATFORM", // -32 "CL_INVALID_DEVICE", // -33 "CL_INVALID_CONTEXT", // -34 "CL_INVALID_QUEUE_PROPERTIES", // -35 "CL_INVALID_COMMAND_QUEUE", // -36 "CL_INVALID_HOST_PTR", // -37 "CL_INVALID_MEM_OBJECT", // -38 "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", // -39 "CL_INVALID_IMAGE_SIZE", // -40 "CL_INVALID_SAMPLER", // -41 "CL_INVALID_BINARY", // -42 "CL_INVALID_BUILD_OPTIONS", // -43 "CL_INVALID_PROGRAM", // -44 "CL_INVALID_PROGRAM_EXECUTABLE", // -45 "CL_INVALID_KERNEL_NAME", // -46 "CL_INVALID_KERNEL_DEFINITION", // -47 "CL_INVALID_KERNEL", // -48 "CL_INVALID_ARG_INDEX", // -49 "CL_INVALID_ARG_VALUE", // -50 "CL_INVALID_ARG_SIZE", // -51 "CL_INVALID_KERNEL_ARGS", // -52 "CL_INVALID_WORK_DIMENSION", // -53 "CL_INVALID_WORK_GROUP_SIZE", // -54 "CL_INVALID_WORK_ITEM_SIZE", // -55 "CL_INVALID_GLOBAL_OFFSET", // -56 "CL_INVALID_EVENT_WAIT_LIST", // -57 "CL_INVALID_EVENT", // -58 "CL_INVALID_OPERATION", // -59 "CL_INVALID_GL_OBJECT", // -60 "CL_INVALID_BUFFER_SIZE", // -61 "CL_INVALID_MIP_LEVEL", // -62 "CL_INVALID_GLOBAL_WORK_SIZE", // -63 "CL_INVALID_PROPERTY", // -64 "CL_INVALID_IMAGE_DESCRIPTOR", // -65 "CL_INVALID_COMPILER_OPTIONS", // -66 "CL_INVALID_LINKER_OPTIONS", // -67 "CL_INVALID_DEVICE_PARTITION_COUNT", // -68 "CL_INVALID_PIPE_SIZE", // -69 "CL_INVALID_DEVICE_QUEUE" // -70 }; static const int errorCount = sizeof(errorString) / sizeof(errorString[0]); const int index = -error; return (index >= 0 && index < errorCount) ? errorString[index] : "UNKNOWN"; } } <|endoftext|>
<commit_before>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: opt_solver.cpp Abstract: Wraps smt::kernel as a solver for optimization Author: Anh-Dung Phan (t-anphan) 2013-10-16 Notes: Based directly on smt_solver. --*/ #include"reg_decl_plugins.h" #include"opt_solver.h" #include"smt_context.h" #include"theory_arith.h" #include"theory_diff_logic.h" namespace opt { opt_solver::opt_solver(ast_manager & mgr, params_ref const & p, symbol const & l): solver_na2as(mgr), m_params(p), m_context(mgr, m_params), m(mgr), m_objective_enabled(false) { m_logic = l; if (m_logic != symbol::null) m_context.set_logic(m_logic); } opt_solver::~opt_solver() { } void opt_solver::updt_params(params_ref const & p) { m_params.updt_params(p); m_context.updt_params(p); } void opt_solver::collect_param_descrs(param_descrs & r) { m_context.collect_param_descrs(r); } void opt_solver::collect_statistics(statistics & st) const { m_context.collect_statistics(st); } void opt_solver::assert_expr(expr * t) { m_context.assert_expr(t); } void opt_solver::push_core() { m_context.push(); } void opt_solver::pop_core(unsigned n) { m_context.pop(n); } smt::theory_opt& opt_solver::get_optimizer() { smt::context& ctx = m_context.get_context(); smt::theory_id arith_id = m_context.m().get_family_id("arith"); smt::theory* arith_theory = ctx.get_theory(arith_id); if (typeid(smt::theory_mi_arith) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_mi_arith&>(*arith_theory); } else if (typeid(smt::theory_i_arith) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_i_arith&>(*arith_theory); } else if (typeid(smt::theory_rdl&) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_rdl&>(*arith_theory); } else if (typeid(smt::theory_idl&) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_idl&>(*arith_theory); } else { UNREACHABLE(); return dynamic_cast<smt::theory_mi_arith&>(*arith_theory); } } lbool opt_solver::check_sat_core(unsigned num_assumptions, expr * const * assumptions) { TRACE("opt_solver_na2as", tout << "opt_opt_solver::check_sat_core: " << num_assumptions << "\n";); lbool r = m_context.check(num_assumptions, assumptions); if (r == l_true && m_objective_enabled) { m_objective_values.reset(); for (unsigned i = 0; i < m_objective_vars.size(); ++i) { smt::theory_var v = m_objective_vars[i]; bool is_bounded = get_optimizer().maximize(v); if (is_bounded) { m_objective_values.push_back(get_optimizer().get_objective_value(v)); } else { inf_eps_rational<inf_rational> r(rational(1), inf_rational(0)); m_objective_values.push_back(r); } } } return r; } void opt_solver::get_unsat_core(ptr_vector<expr> & r) { unsigned sz = m_context.get_unsat_core_size(); for (unsigned i = 0; i < sz; i++) r.push_back(m_context.get_unsat_core_expr(i)); } void opt_solver::get_model(model_ref & m) { m_context.get_model(m); } proof * opt_solver::get_proof() { return m_context.get_proof(); } std::string opt_solver::reason_unknown() const { return m_context.last_failure_as_string(); } void opt_solver::get_labels(svector<symbol> & r) { buffer<symbol> tmp; m_context.get_relevant_labels(0, tmp); r.append(tmp.size(), tmp.c_ptr()); } void opt_solver::set_cancel(bool f) { m_context.set_cancel(f); } void opt_solver::set_progress_callback(progress_callback * callback) { m_callback = callback; m_context.set_progress_callback(callback); } unsigned opt_solver::get_num_assertions() const { return m_context.size(); } expr * opt_solver::get_assertion(unsigned idx) const { SASSERT(idx < get_num_assertions()); return m_context.get_formulas()[idx]; } void opt_solver::display(std::ostream & out) const { m_context.display(out); } smt::theory_var opt_solver::add_objective(app* term) { m_objective_vars.push_back(get_optimizer().add_objective(term)); return m_objective_vars.back(); } vector<inf_eps> const& opt_solver::get_objective_values() { return m_objective_values; } expr_ref opt_solver::block_lower_bound(unsigned var, inf_eps const& val) { if (val.get_infinity().is_pos()) { return expr_ref(m.mk_false(), m); } else if (val.get_infinity().is_neg()) { return expr_ref(m.mk_true(), m); } else { return expr_ref(get_optimizer().block_lower_bound(m_objective_vars[var], val.get_numeral()), m); } } void opt_solver::reset_objectives() { m_objective_vars.reset(); m_objective_values.reset(); } opt_solver::toggle_objective::toggle_objective(opt_solver& s, bool new_value): s(s), m_old_value(s.m_objective_enabled) { s.m_objective_enabled = new_value; } opt_solver::toggle_objective::~toggle_objective() { s.m_objective_enabled = m_old_value; } } <commit_msg>local updates to opt_solver<commit_after>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: opt_solver.cpp Abstract: Wraps smt::kernel as a solver for optimization Author: Anh-Dung Phan (t-anphan) 2013-10-16 Notes: Based directly on smt_solver. --*/ #include"reg_decl_plugins.h" #include"opt_solver.h" #include"smt_context.h" #include"theory_arith.h" #include"theory_diff_logic.h" namespace opt { opt_solver::opt_solver(ast_manager & mgr, params_ref const & p, symbol const & l): solver_na2as(mgr), m_params(p), m_context(mgr, m_params), m(mgr), m_objective_enabled(false) { m_logic = l; if (m_logic != symbol::null) m_context.set_logic(m_logic); } opt_solver::~opt_solver() { } void opt_solver::updt_params(params_ref const & p) { m_params.updt_params(p); m_context.updt_params(p); } void opt_solver::collect_param_descrs(param_descrs & r) { m_context.collect_param_descrs(r); } void opt_solver::collect_statistics(statistics & st) const { m_context.collect_statistics(st); } void opt_solver::assert_expr(expr * t) { m_context.assert_expr(t); } void opt_solver::push_core() { m_context.push(); } void opt_solver::pop_core(unsigned n) { m_context.pop(n); } smt::theory_opt& opt_solver::get_optimizer() { smt::context& ctx = m_context.get_context(); smt::theory_id arith_id = m_context.m().get_family_id("arith"); smt::theory* arith_theory = ctx.get_theory(arith_id); if (typeid(smt::theory_mi_arith) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_mi_arith&>(*arith_theory); } else if (typeid(smt::theory_i_arith) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_i_arith&>(*arith_theory); } else if (typeid(smt::theory_inf_arith) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_inf_arith&>(*arith_theory); } else if (typeid(smt::theory_rdl&) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_rdl&>(*arith_theory); } else if (typeid(smt::theory_idl&) == typeid(*arith_theory)) { return dynamic_cast<smt::theory_idl&>(*arith_theory); } else { UNREACHABLE(); return dynamic_cast<smt::theory_mi_arith&>(*arith_theory); } } lbool opt_solver::check_sat_core(unsigned num_assumptions, expr * const * assumptions) { TRACE("opt_solver_na2as", tout << "opt_opt_solver::check_sat_core: " << num_assumptions << "\n";); lbool r = m_context.check(num_assumptions, assumptions); if (r == l_true && m_objective_enabled) { m_objective_values.reset(); for (unsigned i = 0; i < m_objective_vars.size(); ++i) { smt::theory_var v = m_objective_vars[i]; bool is_bounded = get_optimizer().maximize(v); if (is_bounded) { m_objective_values.push_back(get_optimizer().get_objective_value(v)); } else { inf_eps_rational<inf_rational> r(rational(1), inf_rational(0)); m_objective_values.push_back(r); } } } return r; } void opt_solver::get_unsat_core(ptr_vector<expr> & r) { unsigned sz = m_context.get_unsat_core_size(); for (unsigned i = 0; i < sz; i++) r.push_back(m_context.get_unsat_core_expr(i)); } void opt_solver::get_model(model_ref & m) { m_context.get_model(m); } proof * opt_solver::get_proof() { return m_context.get_proof(); } std::string opt_solver::reason_unknown() const { return m_context.last_failure_as_string(); } void opt_solver::get_labels(svector<symbol> & r) { buffer<symbol> tmp; m_context.get_relevant_labels(0, tmp); r.append(tmp.size(), tmp.c_ptr()); } void opt_solver::set_cancel(bool f) { m_context.set_cancel(f); } void opt_solver::set_progress_callback(progress_callback * callback) { m_callback = callback; m_context.set_progress_callback(callback); } unsigned opt_solver::get_num_assertions() const { return m_context.size(); } expr * opt_solver::get_assertion(unsigned idx) const { SASSERT(idx < get_num_assertions()); return m_context.get_formulas()[idx]; } void opt_solver::display(std::ostream & out) const { m_context.display(out); } smt::theory_var opt_solver::add_objective(app* term) { m_objective_vars.push_back(get_optimizer().add_objective(term)); return m_objective_vars.back(); } vector<inf_eps> const& opt_solver::get_objective_values() { return m_objective_values; } expr_ref opt_solver::block_lower_bound(unsigned var, inf_eps const& val) { if (val.get_infinity().is_pos()) { return expr_ref(m.mk_false(), m); } else if (val.get_infinity().is_neg()) { return expr_ref(m.mk_true(), m); } else { return expr_ref(get_optimizer().block_lower_bound(m_objective_vars[var], val.get_numeral()), m); } } void opt_solver::reset_objectives() { m_objective_vars.reset(); m_objective_values.reset(); } opt_solver::toggle_objective::toggle_objective(opt_solver& s, bool new_value): s(s), m_old_value(s.m_objective_enabled) { s.m_objective_enabled = new_value; } opt_solver::toggle_objective::~toggle_objective() { s.m_objective_enabled = m_old_value; } } <|endoftext|>
<commit_before>#include <algorithm> // random_shuffle, transform #include <cassert> #include <deque> #include <chrono> #include <random> #include <utility> // pair #include <sdd/order/order.hh> #include <sdd/order/strategies/force.hh> #include "mc/classic/dump.hh" #include "mc/classic/make_order.hh" namespace pnmc { namespace mc { namespace classic { using sdd_conf = sdd::conf1; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { using order_identifier = sdd::order_identifier<sdd_conf>; using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>; using order_builder = sdd::order_builder<sdd_conf>; const conf::configuration& conf; mutable unsigned int artificial_id_counter; mk_order_visitor(const conf::configuration& c) : conf(c), artificial_id_counter(0) {} // Place: base case of the recursion, there's no more possible nested hierarchies. result_type operator()(const pn::place* p) const noexcept { return std::make_pair(order_identifier(p->id), order_builder()); } // Hierarchy. result_type operator()(const pn::module_node& m) const noexcept { assert(not m.nested.empty()); std::deque<result_type> tmp; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(*this, *h); tmp.push_back(res); } std::size_t height = 0; for (const auto& p : tmp) { if (not p.second.empty()) { height += p.second.height(); } else { height += 1; // place } } order_builder ob; if (height <= conf.order_min_height) { order_identifier id; for (const auto& p : tmp) { if (not p.second.empty()) { ob = p.second << ob; } else // place { ob.push(p.first, p.second); } } return result_type(id, ob); } else { for (const auto& p : tmp) { ob.push(p.first, p.second); } } return std::make_pair(order_identifier(m.id) , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> make_order(const conf::configuration& conf, statistics& stats, const pn::net& net) { if (conf.order_ordering_force) { std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now(); using identifier_type = sdd_conf::Identifier; using vertex = sdd::force::vertex<identifier_type>; using hyperedge = sdd::force::hyperedge<identifier_type>; // Temporary placeholder for identifiers. std::vector<identifier_type> identifiers; // Collect identifiers. identifiers.reserve(net.places().size()); for (const auto& place : net.places()) { if (place.connected()) { identifiers.emplace_back(place.id); } } // The hypergraph that stores connections between the places of the Petri net. sdd::force::hypergraph<sdd_conf> graph(identifiers.cbegin(), identifiers.cend()); // This container will be used again. identifiers.clear(); // A new connection is created for each transition of the Petri net. for (const auto& transition : net.transitions()) { for (const auto& arc : transition.pre) { identifiers.emplace_back(arc.first); } for (const auto& arc : transition.post) { identifiers.emplace_back(arc.first); } graph.add_hyperedge(identifiers.cbegin(), identifiers.cend()); // We use this container again in the next loop. identifiers.clear(); } // Apply the FORCE ordering strategy. auto force = sdd::force::worker<sdd_conf>(graph); const auto o = force(conf.order_force_iterations); stats.force_duration = std::chrono::system_clock::now() - start; stats.force_spans = force.spans(); // Dump the hypergraph to a DOT file if required by the configuration. dump_hypergraph_dot(conf, graph); return sdd::order<sdd_conf>(o); } else if (not conf.order_force_flat and net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; if (conf.order_random) { std::vector<std::string> tmp; tmp.reserve(net.places().size()); for (const auto& place : net.places()) { if (place.connected()) { tmp.emplace_back(place.id); } } std::random_device rd; std::mt19937 g(rd()); std::shuffle(tmp.begin(), tmp.end(), g); for (const auto& id : tmp) { ob.push(id); } } else { for (const auto& place : net.places()) { if (place.connected()) { ob.push(place.id); } } } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ }}} // namespace pnmc::mc::classic <commit_msg>Warn when a place is not connected to the rest of Petri net.<commit_after>#include <algorithm> // random_shuffle, transform #include <cassert> #include <deque> #include <chrono> #include <random> #include <utility> // pair #include <sdd/order/order.hh> #include <sdd/order/strategies/force.hh> #include "mc/classic/dump.hh" #include "mc/classic/make_order.hh" namespace pnmc { namespace mc { namespace classic { using sdd_conf = sdd::conf1; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { using order_identifier = sdd::order_identifier<sdd_conf>; using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>; using order_builder = sdd::order_builder<sdd_conf>; const conf::configuration& conf; mutable unsigned int artificial_id_counter; mk_order_visitor(const conf::configuration& c) : conf(c), artificial_id_counter(0) {} // Place: base case of the recursion, there's no more possible nested hierarchies. result_type operator()(const pn::place* p) const noexcept { return std::make_pair(order_identifier(p->id), order_builder()); } // Hierarchy. result_type operator()(const pn::module_node& m) const noexcept { assert(not m.nested.empty()); std::deque<result_type> tmp; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(*this, *h); tmp.push_back(res); } std::size_t height = 0; for (const auto& p : tmp) { if (not p.second.empty()) { height += p.second.height(); } else { height += 1; // place } } order_builder ob; if (height <= conf.order_min_height) { order_identifier id; for (const auto& p : tmp) { if (not p.second.empty()) { ob = p.second << ob; } else // place { ob.push(p.first, p.second); } } return result_type(id, ob); } else { for (const auto& p : tmp) { ob.push(p.first, p.second); } } return std::make_pair(order_identifier(m.id) , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> make_order(const conf::configuration& conf, statistics& stats, const pn::net& net) { for (const auto& place : net.places()) { if (not place.connected()) { std::cerr << "Warning: place " << place.id << " is not connected." << std::endl; } } if (conf.order_ordering_force) { std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now(); using identifier_type = sdd_conf::Identifier; using vertex = sdd::force::vertex<identifier_type>; using hyperedge = sdd::force::hyperedge<identifier_type>; // Temporary placeholder for identifiers. std::vector<identifier_type> identifiers; // Collect identifiers. identifiers.reserve(net.places().size()); for (const auto& place : net.places()) { if (place.connected()) { identifiers.emplace_back(place.id); } } // The hypergraph that stores connections between the places of the Petri net. sdd::force::hypergraph<sdd_conf> graph(identifiers.cbegin(), identifiers.cend()); // This container will be used again. identifiers.clear(); // A new connection is created for each transition of the Petri net. for (const auto& transition : net.transitions()) { for (const auto& arc : transition.pre) { identifiers.emplace_back(arc.first); } for (const auto& arc : transition.post) { identifiers.emplace_back(arc.first); } graph.add_hyperedge(identifiers.cbegin(), identifiers.cend()); // We use this container again in the next loop. identifiers.clear(); } // Apply the FORCE ordering strategy. auto force = sdd::force::worker<sdd_conf>(graph); const auto o = force(conf.order_force_iterations); stats.force_duration = std::chrono::system_clock::now() - start; stats.force_spans = force.spans(); // Dump the hypergraph to a DOT file if required by the configuration. dump_hypergraph_dot(conf, graph); return sdd::order<sdd_conf>(o); } else if (not conf.order_force_flat and net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; if (conf.order_random) { std::vector<std::string> tmp; tmp.reserve(net.places().size()); for (const auto& place : net.places()) { if (place.connected()) { tmp.emplace_back(place.id); } } std::random_device rd; std::mt19937 g(rd()); std::shuffle(tmp.begin(), tmp.end(), g); for (const auto& id : tmp) { ob.push(id); } } else { for (const auto& place : net.places()) { if (place.connected()) { ob.push(place.id); } } } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ }}} // namespace pnmc::mc::classic <|endoftext|>
<commit_before>/** Copyright 2015 Joachim Wolff Master Thesis Tutors: Milad Miladi, Fabrizio Costa Winter semester 2015/2016 Chair of Bioinformatics Department of Computer Science Faculty of Engineering Albert-Ludwig-University Freiburg im Breisgau **/ #include <algorithm> #include <iostream> #include <iterator> #include <utility> #ifdef OPENMP #include <omp.h> #endif #include "inverseIndex.h" class sort_map { public: size_t key; size_t val; }; bool mapSortDescByValue(const sort_map& a, const sort_map& b) { return a.val > b.val; }; InverseIndex::InverseIndex(size_t pNumberOfHashFunctions, size_t pBlockSize, size_t pNumberOfCores, size_t pChunkSize, size_t pMaxBinSize, size_t pMinimalBlocksInCommon, size_t pExcessFactor, size_t pMaximalNumberOfHashCollisions) { mNumberOfHashFunctions = pNumberOfHashFunctions; mBlockSize = pBlockSize; mNumberOfCores = pNumberOfCores; mChunkSize = pChunkSize; mMaxBinSize = pMaxBinSize; // mSizeOfNeighborhood = pSizeOfNeighborhood; mMinimalBlocksInCommon = pMinimalBlocksInCommon; mExcessFactor = pExcessFactor; mMaximalNumberOfHashCollisions = pMaximalNumberOfHashCollisions; mInverseIndexUmapVector = new vector__umapVector(); mSignatureStorage = new umap_uniqueElement(); size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1); mInverseIndexUmapVector->resize(inverseIndexSize); mHash = new Hash(); } InverseIndex::~InverseIndex() { for (auto it = (*mSignatureStorage).begin(); it != (*mSignatureStorage).end(); ++it) { delete it->second->instances; delete it->second->signature; delete it->second; } delete mSignatureStorage; delete mInverseIndexUmapVector; } // compute the signature for one instance vsize_t* InverseIndex::computeSignature(const SparseMatrixFloat* pRawData, const size_t pInstance) { vsize_t signatureHash; signatureHash.reserve(mNumberOfHashFunctions); for(size_t j = 0; j < mNumberOfHashFunctions; ++j) { size_t minHashValue = MAX_VALUE; for (size_t i = 0; i < pRawData->getSizeOfInstance(pInstance); ++i) { // hash(size_t pKey, size_t pModulo, size_t pSeed) size_t hashValue = mHash->hash((pRawData->getNextElement(pInstance, i) +1), (j+1) * A, MAX_VALUE); if (hashValue < minHashValue) { minHashValue = hashValue; } } signatureHash[j] = minHashValue; } // reduce number of hash values by a factor of blockSize size_t k = 0; vsize_t* signature = new vsize_t(); signature->reserve((mNumberOfHashFunctions / mBlockSize) + 1); while (k < (mNumberOfHashFunctions)) { // use computed hash value as a seed for the next computation size_t signatureBlockValue = signatureHash[k]; for (size_t j = 0; j < mBlockSize; ++j) { signatureBlockValue = mHash->hash((signatureHash[k+j]), signatureBlockValue * A, MAX_VALUE); } signature->push_back(signatureBlockValue); k += mBlockSize; } return signature; } umap_uniqueElement* InverseIndex::computeSignatureMap(const SparseMatrixFloat* pRawData) { // std::cout << "97I" << std::endl; mDoubleElementsQueryCount = 0; const size_t sizeOfInstances = pRawData->size(); umap_uniqueElement* instanceSignature = new umap_uniqueElement(); (*instanceSignature).reserve(sizeOfInstances); if (mChunkSize <= 0) { mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores)); } #ifdef OPENMP omp_set_dynamic(0); #endif #pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores) for(size_t index = 0; index < pRawData->size(); ++index) { // vsize_t* features = pRawData->getFeatureRow(index); // compute unique id size_t signatureId = 0; for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) { signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1) * A, MAX_VALUE); } // signature is in storage && auto signatureIt = (*mSignatureStorage).find(signatureId); if (signatureIt != (*mSignatureStorage).end() && (instanceSignature->find(signatureId) != instanceSignature->end())) { #pragma omp critical { instanceSignature->operator[](signatureId) = (*mSignatureStorage)[signatureId]; instanceSignature->operator[](signatureId)->instances->push_back(index); mDoubleElementsQueryCount += (*mSignatureStorage)[signatureId]->instances->size(); } continue; } // for every hash function: compute the hash values of all features and take the minimum of these // as the hash value for one hash function --> h_j(x) = argmin (x_i of x) f_j(x_i) vsize_t* signature = computeSignature(pRawData, index); #pragma omp critical { if (instanceSignature->find(signatureId) == instanceSignature->end()) { vsize_t* doubleInstanceVector = new vsize_t(1); (*doubleInstanceVector)[0] = index; uniqueElement* element = new uniqueElement();; element->instances = doubleInstanceVector; element->signature = signature; instanceSignature->operator[](signatureId) = element; } else { instanceSignature->operator[](signatureId)->instances->push_back(index); mDoubleElementsQueryCount += 1; } } } // std::cout << "150I" << std::endl; return instanceSignature; } void InverseIndex::fit(const SparseMatrixFloat* pRawData) { // std::cout << "Fitting started" << std::endl; // std::cout << "156I" << std::endl; mDoubleElementsStorageCount = 0; size_t inverseIndexSize = ceil(((float) mNumberOfHashFunctions / (float) mBlockSize)+1); mInverseIndexUmapVector->resize(inverseIndexSize); // std::cout << "155" << std::endl; if (mChunkSize <= 0) { mChunkSize = ceil(pRawData->size() / static_cast<float>(mNumberOfCores)); } #ifdef OPENMP omp_set_dynamic(0); #endif #pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores) for (size_t index = 0; index < pRawData->size(); ++index) { size_t signatureId = 0; for (size_t j = 0; j < pRawData->getSizeOfInstance(index); ++j) { signatureId = mHash->hash((pRawData->getNextElement(index, j) +1), (signatureId+1) * A, MAX_VALUE); } vsize_t* signature; auto itSignatureStorage = mSignatureStorage->find(signatureId); if (itSignatureStorage == mSignatureStorage->end()) { signature = computeSignature(pRawData, index); } else { signature = itSignatureStorage->second->signature; } #pragma omp critical { if (itSignatureStorage == mSignatureStorage->end()) { vsize_t* doubleInstanceVector = new vsize_t(1); (*doubleInstanceVector)[0] = index; uniqueElement* element = new uniqueElement(); element->instances = doubleInstanceVector; element->signature = signature; mSignatureStorage->operator[](signatureId) = element; } else { mSignatureStorage->operator[](signatureId)->instances->push_back(index); mDoubleElementsStorageCount += 1; } for (size_t j = 0; j < signature->size(); ++j) { auto itHashValue_InstanceVector = mInverseIndexUmapVector->operator[](j).find((*signature)[j]); // if for hash function h_i() the given hash values is already stored if (itHashValue_InstanceVector != mInverseIndexUmapVector->operator[](j).end()) { // insert the instance id if not too many collisions (maxBinSize) if (itHashValue_InstanceVector->second.size() < mMaxBinSize) { // insert only if there wasn't any collisions in the past if (itHashValue_InstanceVector->second.size() > 0) { itHashValue_InstanceVector->second.push_back(index); } } else { // too many collisions: delete stored ids. empty vector is interpreted as an error code // for too many collisions itHashValue_InstanceVector->second.clear(); } } else { // given hash value for the specific hash function was not avaible: insert new hash value vsize_t instanceIdVector; instanceIdVector.push_back(index); mInverseIndexUmapVector->operator[](j)[(*signature)[j]] = instanceIdVector; } } } } // std::cout << "222I" << std::endl; } neighborhood* InverseIndex::kneighbors(const umap_uniqueElement* pSignaturesMap, const int pNneighborhood, const bool pDoubleElementsStorageCount) { // std::cout << "228I" << std::endl; size_t doubleElements = 0; if (pDoubleElementsStorageCount) { doubleElements = mDoubleElementsStorageCount; } else { doubleElements = mDoubleElementsQueryCount; } #ifdef OPENMP omp_set_dynamic(0); #endif vvint* neighbors = new vvint(); vvfloat* distances = new vvfloat(); neighbors->resize(pSignaturesMap->size()+doubleElements); distances->resize(pSignaturesMap->size()+doubleElements); if (mChunkSize <= 0) { mChunkSize = ceil(mInverseIndexUmapVector->size() / static_cast<float>(mNumberOfCores)); } #pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores) for (size_t i = 0; i < pSignaturesMap->size(); ++i) { umap_uniqueElement::const_iterator instanceId = pSignaturesMap->begin(); std::advance(instanceId, i); std::unordered_map<size_t, size_t> neighborhood; const vsize_t* signature = instanceId->second->signature; for (size_t j = 0; j < signature->size(); ++j) { size_t hashID = (*signature)[j]; if (hashID != 0 && hashID != MAX_VALUE) { size_t collisionSize = 0; // std::cout << "258I" << std::endl; umapVector::const_iterator instances = mInverseIndexUmapVector->at(j).find(hashID); // std::cout << "261I" << std::endl; if (instances != mInverseIndexUmapVector->at(j).end()) { collisionSize = instances->second.size(); } else { continue; } if (collisionSize < mMaxBinSize && collisionSize > 0) { for (size_t k = 0; k < instances->second.size(); ++k) { neighborhood[instances->second.at(k)] += 1; } } } // std::cout << "275I" << std::endl; } // std::cout << "278I" << std::endl; std::vector< sort_map > neighborhoodVectorForSorting; for (auto it = neighborhood.begin(); it != neighborhood.end(); ++it) { sort_map mapForSorting; mapForSorting.key = (*it).first; mapForSorting.val = (*it).second; neighborhoodVectorForSorting.push_back(mapForSorting); } // std::cout << "288I" << std::endl; size_t numberOfElementsToSort = pNneighborhood; if (pNneighborhood > neighborhoodVectorForSorting.size()) { numberOfElementsToSort = neighborhoodVectorForSorting.size(); } std::partial_sort(neighborhoodVectorForSorting.begin(), neighborhoodVectorForSorting.begin()+numberOfElementsToSort, neighborhoodVectorForSorting.end(), mapSortDescByValue); size_t sizeOfNeighborhoodAdjusted; if (pNneighborhood == MAX_VALUE) { sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood), neighborhoodVectorForSorting.size()); } else { sizeOfNeighborhoodAdjusted = std::min(static_cast<size_t>(pNneighborhood * mExcessFactor), neighborhoodVectorForSorting.size()); } // std::cout << "304I" << std::endl; size_t count = 0; vvint* neighborsForThisInstance = new vvint(instanceId->second->instances->size()); vvfloat* distancesForThisInstance = new vvfloat(instanceId->second->instances->size()); for (size_t j = 0; j < neighborsForThisInstance->size(); ++j) { vint neighborhoodVector; std::vector<float> distanceVector; if (neighborhoodVectorForSorting[0].key != instanceId->second->instances->operator[](j)) { // std::cout << "instance id first: " << instanceId->second->instances->operator[](j) << std::endl; neighborhoodVector.push_back(instanceId->second->instances->operator[](j)); distanceVector.push_back(0); ++count; } for (auto it = neighborhoodVectorForSorting.begin(); it != neighborhoodVectorForSorting.end(); ++it) { neighborhoodVector.push_back((*it).key); distanceVector.push_back(1 - ((*it).val / static_cast<float>(mMaximalNumberOfHashCollisions))); ++count; if (count >= sizeOfNeighborhoodAdjusted) { (*neighborsForThisInstance)[j] = neighborhoodVector; (*distancesForThisInstance)[j] = distanceVector; break; } } } #pragma omp critical // std::cout << "318I" << std::endl; { for (size_t j = 0; j < instanceId->second->instances->size(); ++j) { (*neighbors)[instanceId->second->instances->operator[](j)] = (*neighborsForThisInstance)[j]; (*distances)[instanceId->second->instances->operator[](j)] = (*distancesForThisInstance)[j]; } } } // std::cout << "326I" << std::endl; neighborhood* neighborhood_ = new neighborhood(); neighborhood_->neighbors = neighbors; neighborhood_->distances = distances; // std::cout << "331I" << std::endl; return neighborhood_; }<commit_msg>Deleted<commit_after><|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_INTERFACE_HH #define DUNE_GDT_LOCALOPERATOR_INTERFACE_HH #include <vector> #include <dune/common/dynmatrix.hh> #include <dune/gdt/basefunctionset/interface.hh> namespace Dune { namespace GDT { namespace LocalOperator { template< class Traits > class Codim0Interface { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().numTmpObjectsRequired()); return asImp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam T Traits of the test BaseFunctionSetInterface implementation * \tparam A Traits of the ansatz BaseFunctionSetInterface implementation * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase,ansatzBase} * \tparam rC{T,a} dimRangeCols of the {testBase,ansatzBase} */ template< class T, class A, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< T, D, d, R, rT, rCT >& testBase, const BaseFunctionSetInterface< A, D, d, R, rA, rCA >& ansatzBase, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(asImp().apply(testBase, ansatzBase, ret, tmpLocalMatrices)); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class Codim0Interface template< class Traits > class Codim1CouplingInterface { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().numTmpObjectsRequired()); return asImp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam TE Traits of the entity test BaseFunctionSetInterface implementation * \tparam AE Traits of the entity ansatz BaseFunctionSetInterface implementation * \tparam TN Traits of the neighbor test BaseFunctionSetInterface implementation * \tparam AN Traits of the neighbor ansatz BaseFunctionSetInterface implementation * \tparam IntersectionType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase*,ansatzBase*} * \tparam rC{T,a} dimRangeCols of the {testBase*,ansatzBase*} */ template< class TE, class AE, class TN, class AN, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< TE, D, d, R, rT, rCT >& testBaseEntity, const BaseFunctionSetInterface< AE, D, d, R, rA, rCA >& ansatzBaseEntity, const BaseFunctionSetInterface< TN, D, d, R, rT, rCT >& testBaseNeighbor, const BaseFunctionSetInterface< AN, D, d, R, rA, rCA >& ansatzBaseNeighbor, const IntersectionType& intersection, Dune::DynamicMatrix< R >& entityEntityRet, Dune::DynamicMatrix< R >& neighborNeighborRet, Dune::DynamicMatrix< R >& entityNeighborRet, Dune::DynamicMatrix< R >& neighborEntityRet, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(asImp().apply(testBaseEntity, ansatzBaseEntity, testBaseNeighbor, ansatzBaseNeighbor, intersection, entityEntityRet, neighborNeighborRet, entityNeighborRet, neighborEntityRet, tmpLocalMatrices)); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class Codim1CouplingInterface template< class Traits > class Codim1BoundaryInterface { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().numTmpObjectsRequired()); return asImp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam T Traits of the test BaseFunctionSetInterface implementation * \tparam A Traits of the ansatz BaseFunctionSetInterface implementation * \tparam IntersectionType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase,ansatzBase} * \tparam rC{T,a} dimRangeCols of the {testBase,ansatzBase} */ template< class T, class A, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< T, D, d, R, rT, rCT >& testBase, const BaseFunctionSetInterface< A, D, d, R, rA, rCA >& ansatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(asImp().apply(testBase, ansatzBase, intersection, ret, tmpLocalMatrices)); } derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } }; // class Codim1BoundaryInterface } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_INTERFACE_HH <commit_msg>[localoperator.interface] update CRTP handling<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_INTERFACE_HH #define DUNE_GDT_LOCALOPERATOR_INTERFACE_HH #include <vector> #include <dune/common/dynmatrix.hh> #include <dune/stuff/common/crtp.hh> #include <dune/gdt/basefunctionset/interface.hh> namespace Dune { namespace GDT { namespace LocalOperator { template< class Traits > class Codim0Interface : public Stuff::CRTPInterface< Codim0Interface< Traits >, Traits > { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_CRTP(this->as_imp().numTmpObjectsRequired()); return this->as_imp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam T Traits of the test BaseFunctionSetInterface implementation * \tparam A Traits of the ansatz BaseFunctionSetInterface implementation * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase,ansatzBase} * \tparam rC{T,a} dimRangeCols of the {testBase,ansatzBase} */ template< class T, class A, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< T, D, d, R, rT, rCT >& testBase, const BaseFunctionSetInterface< A, D, d, R, rA, rCA >& ansatzBase, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_CRTP(this->as_imp().apply(testBase, ansatzBase, ret, tmpLocalMatrices)); } }; // class Codim0Interface template< class Traits > class Codim1CouplingInterface : public Stuff::CRTPInterface< Codim1CouplingInterface< Traits >, Traits > { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_CRTP(this->as_imp().numTmpObjectsRequired()); return this->as_imp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam TE Traits of the entity test BaseFunctionSetInterface implementation * \tparam AE Traits of the entity ansatz BaseFunctionSetInterface implementation * \tparam TN Traits of the neighbor test BaseFunctionSetInterface implementation * \tparam AN Traits of the neighbor ansatz BaseFunctionSetInterface implementation * \tparam IntersectionType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase*,ansatzBase*} * \tparam rC{T,a} dimRangeCols of the {testBase*,ansatzBase*} */ template< class TE, class AE, class TN, class AN, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< TE, D, d, R, rT, rCT >& testBaseEntity, const BaseFunctionSetInterface< AE, D, d, R, rA, rCA >& ansatzBaseEntity, const BaseFunctionSetInterface< TN, D, d, R, rT, rCT >& testBaseNeighbor, const BaseFunctionSetInterface< AN, D, d, R, rA, rCA >& ansatzBaseNeighbor, const IntersectionType& intersection, Dune::DynamicMatrix< R >& entityEntityRet, Dune::DynamicMatrix< R >& neighborNeighborRet, Dune::DynamicMatrix< R >& entityNeighborRet, Dune::DynamicMatrix< R >& neighborEntityRet, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_CRTP(this->as_imp().apply(testBaseEntity, ansatzBaseEntity, testBaseNeighbor, ansatzBaseNeighbor, intersection, entityEntityRet, neighborNeighborRet, entityNeighborRet, neighborEntityRet, tmpLocalMatrices)); } }; // class Codim1CouplingInterface template< class Traits > class Codim1BoundaryInterface : public Stuff::CRTPInterface< Codim1BoundaryInterface< Traits >, Traits > { public: typedef typename Traits::derived_type derived_type; size_t numTmpObjectsRequired() const { CHECK_CRTP(this->as_imp().numTmpObjectsRequired()); return this->as_imp().numTmpObjectsRequired(); } /** * \brief Applies the local operator. * \tparam T Traits of the test BaseFunctionSetInterface implementation * \tparam A Traits of the ansatz BaseFunctionSetInterface implementation * \tparam IntersectionType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \tparam r{T,A} dimRange of the of the {testBase,ansatzBase} * \tparam rC{T,a} dimRangeCols of the {testBase,ansatzBase} */ template< class T, class A, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const BaseFunctionSetInterface< T, D, d, R, rT, rCT >& testBase, const BaseFunctionSetInterface< A, D, d, R, rA, rCA >& ansatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { CHECK_AND_CALL_CRTP(this->as_imp().apply(testBase, ansatzBase, intersection, ret, tmpLocalMatrices)); } }; // class Codim1BoundaryInterface } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_INTERFACE_HH <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Illustrates how to use worker threads that issue completion callbacks #include "base/logging.h" #include "base/message_loop.h" #include "base/task.h" #include "base/threading/worker_pool.h" #include "net/base/completion_callback.h" #include "net/base/test_completion_callback.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" typedef PlatformTest TestOldCompletionCallbackTest; using net::OldCompletionCallback; const int kMagicResult = 8888; // ExampleEmployer is a toy version of HostResolver // TODO: restore damage done in extracting example from real code // (e.g. bring back real destructor, bring back comments) class ExampleEmployer { public: ExampleEmployer(); ~ExampleEmployer(); // Do some imaginary work on a worker thread; // when done, worker posts callback on the original thread. // Returns true on success bool DoSomething(OldCompletionCallback* callback); private: class ExampleWorker; friend class ExampleWorker; scoped_refptr<ExampleWorker> request_; DISALLOW_COPY_AND_ASSIGN(ExampleEmployer); }; // Helper class; this is how ExampleEmployer puts work on a different thread class ExampleEmployer::ExampleWorker : public base::RefCountedThreadSafe<ExampleWorker> { public: ExampleWorker(ExampleEmployer* employer, OldCompletionCallback* callback) : employer_(employer), callback_(callback), origin_loop_(MessageLoop::current()) { } void DoWork(); void DoCallback(); private: friend class base::RefCountedThreadSafe<ExampleWorker>; ~ExampleWorker() {} // Only used on the origin thread (where DoSomething was called). ExampleEmployer* employer_; OldCompletionCallback* callback_; // Used to post ourselves onto the origin thread. base::Lock origin_loop_lock_; MessageLoop* origin_loop_; }; void ExampleEmployer::ExampleWorker::DoWork() { // Running on the worker thread // In a real worker thread, some work would be done here. // Pretend it is, and send the completion callback. Task* reply = NewRunnableMethod(this, &ExampleWorker::DoCallback); // The origin loop could go away while we are trying to post to it, so we // need to call its PostTask method inside a lock. See ~ExampleEmployer. { base::AutoLock locked(origin_loop_lock_); if (origin_loop_) { origin_loop_->PostTask(FROM_HERE, reply); reply = NULL; } } // Does nothing if it got posted. delete reply; } void ExampleEmployer::ExampleWorker::DoCallback() { // Running on the origin thread. // Drop the employer_'s reference to us. Do this before running the // callback since the callback might result in the employer being // destroyed. employer_->request_ = NULL; callback_->Run(kMagicResult); } ExampleEmployer::ExampleEmployer() { } ExampleEmployer::~ExampleEmployer() { } bool ExampleEmployer::DoSomething(OldCompletionCallback* callback) { DCHECK(!request_) << "already in use"; request_ = new ExampleWorker(this, callback); // Dispatch to worker thread... if (!base::WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(request_.get(), &ExampleWorker::DoWork), true)) { NOTREACHED(); request_ = NULL; return false; } return true; } TEST_F(TestOldCompletionCallbackTest, Simple) { ExampleEmployer boss; TestOldCompletionCallback callback; bool queued = boss.DoSomething(&callback); EXPECT_EQ(queued, true); int result = callback.WaitForResult(); EXPECT_EQ(result, kMagicResult); } // TODO: test deleting ExampleEmployer while work outstanding <commit_msg>base::Bind fixes<commit_after>// Copyright (c) 2011 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. // Illustrates how to use worker threads that issue completion callbacks #include "base/bind.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/threading/worker_pool.h" #include "net/base/completion_callback.h" #include "net/base/test_completion_callback.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" typedef PlatformTest TestOldCompletionCallbackTest; using net::OldCompletionCallback; const int kMagicResult = 8888; // ExampleEmployer is a toy version of HostResolver // TODO: restore damage done in extracting example from real code // (e.g. bring back real destructor, bring back comments) class ExampleEmployer { public: ExampleEmployer(); ~ExampleEmployer(); // Do some imaginary work on a worker thread; // when done, worker posts callback on the original thread. // Returns true on success bool DoSomething(OldCompletionCallback* callback); private: class ExampleWorker; friend class ExampleWorker; scoped_refptr<ExampleWorker> request_; DISALLOW_COPY_AND_ASSIGN(ExampleEmployer); }; // Helper class; this is how ExampleEmployer puts work on a different thread class ExampleEmployer::ExampleWorker : public base::RefCountedThreadSafe<ExampleWorker> { public: ExampleWorker(ExampleEmployer* employer, OldCompletionCallback* callback) : employer_(employer), callback_(callback), origin_loop_(MessageLoop::current()) { } void DoWork(); void DoCallback(); private: friend class base::RefCountedThreadSafe<ExampleWorker>; ~ExampleWorker() {} // Only used on the origin thread (where DoSomething was called). ExampleEmployer* employer_; OldCompletionCallback* callback_; // Used to post ourselves onto the origin thread. base::Lock origin_loop_lock_; MessageLoop* origin_loop_; }; void ExampleEmployer::ExampleWorker::DoWork() { // Running on the worker thread // In a real worker thread, some work would be done here. // Pretend it is, and send the completion callback. // The origin loop could go away while we are trying to post to it, so we // need to call its PostTask method inside a lock. See ~ExampleEmployer. { base::AutoLock locked(origin_loop_lock_); if (origin_loop_) origin_loop_->PostTask(FROM_HERE, base::Bind(&ExampleWorker::DoCallback, this)); } } void ExampleEmployer::ExampleWorker::DoCallback() { // Running on the origin thread. // Drop the employer_'s reference to us. Do this before running the // callback since the callback might result in the employer being // destroyed. employer_->request_ = NULL; callback_->Run(kMagicResult); } ExampleEmployer::ExampleEmployer() { } ExampleEmployer::~ExampleEmployer() { } bool ExampleEmployer::DoSomething(OldCompletionCallback* callback) { DCHECK(!request_) << "already in use"; request_ = new ExampleWorker(this, callback); // Dispatch to worker thread... if (!base::WorkerPool::PostTask( FROM_HERE, base::Bind(&ExampleWorker::DoWork, request_.get()), true)) { NOTREACHED(); request_ = NULL; return false; } return true; } TEST_F(TestOldCompletionCallbackTest, Simple) { ExampleEmployer boss; TestOldCompletionCallback callback; bool queued = boss.DoSomething(&callback); EXPECT_EQ(queued, true); int result = callback.WaitForResult(); EXPECT_EQ(result, kMagicResult); } // TODO: test deleting ExampleEmployer while work outstanding <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <typeinfo> namespace osg { static std::auto_ptr<DeleteHandler> s_deleteHandler(0); void Referenced::setDeleteHandler(DeleteHandler* handler) { // s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } } }; // end of namespace osg <commit_msg>Added #include <memory> for Win32 build<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <typeinfo> #include <memory> namespace osg { static std::auto_ptr<DeleteHandler> s_deleteHandler(0); void Referenced::setDeleteHandler(DeleteHandler* handler) { // s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } } }; // end of namespace osg <|endoftext|>
<commit_before>#ifndef LOCALMATRIX_PROXY_HH #define LOCALMATRIX_PROXY_HH #include <vector> #include <assert.h> #include <dune/stuff/common/math.hh> namespace Dune { namespace Stuff { namespace Fem { //! a small proxy object that automagically prevents near-0 value fill-in template< class MatrixPointerType > class LocalMatrixProxy { typedef typename MatrixPointerType::element_type MatrixObjectType; typedef typename MatrixObjectType::LocalMatrixType LocalMatrixType; typedef typename MatrixObjectType::DomainSpaceType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename MatrixObjectType::MatrixType::Ttype FieldType; LocalMatrixType local_matrix_; const double eps_; const unsigned int rows_; const unsigned int cols_; std::vector< FieldType > entries_; public: LocalMatrixProxy(MatrixPointerType& object, const EntityType& self, const EntityType& neigh, const double eps) : local_matrix_( object->localMatrix(self, neigh) ) , eps_(eps) , rows_( local_matrix_.rows() ) , cols_( local_matrix_.columns() ) , entries_( rows_ * cols_, FieldType(0.0) ) {} inline void add(const unsigned int row, const unsigned int col, const FieldType val) { ASSERT_LT(row, rows_); ASSERT_LT(col, cols_); entries_[row * cols_ + col] += val; } ~LocalMatrixProxy() { for (unsigned int i = 0; i < rows_; ++i) { for (unsigned int j = 0; j < cols_; ++j) { const FieldType& i_j = entries_[i * cols_ + j]; if ( !aboutEqual(i_j, 0.0) ) local_matrix_.add(i, j, i_j); } } } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } }; //! a small proxy object that automagically prevents near-0 value fill-in template< class MatrixPointerType > class ISTLLocalMatrixProxy { typedef typename MatrixPointerType::element_type MatrixObjectType; typedef typename MatrixObjectType::LocalMatrixType LocalMatrixType; typedef typename MatrixObjectType::MatrixType::block_type block_type; typedef typename MatrixObjectType::DomainSpaceType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename MatrixObjectType::MatrixType::Ttype FieldType; // LocalMatrixType local_matrix_; MatrixPointerType matrix_pointer_; const EntityType& self_; const EntityType& neigh_; const double eps_; const unsigned int rows_; const unsigned int cols_; std::vector< FieldType > entries_; //! global row numbers std::vector< int > rowMap_; //! global col numbers std::vector< int > colMap_; public: ISTLLocalMatrixProxy(MatrixPointerType& pointer, const EntityType& self, const EntityType& neigh, const double eps) : matrix_pointer_(pointer) , self_(self) , neigh_(neigh) , eps_(eps) , rows_(block_type::rows) , cols_(block_type::cols) , entries_( rows_ * cols_, FieldType(0.0) ) { const auto& domainSpace = matrix_pointer_->rowSpace(); const auto& rangeSpace = matrix_pointer_->colSpace(); rowMap_.resize( domainSpace.baseFunctionSet(self).numBaseFunctions() ); colMap_.resize( rangeSpace.baseFunctionSet(neigh).numBaseFunctions() ); const auto dmend = domainSpace.mapper().end(self); for (auto dmit = domainSpace.mapper().begin(self); dmit != dmend; ++dmit) { // ASSERT_EQ( dmit.global() , domainSpace.mapToGlobal( self, dmit.local() ) ); rowMap_[dmit.local()] = dmit.global(); } const auto rmend = rangeSpace.mapper().end(neigh); for (auto rmit = rangeSpace.mapper().begin(neigh); rmit != rmend; ++rmit) { // ASSERT_EQ( rmit.global() , rangeSpace.mapToGlobal( neigh, rmit.local() ) ); colMap_[rmit.local()] = rmit.global(); } } inline void add(const unsigned int row, const unsigned int col, const FieldType val) { ASSERT_LT(row, rows_); ASSERT_LT(col, cols_); assert( !std::isnan( matrix_pointer_->matrix() (rowMap_[row], colMap_[col]) ) ); entries_[row * cols_ + col] += val; } ~ISTLLocalMatrixProxy() { for (unsigned int i = 0; i < rows_; ++i) { for (unsigned int j = 0; j < cols_; ++j) { const FieldType& i_j = entries_[i * cols_ + j]; if (std::fabs(i_j) > eps_) { assert( !std::isnan(i_j) ); assert( !std::isinf(i_j) ); matrix_pointer_->add(rowMap_[i], colMap_[j], i_j); assert( !std::isnan( matrix_pointer_->matrix() (rowMap_[i], colMap_[j]) ) ); assert( !std::isinf( matrix_pointer_->matrix() (rowMap_[i], colMap_[j]) ) ); } } } } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } }; } // namespace Fem } // namespace Stuff } // namespace Dune #endif // LOCALMATRIX_PROXY_HH /** Copyright (c) 2012, Rene Milk * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <commit_msg>[fem] fixup localmatrixproxy for current fem spm-object<commit_after>#ifndef LOCALMATRIX_PROXY_HH #define LOCALMATRIX_PROXY_HH #include <vector> #include <assert.h> #include <dune/common/float_cmp.hh> namespace Dune { namespace Stuff { namespace Fem { //! a small proxy object that automagically prevents near-0 value fill-in template< class MatrixObjectType > class LocalMatrixProxy { typedef typename MatrixObjectType::LocalMatrixType LocalMatrixType; typedef typename MatrixObjectType::DomainSpaceType::GridType GridType; typedef typename MatrixObjectType::DomainSpaceType::EntityType DomainEntityType; typedef typename MatrixObjectType::RangeSpaceType::EntityType RangeEntityType; typedef typename MatrixObjectType::RangeSpaceType::RangeFieldType FieldType; typedef Dune::FloatCmpOps<FieldType> CompareType; typedef Dune::FloatCmp::DefaultEpsilon<typename CompareType::EpsilonType, CompareType::cstyle> DefaultEpsilon; LocalMatrixType local_matrix_; const double eps_; const unsigned int rows_; const unsigned int cols_; std::vector< FieldType > entries_; public: LocalMatrixProxy(MatrixObjectType& object, const DomainEntityType& self, const RangeEntityType& neigh, const double eps = DefaultEpsilon::value()) : local_matrix_( object.localMatrix(self, neigh) ) , eps_(eps) , rows_( local_matrix_.rows() ) , cols_( local_matrix_.columns() ) , entries_( rows_ * cols_, FieldType(0.0) ) {} inline void add(const unsigned int row, const unsigned int col, const FieldType val) { ASSERT_LT(row, rows_); ASSERT_LT(col, cols_); entries_[row * cols_ + col] += val; } auto domainBaseFunctionSet() const -> decltype(local_matrix_.domainBaseFunctionSet()) { return local_matrix_.domainBaseFunctionSet(); } auto rangeBaseFunctionSet() const -> decltype(local_matrix_.rangeBaseFunctionSet()) { return local_matrix_.rangeBaseFunctionSet(); } ~LocalMatrixProxy() { auto comp = CompareType(eps_); for (unsigned int i = 0; i < rows_; ++i) { for (unsigned int j = 0; j < cols_; ++j) { const FieldType& i_j = entries_[i * cols_ + j]; if ( comp.ne(i_j, 0.0) ) local_matrix_.add(i, j, i_j); } } } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } }; //! a small proxy object that automagically prevents near-0 value fill-in template< class MatrixObjectType > class ISTLLocalMatrixProxy { typedef typename MatrixObjectType::LocalMatrixType LocalMatrixType; typedef typename MatrixObjectType::MatrixType::block_type block_type; typedef typename MatrixObjectType::DomainSpaceType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename MatrixObjectType::MatrixType::Ttype FieldType; // LocalMatrixType local_matrix_; MatrixObjectType matrix_pointer_; const EntityType& self_; const EntityType& neigh_; const double eps_; const unsigned int rows_; const unsigned int cols_; std::vector< FieldType > entries_; //! global row numbers std::vector< int > rowMap_; //! global col numbers std::vector< int > colMap_; public: ISTLLocalMatrixProxy(MatrixObjectType& pointer, const EntityType& self, const EntityType& neigh, const double eps) : matrix_pointer_(pointer) , self_(self) , neigh_(neigh) , eps_(eps) , rows_(block_type::rows) , cols_(block_type::cols) , entries_( rows_ * cols_, FieldType(0.0) ) { const auto& domainSpace = matrix_pointer_->rowSpace(); const auto& rangeSpace = matrix_pointer_->colSpace(); rowMap_.resize( domainSpace.baseFunctionSet(self).numBaseFunctions() ); colMap_.resize( rangeSpace.baseFunctionSet(neigh).numBaseFunctions() ); const auto dmend = domainSpace.mapper().end(self); for (auto dmit = domainSpace.mapper().begin(self); dmit != dmend; ++dmit) { // ASSERT_EQ( dmit.global() , domainSpace.mapToGlobal( self, dmit.local() ) ); rowMap_[dmit.local()] = dmit.global(); } const auto rmend = rangeSpace.mapper().end(neigh); for (auto rmit = rangeSpace.mapper().begin(neigh); rmit != rmend; ++rmit) { // ASSERT_EQ( rmit.global() , rangeSpace.mapToGlobal( neigh, rmit.local() ) ); colMap_[rmit.local()] = rmit.global(); } } inline void add(const unsigned int row, const unsigned int col, const FieldType val) { ASSERT_LT(row, rows_); ASSERT_LT(col, cols_); assert( !std::isnan( matrix_pointer_->matrix() (rowMap_[row], colMap_[col]) ) ); entries_[row * cols_ + col] += val; } ~ISTLLocalMatrixProxy() { for (unsigned int i = 0; i < rows_; ++i) { for (unsigned int j = 0; j < cols_; ++j) { const FieldType& i_j = entries_[i * cols_ + j]; if (std::fabs(i_j) > eps_) { assert( !std::isnan(i_j) ); assert( !std::isinf(i_j) ); matrix_pointer_->add(rowMap_[i], colMap_[j], i_j); assert( !std::isnan( matrix_pointer_->matrix() (rowMap_[i], colMap_[j]) ) ); assert( !std::isinf( matrix_pointer_->matrix() (rowMap_[i], colMap_[j]) ) ); } } } } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } }; } // namespace Fem } // namespace Stuff } // namespace Dune #endif // LOCALMATRIX_PROXY_HH /** Copyright (c) 2012, Rene Milk * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH #define DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH #include <memory> #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Providers { #if HAVE_DUNE_GRID template< class GridImp > class ConstDefault : public ConstProviderInterface< GridImp > { typedef ConstProviderInterface< GridImp > BaseType; public: using typename BaseType::GridType; static const std::string static_id() { return BaseType::static_id(); } ConstDefault(const GridType& grid) : grid_(grid) {} ConstDefault(const GridType* grid_ptr) : grid_(*grid_ptr) {} ConstDefault(std::shared_ptr< const GridType > grid_ptr) : grid_(*grid_ptr) {} ConstDefault(std::unique_ptr< const GridType >&& grid_ptr) : grid_(*grid_ptr) {} virtual ~ConstDefault(){} virtual const GridType& grid() const DS_OVERRIDE { return grid_; } private: const GridType& grid_; }; // class ConstDefault template< class GridImp > class Default : public ProviderInterface< GridImp > { typedef ProviderInterface< GridImp > BaseType; public: using typename BaseType::GridType; static const std::string static_id() { return BaseType::static_id(); } Default(GridType& grid) : grid_(grid) {} Default(GridType* grid_ptr) : grid_(*grid_ptr) {} Default(std::shared_ptr< GridType > grid_ptr) : grid_(*grid_ptr) {} Default(std::unique_ptr< GridType >&& grid_ptr) : grid_(*grid_ptr) {} virtual ~Default(){} virtual GridType& grid() DS_OVERRIDE { return grid_; } virtual const GridType& grid() const DS_OVERRIDE { return grid_; } private: GridType& grid_; }; // class Default #else // HAVE_DUNE_GRID template< class GridImp > class ConstDefault { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; template< class GridImp > class Default { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; #endif // HAVE_DUNE_GRID } // namespace Providers } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH <commit_msg>[grid.provider.default] use shared_ptr as BaseType does<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH #define DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH #include <memory> #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Providers { #if HAVE_DUNE_GRID template< class GridImp > class ConstDefault : public ConstProviderInterface< GridImp > { typedef ConstProviderInterface< GridImp > BaseType; public: using typename BaseType::GridType; static const std::string static_id() { return BaseType::static_id(); } ConstDefault(const GridType& grid) : grid_(grid) {} ConstDefault(const GridType* grid_ptr) : grid_(*grid_ptr) {} ConstDefault(std::shared_ptr< const GridType > grid_ptr) : grid_(*grid_ptr) {} ConstDefault(std::unique_ptr< const GridType >&& grid_ptr) : grid_(*grid_ptr) {} virtual ~ConstDefault(){} virtual const GridType& grid() const DS_OVERRIDE { return grid_; } private: const GridType& grid_; }; // class ConstDefault template< class GridImp > class Default : public ProviderInterface< GridImp > { typedef ProviderInterface< GridImp > BaseType; public: using typename BaseType::GridType; static const std::string static_id() { return BaseType::static_id(); } Default(GridType& grid) : grid_(std::make_shared<GridType>(grid)) {} Default(GridType* grid_ptr) : grid_(std::make_shared<GridType>(*grid_ptr)) {} Default(std::shared_ptr< GridType > grid_ptr) : grid_(grid_ptr) {} Default(std::unique_ptr< GridType >&& grid_ptr) : grid_(std::make_shared(*grid_ptr)) {} virtual ~Default(){} virtual std::shared_ptr<GridType> grid() DS_OVERRIDE { return grid_; } virtual const GridType& grid() const DS_OVERRIDE { return *grid_; } private: std::shared_ptr<GridType> grid_; }; // class Default #else // HAVE_DUNE_GRID template< class GridImp > class ConstDefault { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; template< class GridImp > class Default { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; #endif // HAVE_DUNE_GRID } // namespace Providers } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_DEFAULT_HH <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2003 by Wilfried Huss * * Wilfried.Huss@gmx.at * * * * 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 <krun.h> #include <kdebug.h> #include "karambawidget.h" #include "richtextlabel.h" #include <QAbstractTextDocumentLayout> #include <QPalette> #include <QStringList> #include <QTextFrame> #include <QTextFrameFormat> #include <QTextLength> RichTextLabel::RichTextLabel(KarambaWidget* k) : Meter(k, 0, 0, 100, 100), source(""), colorGrp(k->colorGroup()), m_type(Qt::AutoText) { originalSize = QSize(0, 0); textDoc= new QTextDocument(this); textDoc->setDefaultFont(font()); textDoc->documentLayout()->setPaintDevice(this); p.begin(this); } RichTextLabel::RichTextLabel(KarambaWidget* k, int x, int y, int w, int h) : Meter(k, x, y, w, h), source(""), colorGrp(k->colorGroup()), underlineLinks(false) { kdDebug() << k_funcinfo << x << ", " << y << ", " << w << ", " << h << endl; originalSize = QSize(w, h); textDoc= new QTextDocument(this); textDoc->setDefaultFont(font()); textDoc->documentLayout()->setPaintDevice(this); p.begin(this); } RichTextLabel::~RichTextLabel() { } void RichTextLabel::setText(QString t,QString textformat) { if(textformat.toLower()=="plaintext") setTextFormat(Qt::PlainText); else if(textformat.toLower()=="richtext") setTextFormat(Qt::RichText); else if(textformat.toLower()=="autotext") { setTextFormat(Qt::AutoText); } source=t; if(t.isEmpty()) source=""; if(textFormat()==Qt::PlainText) { textDoc->setPlainText(source); } else if(textFormat()==Qt::RichText) { textDoc->setHtml(source); } else if(textFormat()==Qt::AutoText) { if(Qt::mightBeRichText(source)) textDoc->setHtml(source); else textDoc->setPlainText(source); } textDoc->setPageSize(QSizeF(width(),height()+100)); // kdDebug()<<"setText()"<< source <<"--" << textDoc->documentLayout()->documentSize().toSize() <<"--"<<textDoc->pageSize()<< endl; } void RichTextLabel::setValue(QString text) { setText(text); } void RichTextLabel::setValue(int v) { setText(QString::number(v)); } void RichTextLabel::setFontString(QString f) { setFont(QFont(f)); textDoc->setDefaultFont(font()); } void RichTextLabel::setFontSize(int size) { QFont f=font(); f.setPixelSize(size); setFont(f); textDoc->setDefaultFont(font()); // kdDebug() << "setFontSize" << size << textDoc->documentLayout()->documentSize().toSize()<<"--"<<textDoc->pageSize()<<endl; } int RichTextLabel::getFontSize() const { return font().pixelSize(); } void RichTextLabel::setFixedPitch(bool fp) { QFont f=font(); f.setFixedPitch(fp); setFont(f); textDoc->setDefaultFont(font()); } bool RichTextLabel::getFixedPitch() const { return font().fixedPitch(); } void RichTextLabel::setTextProps(TextField* t) { if(t) { setFontSize(t->getFontSize()); setFont(t->getFont()); colorGrp.setColor(QColorGroup::Text, t->getColor()); kdDebug()<< "setTextProps" << t->getFont() << t->getFontSize() << "--"<< textDoc->pageSize()<< textDoc->documentLayout()->documentSize().toSize()<<endl; } } void RichTextLabel::setWidth(int p_width) { resize(p_width,height()); kdDebug() << "setWidth" << p_width << textDoc->documentLayout()->documentSize().toSize() << "--"<<textDoc->pageSize()<< endl; // if(originalSize.height() < 1) // setHeight(text->height()); } void RichTextLabel::paintEvent(QPaintEvent* ) { #warning need to optimize this /* the setpagesize should have been set earlier, not in paintEvent() */ QPainter p(this); textDoc->setPageSize(textDoc->documentLayout()->documentSize()); QAbstractTextDocumentLayout::PaintContext pc; pc.clip=QRectF(0,0,width(),height()); pc.palette.setCurrentColorGroup(QPalette::Active); pc.palette.setActive(colorGrp); textDoc->documentLayout()->draw(&p,pc); // kdDebug() << "paintEvent" << textDoc->documentLayout()->documentSize().toSize() <<"--" <<textDoc->pageSize().toSize() << endl; } /* bool RichTextLabel::click(QMouseEvent* e) { if (hidden) { return false; } QPoint point(e->x() - getX(), e->y() - getY()); QString anchor = text->anchorAt(point); if (anchor[0] != '#') { if (e->button() == Qt::LeftButton) { KRun :: runCommand(anchor); } return false; } else { //call callback meterClicked return true; } }*/ QString RichTextLabel::anchorAt(qreal x, qreal y) { QPointF point(x , y); QString anchor = textDoc->documentLayout()->anchorAt(point); if (anchor[0] == '#') { return anchor.remove(0, 1); } else { // ASSERT: should never happen return ""; } } bool RichTextLabel::insideActiveArea(qreal x, qreal y) { QPointF point(x, y); return textDoc->documentLayout()->anchorAt(point) != ""; // && text -> inText(point); } void RichTextLabel::setColorGroup(const QColorGroup &colorg) { colorGrp = colorg; } const QColorGroup & RichTextLabel::getColorGroup() const { return colorGrp; } void RichTextLabel::updateData() { kdDebug() << "updateData" << m_format << endl; QString format = QString(m_format); QRegExp rx("([\\s]%[.\\d\\w]+[\\s])"); rx.indexIn(format); QStringList capList=rx.capturedTexts(); foreach(QString cap, capList) { QString temp=cap; temp.remove('%'); temp=temp.trimmed(); QVariant replText=decodeDot(temp); kdDebug() << cap << capList << endl; format.replace(cap,replText.toString()); } setValue(format); kdDebug() << "updateData" << format << endl; } #include "richtextlabel.moc" <commit_msg>I am fade up with RichTextLabel class. The bar example shows erratic behavour, which in just not understandable , why. It looks like loading of widgets has something to do with this. Please, if you can, fix it. Otherwise I will do later.<commit_after>/*************************************************************************** * Copyright (C) 2003 by Wilfried Huss * * Wilfried.Huss@gmx.at * * * * 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 <krun.h> #include <kdebug.h> #include "karambawidget.h" #include "richtextlabel.h" #include <QAbstractTextDocumentLayout> #include <QPalette> #include <QStringList> #include <QTextFrame> #include <QTextFrameFormat> #include <QTextLength> RichTextLabel::RichTextLabel(KarambaWidget* k) : Meter(k, 0, 0, 100, 100), source(""), colorGrp(k->colorGroup()), m_type(Qt::AutoText) { originalSize = QSize(0, 0); textDoc= new QTextDocument(this); textDoc->documentLayout()->setPaintDevice(this); p.begin(this); } RichTextLabel::RichTextLabel(KarambaWidget* k, int x, int y, int w, int h) : Meter(k, x, y, w, h), source(""), colorGrp(k->colorGroup()), underlineLinks(false) { kdDebug() << k_funcinfo << x << ", " << y << ", " << w << ", " << h << endl; originalSize = QSize(w, h); textDoc= new QTextDocument(this); textDoc->documentLayout()->setPaintDevice(this); p.begin(this); } RichTextLabel::~RichTextLabel() { } void RichTextLabel::setText(QString t,QString textformat) { if(textformat.toLower()=="plaintext") setTextFormat(Qt::PlainText); else if(textformat.toLower()=="richtext") setTextFormat(Qt::RichText); else if(textformat.toLower()=="autotext") { setTextFormat(Qt::AutoText); } source=t; if(t.isEmpty()) source=""; if(textFormat()==Qt::PlainText) { textDoc->setPlainText(source); } else if(textFormat()==Qt::RichText) { textDoc->setHtml(source); } else if(textFormat()==Qt::AutoText) { if(Qt::mightBeRichText(source)) textDoc->setHtml(source); else textDoc->setPlainText(source); } } void RichTextLabel::setValue(QString text) { setText(text); } void RichTextLabel::setValue(int v) { setText(QString::number(v)); } void RichTextLabel::setFontString(QString f) { setFont(QFont(f)); } void RichTextLabel::setFontSize(int size) { QFont f=font(); f.setPixelSize(size); setFont(f); // kdDebug() << "setFontSize" << size << textDoc->documentLayout()->documentSize().toSize()<<"--"<<textDoc->pageSize()<<endl; } int RichTextLabel::getFontSize() const { return font().pixelSize(); } void RichTextLabel::setFixedPitch(bool fp) { QFont f=font(); f.setFixedPitch(fp); setFont(f); } bool RichTextLabel::getFixedPitch() const { return font().fixedPitch(); } void RichTextLabel::setTextProps(TextField* t) { if(t) { setFontSize(t->getFontSize()); setFont(t->getFont()); colorGrp.setColor(QColorGroup::Text, t->getColor()); // kdDebug()<< "setTextProps" << t->getFont() << t->getFontSize() << "--"<< textDoc->pageSize()<< textDoc->documentLayout()->documentSize().toSize()<<endl; } } void RichTextLabel::setWidth(int p_width) { resize(p_width,height()); // kdDebug() << "setWidth" << p_width << textDoc->documentLayout()->documentSize().toSize() << "--"<<textDoc->pageSize()<< endl; // if(originalSize.height() < 1) // setHeight(text->height()); } void RichTextLabel::paintEvent(QPaintEvent* ) { #warning need to optimize this QPainter p(this); QTextBlock block = textDoc->begin(); qreal y = 0; while(block.isValid()) { QTextLayout *layout = block.layout(); layout->beginLayout(); while(1) { QTextLine line = layout->createLine(); if(!line.isValid()) { break; } line.setLineWidth(width()); line.setPosition(QPointF(line.x(), y)); y += line.height(); } layout->endLayout(); block = block.next(); } block=textDoc->begin(); QPointF posText(0,0); while(block.isValid()) { QTextLayout *layout = block.layout(); // draw text p.setBrush(colorGrp.text()); p.setPen(colorGrp.text()); layout->draw(&p, posText); block = block.next(); } } /* bool RichTextLabel::click(QMouseEvent* e) { if (hidden) { return false; } QPoint point(e->x() - getX(), e->y() - getY()); QString anchor = text->anchorAt(point); if (anchor[0] != '#') { if (e->button() == Qt::LeftButton) { KRun :: runCommand(anchor); } return false; } else { //call callback meterClicked return true; } }*/ QString RichTextLabel::anchorAt(qreal x, qreal y) { QPointF point(x , y); QString anchor = textDoc->documentLayout()->anchorAt(point); if (anchor[0] == '#') { return anchor.remove(0, 1); } else { // ASSERT: should never happen return ""; } } bool RichTextLabel::insideActiveArea(qreal x, qreal y) { QPointF point(x, y); return textDoc->documentLayout()->anchorAt(point) != ""; // && text -> inText(point); } void RichTextLabel::setColorGroup(const QColorGroup &colorg) { colorGrp = colorg; } const QColorGroup & RichTextLabel::getColorGroup() const { return colorGrp; } void RichTextLabel::updateData() { kdDebug() << "updateData" << m_format << endl; QString format = QString(m_format); QRegExp rx("([\\s]%[.\\d\\w]+[\\s])"); rx.indexIn(format); QStringList capList=rx.capturedTexts(); foreach(QString cap, capList) { QString temp=cap; temp.remove('%'); temp=temp.trimmed(); QVariant replText=decodeDot(temp); kdDebug() << cap << capList << endl; format.replace(cap,replText.toString()); } setValue(format); kdDebug() << "updateData" << format << endl; } #include "richtextlabel.moc" <|endoftext|>
<commit_before><commit_msg>Change a FAILS_ to DISABLED_, since FAILS_ doesnt help when the test crashes.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _EDTSPELL_HXX #define _EDTSPELL_HXX #include <svtools/svxbox.hxx> #include <editeng/svxenum.hxx> #include <editeng/splwrap.hxx> #include <editeng/svxacorr.hxx> #include <com/sun/star/uno/Reference.h> #include <editeng/editengdllapi.h> namespace com { namespace sun { namespace star { namespace linguistic2 { class XSpellChecker1; }}}} class EditView; class ImpEditEngine; class ContentNode; class EditSpellWrapper : public SvxSpellWrapper { private: EditView* pEditView; void CheckSpellTo(); protected: virtual void SpellStart( SvxSpellArea eArea ); virtual BOOL SpellContinue(); // Bereich pruefen virtual void ReplaceAll( const String &rNewText, INT16 nLanguage ); virtual void SpellEnd(); virtual BOOL SpellMore(); virtual BOOL HasOtherCnt(); virtual void ScrollArea(); virtual void ChangeWord( const String& rNewWord, const USHORT nLang ); virtual void ChangeThesWord( const String& rNewWord ); virtual void AutoCorrect( const String& rOldWord, const String& rNewWord ); public: EditSpellWrapper( Window* pWin, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xChecker, BOOL bIsStart, BOOL bIsAllRight, EditView* pView ); }; struct WrongRange { USHORT nStart; USHORT nEnd; WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; } }; SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 ) #define NOT_INVALID 0xFFFF class WrongList : private WrongRanges { private: USHORT nInvalidStart; USHORT nInvalidEnd; BOOL DbgIsBuggy() const; public: WrongList(); ~WrongList(); BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; } void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; } void MarkInvalid( USHORT nS, USHORT nE ); USHORT Count() const { return WrongRanges::Count(); } // Wenn man weiss was man tut: WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); } void InsertWrong( const WrongRange& rWrong, USHORT nPos ); USHORT GetInvalidStart() const { return nInvalidStart; } USHORT& GetInvalidStart() { return nInvalidStart; } USHORT GetInvalidEnd() const { return nInvalidEnd; } USHORT& GetInvalidEnd() { return nInvalidEnd; } void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep ); void TextDeleted( USHORT nPos, USHORT nChars ); void ResetRanges() { Remove( 0, Count() ); } BOOL HasWrongs() const { return Count() != 0; } void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange ); BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const; BOOL HasWrong( USHORT nStart, USHORT nEnd ) const; BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const; void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode ); void MarkWrongsInvalid(); WrongList* Clone() const; // #i102062# bool operator==(const WrongList& rCompare) const; }; inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos ) { WrongRanges::Insert( rWrong, nPos ); #ifdef DBG_UTIL DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" ); #endif } class EdtAutoCorrDoc : public SvxAutoCorrDoc { ImpEditEngine* pImpEE; ContentNode* pCurNode; USHORT nCursor; BOOL bAllowUndoAction; BOOL bUndoAction; protected: void ImplStartUndoAction(); public: EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns ); ~EdtAutoCorrDoc(); virtual BOOL Delete( USHORT nStt, USHORT nEnd ); virtual BOOL Insert( USHORT nPos, const String& rTxt ); virtual BOOL Replace( USHORT nPos, const String& rTxt ); virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& ); virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL ); virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd ); virtual const String* GetPrevPara( BOOL bAtNormalPos ); virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos, SvxAutoCorrect& rACorrect, const String** ppPara ); virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const; USHORT GetCursor() const { return nCursor; } }; #endif // EDTSPELL <commit_msg>#i115916# replacements of one character to multiple characters fixed<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _EDTSPELL_HXX #define _EDTSPELL_HXX #include <svtools/svxbox.hxx> #include <editeng/svxenum.hxx> #include <editeng/splwrap.hxx> #include <editeng/svxacorr.hxx> #include <com/sun/star/uno/Reference.h> #include <editeng/editengdllapi.h> namespace com { namespace sun { namespace star { namespace linguistic2 { class XSpellChecker1; }}}} class EditView; class ImpEditEngine; class ContentNode; class EditSpellWrapper : public SvxSpellWrapper { private: EditView* pEditView; void CheckSpellTo(); protected: virtual void SpellStart( SvxSpellArea eArea ); virtual BOOL SpellContinue(); // Bereich pruefen virtual void ReplaceAll( const String &rNewText, INT16 nLanguage ); virtual void SpellEnd(); virtual BOOL SpellMore(); virtual BOOL HasOtherCnt(); virtual void ScrollArea(); virtual void ChangeWord( const String& rNewWord, const USHORT nLang ); virtual void ChangeThesWord( const String& rNewWord ); virtual void AutoCorrect( const String& rOldWord, const String& rNewWord ); public: EditSpellWrapper( Window* pWin, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xChecker, BOOL bIsStart, BOOL bIsAllRight, EditView* pView ); }; struct WrongRange { USHORT nStart; USHORT nEnd; WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; } }; SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 ) #define NOT_INVALID 0xFFFF class WrongList : private WrongRanges { private: USHORT nInvalidStart; USHORT nInvalidEnd; BOOL DbgIsBuggy() const; public: WrongList(); ~WrongList(); BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; } void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; } void MarkInvalid( USHORT nS, USHORT nE ); USHORT Count() const { return WrongRanges::Count(); } // Wenn man weiss was man tut: WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); } void InsertWrong( const WrongRange& rWrong, USHORT nPos ); USHORT GetInvalidStart() const { return nInvalidStart; } USHORT& GetInvalidStart() { return nInvalidStart; } USHORT GetInvalidEnd() const { return nInvalidEnd; } USHORT& GetInvalidEnd() { return nInvalidEnd; } void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep ); void TextDeleted( USHORT nPos, USHORT nChars ); void ResetRanges() { Remove( 0, Count() ); } BOOL HasWrongs() const { return Count() != 0; } void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange ); BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const; BOOL HasWrong( USHORT nStart, USHORT nEnd ) const; BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const; void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode ); void MarkWrongsInvalid(); WrongList* Clone() const; // #i102062# bool operator==(const WrongList& rCompare) const; }; inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos ) { WrongRanges::Insert( rWrong, nPos ); #ifdef DBG_UTIL DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" ); #endif } class EdtAutoCorrDoc : public SvxAutoCorrDoc { ImpEditEngine* pImpEE; ContentNode* pCurNode; USHORT nCursor; BOOL bAllowUndoAction; BOOL bUndoAction; protected: void ImplStartUndoAction(); public: EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns ); ~EdtAutoCorrDoc(); virtual BOOL Delete( USHORT nStt, USHORT nEnd ); virtual BOOL Insert( USHORT nPos, const String& rTxt ); virtual BOOL Replace( USHORT nPos, const String& rTxt ); virtual BOOL ReplaceRange( xub_StrLen nPos, xub_StrLen nLen, const String& rTxt ); virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& ); virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL ); virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd ); virtual const String* GetPrevPara( BOOL bAtNormalPos ); virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos, SvxAutoCorrect& rACorrect, const String** ppPara ); virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const; USHORT GetCursor() const { return nCursor; } }; #endif // EDTSPELL <|endoftext|>
<commit_before>/* -*- indent-tabs-mode: nil -*- */ /* ODBCConnection.cpp Qore ODBC module Copyright (C) 2016 Ondrej Musil 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 "ODBCConnection.h" #include <memory> #include "qore/QoreLib.h" #include "ErrorHelper.h" #include "ODBCStatement.h" ODBCConnection::ODBCConnection(Datasource* d, ExceptionSink* xsink) : ds(d), connected(false), clientVer(0), serverVer(0) { SQLRETURN ret; // Allocate an environment handle. ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); if (!SQL_SUCCEEDED(ret)) { // error xsink->raiseException("DBI:ODBC:ENV-HANDLE-ERROR", "could not allocate an environment handle"); return; } // Use ODBC version 3. SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0); // Allocate a connection handle. ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbConn); if (!SQL_SUCCEEDED(ret)) { // error xsink->raiseException("DBI:ODBC:CONNECTION-HANDLE-ERROR", "could not allocate a connection handle"); return; } // Set connection attributes. SQLSetConnectAttr(dbConn, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER); SQLSetConnectAttr(dbConn, SQL_ATTR_QUIET_MODE, NULL, SQL_IS_POINTER); SQLSetConnectAttr(dbConn, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER)60, SQL_IS_UINTEGER); SQLSetConnectAttr(dbConn, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER)60, SQL_IS_UINTEGER); // Create ODBC connection string. QoreString connStr(QEM.findCreate("ASCII")); if(prepareConnectionString(connStr, xsink)) return; SQLCHAR* odbcDS = reinterpret_cast<SQLCHAR*>(const_cast<char*>(connStr.getBuffer())); // Connect. ret = SQLDriverConnectA(dbConn, NULL, odbcDS, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:CONNECTION-ERROR", "could not connect to the driver", xsink); return; } connected = true; // Get DBMS (server) version. char verStr[128]; // Will contain ver in the form "01.02.0034" SQLSMALLINT unused; ret = SQLGetInfoA(dbConn, SQL_DBMS_VER, verStr, 128, &unused); if (SQL_SUCCEEDED(ret)) { serverVer = parseOdbcVersion(verStr); } // Get ODBC DB driver version. ret = SQLGetInfoA(dbConn, SQL_DRIVER_VER, verStr, 128, &unused); if (SQL_SUCCEEDED(ret)) { clientVer = parseOdbcVersion(verStr); } // timezones, encoding // ??? ds->setDBEncoding("UTF-16"); } ODBCConnection::~ODBCConnection() { while (connected) { SQLRETURN ret = SQLDisconnect(dbConn); if (SQL_SUCCEEDED(ret)) break; qore_usleep(50*1000); // Sleep in intervals of 50 ms until disconnected. } // Free up allocated handles. if (dbConn != SQL_NULL_HDBC) SQLFreeHandle(SQL_HANDLE_DBC, dbConn); if (env != SQL_NULL_HENV) SQLFreeHandle(SQL_HANDLE_ENV, env); } int ODBCConnection::commit(ExceptionSink* xsink) { SQLRETURN ret = SQLEndTran(SQL_HANDLE_DBC, dbConn, SQL_COMMIT); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:COMMIT-ERROR", "could not commit the transaction", xsink); return -1; } return 0; } int ODBCConnection::rollback(ExceptionSink* xsink) { SQLRETURN ret = SQLEndTran(SQL_HANDLE_DBC, dbConn, SQL_ROLLBACK); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:ROLLBACK-ERROR", "could not rollback the transaction", xsink); return -1; } return 0; } QoreListNode* ODBCConnection::selectRows(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; return res.getOutputList(xsink); } QoreHashNode* ODBCConnection::selectRow(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; return res.getSingleRow(xsink); } AbstractQoreNode* ODBCConnection::exec(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; if (res.hasResultData()) return res.getOutputHash(xsink); return new QoreBigIntNode(res.rowsAffected()); } AbstractQoreNode* ODBCConnection::execRaw(const QoreString* qstr, ExceptionSink* xsink) { ODBCStatement res(this, xsink); // Convert string to required character encoding or copy. std::unique_ptr<QoreString> str(qstr->convertEncoding(QEM.findCreate("ASCII"), xsink)); if (!str.get()) return NULL; if (res.exec(str->getBuffer(), xsink)) return NULL; if (res.hasResultData()) return res.getOutputHash(xsink); return new QoreBigIntNode(res.rowsAffected()); } void ODBCConnection::allocStatementHandle(SQLHSTMT& stmt, ExceptionSink* xsink) { SQLRETURN ret = SQLAllocHandle(SQL_HANDLE_STMT, dbConn, &stmt); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:STATEMENT-ALLOC-ERROR", "could not allocate a statement handle", xsink); } } void ODBCConnection::handleDbcError(const char* err, const char* desc, ExceptionSink* xsink) { std::string s(desc); ErrorHelper::extractDiag(SQL_HANDLE_DBC, dbConn, s); xsink->raiseException(err, s.c_str()); } int ODBCConnection::prepareConnectionString(QoreString& str, ExceptionSink* xsink) { if (ds->getDBName() && strlen(ds->getDBName()) > 0) str.sprintf("DSN=%s;", ds->getDBName()); if (ds->getUsername()) str.sprintf("UID=%s;", ds->getUsername()); if (ds->getPassword()) str.sprintf("PWD=%s;", ds->getPassword()); ConstHashIterator hi(ds->getConnectOptions()); while (hi.next()) { const AbstractQoreNode* val = hi.getValue(); if (!val) continue; qore_type_t ntype = val->getType(); switch (ntype) { case NT_STRING: { const QoreStringNode* strNode = reinterpret_cast<const QoreStringNode*>(val); TempEncodingHelper tstr(strNode, QEM.findCreate("ASCII"), xsink); if (*xsink) return -1; std::unique_ptr<QoreString> key(hi.getKeyString()); key->tolwr(); if (key->equal("driver")) { str.sprintf("%s={%s};", hi.getKey(), tstr->getBuffer()); } else { str.sprintf("%s=%s;", hi.getKey(), tstr->getBuffer()); } break; } case NT_INT: case NT_FLOAT: case NT_NUMBER: { QoreStringValueHelper vh(val); str.sprintf("%s=%s;", hi.getKey(), vh->getBuffer()); break; } case NT_BOOLEAN: { bool b = reinterpret_cast<const QoreBoolNode*>(val)->getValue(); str.sprintf("%s=%s;", hi.getKey(), b ? "1" : "0"); break; } default: { xsink->raiseException("DBI:ODBC:OPTION-ERROR", "option values of type '%s' are not supported by the ODBC driver", val->getTypeName()); return -1; } } // switch } // while return 0; } // Version string is in the form "xx.xx.xxxx". int ODBCConnection::parseOdbcVersion(const char* str) { int major, minor, sub; major = minor = sub = 0; major += (str[0] - 48) * 10; major += str[1] - 48; minor += (str[3] - 48) * 10; minor += str[4] - 48; sub += (str[6] - 48) * 1000; sub += (str[7] - 48) * 100; sub += (str[8] - 48) * 10; sub += str[9] - 48; return major*1000000 + minor*10000 + sub; } <commit_msg>Improved error message for when the connection fails.<commit_after>/* -*- indent-tabs-mode: nil -*- */ /* ODBCConnection.cpp Qore ODBC module Copyright (C) 2016 Ondrej Musil 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 "ODBCConnection.h" #include <memory> #include "qore/QoreLib.h" #include "ErrorHelper.h" #include "ODBCStatement.h" ODBCConnection::ODBCConnection(Datasource* d, ExceptionSink* xsink) : ds(d), connected(false), clientVer(0), serverVer(0) { SQLRETURN ret; // Allocate an environment handle. ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); if (!SQL_SUCCEEDED(ret)) { // error xsink->raiseException("DBI:ODBC:ENV-HANDLE-ERROR", "could not allocate an environment handle"); return; } // Use ODBC version 3. SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0); // Allocate a connection handle. ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbConn); if (!SQL_SUCCEEDED(ret)) { // error xsink->raiseException("DBI:ODBC:CONNECTION-HANDLE-ERROR", "could not allocate a connection handle"); return; } // Set connection attributes. SQLSetConnectAttr(dbConn, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER); SQLSetConnectAttr(dbConn, SQL_ATTR_QUIET_MODE, NULL, SQL_IS_POINTER); SQLSetConnectAttr(dbConn, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER)60, SQL_IS_UINTEGER); SQLSetConnectAttr(dbConn, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER)60, SQL_IS_UINTEGER); // Create ODBC connection string. QoreString connStr(QEM.findCreate("ASCII")); if(prepareConnectionString(connStr, xsink)) return; SQLCHAR* odbcDS = reinterpret_cast<SQLCHAR*>(const_cast<char*>(connStr.getBuffer())); // Connect. ret = SQLDriverConnectA(dbConn, NULL, odbcDS, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (!SQL_SUCCEEDED(ret)) { // error std::string s("could not connect to the datasource; connection string: '%s'"); ErrorHelper::extractDiag(SQL_HANDLE_DBC, dbConn, s); xsink->raiseException("DBI:ODBC:CONNECTION-ERROR", s.c_str(), connStr.getBuffer()); return; } connected = true; // Get DBMS (server) version. char verStr[128]; // Will contain ver in the form "01.02.0034" SQLSMALLINT unused; ret = SQLGetInfoA(dbConn, SQL_DBMS_VER, verStr, 128, &unused); if (SQL_SUCCEEDED(ret)) { serverVer = parseOdbcVersion(verStr); } // Get ODBC DB driver version. ret = SQLGetInfoA(dbConn, SQL_DRIVER_VER, verStr, 128, &unused); if (SQL_SUCCEEDED(ret)) { clientVer = parseOdbcVersion(verStr); } // timezones, encoding // ??? ds->setDBEncoding("UTF-16"); } ODBCConnection::~ODBCConnection() { while (connected) { SQLRETURN ret = SQLDisconnect(dbConn); if (SQL_SUCCEEDED(ret)) break; qore_usleep(50*1000); // Sleep in intervals of 50 ms until disconnected. } // Free up allocated handles. if (dbConn != SQL_NULL_HDBC) SQLFreeHandle(SQL_HANDLE_DBC, dbConn); if (env != SQL_NULL_HENV) SQLFreeHandle(SQL_HANDLE_ENV, env); } int ODBCConnection::commit(ExceptionSink* xsink) { SQLRETURN ret = SQLEndTran(SQL_HANDLE_DBC, dbConn, SQL_COMMIT); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:COMMIT-ERROR", "could not commit the transaction", xsink); return -1; } return 0; } int ODBCConnection::rollback(ExceptionSink* xsink) { SQLRETURN ret = SQLEndTran(SQL_HANDLE_DBC, dbConn, SQL_ROLLBACK); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:ROLLBACK-ERROR", "could not rollback the transaction", xsink); return -1; } return 0; } QoreListNode* ODBCConnection::selectRows(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; return res.getOutputList(xsink); } QoreHashNode* ODBCConnection::selectRow(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; return res.getSingleRow(xsink); } AbstractQoreNode* ODBCConnection::exec(const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCStatement res(this, xsink); if (res.exec(qstr, args, xsink)) return NULL; if (res.hasResultData()) return res.getOutputHash(xsink); return new QoreBigIntNode(res.rowsAffected()); } AbstractQoreNode* ODBCConnection::execRaw(const QoreString* qstr, ExceptionSink* xsink) { ODBCStatement res(this, xsink); // Convert string to required character encoding or copy. std::unique_ptr<QoreString> str(qstr->convertEncoding(QEM.findCreate("ASCII"), xsink)); if (!str.get()) return NULL; if (res.exec(str->getBuffer(), xsink)) return NULL; if (res.hasResultData()) return res.getOutputHash(xsink); return new QoreBigIntNode(res.rowsAffected()); } void ODBCConnection::allocStatementHandle(SQLHSTMT& stmt, ExceptionSink* xsink) { SQLRETURN ret = SQLAllocHandle(SQL_HANDLE_STMT, dbConn, &stmt); if (!SQL_SUCCEEDED(ret)) { // error handleDbcError("DBI:ODBC:STATEMENT-ALLOC-ERROR", "could not allocate a statement handle", xsink); } } void ODBCConnection::handleDbcError(const char* err, const char* desc, ExceptionSink* xsink) { std::string s(desc); ErrorHelper::extractDiag(SQL_HANDLE_DBC, dbConn, s); xsink->raiseException(err, s.c_str()); } int ODBCConnection::prepareConnectionString(QoreString& str, ExceptionSink* xsink) { if (ds->getDBName() && strlen(ds->getDBName()) > 0) str.sprintf("DSN=%s;", ds->getDBName()); if (ds->getUsername()) str.sprintf("UID=%s;", ds->getUsername()); if (ds->getPassword()) str.sprintf("PWD=%s;", ds->getPassword()); ConstHashIterator hi(ds->getConnectOptions()); while (hi.next()) { const AbstractQoreNode* val = hi.getValue(); if (!val) continue; qore_type_t ntype = val->getType(); switch (ntype) { case NT_STRING: { const QoreStringNode* strNode = reinterpret_cast<const QoreStringNode*>(val); TempEncodingHelper tstr(strNode, QEM.findCreate("ASCII"), xsink); if (*xsink) return -1; std::unique_ptr<QoreString> key(hi.getKeyString()); key->tolwr(); if (key->equal("driver")) { str.sprintf("%s={%s};", hi.getKey(), tstr->getBuffer()); } else { str.sprintf("%s=%s;", hi.getKey(), tstr->getBuffer()); } break; } case NT_INT: case NT_FLOAT: case NT_NUMBER: { QoreStringValueHelper vh(val); str.sprintf("%s=%s;", hi.getKey(), vh->getBuffer()); break; } case NT_BOOLEAN: { bool b = reinterpret_cast<const QoreBoolNode*>(val)->getValue(); str.sprintf("%s=%s;", hi.getKey(), b ? "1" : "0"); break; } default: { xsink->raiseException("DBI:ODBC:OPTION-ERROR", "option values of type '%s' are not supported by the ODBC driver", val->getTypeName()); return -1; } } // switch } // while return 0; } // Version string is in the form "xx.xx.xxxx". int ODBCConnection::parseOdbcVersion(const char* str) { int major, minor, sub; major = minor = sub = 0; major += (str[0] - 48) * 10; major += str[1] - 48; minor += (str[3] - 48) * 10; minor += str[4] - 48; sub += (str[6] - 48) * 1000; sub += (str[7] - 48) * 100; sub += (str[8] - 48) * 10; sub += str[9] - 48; return major*1000000 + minor*10000 + sub; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 "assert.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/OptimizerUtils.hpp" #include "mtac/Utils.hpp" #include "mtac/Quadruple.hpp" #include "mtac/If.hpp" #include "mtac/IfFalse.hpp" using namespace eddic; void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::Quadruple> quadruple){ if(quadruple->arg1){ if(mtac::isInt(*quadruple->arg1)){ if(quadruple->op == mtac::Operator::MINUS){ replaceRight(*this, quadruple, -1 * boost::get<int>(*quadruple->arg1), mtac::Operator::ASSIGN); } else if(quadruple->op == mtac::Operator::NOT){ int lhs = boost::get<int>(*quadruple->arg1); if(lhs == 0){ replaceRight(*this, quadruple, 1, mtac::Operator::ASSIGN); } else { replaceRight(*this, quadruple, 0, mtac::Operator::ASSIGN); } } else if(quadruple->op == mtac::Operator::I2F){ replaceRight(*this, quadruple, (float) boost::get<int>(*quadruple->arg1), mtac::Operator::FASSIGN); } else if(quadruple->arg2 && mtac::isInt(*quadruple->arg2)){ int lhs = boost::get<int>(*quadruple->arg1); int rhs = boost::get<int>(*quadruple->arg2); switch(quadruple->op){ case mtac::Operator::ADD: replaceRight(*this, quadruple, lhs + rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::SUB: replaceRight(*this, quadruple, lhs - rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::MUL: replaceRight(*this, quadruple, lhs * rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::DIV: replaceRight(*this, quadruple, lhs / rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::MOD: replaceRight(*this, quadruple, lhs % rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::GREATER: replaceRight(*this, quadruple, static_cast<int>(lhs > rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::GREATER_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs >= rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::LESS: replaceRight(*this, quadruple, static_cast<int>(lhs < rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::LESS_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs <= rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs == rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::NOT_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs != rhs), mtac::Operator::ASSIGN); break; default: break; } } } else if(mtac::isFloat(*quadruple->arg1)){ if(quadruple->op == mtac::Operator::FMINUS){ replaceRight(*this, quadruple, -1 * boost::get<double>(*quadruple->arg1), mtac::Operator::FASSIGN); } else if(quadruple->op == mtac::Operator::F2I){ replaceRight(*this, quadruple, (int) boost::get<double>(*quadruple->arg1), mtac::Operator::ASSIGN); } else if(quadruple->arg2 && mtac::isInt(*quadruple->arg2)){ double lhs = boost::get<double>(*quadruple->arg1); double rhs = boost::get<double>(*quadruple->arg2); switch(quadruple->op){ case mtac::Operator::FADD: replaceRight(*this, quadruple, lhs + rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FSUB: replaceRight(*this, quadruple, lhs - rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FMUL: replaceRight(*this, quadruple, lhs * rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FDIV: replaceRight(*this, quadruple, lhs / rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FG: replaceRight(*this, quadruple, static_cast<int>(lhs > rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FGE: replaceRight(*this, quadruple, static_cast<int>(lhs >= rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FL: replaceRight(*this, quadruple, static_cast<int>(lhs < rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FLE: replaceRight(*this, quadruple, static_cast<int>(lhs <= rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FE: replaceRight(*this, quadruple, static_cast<int>(lhs == rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FNE: replaceRight(*this, quadruple, static_cast<int>(lhs != rhs), mtac::Operator::FASSIGN); break; default: break; } } } } } namespace { template<typename T> bool computeValueInt(T& if_){ int left = boost::get<int>(if_->arg1); int right = boost::get<int>(*if_->arg2); switch(*if_->op){ case mtac::BinaryOperator::EQUALS: return left == right; case mtac::BinaryOperator::NOT_EQUALS: return left != right; case mtac::BinaryOperator::LESS: return left < right; case mtac::BinaryOperator::LESS_EQUALS: return left <= right; case mtac::BinaryOperator::GREATER: return left > right; case mtac::BinaryOperator::GREATER_EQUALS: return left >= right; default: ASSERT_PATH_NOT_TAKEN("Unhandled operator"); } } template<typename T> bool computeValueFloat(T& if_){ double left = boost::get<double>(if_->arg1); double right = boost::get<double>(*if_->arg2); switch(*if_->op){ case mtac::BinaryOperator::FE: return left == right; case mtac::BinaryOperator::FNE: return left != right; case mtac::BinaryOperator::FL: return left < right; case mtac::BinaryOperator::FLE: return left <= right; case mtac::BinaryOperator::FG: return left > right; case mtac::BinaryOperator::FGE: return left >= right; default: ASSERT_PATH_NOT_TAKEN("Unhandled operator"); } } } //End of anonymous namespace void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::IfFalse> ifFalse){ if(ifFalse->op){ if(mtac::isInt(ifFalse->arg1) && mtac::isInt(*ifFalse->arg2)){ bool value = computeValueInt(ifFalse); ifFalse->op.reset(); ifFalse->arg1 = value ? 1 : 0; ifFalse->arg2.reset(); optimized = true; } else if(mtac::isFloat(ifFalse->arg1) && mtac::isFloat(*ifFalse->arg2)){ bool value = computeValueFloat(ifFalse); ifFalse->op.reset(); ifFalse->arg1 = value ? 1 : 0; ifFalse->arg2.reset(); optimized = true; } } } void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::If> if_){ if(if_->op){ if(mtac::isInt(if_->arg1) && mtac::isInt(*if_->arg2)){ bool value = computeValueInt(if_); if_->op.reset(); if_->arg1 = value ? 1 : 0; if_->arg2.reset(); optimized = true; } else if(mtac::isFloat(if_->arg1) && mtac::isFloat(*if_->arg2)){ bool value = computeValueFloat(if_); if_->op.reset(); if_->arg1 = value ? 1 : 0; if_->arg2.reset(); optimized = true; } } } <commit_msg>Fix the condition<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 "assert.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/OptimizerUtils.hpp" #include "mtac/Utils.hpp" #include "mtac/Quadruple.hpp" #include "mtac/If.hpp" #include "mtac/IfFalse.hpp" using namespace eddic; void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::Quadruple> quadruple){ if(quadruple->arg1){ if(mtac::isInt(*quadruple->arg1)){ if(quadruple->op == mtac::Operator::MINUS){ replaceRight(*this, quadruple, -1 * boost::get<int>(*quadruple->arg1), mtac::Operator::ASSIGN); } else if(quadruple->op == mtac::Operator::NOT){ int lhs = boost::get<int>(*quadruple->arg1); if(lhs == 0){ replaceRight(*this, quadruple, 1, mtac::Operator::ASSIGN); } else { replaceRight(*this, quadruple, 0, mtac::Operator::ASSIGN); } } else if(quadruple->op == mtac::Operator::I2F){ replaceRight(*this, quadruple, (float) boost::get<int>(*quadruple->arg1), mtac::Operator::FASSIGN); } else if(quadruple->arg2 && mtac::isInt(*quadruple->arg2)){ int lhs = boost::get<int>(*quadruple->arg1); int rhs = boost::get<int>(*quadruple->arg2); switch(quadruple->op){ case mtac::Operator::ADD: replaceRight(*this, quadruple, lhs + rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::SUB: replaceRight(*this, quadruple, lhs - rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::MUL: replaceRight(*this, quadruple, lhs * rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::DIV: replaceRight(*this, quadruple, lhs / rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::MOD: replaceRight(*this, quadruple, lhs % rhs, mtac::Operator::ASSIGN); break; case mtac::Operator::GREATER: replaceRight(*this, quadruple, static_cast<int>(lhs > rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::GREATER_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs >= rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::LESS: replaceRight(*this, quadruple, static_cast<int>(lhs < rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::LESS_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs <= rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs == rhs), mtac::Operator::ASSIGN); break; case mtac::Operator::NOT_EQUALS: replaceRight(*this, quadruple, static_cast<int>(lhs != rhs), mtac::Operator::ASSIGN); break; default: break; } } } else if(mtac::isFloat(*quadruple->arg1)){ if(quadruple->op == mtac::Operator::FMINUS){ replaceRight(*this, quadruple, -1 * boost::get<double>(*quadruple->arg1), mtac::Operator::FASSIGN); } else if(quadruple->op == mtac::Operator::F2I){ replaceRight(*this, quadruple, (int) boost::get<double>(*quadruple->arg1), mtac::Operator::ASSIGN); } else if(quadruple->arg2 && mtac::isFloat(*quadruple->arg2)){ double lhs = boost::get<double>(*quadruple->arg1); double rhs = boost::get<double>(*quadruple->arg2); switch(quadruple->op){ case mtac::Operator::FADD: replaceRight(*this, quadruple, lhs + rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FSUB: replaceRight(*this, quadruple, lhs - rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FMUL: replaceRight(*this, quadruple, lhs * rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FDIV: replaceRight(*this, quadruple, lhs / rhs, mtac::Operator::FASSIGN); break; case mtac::Operator::FG: replaceRight(*this, quadruple, static_cast<int>(lhs > rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FGE: replaceRight(*this, quadruple, static_cast<int>(lhs >= rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FL: replaceRight(*this, quadruple, static_cast<int>(lhs < rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FLE: replaceRight(*this, quadruple, static_cast<int>(lhs <= rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FE: replaceRight(*this, quadruple, static_cast<int>(lhs == rhs), mtac::Operator::FASSIGN); break; case mtac::Operator::FNE: replaceRight(*this, quadruple, static_cast<int>(lhs != rhs), mtac::Operator::FASSIGN); break; default: break; } } } } } namespace { template<typename T> bool computeValueInt(T& if_){ int left = boost::get<int>(if_->arg1); int right = boost::get<int>(*if_->arg2); switch(*if_->op){ case mtac::BinaryOperator::EQUALS: return left == right; case mtac::BinaryOperator::NOT_EQUALS: return left != right; case mtac::BinaryOperator::LESS: return left < right; case mtac::BinaryOperator::LESS_EQUALS: return left <= right; case mtac::BinaryOperator::GREATER: return left > right; case mtac::BinaryOperator::GREATER_EQUALS: return left >= right; default: ASSERT_PATH_NOT_TAKEN("Unhandled operator"); } } template<typename T> bool computeValueFloat(T& if_){ double left = boost::get<double>(if_->arg1); double right = boost::get<double>(*if_->arg2); switch(*if_->op){ case mtac::BinaryOperator::FE: return left == right; case mtac::BinaryOperator::FNE: return left != right; case mtac::BinaryOperator::FL: return left < right; case mtac::BinaryOperator::FLE: return left <= right; case mtac::BinaryOperator::FG: return left > right; case mtac::BinaryOperator::FGE: return left >= right; default: ASSERT_PATH_NOT_TAKEN("Unhandled operator"); } } } //End of anonymous namespace void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::IfFalse> ifFalse){ if(ifFalse->op){ if(mtac::isInt(ifFalse->arg1) && mtac::isInt(*ifFalse->arg2)){ bool value = computeValueInt(ifFalse); ifFalse->op.reset(); ifFalse->arg1 = value ? 1 : 0; ifFalse->arg2.reset(); optimized = true; } else if(mtac::isFloat(ifFalse->arg1) && mtac::isFloat(*ifFalse->arg2)){ bool value = computeValueFloat(ifFalse); ifFalse->op.reset(); ifFalse->arg1 = value ? 1 : 0; ifFalse->arg2.reset(); optimized = true; } } } void mtac::ConstantFolding::operator()(std::shared_ptr<mtac::If> if_){ if(if_->op){ if(mtac::isInt(if_->arg1) && mtac::isInt(*if_->arg2)){ bool value = computeValueInt(if_); if_->op.reset(); if_->arg1 = value ? 1 : 0; if_->arg2.reset(); optimized = true; } else if(mtac::isFloat(if_->arg1) && mtac::isFloat(*if_->arg2)){ bool value = computeValueFloat(if_); if_->op.reset(); if_->arg1 = value ? 1 : 0; if_->arg2.reset(); optimized = true; } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the $MODULE$ of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <QtTest> class tst_QTouchEventWidget : public QWidget { public: bool seenTouchBegin, seenTouchUpdate, seenTouchEnd; bool acceptTouchBegin, acceptTouchUpdate, acceptTouchEnd; tst_QTouchEventWidget() : QWidget() { reset(); } void reset() { seenTouchBegin = seenTouchUpdate = seenTouchEnd = false; acceptTouchBegin = acceptTouchUpdate = acceptTouchEnd = true; } bool event(QEvent *event) { switch (event->type()) { case QEvent::TouchBegin: if (seenTouchBegin) qWarning("TouchBegin: already seen a TouchBegin"); if (seenTouchUpdate) qWarning("TouchBegin: TouchUpdate cannot happen before TouchBegin"); if (seenTouchEnd) qWarning("TouchBegin: TouchEnd cannot happen before TouchBegin"); seenTouchBegin = !seenTouchBegin && !seenTouchUpdate && !seenTouchEnd; event->setAccepted(acceptTouchBegin); break; case QEvent::TouchUpdate: if (!seenTouchBegin) qWarning("TouchUpdate: have not seen TouchBegin"); if (seenTouchEnd) qWarning("TouchUpdate: TouchEnd cannot happen before TouchUpdate"); seenTouchUpdate = seenTouchBegin && !seenTouchEnd; event->setAccepted(acceptTouchUpdate); break; case QEvent::TouchEnd: if (!seenTouchBegin) qWarning("TouchEnd: have not seen TouchBegin"); if (seenTouchEnd) qWarning("TouchEnd: already seen a TouchEnd"); seenTouchEnd = seenTouchBegin && !seenTouchEnd; event->setAccepted(acceptTouchEnd); break; default: return QWidget::event(event); } return true; } }; class tst_QTouchEvent : public QObject { Q_OBJECT public: tst_QTouchEvent() { } ~tst_QTouchEvent() { } private slots: void touchDisabledByDefault(); void touchEventAcceptedByDefault(); void touchBeginPropagatesWhenIgnored(); }; void tst_QTouchEvent::touchDisabledByDefault() { // the widget attribute is not enabled by default QWidget widget; QVERIFY(!widget.testAttribute(Qt::WA_AcceptTouchEvents)); // events should not be accepted since they are not enabled QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&widget, &touchEvent); QVERIFY(!res); QVERIFY(!touchEvent.isAccepted()); } void tst_QTouchEvent::touchEventAcceptedByDefault() { // enabling touch events should automatically accept touch events QWidget widget; widget.setAttribute(Qt::WA_AcceptTouchEvents); // QWidget doesn't handle touch event by default, so sending it fails // (but the event is accepted) QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&widget, &touchEvent); QVERIFY(!res); QVERIFY(touchEvent.isAccepted()); // tst_QTouchEventWidget does handle, sending succeeds tst_QTouchEventWidget touchWidget; touchWidget.setAttribute(Qt::WA_AcceptTouchEvents); touchEvent.ignore(); res = QApplication::sendEvent(&touchWidget, &touchEvent); QVERIFY(res); QVERIFY(touchEvent.isAccepted()); } void tst_QTouchEvent::touchBeginPropagatesWhenIgnored() { tst_QTouchEventWidget window, child, grandchild; child.setParent(&window); grandchild.setParent(&child); // all widgets accept touch events, but window.setAttribute(Qt::WA_AcceptTouchEvents); child.setAttribute(Qt::WA_AcceptTouchEvents); grandchild.setAttribute(Qt::WA_AcceptTouchEvents); grandchild.acceptTouchBegin = false; QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&grandchild, &touchEvent); QVERIFY(res); QVERIFY(touchEvent.isAccepted()); QVERIFY(grandchild.seenTouchBegin); QVERIFY(child.seenTouchBegin); QVERIFY(!window.seenTouchBegin); } QTEST_MAIN(tst_QTouchEvent) #include "tst_qtouchevent.moc" <commit_msg>test that QEvent::TouchUpdate and TouchEnd never propagate<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the $MODULE$ of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <QtTest> class tst_QTouchEventWidget : public QWidget { public: bool seenTouchBegin, seenTouchUpdate, seenTouchEnd; bool acceptTouchBegin, acceptTouchUpdate, acceptTouchEnd; tst_QTouchEventWidget() : QWidget() { reset(); } void reset() { seenTouchBegin = seenTouchUpdate = seenTouchEnd = false; acceptTouchBegin = acceptTouchUpdate = acceptTouchEnd = true; } bool event(QEvent *event) { switch (event->type()) { case QEvent::TouchBegin: if (seenTouchBegin) qWarning("TouchBegin: already seen a TouchBegin"); if (seenTouchUpdate) qWarning("TouchBegin: TouchUpdate cannot happen before TouchBegin"); if (seenTouchEnd) qWarning("TouchBegin: TouchEnd cannot happen before TouchBegin"); seenTouchBegin = !seenTouchBegin && !seenTouchUpdate && !seenTouchEnd; event->setAccepted(acceptTouchBegin); break; case QEvent::TouchUpdate: if (!seenTouchBegin) qWarning("TouchUpdate: have not seen TouchBegin"); if (seenTouchEnd) qWarning("TouchUpdate: TouchEnd cannot happen before TouchUpdate"); seenTouchUpdate = seenTouchBegin && !seenTouchEnd; event->setAccepted(acceptTouchUpdate); break; case QEvent::TouchEnd: if (!seenTouchBegin) qWarning("TouchEnd: have not seen TouchBegin"); if (seenTouchEnd) qWarning("TouchEnd: already seen a TouchEnd"); seenTouchEnd = seenTouchBegin && !seenTouchEnd; event->setAccepted(acceptTouchEnd); break; default: return QWidget::event(event); } return true; } }; class tst_QTouchEvent : public QObject { Q_OBJECT public: tst_QTouchEvent() { } ~tst_QTouchEvent() { } private slots: void touchDisabledByDefault(); void touchEventAcceptedByDefault(); void touchBeginPropagatesWhenIgnored(); void touchUpdateAndEndNeverPropagate(); }; void tst_QTouchEvent::touchDisabledByDefault() { // the widget attribute is not enabled by default QWidget widget; QVERIFY(!widget.testAttribute(Qt::WA_AcceptTouchEvents)); // events should not be accepted since they are not enabled QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&widget, &touchEvent); QVERIFY(!res); QVERIFY(!touchEvent.isAccepted()); } void tst_QTouchEvent::touchEventAcceptedByDefault() { // enabling touch events should automatically accept touch events QWidget widget; widget.setAttribute(Qt::WA_AcceptTouchEvents); // QWidget doesn't handle touch event by default, so sending it fails // (but the event is accepted) QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&widget, &touchEvent); QVERIFY(!res); QVERIFY(touchEvent.isAccepted()); // tst_QTouchEventWidget does handle, sending succeeds tst_QTouchEventWidget touchWidget; touchWidget.setAttribute(Qt::WA_AcceptTouchEvents); touchEvent.ignore(); res = QApplication::sendEvent(&touchWidget, &touchEvent); QVERIFY(res); QVERIFY(touchEvent.isAccepted()); } void tst_QTouchEvent::touchBeginPropagatesWhenIgnored() { tst_QTouchEventWidget window, child, grandchild; child.setParent(&window); grandchild.setParent(&child); // all widgets accept touch events, grandchild ignores, so child sees the event, but not window window.setAttribute(Qt::WA_AcceptTouchEvents); child.setAttribute(Qt::WA_AcceptTouchEvents); grandchild.setAttribute(Qt::WA_AcceptTouchEvents); grandchild.acceptTouchBegin = false; QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&grandchild, &touchEvent); QVERIFY(res); QVERIFY(touchEvent.isAccepted()); QVERIFY(grandchild.seenTouchBegin); QVERIFY(child.seenTouchBegin); QVERIFY(!window.seenTouchBegin); } void tst_QTouchEvent::touchUpdateAndEndNeverPropagate() { tst_QTouchEventWidget window, child; child.setParent(&window); window.setAttribute(Qt::WA_AcceptTouchEvents); child.setAttribute(Qt::WA_AcceptTouchEvents); child.acceptTouchUpdate = false; child.acceptTouchEnd = false; QList<QTouchEvent::TouchPoint> touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); QTouchEvent touchBeginEvent(QEvent::TouchBegin, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); bool res = QApplication::sendEvent(&child, &touchBeginEvent); QVERIFY(res); QVERIFY(touchBeginEvent.isAccepted()); QVERIFY(child.seenTouchBegin); QVERIFY(!window.seenTouchBegin); // send the touch update to the child, but ignore it, it doesn't propagate QTouchEvent touchUpdateEvent(QEvent::TouchUpdate, Qt::NoModifier, Qt::TouchPointMoved, touchPoints); res = QApplication::sendEvent(&child, &touchUpdateEvent); QVERIFY(res); QVERIFY(!touchUpdateEvent.isAccepted()); QVERIFY(child.seenTouchUpdate); QVERIFY(!window.seenTouchUpdate); // send the touch end, same thing should happen as with touch update QTouchEvent touchEndEvent(QEvent::TouchEnd, Qt::NoModifier, Qt::TouchPointMoved, touchPoints); res = QApplication::sendEvent(&child, &touchEndEvent); QVERIFY(res); QVERIFY(!touchEndEvent.isAccepted()); QVERIFY(child.seenTouchEnd); QVERIFY(!window.seenTouchEnd); } QTEST_MAIN(tst_QTouchEvent) #include "tst_qtouchevent.moc" <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // Boost headers. #include "boost/static_assert.hpp" // 3ds Max headers. #include <bitmap.h> #include <iInstanceMgr.h> #include <INodeTab.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <set> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = film_width * aspect; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } params.insert("near_z", view_params.hither); asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent( max_to_as(Inverse(view_params.affineTM)))); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } bool create_mesh_object( asr::Assembly& assembly, INode* object_node, const TimeValue time, std::string& object_name) { // Compute a unique name for the instantiated object. Object* max_object = object_node->GetObjectRef(); object_name = utf8_encode(max_object->GetObjectName()); if (assembly.objects().get_by_name(object_name.c_str()) != 0) object_name = asr::make_unique_name(object_name, assembly.objects()); // Retrieve the ObjectState at the desired time. const ObjectState object_state = object_node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return false; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Make sure the input mesh has vertex normals. mesh.checkNormals(TRUE); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); object->push_vertex(asr::GVector3(v.x, v.y, v.z)); } // Copy vertex normals and triangles to mesh object. object->reserve_vertex_normals(mesh.getNumFaces() * 3); object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const DWORD face_smgroup = face.getSmGroup(); const MtlID face_mat = face.getMatID(); asf::uint32 normal_indices[3]; if (face_smgroup == 0) { // No smooth group for this face, use the face normal. const Point3& n = mesh.getFaceNormal(i); const asf::uint32 normal_index = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); normal_indices[0] = normal_index; normal_indices[1] = normal_index; normal_indices[2] = normal_index; } else { for (int j = 0; j < 3; ++j) { RVertex& rvertex = mesh.getRVert(face.getVert(j)); const size_t normal_count = rvertex.rFlags & NORCT_MASK; if (normal_count == 1) { // This vertex has a single normal. const Point3& n = rvertex.rn.getNormal(); normal_indices[j] = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); } else { // This vertex has multiple normals. for (size_t k = 0; k < normal_count; ++k) { // Find the normal for this smooth group and material. RNormal& rn = rvertex.ern[k]; if ((face_smgroup & rn.getSmGroup()) && face_mat == rn.getMtlIndex()) { const Point3& n = rn.getNormal(); normal_indices[j] = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); break; } } } } } BOOST_STATIC_ASSERT(sizeof(DWORD) == sizeof(asf::uint32)); asr::Triangle triangle; triangle.m_v0 = face.getVert(0); triangle.m_v1 = face.getVert(1); triangle.m_v2 = face.getVert(2); triangle.m_n0 = normal_indices[0]; triangle.m_n1 = normal_indices[1]; triangle.m_n2 = normal_indices[2]; triangle.m_a0 = asr::Triangle::None; triangle.m_a1 = asr::Triangle::None; triangle.m_a2 = asr::Triangle::None; object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); // todo: optimize the object. } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); return true; } void create_object_instance( asr::Assembly& assembly, INode* instance_node, const std::string& object_name, const TimeValue time) { // Compute a unique name for this instance. std::string instance_name = object_name + "_inst"; //utf8_encode(instance_node->GetName()); if (assembly.object_instances().get_by_name(instance_name.c_str()) != 0) instance_name = asr::make_unique_name(instance_name, assembly.object_instances()); // Create the instance and insert it into the assembly. const Matrix3 obj_to_world = instance_node->GetObjTMAfterWSM(time); assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent(max_to_as(obj_to_world)), asf::StringDictionary())); } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time, std::set<INode*>& visited) { // Skip nodes that we already visited as instances of other objects. if (visited.find(node) != visited.end()) return; // Collect the instances. INodeTab instances; const unsigned long instance_count = IInstanceMgr::GetInstanceMgr()->GetInstances(*node, instances); assert(instances.Count() > 0); // Mark all the instance nodes as visited. for (int i = 0, e = instances.Count(); i < e; ++i) visited.insert(instances[i]); // Create the object. std::string object_name; const bool success = create_mesh_object( assembly, instances[0], time, object_name); if (success) { // Create the instances. for (int i = 0, e = instances.Count(); i < e; ++i) { create_object_instance( assembly, instances[i], object_name, time); } } } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { std::set<INode*> visited; for (size_t i = 0, e = entities.m_objects.size(); i < e; ++i) add_object(assembly, entities.m_objects[i], time, visited); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <commit_msg>Fix object and instance names<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // Boost headers. #include "boost/static_assert.hpp" // 3ds Max headers. #include <bitmap.h> #include <iInstanceMgr.h> #include <INodeTab.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <set> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = film_width * aspect; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } params.insert("near_z", view_params.hither); asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent( max_to_as(Inverse(view_params.affineTM)))); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } bool create_mesh_object( asr::Assembly& assembly, INode* object_node, const TimeValue time, std::string& object_name) { // Compute a unique name for the instantiated object. object_name = utf8_encode(object_node->GetName()); if (assembly.objects().get_by_name(object_name.c_str()) != 0) object_name = asr::make_unique_name(object_name + "_", assembly.objects()); // Retrieve the ObjectState at the desired time. const ObjectState object_state = object_node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return false; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Make sure the input mesh has vertex normals. mesh.checkNormals(TRUE); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); object->push_vertex(asr::GVector3(v.x, v.y, v.z)); } // Copy vertex normals and triangles to mesh object. object->reserve_vertex_normals(mesh.getNumFaces() * 3); object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const DWORD face_smgroup = face.getSmGroup(); const MtlID face_mat = face.getMatID(); asf::uint32 normal_indices[3]; if (face_smgroup == 0) { // No smooth group for this face, use the face normal. const Point3& n = mesh.getFaceNormal(i); const asf::uint32 normal_index = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); normal_indices[0] = normal_index; normal_indices[1] = normal_index; normal_indices[2] = normal_index; } else { for (int j = 0; j < 3; ++j) { RVertex& rvertex = mesh.getRVert(face.getVert(j)); const size_t normal_count = rvertex.rFlags & NORCT_MASK; if (normal_count == 1) { // This vertex has a single normal. const Point3& n = rvertex.rn.getNormal(); normal_indices[j] = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); } else { // This vertex has multiple normals. for (size_t k = 0; k < normal_count; ++k) { // Find the normal for this smooth group and material. RNormal& rn = rvertex.ern[k]; if ((face_smgroup & rn.getSmGroup()) && face_mat == rn.getMtlIndex()) { const Point3& n = rn.getNormal(); normal_indices[j] = static_cast<asf::uint32>( object->push_vertex_normal(asr::GVector3(n.x, n.y, n.z))); break; } } } } } BOOST_STATIC_ASSERT(sizeof(DWORD) == sizeof(asf::uint32)); asr::Triangle triangle; triangle.m_v0 = face.getVert(0); triangle.m_v1 = face.getVert(1); triangle.m_v2 = face.getVert(2); triangle.m_n0 = normal_indices[0]; triangle.m_n1 = normal_indices[1]; triangle.m_n2 = normal_indices[2]; triangle.m_a0 = asr::Triangle::None; triangle.m_a1 = asr::Triangle::None; triangle.m_a2 = asr::Triangle::None; object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); // todo: optimize the object. } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); return true; } void create_object_instance( asr::Assembly& assembly, INode* instance_node, const std::string& object_name, const TimeValue time) { // Compute a unique name for this instance. std::string instance_name = asr::make_unique_name(object_name + "_inst", assembly.object_instances()); // Create the instance and insert it into the assembly. const Matrix3 obj_to_world = instance_node->GetObjTMAfterWSM(time); assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent(max_to_as(obj_to_world)), asf::StringDictionary())); } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time, std::set<INode*>& visited) { // Skip nodes that we already visited as instances of other objects. if (visited.find(node) != visited.end()) return; // Collect the instances. INodeTab instances; const unsigned long instance_count = IInstanceMgr::GetInstanceMgr()->GetInstances(*node, instances); assert(instances.Count() > 0); // Mark all the instance nodes as visited. for (int i = 0, e = instances.Count(); i < e; ++i) visited.insert(instances[i]); // Create the object. std::string object_name; const bool success = create_mesh_object( assembly, instances[0], time, object_name); if (success) { // Create the instances. for (int i = 0, e = instances.Count(); i < e; ++i) { create_object_instance( assembly, instances[i], object_name, time); } } } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { std::set<INode*> visited; for (size_t i = 0, e = entities.m_objects.size(); i < e; ++i) add_object(assembly, entities.m_objects[i], time, visited); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 <inttypes.h> #include "BundleCompiler.h" #include "Vector.h" #include "DynamicString.h" #include "Allocator.h" #include "OS.h" #include "Log.h" #include "Resource.h" #include "Path.h" #include "DiskFilesystem.h" #include "TempAllocator.h" namespace crown { namespace mesh_resource { extern void compile(Filesystem&, const char*, File*); } namespace texture_resource { extern void compile(Filesystem&, const char*, File*); } namespace package_resource { extern void compile(Filesystem&, const char*, File*); } namespace lua_resource { extern void compile(Filesystem&, const char*, File*); } namespace physics_resource { extern void compile(Filesystem&, const char*, File*); } namespace physics_config_resource { extern void compile(Filesystem&, const char*, File*); } namespace unit_resource { extern void compile(Filesystem&, const char*, File*); } namespace sound_resource { extern void compile(Filesystem&, const char*, File*); } namespace sprite_resource { extern void compile(Filesystem&, const char*, File*); } namespace material_resource { extern void compile(Filesystem&, const char*, File*); } namespace font_resource { extern void compile(Filesystem&, const char*, File*); } namespace level_resource { extern void compile(Filesystem&, const char*, File*); } //----------------------------------------------------------------------------- BundleCompiler::BundleCompiler() { } //----------------------------------------------------------------------------- bool BundleCompiler::compile(const char* bundle_dir, const char* source_dir, const char* resource) { Vector<DynamicString> files(default_allocator()); if (resource == NULL) { BundleCompiler::scan(source_dir, "", files); // Create bundle dir if does not exist DiskFilesystem temp; if (!temp.is_directory(bundle_dir) || !temp.is_file(bundle_dir)) { temp.create_directory(bundle_dir); } // Copy crown.config to bundle dir DiskFilesystem src_fs(source_dir); DiskFilesystem dst_fs(bundle_dir); if (src_fs.is_file("crown.config")) { File* src = src_fs.open("crown.config", FOM_READ); File* dst = dst_fs.open("crown.config", FOM_WRITE); src->copy_to(*dst, src->size()); src_fs.close(src); dst_fs.close(dst); } else { CE_LOGD("'crown.config' does not exist."); return false; } } else { DynamicString filename(default_allocator()); filename = resource; vector::push_back(files, filename); } // Compile all resources for (uint32_t i = 0; i < vector::size(files); i++) { if (files[i].ends_with(".tga")) continue; if (files[i].ends_with(".dds")) continue; if (files[i].starts_with(".")) continue; const char* filename = files[i].c_str(); char filename_extension[512]; char filename_without_extension[512]; path::extension(filename, filename_extension, 512); path::filename_without_extension(filename, filename_without_extension, 512); ResourceId name(filename_extension, filename_without_extension); char out_name[512]; snprintf(out_name, 512, "%.16lx-%.16lx", name.type, name.name); uint64_t resource_type_hash = name.type; // Skip crown.config file if (resource_type_hash == CONFIG_TYPE) { continue; } CE_LOGI("%s <= %s", out_name, filename); DiskFilesystem root_fs(source_dir); DiskFilesystem dest_fs(bundle_dir); // Open destination file File* out_file = dest_fs.open(out_name, FOM_WRITE); if (out_file) { if (resource_type_hash == MESH_TYPE) { mesh_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == TEXTURE_TYPE) { texture_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == LUA_TYPE) { lua_resource::compile(root_fs, filename, out_file); } else if(resource_type_hash == SOUND_TYPE) { sound_resource::compile(root_fs, filename, out_file); } else if(resource_type_hash == SPRITE_TYPE) { sprite_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == PACKAGE_TYPE) { package_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == UNIT_TYPE) { unit_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == PHYSICS_TYPE) { physics_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == MATERIAL_TYPE) { material_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == PHYSICS_CONFIG_TYPE) { physics_config_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == FONT_TYPE) { font_resource::compile(root_fs, filename, out_file); } else if (resource_type_hash == LEVEL_TYPE) { level_resource::compile(root_fs, filename, out_file); } else { CE_LOGE("Oops, unknown resource type!"); return false; } dest_fs.close(out_file); } } return true; } void BundleCompiler::scan(const char* source_dir, const char* cur_dir, Vector<DynamicString>& files) { Vector<DynamicString> my_files(default_allocator()); DiskFilesystem fs(source_dir); fs.list_files(cur_dir, my_files); for (uint32_t i = 0; i < vector::size(my_files); i++) { DynamicString file_i(default_allocator()); if (string::strcmp(cur_dir, "") != 0) { file_i += cur_dir; file_i += '/'; } file_i += my_files[i]; if (fs.is_directory(file_i.c_str())) { BundleCompiler::scan(source_dir, file_i.c_str(), files); } else // Assume a regular file { vector::push_back(files, file_i); } } } } // namespace crown <commit_msg>Fix resource names when compiling from 32 bit<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 "BundleCompiler.h" #include "Vector.h" #include "DynamicString.h" #include "Allocator.h" #include "OS.h" #include "Log.h" #include "Resource.h" #include "Path.h" #include "DiskFilesystem.h" #include "TempAllocator.h" #include <inttypes.h> namespace crown { namespace mesh_resource { extern void compile(Filesystem&, const char*, File*); } namespace texture_resource { extern void compile(Filesystem&, const char*, File*); } namespace package_resource { extern void compile(Filesystem&, const char*, File*); } namespace lua_resource { extern void compile(Filesystem&, const char*, File*); } namespace physics_resource { extern void compile(Filesystem&, const char*, File*); } namespace physics_config_resource { extern void compile(Filesystem&, const char*, File*); } namespace unit_resource { extern void compile(Filesystem&, const char*, File*); } namespace sound_resource { extern void compile(Filesystem&, const char*, File*); } namespace sprite_resource { extern void compile(Filesystem&, const char*, File*); } namespace material_resource { extern void compile(Filesystem&, const char*, File*); } namespace font_resource { extern void compile(Filesystem&, const char*, File*); } namespace level_resource { extern void compile(Filesystem&, const char*, File*); } //----------------------------------------------------------------------------- BundleCompiler::BundleCompiler() { } //----------------------------------------------------------------------------- bool BundleCompiler::compile(const char* bundle_dir, const char* source_dir, const char* resource) { Vector<DynamicString> files(default_allocator()); if (resource == NULL) { BundleCompiler::scan(source_dir, "", files); // Create bundle dir if does not exist DiskFilesystem temp; if (!temp.is_directory(bundle_dir) || !temp.is_file(bundle_dir)) { temp.create_directory(bundle_dir); } // Copy crown.config to bundle dir DiskFilesystem src_fs(source_dir); DiskFilesystem dst_fs(bundle_dir); if (src_fs.is_file("crown.config")) { File* src = src_fs.open("crown.config", FOM_READ); File* dst = dst_fs.open("crown.config", FOM_WRITE); src->copy_to(*dst, src->size()); src_fs.close(src); dst_fs.close(dst); } else { CE_LOGD("'crown.config' does not exist."); return false; } } else { DynamicString filename(default_allocator()); filename = resource; vector::push_back(files, filename); } // Compile all resources for (uint32_t i = 0; i < vector::size(files); i++) { if (files[i].ends_with(".tga")) continue; if (files[i].ends_with(".dds")) continue; if (files[i].starts_with(".")) continue; if (files[i].ends_with(".config")) continue; const char* filename = files[i].c_str(); char filename_extension[512]; char filename_without_extension[512]; path::extension(filename, filename_extension, 512); path::filename_without_extension(filename, filename_without_extension, 512); const ResourceId name(filename_extension, filename_without_extension); char out_name[512]; snprintf(out_name, 512, "%.16"PRIx64"-%.16"PRIx64, name.type, name.name); CE_LOGI("%s <= %s", out_name, filename); DiskFilesystem root_fs(source_dir); DiskFilesystem dest_fs(bundle_dir); // Open destination file File* out_file = dest_fs.open(out_name, FOM_WRITE); if (out_file) { if (name.type == MESH_TYPE) { mesh_resource::compile(root_fs, filename, out_file); } else if (name.type == TEXTURE_TYPE) { texture_resource::compile(root_fs, filename, out_file); } else if (name.type == LUA_TYPE) { lua_resource::compile(root_fs, filename, out_file); } else if(name.type == SOUND_TYPE) { sound_resource::compile(root_fs, filename, out_file); } else if(name.type == SPRITE_TYPE) { sprite_resource::compile(root_fs, filename, out_file); } else if (name.type == PACKAGE_TYPE) { package_resource::compile(root_fs, filename, out_file); } else if (name.type == UNIT_TYPE) { unit_resource::compile(root_fs, filename, out_file); } else if (name.type == PHYSICS_TYPE) { physics_resource::compile(root_fs, filename, out_file); } else if (name.type == MATERIAL_TYPE) { material_resource::compile(root_fs, filename, out_file); } else if (name.type == PHYSICS_CONFIG_TYPE) { physics_config_resource::compile(root_fs, filename, out_file); } else if (name.type == FONT_TYPE) { font_resource::compile(root_fs, filename, out_file); } else if (name.type == LEVEL_TYPE) { level_resource::compile(root_fs, filename, out_file); } else { CE_LOGE("Oops, unknown resource type!"); return false; } dest_fs.close(out_file); } } return true; } void BundleCompiler::scan(const char* source_dir, const char* cur_dir, Vector<DynamicString>& files) { Vector<DynamicString> my_files(default_allocator()); DiskFilesystem fs(source_dir); fs.list_files(cur_dir, my_files); for (uint32_t i = 0; i < vector::size(my_files); i++) { DynamicString file_i(default_allocator()); if (string::strcmp(cur_dir, "") != 0) { file_i += cur_dir; file_i += '/'; } file_i += my_files[i]; if (fs.is_directory(file_i.c_str())) { BundleCompiler::scan(source_dir, file_i.c_str(), files); } else // Assume a regular file { vector::push_back(files, file_i); } } } } // namespace crown <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * \file EventHandler.hxx * Interface for handling NMRAnet events. * * @author Balazs Racz * @date 29 September 2013 */ #ifndef _OPENLCB_EVENTHANDLER_HXX_ #define _OPENLCB_EVENTHANDLER_HXX_ #include <stdint.h> #include "executor/Notifiable.hxx" #include "utils/AsyncMutex.hxx" #include "utils/macros.h" #include "utils/Singleton.hxx" #include "openlcb/WriteHelper.hxx" namespace openlcb { typedef uint64_t EventId; class Node; class EventHandler; /*enum EventMask { EVENT_EXACT_MASK = 1, EVENT_ALL_MASK = 0xffffffffffffffffULL };*/ /// Shared notification structure that is assembled for each incoming /// event-related message, and passed around to all event handlers. typedef struct { /// The event ID from the incoming message. EventId event; /// Specifies the mask in case the request is for an event range. The low /// bits are set to one, the high bits are set to zero. Ranges of size 1 /// have /// mask==0, a range that covers all events has mask==0xffff...f. EventId mask; /// Information about the sender of the incoming event-related OpenLCB /// message. It is not specified whether the node_id or the alias is /// specified, but they are not both zero. NodeHandle src_node; /// nullptr for global messages; points to the specific virtual node for /// addressed events identify message. Node *dst_node; /// For producer/consumer identified messages, specifies the state of the /// producer/consumer as the sender of the message /// (valid/invalid/unknown/reserved). EventState state; /// These allow event handlers to produce up to four messages per /// invocation. They are always available at the entry to an event handler /// function. template <int N> WriteHelper *event_write_helper() { static_assert(1 <= N && N <= 4, "WriteHelper out of range."); return write_helpers + (N - 1); } private: /// Static objects usable by all event handler implementations. WriteHelper *write_helpers; } EventReport; /// Structure used in registering event handlers. class EventRegistryEntry { public: /// Stores the event ID or beginning of range for which to register the /// given handler. EventId event; /// Pointer to the handler. EventHandler *handler; /// Opaque user argument. The event handlers may use this to store /// arbitrary data. uint32_t user_arg; EventRegistryEntry(EventHandler *_handler, EventId _event) : event(_event) , handler(_handler) , user_arg(0) { } EventRegistryEntry(EventHandler *_handler, EventId _event, unsigned _user_arg) : event(_event) , handler(_handler) , user_arg(_user_arg) { } }; /// Abstract base class for all event handlers. Instances of this class can /// get registered with the event service to receive notifications of incoming /// event messages from the bus. class EventHandler { public: using EventReport = openlcb::EventReport; using EventRegistryEntry = openlcb::EventRegistryEntry; using EventId = openlcb::EventId; virtual ~EventHandler() { } /// Called on incoming EventReport messages. @param event stores /// information about the incoming message. Filled: src_node, event. Mask /// is always 1 (filled in). state is not filled in. @param registry_entry /// gives the registry entry for which the current handler is being /// called. @param done must be notified when the processing is done. virtual void handle_event_report(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending ConsumerIdentified for this event. /// @param event stores information about the incoming message. Filled: /// event_id, mask=1, src_node, state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// done must be notified when the processing is done. virtual void handle_consumer_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); }; /// Called on another node sending ConsumerRangeIdentified. @param event /// stores information about the incoming message. Filled: event id, mask /// (!= 1), src_node. Not filled: state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// done must be notified when the processing is done. virtual void handle_consumer_range_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on another node sending ProducerIdentified for this event. /// @param event stores information about the incoming message. Filled: /// event_id, mask=1, src_node, state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// user_arg is an opaque argument passed in from the registration. @param /// done must be notified when the processing is done. virtual void handle_producer_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on another node sending ProducerRangeIdentified for this /// event. @param event stores information about the incoming /// message. Filled: event id, mask (!= 1), src_node. Not filled: state. /// @param registry_entry gives the registry entry for which the current /// handler is being called. @param done must be notified when the /// processing is done. virtual void handle_producer_range_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on the need of sending out identification messages. @param event /// is NULL. This happens on startup, or when a global or addressed /// IdentifyGlobal message arrives. Might have destination node id! @param /// registry_entry gives the registry entry for which the current handler /// is being called. @param done must be notified when the processing is /// done. virtual void handle_identify_global(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending IdentifyConsumer. @param event stores /// information about the incoming message. Filled: src_node, event, /// mask=1. Not filled: state. @param registry_entry gives the registry /// entry for which the current handler is being called. @param done must /// be notified when the processing is done. virtual void handle_identify_consumer(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending IdentifyProducer. @param event stores /// information about the incoming message. Filled: src_node, event, /// mask=1. Not filled: state. @param registry_entry gives the registry /// entry for which the current handler is being called. @param done must /// be notified when the processing is done. virtual void handle_identify_producer(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; }; typedef void (EventHandler::*EventHandlerFunction)( const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done); class EventIterator; /// Global static object for registering event handlers. /// /// Usage: create one of the implementation classes depending on the resource /// requirements of your binary. In the event handlers constructor, register /// the event handler via the singleton pointer. /// class EventRegistry : public Singleton<EventRegistry> { public: virtual ~EventRegistry(); /** Computes the alignment mask for registering an event range. Updates the * event by rounding and returns the mask value to be sent to the * register_handler function. * @param event is the event id to be registered. Will be modified. * @param size is the number of events to register from that offset. [event, * event+size) will be the registration range. */ static unsigned align_mask(EventId *event, unsigned size); /// Adds a new event handler to the registry. virtual void register_handler(const EventRegistryEntry &entry, unsigned mask) = 0; /// Removes all registered instances of a given event handler pointer. virtual void unregister_handler(EventHandler *handler) = 0; /// Creates a new event iterator. Caller takes ownership of object. virtual EventIterator *create_iterator() = 0; /// Returns a monotonically increasing number that will change every time /// the set of registered event handlers change. Whenever this number /// changes, the iterators are invalidated and must be cleared. unsigned get_epoch() { return dirtyCounter_; } protected: EventRegistry(); /// Implementations must call this function from register and unregister /// handler to mark iterators being invalidated. void set_dirty() { ++dirtyCounter_; } private: static EventRegistry *instance_; /// This counter will be incremented every time the set of event handlers /// change (and thus the event iterators are invalidated). unsigned dirtyCounter_ = 0; DISALLOW_COPY_AND_ASSIGN(EventRegistry); }; }; /* namespace openlcb */ #endif // _OPENLCB_EVENTHANDLER_HXX_ <commit_msg>Adds the event write helpers to be owned by the EventReport structure. Restricts creation rights of the EventReport structure because it is now costly in terms of RAM.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * \file EventHandler.hxx * Interface for handling NMRAnet events. * * @author Balazs Racz * @date 29 September 2013 */ #ifndef _OPENLCB_EVENTHANDLER_HXX_ #define _OPENLCB_EVENTHANDLER_HXX_ #include <stdint.h> #include "executor/Notifiable.hxx" #include "utils/AsyncMutex.hxx" #include "utils/macros.h" #include "utils/Singleton.hxx" #include "openlcb/WriteHelper.hxx" namespace openlcb { typedef uint64_t EventId; class Node; class EventHandler; /*enum EventMask { EVENT_EXACT_MASK = 1, EVENT_ALL_MASK = 0xffffffffffffffffULL };*/ /// Shared notification structure that is assembled for each incoming /// event-related message, and passed around to all event handlers. struct EventReport { /// The event ID from the incoming message. EventId event; /// Specifies the mask in case the request is for an event range. The low /// bits are set to one, the high bits are set to zero. Ranges of size 1 /// have /// mask==0, a range that covers all events has mask==0xffff...f. EventId mask; /// Information about the sender of the incoming event-related OpenLCB /// message. It is not specified whether the node_id or the alias is /// specified, but they are not both zero. NodeHandle src_node; /// nullptr for global messages; points to the specific virtual node for /// addressed events identify message. Node *dst_node; /// For producer/consumer identified messages, specifies the state of the /// producer/consumer as the sender of the message /// (valid/invalid/unknown/reserved). EventState state; /// These allow event handlers to produce up to four messages per /// invocation. They are always available at the entry to an event handler /// function. template <int N> WriteHelper *event_write_helper() { static_assert(1 <= N && N <= 4, "WriteHelper out of range."); return write_helpers + (N - 1); } private: /// Constrained access to the constructors. We do this because the /// EventReport structure is pretty expensive due to the statically /// allocated memory of the write helpers. Only the EventIteratorFlow /// should have objects of this type. EventReport() {} friend class EventIteratorFlow; /// Static objects usable by all event handler implementations. WriteHelper write_helpers[4]; }; /// Structure used in registering event handlers. class EventRegistryEntry { public: /// Stores the event ID or beginning of range for which to register the /// given handler. EventId event; /// Pointer to the handler. EventHandler *handler; /// Opaque user argument. The event handlers may use this to store /// arbitrary data. uint32_t user_arg; EventRegistryEntry(EventHandler *_handler, EventId _event) : event(_event) , handler(_handler) , user_arg(0) { } EventRegistryEntry(EventHandler *_handler, EventId _event, unsigned _user_arg) : event(_event) , handler(_handler) , user_arg(_user_arg) { } }; /// Abstract base class for all event handlers. Instances of this class can /// get registered with the event service to receive notifications of incoming /// event messages from the bus. class EventHandler { public: using EventReport = openlcb::EventReport; using EventRegistryEntry = openlcb::EventRegistryEntry; using EventId = openlcb::EventId; virtual ~EventHandler() { } /// Called on incoming EventReport messages. @param event stores /// information about the incoming message. Filled: src_node, event. Mask /// is always 1 (filled in). state is not filled in. @param registry_entry /// gives the registry entry for which the current handler is being /// called. @param done must be notified when the processing is done. virtual void handle_event_report(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending ConsumerIdentified for this event. /// @param event stores information about the incoming message. Filled: /// event_id, mask=1, src_node, state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// done must be notified when the processing is done. virtual void handle_consumer_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); }; /// Called on another node sending ConsumerRangeIdentified. @param event /// stores information about the incoming message. Filled: event id, mask /// (!= 1), src_node. Not filled: state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// done must be notified when the processing is done. virtual void handle_consumer_range_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on another node sending ProducerIdentified for this event. /// @param event stores information about the incoming message. Filled: /// event_id, mask=1, src_node, state. @param registry_entry gives the /// registry entry for which the current handler is being called. @param /// user_arg is an opaque argument passed in from the registration. @param /// done must be notified when the processing is done. virtual void handle_producer_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on another node sending ProducerRangeIdentified for this /// event. @param event stores information about the incoming /// message. Filled: event id, mask (!= 1), src_node. Not filled: state. /// @param registry_entry gives the registry entry for which the current /// handler is being called. @param done must be notified when the /// processing is done. virtual void handle_producer_range_identified(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { done->notify(); } /// Called on the need of sending out identification messages. @param event /// is NULL. This happens on startup, or when a global or addressed /// IdentifyGlobal message arrives. Might have destination node id! @param /// registry_entry gives the registry entry for which the current handler /// is being called. @param done must be notified when the processing is /// done. virtual void handle_identify_global(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending IdentifyConsumer. @param event stores /// information about the incoming message. Filled: src_node, event, /// mask=1. Not filled: state. @param registry_entry gives the registry /// entry for which the current handler is being called. @param done must /// be notified when the processing is done. virtual void handle_identify_consumer(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; /// Called on another node sending IdentifyProducer. @param event stores /// information about the incoming message. Filled: src_node, event, /// mask=1. Not filled: state. @param registry_entry gives the registry /// entry for which the current handler is being called. @param done must /// be notified when the processing is done. virtual void handle_identify_producer(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) = 0; }; typedef void (EventHandler::*EventHandlerFunction)( const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done); class EventIterator; /// Global static object for registering event handlers. /// /// Usage: create one of the implementation classes depending on the resource /// requirements of your binary. In the event handlers constructor, register /// the event handler via the singleton pointer. /// class EventRegistry : public Singleton<EventRegistry> { public: virtual ~EventRegistry(); /** Computes the alignment mask for registering an event range. Updates the * event by rounding and returns the mask value to be sent to the * register_handler function. * @param event is the event id to be registered. Will be modified. * @param size is the number of events to register from that offset. [event, * event+size) will be the registration range. */ static unsigned align_mask(EventId *event, unsigned size); /// Adds a new event handler to the registry. virtual void register_handler(const EventRegistryEntry &entry, unsigned mask) = 0; /// Removes all registered instances of a given event handler pointer. virtual void unregister_handler(EventHandler *handler) = 0; /// Creates a new event iterator. Caller takes ownership of object. virtual EventIterator *create_iterator() = 0; /// Returns a monotonically increasing number that will change every time /// the set of registered event handlers change. Whenever this number /// changes, the iterators are invalidated and must be cleared. unsigned get_epoch() { return dirtyCounter_; } protected: EventRegistry(); /// Implementations must call this function from register and unregister /// handler to mark iterators being invalidated. void set_dirty() { ++dirtyCounter_; } private: static EventRegistry *instance_; /// This counter will be incremented every time the set of event handlers /// change (and thus the event iterators are invalidated). unsigned dirtyCounter_ = 0; DISALLOW_COPY_AND_ASSIGN(EventRegistry); }; }; /* namespace openlcb */ #endif // _OPENLCB_EVENTHANDLER_HXX_ <|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 "TkoTracker.h" #include <cassert> #include <functional> #include <unordered_map> #include <folly/MapUtil.h> #include "mcrouter/ProxyDestinationBase.h" #include "mcrouter/TkoCounters.h" #include "mcrouter/lib/network/AccessPoint.h" namespace facebook { namespace memcache { namespace mcrouter { std::pair<bool, bool> PoolTkoTracker::incNumDestinationsSoftTko() { if (failOpen_) { return {failOpen_, false}; } auto& curVal = numDestinationsSoftTko_; size_t oldVal = curVal; bool stateChanged = false; do { if (oldVal == failOpenEnterNumSoftTkos_) { failOpen_ = true; stateChanged = true; break; } } while (!numDestinationsSoftTko_.compare_exchange_weak(oldVal, oldVal + 1)); return {failOpen_, stateChanged}; } bool PoolTkoTracker::decNumDestinationsSoftTko() { auto& curVal = numDestinationsSoftTko_; size_t oldVal = curVal; do { if (failOpen_ && oldVal == failOpenExitNumSoftTkos_) { failOpen_ = false; return true; } } while (!numDestinationsSoftTko_.compare_exchange_weak(oldVal, oldVal - 1)); return false; } TkoTracker::TkoTracker(size_t tkoThreshold, TkoTrackerMap& trackerMap) : tkoThreshold_(tkoThreshold), trackerMap_(trackerMap) {} bool TkoTracker::isHardTko() const { uintptr_t curSumFailures = sumFailures_; return (curSumFailures > tkoThreshold_ && curSumFailures % 2 == 1); } bool TkoTracker::isSoftTko() const { uintptr_t curSumFailures = sumFailures_; return (curSumFailures > tkoThreshold_ && curSumFailures % 2 == 0); } const TkoCounters& TkoTracker::globalTkos() const { return trackerMap_.globalTkos_; } bool TkoTracker::incrementSoftTkoCount(ProxyDestinationBase* pdstn) { if (poolTracker_) { auto result = poolTracker_->incNumDestinationsSoftTko(); if (result.first) { if (result.second) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::ENTER_FAIL_OPEN); } return false; } } trackerMap_.globalTkos_.softTkos++; if (poolTracker_) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::INC_SOFT_TKOS); } return true; } void TkoTracker::decrementSoftTkoCount(ProxyDestinationBase* pdstn) { // Decrement the counter and ensure we haven't gone below 0 size_t oldSoftTkos = trackerMap_.globalTkos_.softTkos.fetch_sub(1); (void)oldSoftTkos; assert(oldSoftTkos != 0); if (poolTracker_) { if (poolTracker_->decNumDestinationsSoftTko()) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::EXIT_FAIL_OPEN); } pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::DEC_SOFT_TKOS); } } bool TkoTracker::setSumFailures(uintptr_t value) { uintptr_t curSumFailures = sumFailures_; do { /* If the destination is TKO but we're not responsible we can't change state, so return. */ if (curSumFailures > tkoThreshold_) { return false; } } while (!sumFailures_.compare_exchange_weak(curSumFailures, value)); return true; } bool TkoTracker::recordSoftFailure( ProxyDestinationBase* pdstn, carbon::Result result) { // We increment soft tko count first before actually taking responsibility // for the TKO. This means we run the risk that multiple proxies // increment the count for the same destination, causing us to be overly // conservative. Eventually this will get corrected, as only one proxy can // ever mark it TKO, but we may be inconsistent for a very short time. ++consecutiveFailureCount_; // If host is in any state of TKO, we just leave it alone if (isTko()) { return false; } uintptr_t curSumFailures = sumFailures_; uintptr_t value = 0; uintptr_t pdstnAddr = reinterpret_cast<uintptr_t>(pdstn); do { // If we're one failure below the limit, we're about to enter softTKO if (curSumFailures == tkoThreshold_ - 1) { // Note: we need to check value to ensure we didn't already increment // the counter in a previous iteration // If the fail-open state has entered, exit without making the // pdstn as soft tko if (value != pdstnAddr && !incrementSoftTkoCount(pdstn)) { return false; } value = pdstnAddr; } else { if (value == pdstnAddr) { // a previous loop iteration attempted to soft TKO the box, // so we need to undo that decrementSoftTkoCount(pdstn); } // Someone else is responsible, so quit if (curSumFailures > tkoThreshold_) { return false; } else { value = curSumFailures + 1; } } } while (!sumFailures_.compare_exchange_weak(curSumFailures, value)); if (value == pdstnAddr) { tkoReason_.store(result, std::memory_order_relaxed); return true; } return false; } bool TkoTracker::recordHardFailure( ProxyDestinationBase* pdstn, carbon::Result result) { ++consecutiveFailureCount_; if (isHardTko()) { return false; } // If we were already TKO and responsible, but not hard TKO, it means we were // in soft TKO before. We need decrement the counter and convert to hard // TKO if (isResponsible(pdstn)) { // convert to hard failure sumFailures_ |= 1; decrementSoftTkoCount(pdstn); ++trackerMap_.globalTkos_.hardTkos; // We've already been marked responsible return false; } // If the call below succeeds we marked the box TKO and took responsibility. bool success = setSumFailures(reinterpret_cast<uintptr_t>(pdstn) | 1); if (success) { ++trackerMap_.globalTkos_.hardTkos; tkoReason_.store(result, std::memory_order_relaxed); } return success; } bool TkoTracker::isResponsible(ProxyDestinationBase* pdstn) const { return (sumFailures_ & ~1) == reinterpret_cast<uintptr_t>(pdstn); } bool TkoTracker::recordSuccess(ProxyDestinationBase* pdstn) { // If we're responsible, no one else can change any state and we're // effectively under mutex. if (isResponsible(pdstn)) { // Coming out of TKO, we need to decrement counters if (isSoftTko()) { decrementSoftTkoCount(pdstn); } if (isHardTko()) { --trackerMap_.globalTkos_.hardTkos; } sumFailures_ = 0; consecutiveFailureCount_ = 0; tkoReason_.store(carbon::Result::UNKNOWN, std::memory_order_relaxed); return true; } // Skip resetting failures if the counter is at zero. // If an error races here and increments the counter, // we can pretend this success happened before the error, // and the state is consistent. // If we don't skip here we end up doing CAS on a shared state // every single request. if (sumFailures_ != 0 && setSumFailures(0)) { consecutiveFailureCount_ = 0; } return false; } bool TkoTracker::removeDestination(ProxyDestinationBase* pdstn) { // We should clear the TKO state if pdstn is responsible if (isResponsible(pdstn)) { return recordSuccess(pdstn); } return false; } TkoTracker::~TkoTracker() { trackerMap_.removeTracker(key_); } std::shared_ptr<PoolTkoTracker> TkoTrackerMap::createPoolTkoTracker( std::string poolName, uint32_t numEnterSoftTkos, uint32_t numExitSoftTkos) { std::shared_ptr<PoolTkoTracker> poolTracker; std::lock_guard<std::mutex> lock(mx_); auto it = poolTrackers_.find(poolName); if (it == poolTrackers_.end() || (poolTracker = it->second.lock()) == nullptr) { poolTracker.reset(new PoolTkoTracker(numEnterSoftTkos, numExitSoftTkos)); auto trackerIt = poolTrackers_.emplace(poolName, poolTracker); if (!trackerIt.second) { trackerIt.first->second = poolTracker; } } return poolTracker; } void TkoTrackerMap::updateTracker( ProxyDestinationBase& pdstn, const size_t tkoThreshold, const std::shared_ptr<PoolTkoTracker>& poolTkoTracker) { auto key = pdstn.accessPoint()->toHostPortString(); // This shared pointer has to be destroyed after releasing "mx_". // The reason is that when "tracker" goes out of scope, we might destroy // the TkoTracker it points to, which would again try to lock "mx_" // (triggering an UB). std::shared_ptr<TkoTracker> tracker; { std::lock_guard<std::mutex> lock(mx_); auto it = trackers_.find(key); if (it == trackers_.end() || (tracker = it->second.lock()) == nullptr) { tracker.reset(new TkoTracker(tkoThreshold, *this)); auto trackerIt = trackers_.emplace(key, tracker); if (!trackerIt.second) { trackerIt.first->second = tracker; } tracker->key_ = trackerIt.first->first; } } if (poolTkoTracker) { tracker->setPoolTracker(poolTkoTracker); } pdstn.setTracker(std::move(tracker)); } std::unordered_map<std::string, std::pair<bool, size_t>> TkoTrackerMap::getSuspectServers() const { std::unordered_map<std::string, std::pair<bool, size_t>> result; foreachTkoTracker( [&result](folly::StringPiece key, const TkoTracker& tracker) mutable { auto failures = tracker.consecutiveFailureCount(); if (failures > 0) { result.emplace(key.str(), std::make_pair(tracker.isTko(), failures)); } }); return result; } size_t TkoTrackerMap::getSuspectServersCount() const { size_t result = 0; foreachTkoTracker( [&result](folly::StringPiece, const TkoTracker& tracker) mutable { if (tracker.consecutiveFailureCount() > 0) { ++result; } }); return result; } void TkoTrackerMap::foreachTkoTracker( std::function<void(folly::StringPiece, const TkoTracker&)> func) const { // We allocate a vector to delay the desctruction of TkoTrackers until after // we release the lock. This is done to avoid the following race: // After successfully locking the weak_ptr, we might become the last // holder of the shared_ptr to TkoTracker. If that's the case, it would // trigger destruction of TkoTracker, which would try to grab "mx_" and // remove itself from the map. // If we didn't have the lock, this would case two issues: // - We would try to lock "mx_" again from the same thread (which is UB). // - We would change "trackers_" while iterating over it. std::vector<std::shared_ptr<TkoTracker>> lockedTrackers; lockedTrackers.reserve(trackers_.size()); { std::lock_guard<std::mutex> lock(mx_); for (const auto& it : trackers_) { if (auto tracker = it.second.lock()) { func(it.first, *tracker); lockedTrackers.emplace_back(std::move(tracker)); } } } } void TkoTrackerMap::removeTracker(folly::StringPiece key) noexcept { std::lock_guard<std::mutex> lock(mx_); auto it = trackers_.find(key); if (it != trackers_.end()) { trackers_.erase(it); } } } // namespace mcrouter } // namespace memcache } // namespace facebook <commit_msg>Obtain a short-lived lock when trying to preallocate TKO trackers vector<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 "TkoTracker.h" #include <cassert> #include <functional> #include <unordered_map> #include <folly/MapUtil.h> #include "mcrouter/ProxyDestinationBase.h" #include "mcrouter/TkoCounters.h" #include "mcrouter/lib/network/AccessPoint.h" namespace facebook { namespace memcache { namespace mcrouter { std::pair<bool, bool> PoolTkoTracker::incNumDestinationsSoftTko() { if (failOpen_) { return {failOpen_, false}; } auto& curVal = numDestinationsSoftTko_; size_t oldVal = curVal; bool stateChanged = false; do { if (oldVal == failOpenEnterNumSoftTkos_) { failOpen_ = true; stateChanged = true; break; } } while (!numDestinationsSoftTko_.compare_exchange_weak(oldVal, oldVal + 1)); return {failOpen_, stateChanged}; } bool PoolTkoTracker::decNumDestinationsSoftTko() { auto& curVal = numDestinationsSoftTko_; size_t oldVal = curVal; do { if (failOpen_ && oldVal == failOpenExitNumSoftTkos_) { failOpen_ = false; return true; } } while (!numDestinationsSoftTko_.compare_exchange_weak(oldVal, oldVal - 1)); return false; } TkoTracker::TkoTracker(size_t tkoThreshold, TkoTrackerMap& trackerMap) : tkoThreshold_(tkoThreshold), trackerMap_(trackerMap) {} bool TkoTracker::isHardTko() const { uintptr_t curSumFailures = sumFailures_; return (curSumFailures > tkoThreshold_ && curSumFailures % 2 == 1); } bool TkoTracker::isSoftTko() const { uintptr_t curSumFailures = sumFailures_; return (curSumFailures > tkoThreshold_ && curSumFailures % 2 == 0); } const TkoCounters& TkoTracker::globalTkos() const { return trackerMap_.globalTkos_; } bool TkoTracker::incrementSoftTkoCount(ProxyDestinationBase* pdstn) { if (poolTracker_) { auto result = poolTracker_->incNumDestinationsSoftTko(); if (result.first) { if (result.second) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::ENTER_FAIL_OPEN); } return false; } } trackerMap_.globalTkos_.softTkos++; if (poolTracker_) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::INC_SOFT_TKOS); } return true; } void TkoTracker::decrementSoftTkoCount(ProxyDestinationBase* pdstn) { // Decrement the counter and ensure we haven't gone below 0 size_t oldSoftTkos = trackerMap_.globalTkos_.softTkos.fetch_sub(1); (void)oldSoftTkos; assert(oldSoftTkos != 0); if (poolTracker_) { if (poolTracker_->decNumDestinationsSoftTko()) { pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::EXIT_FAIL_OPEN); } pdstn->updateSoftTkoStats(GlobalSoftTkoUpdateType::DEC_SOFT_TKOS); } } bool TkoTracker::setSumFailures(uintptr_t value) { uintptr_t curSumFailures = sumFailures_; do { /* If the destination is TKO but we're not responsible we can't change state, so return. */ if (curSumFailures > tkoThreshold_) { return false; } } while (!sumFailures_.compare_exchange_weak(curSumFailures, value)); return true; } bool TkoTracker::recordSoftFailure( ProxyDestinationBase* pdstn, carbon::Result result) { // We increment soft tko count first before actually taking responsibility // for the TKO. This means we run the risk that multiple proxies // increment the count for the same destination, causing us to be overly // conservative. Eventually this will get corrected, as only one proxy can // ever mark it TKO, but we may be inconsistent for a very short time. ++consecutiveFailureCount_; // If host is in any state of TKO, we just leave it alone if (isTko()) { return false; } uintptr_t curSumFailures = sumFailures_; uintptr_t value = 0; uintptr_t pdstnAddr = reinterpret_cast<uintptr_t>(pdstn); do { // If we're one failure below the limit, we're about to enter softTKO if (curSumFailures == tkoThreshold_ - 1) { // Note: we need to check value to ensure we didn't already increment // the counter in a previous iteration // If the fail-open state has entered, exit without making the // pdstn as soft tko if (value != pdstnAddr && !incrementSoftTkoCount(pdstn)) { return false; } value = pdstnAddr; } else { if (value == pdstnAddr) { // a previous loop iteration attempted to soft TKO the box, // so we need to undo that decrementSoftTkoCount(pdstn); } // Someone else is responsible, so quit if (curSumFailures > tkoThreshold_) { return false; } else { value = curSumFailures + 1; } } } while (!sumFailures_.compare_exchange_weak(curSumFailures, value)); if (value == pdstnAddr) { tkoReason_.store(result, std::memory_order_relaxed); return true; } return false; } bool TkoTracker::recordHardFailure( ProxyDestinationBase* pdstn, carbon::Result result) { ++consecutiveFailureCount_; if (isHardTko()) { return false; } // If we were already TKO and responsible, but not hard TKO, it means we were // in soft TKO before. We need decrement the counter and convert to hard // TKO if (isResponsible(pdstn)) { // convert to hard failure sumFailures_ |= 1; decrementSoftTkoCount(pdstn); ++trackerMap_.globalTkos_.hardTkos; // We've already been marked responsible return false; } // If the call below succeeds we marked the box TKO and took responsibility. bool success = setSumFailures(reinterpret_cast<uintptr_t>(pdstn) | 1); if (success) { ++trackerMap_.globalTkos_.hardTkos; tkoReason_.store(result, std::memory_order_relaxed); } return success; } bool TkoTracker::isResponsible(ProxyDestinationBase* pdstn) const { return (sumFailures_ & ~1) == reinterpret_cast<uintptr_t>(pdstn); } bool TkoTracker::recordSuccess(ProxyDestinationBase* pdstn) { // If we're responsible, no one else can change any state and we're // effectively under mutex. if (isResponsible(pdstn)) { // Coming out of TKO, we need to decrement counters if (isSoftTko()) { decrementSoftTkoCount(pdstn); } if (isHardTko()) { --trackerMap_.globalTkos_.hardTkos; } sumFailures_ = 0; consecutiveFailureCount_ = 0; tkoReason_.store(carbon::Result::UNKNOWN, std::memory_order_relaxed); return true; } // Skip resetting failures if the counter is at zero. // If an error races here and increments the counter, // we can pretend this success happened before the error, // and the state is consistent. // If we don't skip here we end up doing CAS on a shared state // every single request. if (sumFailures_ != 0 && setSumFailures(0)) { consecutiveFailureCount_ = 0; } return false; } bool TkoTracker::removeDestination(ProxyDestinationBase* pdstn) { // We should clear the TKO state if pdstn is responsible if (isResponsible(pdstn)) { return recordSuccess(pdstn); } return false; } TkoTracker::~TkoTracker() { trackerMap_.removeTracker(key_); } std::shared_ptr<PoolTkoTracker> TkoTrackerMap::createPoolTkoTracker( std::string poolName, uint32_t numEnterSoftTkos, uint32_t numExitSoftTkos) { std::shared_ptr<PoolTkoTracker> poolTracker; std::lock_guard<std::mutex> lock(mx_); auto it = poolTrackers_.find(poolName); if (it == poolTrackers_.end() || (poolTracker = it->second.lock()) == nullptr) { poolTracker.reset(new PoolTkoTracker(numEnterSoftTkos, numExitSoftTkos)); auto trackerIt = poolTrackers_.emplace(poolName, poolTracker); if (!trackerIt.second) { trackerIt.first->second = poolTracker; } } return poolTracker; } void TkoTrackerMap::updateTracker( ProxyDestinationBase& pdstn, const size_t tkoThreshold, const std::shared_ptr<PoolTkoTracker>& poolTkoTracker) { auto key = pdstn.accessPoint()->toHostPortString(); // This shared pointer has to be destroyed after releasing "mx_". // The reason is that when "tracker" goes out of scope, we might destroy // the TkoTracker it points to, which would again try to lock "mx_" // (triggering an UB). std::shared_ptr<TkoTracker> tracker; { std::lock_guard<std::mutex> lock(mx_); auto it = trackers_.find(key); if (it == trackers_.end() || (tracker = it->second.lock()) == nullptr) { tracker.reset(new TkoTracker(tkoThreshold, *this)); auto trackerIt = trackers_.emplace(key, tracker); if (!trackerIt.second) { trackerIt.first->second = tracker; } tracker->key_ = trackerIt.first->first; } } if (poolTkoTracker) { tracker->setPoolTracker(poolTkoTracker); } pdstn.setTracker(std::move(tracker)); } std::unordered_map<std::string, std::pair<bool, size_t>> TkoTrackerMap::getSuspectServers() const { std::unordered_map<std::string, std::pair<bool, size_t>> result; foreachTkoTracker( [&result](folly::StringPiece key, const TkoTracker& tracker) mutable { auto failures = tracker.consecutiveFailureCount(); if (failures > 0) { result.emplace(key.str(), std::make_pair(tracker.isTko(), failures)); } }); return result; } size_t TkoTrackerMap::getSuspectServersCount() const { size_t result = 0; foreachTkoTracker( [&result](folly::StringPiece, const TkoTracker& tracker) mutable { if (tracker.consecutiveFailureCount() > 0) { ++result; } }); return result; } void TkoTrackerMap::foreachTkoTracker( std::function<void(folly::StringPiece, const TkoTracker&)> func) const { // We allocate a vector to delay the desctruction of TkoTrackers until after // we release the lock. This is done to avoid the following race: // After successfully locking the weak_ptr, we might become the last // holder of the shared_ptr to TkoTracker. If that's the case, it would // trigger destruction of TkoTracker, which would try to grab "mx_" and // remove itself from the map. // If we didn't have the lock, this would case two issues: // - We would try to lock "mx_" again from the same thread (which is UB). // - We would change "trackers_" while iterating over it. std::vector<std::shared_ptr<TkoTracker>> lockedTrackers; // Preallocate lockedTrackers decltype(lockedTrackers)::size_type trackersCount; { std::lock_guard<std::mutex> lock(mx_); trackersCount = trackers_.size(); } lockedTrackers.reserve(trackersCount); { std::lock_guard<std::mutex> lock(mx_); for (const auto& it : trackers_) { if (auto tracker = it.second.lock()) { func(it.first, *tracker); lockedTrackers.emplace_back(std::move(tracker)); } } } } void TkoTrackerMap::removeTracker(folly::StringPiece key) noexcept { std::lock_guard<std::mutex> lock(mx_); auto it = trackers_.find(key); if (it != trackers_.end()) { trackers_.erase(it); } } } // namespace mcrouter } // namespace memcache } // namespace facebook <|endoftext|>
<commit_before>inline void Potential::init() { if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { /* compute values of spherical Bessel functions at MT boundary */ sbessel_mt_ = mdarray<double, 3>(lmax_ + pseudo_density_order + 2, unit_cell_.num_atom_types(), ctx_.gvec().num_shells()); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { for (int igs = 0; igs < ctx_.gvec().num_shells(); igs++) { gsl_sf_bessel_jl_array(lmax_ + pseudo_density_order + 1, ctx_.gvec().shell_len(igs) * unit_cell_.atom_type(iat).mt_radius(), &sbessel_mt_(0, iat, igs)); } } /* compute moments of spherical Bessel functions * * In[]:= Integrate[SphericalBesselJ[l,G*x]*x^(2+l),{x,0,R},Assumptions->{R>0,G>0,l>=0}] * Out[]= (Sqrt[\[Pi]/2] R^(3/2+l) BesselJ[3/2+l,G R])/G^(3/2) * * and use relation between Bessel and spherical Bessel functions: * Subscript[j, n](z)=Sqrt[\[Pi]/2]/Sqrt[z]Subscript[J, n+1/2](z) */ sbessel_mom_ = mdarray<double, 3>(ctx_.lmax_rho() + 1, unit_cell_.num_atom_types(), ctx_.gvec().num_shells()); //sbessel_mom_.allocate(); sbessel_mom_.zero(); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { sbessel_mom_(0, iat, 0) = std::pow(unit_cell_.atom_type(iat).mt_radius(), 3) / 3.0; // for |G|=0 for (int igs = 1; igs < ctx_.gvec().num_shells(); igs++) { for (int l = 0; l <= ctx_.lmax_rho(); l++) { sbessel_mom_(l, iat, igs) = std::pow(unit_cell_.atom_type(iat).mt_radius(), l + 2) * sbessel_mt_(l + 1, iat, igs) / ctx_.gvec().shell_len(igs); } } } #ifdef __PRINT_OBJECT_HASH DUMP("hash(sbessel_mom): %16llX", sbessel_mom_.hash()); #endif /* compute Gamma[5/2 + n + l] / Gamma[3/2 + l] / R^l * * use Gamma[1/2 + p] = (2p - 1)!!/2^p Sqrt[Pi] */ gamma_factors_R_ = mdarray<double, 2>(ctx_.lmax_rho() + 1, unit_cell_.num_atom_types()); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { for (int l = 0; l <= ctx_.lmax_rho(); l++) { long double Rl = std::pow(unit_cell_.atom_type(iat).mt_radius(), l); int n_min = (2 * l + 3); int n_max = (2 * l + 1) + (2 * pseudo_density_order + 2); /* split factorial product into two parts to avoid overflow */ long double f1 = 1.0; long double f2 = 1.0; for (int n = n_min; n <= n_max; n += 2) { if (f1 < Rl) { f1 *= (n / 2.0); } else { f2 *= (n / 2.0); } } gamma_factors_R_(l, iat) = static_cast<double>((f1 / Rl) * f2); } } } } <commit_msg>cleanup<commit_after>inline void Potential::init() { if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { /* compute values of spherical Bessel functions at MT boundary */ sbessel_mt_ = mdarray<double, 3>(lmax_ + pseudo_density_order + 2, unit_cell_.num_atom_types(), ctx_.gvec().num_shells()); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { for (int igs = 0; igs < ctx_.gvec().num_shells(); igs++) { gsl_sf_bessel_jl_array(lmax_ + pseudo_density_order + 1, ctx_.gvec().shell_len(igs) * unit_cell_.atom_type(iat).mt_radius(), &sbessel_mt_(0, iat, igs)); } } /* compute moments of spherical Bessel functions * * In[]:= Integrate[SphericalBesselJ[l,G*x]*x^(2+l),{x,0,R},Assumptions->{R>0,G>0,l>=0}] * Out[]= (Sqrt[\[Pi]/2] R^(3/2+l) BesselJ[3/2+l,G R])/G^(3/2) * * and use relation between Bessel and spherical Bessel functions: * Subscript[j, n](z)=Sqrt[\[Pi]/2]/Sqrt[z]Subscript[J, n+1/2](z) */ sbessel_mom_ = mdarray<double, 3>(ctx_.lmax_rho() + 1, unit_cell_.num_atom_types(), ctx_.gvec().num_shells()); sbessel_mom_.zero(); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { sbessel_mom_(0, iat, 0) = std::pow(unit_cell_.atom_type(iat).mt_radius(), 3) / 3.0; // for |G|=0 for (int igs = 1; igs < ctx_.gvec().num_shells(); igs++) { for (int l = 0; l <= ctx_.lmax_rho(); l++) { sbessel_mom_(l, iat, igs) = std::pow(unit_cell_.atom_type(iat).mt_radius(), l + 2) * sbessel_mt_(l + 1, iat, igs) / ctx_.gvec().shell_len(igs); } } } #ifdef __PRINT_OBJECT_HASH DUMP("hash(sbessel_mom): %16llX", sbessel_mom_.hash()); #endif /* compute Gamma[5/2 + n + l] / Gamma[3/2 + l] / R^l * * use Gamma[1/2 + p] = (2p - 1)!!/2^p Sqrt[Pi] */ gamma_factors_R_ = mdarray<double, 2>(ctx_.lmax_rho() + 1, unit_cell_.num_atom_types()); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { for (int l = 0; l <= ctx_.lmax_rho(); l++) { long double Rl = std::pow(unit_cell_.atom_type(iat).mt_radius(), l); int n_min = (2 * l + 3); int n_max = (2 * l + 1) + (2 * pseudo_density_order + 2); /* split factorial product into two parts to avoid overflow */ long double f1 = 1.0; long double f2 = 1.0; for (int n = n_min; n <= n_max; n += 2) { if (f1 < Rl) { f1 *= (n / 2.0); } else { f2 *= (n / 2.0); } } gamma_factors_R_(l, iat) = static_cast<double>((f1 / Rl) * f2); } } } } <|endoftext|>
<commit_before>/* * Copyright 2008-2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/detail/config.h> #include <thrust/system/tbb/detail/reduce_by_key.h> #include <thrust/iterator/reverse_iterator.h> #include <thrust/system/cpp/memory.h> #include <thrust/system/tbb/detail/execution_policy.h> #include <thrust/system/tbb/detail/reduce_intervals.h> #include <thrust/detail/minmax.h> #include <thrust/detail/temporary_array.h> #include <thrust/detail/range/tail_flags.h> #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> #include <tbb/tbb_thread.h> #include <cassert> namespace thrust { namespace system { namespace tbb { namespace detail { namespace reduce_by_key_detail { template<typename L, typename R> inline L divide_ri(const L x, const R y) { return (x + (y - 1)) / y; } template<typename InputIterator, typename BinaryFunction, typename OutputIterator = void> struct partial_sum_type : thrust::detail::eval_if< thrust::detail::has_result_type<BinaryFunction>::value, thrust::detail::result_type<BinaryFunction>, thrust::detail::eval_if< thrust::detail::is_output_iterator<OutputIterator>::value, thrust::iterator_value<InputIterator>, thrust::iterator_value<OutputIterator> > > {}; template<typename InputIterator, typename BinaryFunction> struct partial_sum_type<InputIterator,BinaryFunction,void> : thrust::detail::eval_if< thrust::detail::has_result_type<BinaryFunction>::value, thrust::detail::result_type<BinaryFunction>, thrust::iterator_value<InputIterator> > {}; template<typename InputIterator1, typename InputIterator2, typename BinaryPredicate, typename BinaryFunction> thrust::pair< InputIterator1, thrust::pair< typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > > reduce_last_segment_backward(InputIterator1 keys_first, InputIterator1 keys_last, InputIterator2 values_first, BinaryPredicate binary_pred, BinaryFunction binary_op) { typename thrust::iterator_difference<InputIterator1>::type n = keys_last - keys_first; // reverse the ranges and consume from the end thrust::reverse_iterator<InputIterator1> keys_first_r(keys_last); thrust::reverse_iterator<InputIterator1> keys_last_r(keys_first); thrust::reverse_iterator<InputIterator2> values_first_r(values_first + n); typename InputIterator1::value_type result_key = *keys_first_r; typename partial_sum_type<InputIterator2,BinaryFunction>::type result_value = *values_first_r; // consume the entirety of the first key's sequence for(++keys_first_r, ++values_first_r; (keys_first_r != keys_last_r) && binary_pred(*keys_first_r, result_key); ++keys_first_r, ++values_first_r) { result_value = binary_op(result_value, *values_first_r); } return thrust::make_pair(keys_first_r.base(), thrust::make_pair(result_key, result_value)); } template<typename InputIterator1, typename InputIterator2, typename OutputIterator1, typename OutputIterator2, typename BinaryPredicate, typename BinaryFunction> thrust::tuple< OutputIterator1, OutputIterator2, typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > reduce_by_key_with_carry(InputIterator1 keys_first, InputIterator1 keys_last, InputIterator2 values_first, OutputIterator1 keys_output, OutputIterator2 values_output, BinaryPredicate binary_pred, BinaryFunction binary_op) { // first, consume the last sequence to produce the carry // XXX is there an elegant way to pose this such that we don't need to default construct carry? thrust::pair< typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > carry; thrust::tie(keys_last, carry) = reduce_last_segment_backward(keys_first, keys_last, values_first, binary_pred, binary_op); // finish with sequential reduce_by_key thrust::cpp::tag seq; thrust::tie(keys_output, values_output) = thrust::reduce_by_key(seq, keys_first, keys_last, values_first, keys_output, values_output, binary_pred, binary_op); return thrust::make_tuple(keys_output, values_output, carry.first, carry.second); } template<typename Iterator> bool interval_has_carry(size_t interval_idx, size_t interval_size, size_t num_intervals, Iterator tail_flags) { // to discover whether the interval has a carry, look at the tail_flag corresponding to its last element // the final interval never has a carry by definition return (interval_idx + 1 < num_intervals) ? !tail_flags[(interval_idx + 1) * interval_size - 1] : false; } template<typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename Iterator5, typename Iterator6, typename BinaryPredicate, typename BinaryFunction> struct serial_reduce_by_key_body { typedef typename thrust::iterator_difference<Iterator1>::type size_type; Iterator1 keys_first; Iterator2 values_first; Iterator3 result_offset; Iterator4 keys_result; Iterator5 values_result; Iterator6 carry_result; size_type n; size_type interval_size; size_type num_intervals; BinaryPredicate binary_pred; BinaryFunction binary_op; serial_reduce_by_key_body(Iterator1 keys_first, Iterator2 values_first, Iterator3 result_offset, Iterator4 keys_result, Iterator5 values_result, Iterator6 carry_result, size_type n, size_type interval_size, size_type num_intervals, BinaryPredicate binary_pred, BinaryFunction binary_op) : keys_first(keys_first), values_first(values_first), result_offset(result_offset), keys_result(keys_result), values_result(values_result), carry_result(carry_result), n(n), interval_size(interval_size), num_intervals(num_intervals), binary_pred(binary_pred), binary_op(binary_op) {} void operator()(const ::tbb::blocked_range<size_type> &r) const { assert(r.size() == 1); const size_type interval_idx = r.begin(); const size_type offset_to_first = interval_size * interval_idx; const size_type offset_to_last = thrust::min(n, offset_to_first + interval_size); Iterator1 my_keys_first = keys_first + offset_to_first; Iterator1 my_keys_last = keys_first + offset_to_last; Iterator2 my_values_first = values_first + offset_to_first; Iterator3 my_result_offset = result_offset + interval_idx; Iterator4 my_keys_result = keys_result + *my_result_offset; Iterator5 my_values_result = values_result + *my_result_offset; Iterator6 my_carry_result = carry_result + interval_idx; // consume the rest of the interval with reduce_by_key typedef typename thrust::iterator_value<Iterator1>::type key_type; typedef typename partial_sum_type<Iterator2,BinaryFunction>::type value_type; // XXX is there a way to pose this so that we don't require default construction of carry? thrust::pair<key_type, value_type> carry; thrust::tie(my_keys_result, my_values_result, carry.first, carry.second) = reduce_by_key_with_carry(my_keys_first, my_keys_last, my_values_first, my_keys_result, my_values_result, binary_pred, binary_op); // store to carry only when we actually have a carry // store to my_keys_result & my_values_result otherwise // create tail_flags so we can check for a carry thrust::detail::tail_flags<Iterator1,BinaryPredicate> flags = thrust::detail::make_tail_flags(keys_first, keys_first + n, binary_pred); if(interval_has_carry(interval_idx, interval_size, num_intervals, flags.begin())) { // we can ignore the carry's key // XXX because the carry result is uninitialized, we should copy construct *my_carry_result = carry.second; } else { *my_keys_result = carry.first; *my_values_result = carry.second; } } }; template<typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename Iterator5, typename Iterator6, typename BinaryPredicate, typename BinaryFunction> serial_reduce_by_key_body<Iterator1,Iterator2,Iterator3,Iterator4,Iterator5,Iterator6,BinaryPredicate,BinaryFunction> make_serial_reduce_by_key_body(Iterator1 keys_first, Iterator2 values_first, Iterator3 result_offset, Iterator4 keys_result, Iterator5 values_result, Iterator6 carry_result, typename thrust::iterator_difference<Iterator1>::type n, size_t interval_size, size_t num_intervals, BinaryPredicate binary_pred, BinaryFunction binary_op) { return serial_reduce_by_key_body<Iterator1,Iterator2,Iterator3,Iterator4,Iterator5,Iterator6,BinaryPredicate,BinaryFunction>(keys_first, values_first, result_offset, keys_result, values_result, carry_result, n, interval_size, num_intervals, binary_pred, binary_op); } } // end reduce_by_key_detail template<typename DerivedPolicy, typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename BinaryPredicate, typename BinaryFunction> thrust::pair<Iterator3,Iterator4> reduce_by_key(thrust::tbb::execution_policy<DerivedPolicy> &exec, Iterator1 keys_first, Iterator1 keys_last, Iterator2 values_first, Iterator3 keys_result, Iterator4 values_result, BinaryPredicate binary_pred, BinaryFunction binary_op) { typedef typename thrust::iterator_difference<Iterator1>::type difference_type; difference_type n = keys_last - keys_first; if(n == 0) return thrust::make_pair(keys_result, values_result); // XXX this value is a tuning opportunity const difference_type parallelism_threshold = 10000; if(n < parallelism_threshold) { // don't bother parallelizing for small n thrust::cpp::tag seq; return thrust::reduce_by_key(seq, keys_first, keys_last, values_first, keys_result, values_result, binary_pred, binary_op); } // count the number of processors const unsigned int p = thrust::max<unsigned int>(1u, ::tbb::tbb_thread::hardware_concurrency()); // generate O(P) intervals of sequential work // XXX oversubscribing is a tuning opportunity const unsigned int subscription_rate = 1; difference_type interval_size = thrust::min<difference_type>(parallelism_threshold, thrust::max<difference_type>(n, n / (subscription_rate * p))); difference_type num_intervals = reduce_by_key_detail::divide_ri(n, interval_size); // decompose the input into intervals of size N / num_intervals // add one extra element to this vector to store the size of the entire result thrust::detail::temporary_array<difference_type, DerivedPolicy> interval_output_offsets(0, exec, num_intervals + 1); // first count the number of tail flags in each interval thrust::detail::tail_flags<Iterator1,BinaryPredicate> tail_flags = thrust::detail::make_tail_flags(keys_first, keys_last, binary_pred); thrust::system::tbb::detail::reduce_intervals(exec, tail_flags.begin(), tail_flags.end(), interval_size, interval_output_offsets.begin() + 1, thrust::plus<size_t>()); interval_output_offsets[0] = 0; // scan the counts to get each body's output offset thrust::cpp::tag seq; thrust::inclusive_scan(seq, interval_output_offsets.begin() + 1, interval_output_offsets.end(), interval_output_offsets.begin() + 1); // do a reduce_by_key serially in each thread // the final interval never has a carry by definition, so don't reserve space for it typedef typename reduce_by_key_detail::partial_sum_type<Iterator2,BinaryFunction>::type carry_type; thrust::detail::temporary_array<carry_type, DerivedPolicy> carries(0, exec, num_intervals - 1); // force grainsize == 1 with simple_partioner() ::tbb::parallel_for(::tbb::blocked_range<difference_type>(0, num_intervals, 1), reduce_by_key_detail::make_serial_reduce_by_key_body(keys_first, values_first, interval_output_offsets.begin(), keys_result, values_result, carries.begin(), n, interval_size, num_intervals, binary_pred, binary_op), ::tbb::simple_partitioner()); difference_type size_of_result = interval_output_offsets[num_intervals]; // sequentially accumulate the carries // note that the last interval does not have a carry // XXX find a way to express this loop via a sequential algorithm, perhaps reduce_by_key for(typename thrust::detail::temporary_array<carry_type,DerivedPolicy>::size_type i = 0; i < carries.size(); ++i) { // if our interval has a carry, then we need to sum the carry to the next interval's output offset // if it does not have a carry, then we need to ignore carry_value[i] if(reduce_by_key_detail::interval_has_carry(i, interval_size, num_intervals, tail_flags.begin())) { difference_type output_idx = interval_output_offsets[i+1]; values_result[output_idx] = binary_op(values_result[output_idx], carries[i]); } } return thrust::make_pair(keys_result + size_of_result, values_result + size_of_result); } } // end detail } // end tbb } // end system } // end thrust <commit_msg>include cpp's execution_policy.h instead of memory.h inside TBB's reduce_by_key implementation.<commit_after>/* * Copyright 2008-2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/detail/config.h> #include <thrust/system/tbb/detail/reduce_by_key.h> #include <thrust/iterator/reverse_iterator.h> #include <thrust/system/cpp/execution_policy.h> #include <thrust/system/tbb/detail/execution_policy.h> #include <thrust/system/tbb/detail/reduce_intervals.h> #include <thrust/detail/minmax.h> #include <thrust/detail/temporary_array.h> #include <thrust/detail/range/tail_flags.h> #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> #include <tbb/tbb_thread.h> #include <cassert> namespace thrust { namespace system { namespace tbb { namespace detail { namespace reduce_by_key_detail { template<typename L, typename R> inline L divide_ri(const L x, const R y) { return (x + (y - 1)) / y; } template<typename InputIterator, typename BinaryFunction, typename OutputIterator = void> struct partial_sum_type : thrust::detail::eval_if< thrust::detail::has_result_type<BinaryFunction>::value, thrust::detail::result_type<BinaryFunction>, thrust::detail::eval_if< thrust::detail::is_output_iterator<OutputIterator>::value, thrust::iterator_value<InputIterator>, thrust::iterator_value<OutputIterator> > > {}; template<typename InputIterator, typename BinaryFunction> struct partial_sum_type<InputIterator,BinaryFunction,void> : thrust::detail::eval_if< thrust::detail::has_result_type<BinaryFunction>::value, thrust::detail::result_type<BinaryFunction>, thrust::iterator_value<InputIterator> > {}; template<typename InputIterator1, typename InputIterator2, typename BinaryPredicate, typename BinaryFunction> thrust::pair< InputIterator1, thrust::pair< typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > > reduce_last_segment_backward(InputIterator1 keys_first, InputIterator1 keys_last, InputIterator2 values_first, BinaryPredicate binary_pred, BinaryFunction binary_op) { typename thrust::iterator_difference<InputIterator1>::type n = keys_last - keys_first; // reverse the ranges and consume from the end thrust::reverse_iterator<InputIterator1> keys_first_r(keys_last); thrust::reverse_iterator<InputIterator1> keys_last_r(keys_first); thrust::reverse_iterator<InputIterator2> values_first_r(values_first + n); typename InputIterator1::value_type result_key = *keys_first_r; typename partial_sum_type<InputIterator2,BinaryFunction>::type result_value = *values_first_r; // consume the entirety of the first key's sequence for(++keys_first_r, ++values_first_r; (keys_first_r != keys_last_r) && binary_pred(*keys_first_r, result_key); ++keys_first_r, ++values_first_r) { result_value = binary_op(result_value, *values_first_r); } return thrust::make_pair(keys_first_r.base(), thrust::make_pair(result_key, result_value)); } template<typename InputIterator1, typename InputIterator2, typename OutputIterator1, typename OutputIterator2, typename BinaryPredicate, typename BinaryFunction> thrust::tuple< OutputIterator1, OutputIterator2, typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > reduce_by_key_with_carry(InputIterator1 keys_first, InputIterator1 keys_last, InputIterator2 values_first, OutputIterator1 keys_output, OutputIterator2 values_output, BinaryPredicate binary_pred, BinaryFunction binary_op) { // first, consume the last sequence to produce the carry // XXX is there an elegant way to pose this such that we don't need to default construct carry? thrust::pair< typename InputIterator1::value_type, typename partial_sum_type<InputIterator2,BinaryFunction>::type > carry; thrust::tie(keys_last, carry) = reduce_last_segment_backward(keys_first, keys_last, values_first, binary_pred, binary_op); // finish with sequential reduce_by_key thrust::cpp::tag seq; thrust::tie(keys_output, values_output) = thrust::reduce_by_key(seq, keys_first, keys_last, values_first, keys_output, values_output, binary_pred, binary_op); return thrust::make_tuple(keys_output, values_output, carry.first, carry.second); } template<typename Iterator> bool interval_has_carry(size_t interval_idx, size_t interval_size, size_t num_intervals, Iterator tail_flags) { // to discover whether the interval has a carry, look at the tail_flag corresponding to its last element // the final interval never has a carry by definition return (interval_idx + 1 < num_intervals) ? !tail_flags[(interval_idx + 1) * interval_size - 1] : false; } template<typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename Iterator5, typename Iterator6, typename BinaryPredicate, typename BinaryFunction> struct serial_reduce_by_key_body { typedef typename thrust::iterator_difference<Iterator1>::type size_type; Iterator1 keys_first; Iterator2 values_first; Iterator3 result_offset; Iterator4 keys_result; Iterator5 values_result; Iterator6 carry_result; size_type n; size_type interval_size; size_type num_intervals; BinaryPredicate binary_pred; BinaryFunction binary_op; serial_reduce_by_key_body(Iterator1 keys_first, Iterator2 values_first, Iterator3 result_offset, Iterator4 keys_result, Iterator5 values_result, Iterator6 carry_result, size_type n, size_type interval_size, size_type num_intervals, BinaryPredicate binary_pred, BinaryFunction binary_op) : keys_first(keys_first), values_first(values_first), result_offset(result_offset), keys_result(keys_result), values_result(values_result), carry_result(carry_result), n(n), interval_size(interval_size), num_intervals(num_intervals), binary_pred(binary_pred), binary_op(binary_op) {} void operator()(const ::tbb::blocked_range<size_type> &r) const { assert(r.size() == 1); const size_type interval_idx = r.begin(); const size_type offset_to_first = interval_size * interval_idx; const size_type offset_to_last = thrust::min(n, offset_to_first + interval_size); Iterator1 my_keys_first = keys_first + offset_to_first; Iterator1 my_keys_last = keys_first + offset_to_last; Iterator2 my_values_first = values_first + offset_to_first; Iterator3 my_result_offset = result_offset + interval_idx; Iterator4 my_keys_result = keys_result + *my_result_offset; Iterator5 my_values_result = values_result + *my_result_offset; Iterator6 my_carry_result = carry_result + interval_idx; // consume the rest of the interval with reduce_by_key typedef typename thrust::iterator_value<Iterator1>::type key_type; typedef typename partial_sum_type<Iterator2,BinaryFunction>::type value_type; // XXX is there a way to pose this so that we don't require default construction of carry? thrust::pair<key_type, value_type> carry; thrust::tie(my_keys_result, my_values_result, carry.first, carry.second) = reduce_by_key_with_carry(my_keys_first, my_keys_last, my_values_first, my_keys_result, my_values_result, binary_pred, binary_op); // store to carry only when we actually have a carry // store to my_keys_result & my_values_result otherwise // create tail_flags so we can check for a carry thrust::detail::tail_flags<Iterator1,BinaryPredicate> flags = thrust::detail::make_tail_flags(keys_first, keys_first + n, binary_pred); if(interval_has_carry(interval_idx, interval_size, num_intervals, flags.begin())) { // we can ignore the carry's key // XXX because the carry result is uninitialized, we should copy construct *my_carry_result = carry.second; } else { *my_keys_result = carry.first; *my_values_result = carry.second; } } }; template<typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename Iterator5, typename Iterator6, typename BinaryPredicate, typename BinaryFunction> serial_reduce_by_key_body<Iterator1,Iterator2,Iterator3,Iterator4,Iterator5,Iterator6,BinaryPredicate,BinaryFunction> make_serial_reduce_by_key_body(Iterator1 keys_first, Iterator2 values_first, Iterator3 result_offset, Iterator4 keys_result, Iterator5 values_result, Iterator6 carry_result, typename thrust::iterator_difference<Iterator1>::type n, size_t interval_size, size_t num_intervals, BinaryPredicate binary_pred, BinaryFunction binary_op) { return serial_reduce_by_key_body<Iterator1,Iterator2,Iterator3,Iterator4,Iterator5,Iterator6,BinaryPredicate,BinaryFunction>(keys_first, values_first, result_offset, keys_result, values_result, carry_result, n, interval_size, num_intervals, binary_pred, binary_op); } } // end reduce_by_key_detail template<typename DerivedPolicy, typename Iterator1, typename Iterator2, typename Iterator3, typename Iterator4, typename BinaryPredicate, typename BinaryFunction> thrust::pair<Iterator3,Iterator4> reduce_by_key(thrust::tbb::execution_policy<DerivedPolicy> &exec, Iterator1 keys_first, Iterator1 keys_last, Iterator2 values_first, Iterator3 keys_result, Iterator4 values_result, BinaryPredicate binary_pred, BinaryFunction binary_op) { typedef typename thrust::iterator_difference<Iterator1>::type difference_type; difference_type n = keys_last - keys_first; if(n == 0) return thrust::make_pair(keys_result, values_result); // XXX this value is a tuning opportunity const difference_type parallelism_threshold = 10000; if(n < parallelism_threshold) { // don't bother parallelizing for small n thrust::cpp::tag seq; return thrust::reduce_by_key(seq, keys_first, keys_last, values_first, keys_result, values_result, binary_pred, binary_op); } // count the number of processors const unsigned int p = thrust::max<unsigned int>(1u, ::tbb::tbb_thread::hardware_concurrency()); // generate O(P) intervals of sequential work // XXX oversubscribing is a tuning opportunity const unsigned int subscription_rate = 1; difference_type interval_size = thrust::min<difference_type>(parallelism_threshold, thrust::max<difference_type>(n, n / (subscription_rate * p))); difference_type num_intervals = reduce_by_key_detail::divide_ri(n, interval_size); // decompose the input into intervals of size N / num_intervals // add one extra element to this vector to store the size of the entire result thrust::detail::temporary_array<difference_type, DerivedPolicy> interval_output_offsets(0, exec, num_intervals + 1); // first count the number of tail flags in each interval thrust::detail::tail_flags<Iterator1,BinaryPredicate> tail_flags = thrust::detail::make_tail_flags(keys_first, keys_last, binary_pred); thrust::system::tbb::detail::reduce_intervals(exec, tail_flags.begin(), tail_flags.end(), interval_size, interval_output_offsets.begin() + 1, thrust::plus<size_t>()); interval_output_offsets[0] = 0; // scan the counts to get each body's output offset thrust::cpp::tag seq; thrust::inclusive_scan(seq, interval_output_offsets.begin() + 1, interval_output_offsets.end(), interval_output_offsets.begin() + 1); // do a reduce_by_key serially in each thread // the final interval never has a carry by definition, so don't reserve space for it typedef typename reduce_by_key_detail::partial_sum_type<Iterator2,BinaryFunction>::type carry_type; thrust::detail::temporary_array<carry_type, DerivedPolicy> carries(0, exec, num_intervals - 1); // force grainsize == 1 with simple_partioner() ::tbb::parallel_for(::tbb::blocked_range<difference_type>(0, num_intervals, 1), reduce_by_key_detail::make_serial_reduce_by_key_body(keys_first, values_first, interval_output_offsets.begin(), keys_result, values_result, carries.begin(), n, interval_size, num_intervals, binary_pred, binary_op), ::tbb::simple_partitioner()); difference_type size_of_result = interval_output_offsets[num_intervals]; // sequentially accumulate the carries // note that the last interval does not have a carry // XXX find a way to express this loop via a sequential algorithm, perhaps reduce_by_key for(typename thrust::detail::temporary_array<carry_type,DerivedPolicy>::size_type i = 0; i < carries.size(); ++i) { // if our interval has a carry, then we need to sum the carry to the next interval's output offset // if it does not have a carry, then we need to ignore carry_value[i] if(reduce_by_key_detail::interval_has_carry(i, interval_size, num_intervals, tail_flags.begin())) { difference_type output_idx = interval_output_offsets[i+1]; values_result[output_idx] = binary_op(values_result[output_idx], carries[i]); } } return thrust::make_pair(keys_result + size_of_result, values_result + size_of_result); } } // end detail } // end tbb } // end system } // end thrust <|endoftext|>
<commit_before>/* * * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca. * * 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 "QueryInterface.h" #include "util/Assert.h" #include "Solver.h" #include "util/Constants.h" QueryInterface::QueryInterface( Solver& s ) : solver( s ) { } void QueryInterface::computeCautiousConsequences( unsigned int ALGORITHM ) { if( !computeFirstModel() ) { solver.foundIncoherence(); return; } switch( ALGORITHM ) { case ITERATIVE_COHERENCE_TESTING: iterativeCoherenceTesting(); break; case OVERESTIMATE_REDUCTION: overestimateReduction(); break; case CHUNK_BASED: { unsigned int param = 2; if( wasp::Options::chunkSize != UINT_MAX ) param = wasp::Options::chunkSize; else if( wasp::Options::chunkPercentage != UINT_MAX ) param = ( candidates.size() * wasp::Options::chunkPercentage ) / 100; if( param == 1 ) iterativeCoherenceTesting(); else if( param >= candidates.size() ) overestimateReduction(); else chunkAlgorithm(param); } break; default: ErrorMessage::errorGeneric( "Inserted invalid algorithm for query answering." ); } solver.printCautiousConsequences( answers ); } void QueryInterface::iterativeCoherenceTesting() { solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); vector< Literal > assumptions; while( !candidates.empty() ) { Var v = candidates.back(); if( !solver.isUndefined( v ) ) { assert( solver.getDecisionLevel( v ) == 0 ); if( solver.isTrue( v ) ) addAnswer( v ); candidates.pop_back(); continue; } assert( solver.isUndefined( v ) ); assumptions.push_back( Literal( v, NEGATIVE ) ); unsigned int result = solver.solve( assumptions ); if( result == COHERENT ) reduceCandidates(); else { assert( result == INCOHERENT ); addAnswer( v ); candidates.pop_back(); } solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); assumptions.clear(); } } void QueryInterface::overestimateReduction() { solver.turnOffSimplifications(); Clause* clausePointer = computeClauseFromCandidates(); unsigned int size = clausePointer->size(); solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) goto end; while( solver.solve() == COHERENT ) { if( size > 2 ) { assert( clausePointer->size() > 2 ); solver.detachClause( *clausePointer ); } clausePointer = computeClauseFromCandidates(); size = clausePointer->size(); solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) goto end; } end:; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ i ]; addAnswer( v ); } } bool QueryInterface::computeFirstModel() { unsigned int result = solver.solve(); if( result == INCOHERENT ) return false; assert( result == COHERENT ); computeCandidates(); return true; } void QueryInterface::computeCandidates() { for( unsigned int i = 1; i <= solver.numberOfVariables(); i++ ) { Var v = i; if( VariableNames::isHidden( v ) ) continue; assert_msg( !solver.hasBeenEliminated( v ), "Variable " << Literal( v, POSITIVE ) << " has been deleted" ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else candidates.push_back( v ); } } void QueryInterface::reduceCandidates() { unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ j ] = candidates[ i ]; assert( !solver.isUndefined( v ) ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else j++; } candidates.shrink( j ); printCandidates(); } Clause* QueryInterface::computeClauseFromCandidates() { Clause* clause = new Clause(); unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ j ] = candidates[ i ]; assert( !solver.isUndefined( v ) ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else { clause->addLiteral( Literal( v, NEGATIVE ) ); j++; } } candidates.shrink( j ); clause->setCanBeDeleted( false ); printCandidates(); return clause; } Clause* QueryInterface::computeClauseForChunk( unsigned int chunkSize, Var& auxVar ) { Clause* clause = new Clause(); unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; for( unsigned int i = 0; i < limit; i++ ) clause->addLiteral( Literal( candidates[ i ], NEGATIVE ) ); solver.addVariableRuntime(); auxVar = solver.numberOfVariables(); clause->addLiteral( Literal( auxVar, POSITIVE ) ); clause->setCanBeDeleted( false ); return clause; } void QueryInterface::addAnswer( Var v ) { if( wasp::Options::queryVerbosity >= 1 ) cout << "Certain answer: " << Literal( v, POSITIVE ) << endl; answers.push_back( v ); } void QueryInterface::printCandidates() { if( wasp::Options::queryVerbosity < 2 ) return; if( wasp::Options::queryVerbosity == 2 ) cout << "Number of possible answers: " << candidates.size() << endl; else { cout << "Candidates:"; for( unsigned int i = 0; i < candidates.size(); i++ ) cout << " " << Literal( candidates[ i ], POSITIVE ); cout << endl; } } void QueryInterface::reduceCandidatesForChunk( unsigned int chunkSize ) { unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { candidates[ j ] = candidates[ i ]; if( i >= limit ) j++; } candidates.shrink( j ); printCandidates(); } void QueryInterface::chunkAlgorithm( unsigned int chunkSize ) { assert( chunkSize < candidates.size() ); solver.unrollToZero(); solver.clearConflictStatus(); solver.turnOffSimplifications(); Var auxVar = 0; Clause* clausePointer = computeClauseForChunk( chunkSize, auxVar ); assert( auxVar != 0 ); unsigned int size = clausePointer->size(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) return; vector< Literal > assumptions; while( true ) { assumptions.clear(); assumptions.push_back( Literal( auxVar, NEGATIVE ) ); if( solver.solve( assumptions ) == COHERENT ) reduceCandidates(); else { unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; for( unsigned int i = 0; i < limit; i++ ) addAnswer( candidates[ i ] ); reduceCandidatesForChunk( chunkSize ); } if( candidates.empty() ) return; solver.unrollToZero(); solver.clearConflictStatus(); if( size > 2 ) { assert( clausePointer->size() > 2 ); solver.detachClause( *clausePointer ); } #ifndef NDEBUG bool res = #endif solver.addClauseRuntime( Literal( auxVar, POSITIVE ) ); assert( res ); auxVar = 0; clausePointer = computeClauseForChunk( chunkSize, auxVar ); assert( auxVar != 0 ); size = clausePointer->size(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); #ifndef NDEBUG res = #endif solver.addClauseRuntime( clausePointer ); assert( res ); } }<commit_msg>Fixed bug.<commit_after>/* * * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca. * * 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 "QueryInterface.h" #include "util/Assert.h" #include "Solver.h" #include "util/Constants.h" QueryInterface::QueryInterface( Solver& s ) : solver( s ) { } void QueryInterface::computeCautiousConsequences( unsigned int ALGORITHM ) { if( !computeFirstModel() ) { solver.foundIncoherence(); return; } switch( ALGORITHM ) { case ITERATIVE_COHERENCE_TESTING: iterativeCoherenceTesting(); break; case OVERESTIMATE_REDUCTION: overestimateReduction(); break; case CHUNK_BASED: { unsigned int param = 2; if( wasp::Options::chunkSize != UINT_MAX ) param = wasp::Options::chunkSize; else if( wasp::Options::chunkPercentage != UINT_MAX ) param = ( candidates.size() * wasp::Options::chunkPercentage ) / 100; if( param == 1 ) iterativeCoherenceTesting(); else if( param >= candidates.size() ) overestimateReduction(); else chunkAlgorithm(param); } break; default: ErrorMessage::errorGeneric( "Inserted invalid algorithm for query answering." ); } solver.printCautiousConsequences( answers ); } void QueryInterface::iterativeCoherenceTesting() { solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); vector< Literal > assumptions; while( !candidates.empty() ) { Var v = candidates.back(); if( !solver.isUndefined( v ) ) { assert( solver.getDecisionLevel( v ) == 0 ); if( solver.isTrue( v ) ) addAnswer( v ); candidates.pop_back(); continue; } assert( solver.isUndefined( v ) ); assumptions.push_back( Literal( v, NEGATIVE ) ); unsigned int result = solver.solve( assumptions ); if( result == COHERENT ) reduceCandidates(); else { assert( result == INCOHERENT ); addAnswer( v ); candidates.pop_back(); } solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); assumptions.clear(); } } void QueryInterface::overestimateReduction() { solver.turnOffSimplifications(); Clause* clausePointer = computeClauseFromCandidates(); unsigned int size = clausePointer->size(); solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) goto end; while( solver.solve() == COHERENT ) { if( size > 2 ) { assert( clausePointer->size() > 2 ); solver.detachClause( *clausePointer ); } clausePointer = computeClauseFromCandidates(); size = clausePointer->size(); solver.unrollToZero(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) goto end; } end:; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ i ]; addAnswer( v ); } } bool QueryInterface::computeFirstModel() { unsigned int result = solver.solve(); if( result == INCOHERENT ) return false; assert( result == COHERENT ); computeCandidates(); return true; } void QueryInterface::computeCandidates() { for( unsigned int i = 1; i <= solver.numberOfVariables(); i++ ) { Var v = i; if( VariableNames::isHidden( v ) ) continue; assert_msg( !solver.hasBeenEliminated( v ), "Variable " << Literal( v, POSITIVE ) << " has been deleted" ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else candidates.push_back( v ); } } void QueryInterface::reduceCandidates() { unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ j ] = candidates[ i ]; assert( !solver.isUndefined( v ) ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else j++; } candidates.shrink( j ); printCandidates(); } Clause* QueryInterface::computeClauseFromCandidates() { Clause* clause = new Clause(); unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { Var v = candidates[ j ] = candidates[ i ]; assert( !solver.isUndefined( v ) ); if( !solver.isTrue( v ) ) continue; if( solver.getDecisionLevel( v ) == 0 ) addAnswer( v ); else { clause->addLiteral( Literal( v, NEGATIVE ) ); j++; } } candidates.shrink( j ); clause->setCanBeDeleted( false ); printCandidates(); return clause; } Clause* QueryInterface::computeClauseForChunk( unsigned int chunkSize, Var& auxVar ) { Clause* clause = new Clause(); unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; for( unsigned int i = 0; i < limit; i++ ) { assert( solver.isUndefined( candidates[ i ] ) ); clause->addLiteral( Literal( candidates[ i ], NEGATIVE ) ); } solver.addVariableRuntime(); auxVar = solver.numberOfVariables(); clause->addLiteral( Literal( auxVar, POSITIVE ) ); clause->setCanBeDeleted( false ); return clause; } void QueryInterface::addAnswer( Var v ) { if( wasp::Options::queryVerbosity >= 1 ) cout << "Certain answer: " << Literal( v, POSITIVE ) << endl; answers.push_back( v ); } void QueryInterface::printCandidates() { if( wasp::Options::queryVerbosity < 2 ) return; if( wasp::Options::queryVerbosity == 2 ) cout << "Number of possible answers: " << candidates.size() << endl; else { cout << "Candidates:"; for( unsigned int i = 0; i < candidates.size(); i++ ) cout << " " << Literal( candidates[ i ], POSITIVE ); cout << endl; } } void QueryInterface::reduceCandidatesForChunk( unsigned int chunkSize ) { assert( solver.getCurrentDecisionLevel() == 0 ); unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; unsigned int j = 0; for( unsigned int i = 0; i < candidates.size(); i++ ) { candidates[ j ] = candidates[ i ]; if( i >= limit ) { if( solver.isUndefined( candidates[ i ] ) ) j++; else if( solver.isTrue( candidates[ i ] ) ) addAnswer( candidates[ i ] ); } } candidates.shrink( j ); printCandidates(); } void QueryInterface::chunkAlgorithm( unsigned int chunkSize ) { assert( chunkSize < candidates.size() ); solver.unrollToZero(); solver.clearConflictStatus(); solver.turnOffSimplifications(); Var auxVar = 0; Clause* clausePointer = computeClauseForChunk( chunkSize, auxVar ); assert( auxVar != 0 ); unsigned int size = clausePointer->size(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); if( !solver.addClauseRuntime( clausePointer ) ) return; vector< Literal > assumptions; while( true ) { assumptions.clear(); assumptions.push_back( Literal( auxVar, NEGATIVE ) ); if( solver.solve( assumptions ) == COHERENT ) { reduceCandidates(); solver.unrollToZero(); solver.clearConflictStatus(); } else { unsigned int limit = chunkSize > candidates.size() ? candidates.size() : chunkSize; for( unsigned int i = 0; i < limit; i++ ) addAnswer( candidates[ i ] ); solver.unrollToZero(); solver.clearConflictStatus(); reduceCandidatesForChunk( chunkSize ); } if( candidates.empty() ) return; if( size > 2 ) { assert( clausePointer->size() > 2 ); solver.detachClause( *clausePointer ); } #ifndef NDEBUG bool res = #endif solver.addClauseRuntime( Literal( auxVar, POSITIVE ) ); assert( res ); auxVar = 0; clausePointer = computeClauseForChunk( chunkSize, auxVar ); assert( auxVar != 0 ); size = clausePointer->size(); assert( solver.getCurrentDecisionLevel() == 0 ); assert( !solver.conflictDetected() ); #ifndef NDEBUG res = #endif solver.addClauseRuntime( clausePointer ); assert( res ); } }<|endoftext|>
<commit_before>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Each thread sieves a distance of /// segment_size * segments_per_thread. Once all threads have /// processed their intervals we calculate a new interval size /// based on the ideas below. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval size. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <imath.hpp> #include <int128_t.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_avg(thread_timings_t& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } /// Relative standard deviation double rel_std_dev(thread_timings_t& timings) { size_t n = timings.size(); double avg = get_avg(timings); double sum = 0; if (avg == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - avg; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / avg; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } void S2LoadBalancer::init(maxint_t x, int64_t y, int64_t threads) { // determined by benchmarking double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.01 * log_threads; double divisor = log(log(x_)) * log(x_); update_min_size(divisor); double alpha = get_alpha(x, y); smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * iroot<6>(x))); } double S2LoadBalancer::get_rsd() const { return rsd_; } double S2LoadBalancer::get_avg_seconds() const { return total_seconds_ / count_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } /// Increase if relative std dev < pivot. /// Decrease if relative std dev > pivot. /// double S2LoadBalancer::get_pivot(double seconds) const { double log_seconds = log(seconds); log_seconds = max(min_seconds_, log_seconds); double dont_decrease = decrease_dividend_ / (seconds * log_seconds); dont_decrease = min(dont_decrease, rsd_); return rsd_ + dont_decrease; } bool S2LoadBalancer::is_increase(double seconds, double pivot) const { return (seconds < min_seconds_ || seconds < get_avg_seconds()) && !is_decrease(seconds, pivot); } bool S2LoadBalancer::is_decrease(double seconds, double pivot) const { return seconds > min_seconds_ && rsd_ > pivot; } void S2LoadBalancer::update_min_size(double divisor) { int64_t min_size = 1 << 9; int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } void S2LoadBalancer::update(int64_t* segment_size, int64_t* segments_per_thread, int64_t low, int64_t threads, thread_timings_t& timings) { count_++; double seconds = get_avg(timings); total_seconds_ += seconds; double pivot = get_pivot(seconds); rsd_ = max(0.1, rel_std_dev(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (is_increase(seconds, pivot)) *segment_size <<= 1; else if (is_decrease(seconds, pivot)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) update(segments_per_thread, seconds, pivot); int64_t thread_distance = *segment_size * *segments_per_thread; int64_t high = low + thread_distance * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; thread_distance = *segment_size * *segments_per_thread; high = low + thread_distance * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } /// Increase the segments_per_thread if the relative standard /// deviation of the thread run times is small, or /// decrease the segments_per_thread if the relative standard /// deviation of the thread run times is large. /// void S2LoadBalancer::update(int64_t* segments_per_thread, double seconds, double pivot) { if (is_increase(seconds, pivot) || is_decrease(seconds, pivot)) { if (seconds < min_seconds_) *segments_per_thread *= 2; else { double factor = pivot / rsd_; factor = in_between(0.5, factor, 2); double segments = *segments_per_thread * factor; segments = max(1.0, segments); *segments_per_thread = (int64_t) segments; } } } } // namespace <commit_msg>Remove comment<commit_after>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Each thread sieves a distance of /// segment_size * segments_per_thread. Once all threads have /// processed their intervals we calculate a new interval size /// based on the ideas below. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval size. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <imath.hpp> #include <int128_t.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_avg(thread_timings_t& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } /// Relative standard deviation double rel_std_dev(thread_timings_t& timings) { size_t n = timings.size(); double avg = get_avg(timings); double sum = 0; if (avg == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - avg; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / avg; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } void S2LoadBalancer::init(maxint_t x, int64_t y, int64_t threads) { double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.01 * log_threads; double divisor = log(log(x_)) * log(x_); update_min_size(divisor); double alpha = get_alpha(x, y); smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * iroot<6>(x))); } double S2LoadBalancer::get_rsd() const { return rsd_; } double S2LoadBalancer::get_avg_seconds() const { return total_seconds_ / count_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } /// Increase if relative std dev < pivot. /// Decrease if relative std dev > pivot. /// double S2LoadBalancer::get_pivot(double seconds) const { double log_seconds = log(seconds); log_seconds = max(min_seconds_, log_seconds); double dont_decrease = decrease_dividend_ / (seconds * log_seconds); dont_decrease = min(dont_decrease, rsd_); return rsd_ + dont_decrease; } bool S2LoadBalancer::is_increase(double seconds, double pivot) const { return (seconds < min_seconds_ || seconds < get_avg_seconds()) && !is_decrease(seconds, pivot); } bool S2LoadBalancer::is_decrease(double seconds, double pivot) const { return seconds > min_seconds_ && rsd_ > pivot; } void S2LoadBalancer::update_min_size(double divisor) { int64_t min_size = 1 << 9; int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } void S2LoadBalancer::update(int64_t* segment_size, int64_t* segments_per_thread, int64_t low, int64_t threads, thread_timings_t& timings) { count_++; double seconds = get_avg(timings); total_seconds_ += seconds; double pivot = get_pivot(seconds); rsd_ = max(0.1, rel_std_dev(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (is_increase(seconds, pivot)) *segment_size <<= 1; else if (is_decrease(seconds, pivot)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) update(segments_per_thread, seconds, pivot); int64_t thread_distance = *segment_size * *segments_per_thread; int64_t high = low + thread_distance * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; thread_distance = *segment_size * *segments_per_thread; high = low + thread_distance * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } /// Increase the segments_per_thread if the relative standard /// deviation of the thread run times is small, or /// decrease the segments_per_thread if the relative standard /// deviation of the thread run times is large. /// void S2LoadBalancer::update(int64_t* segments_per_thread, double seconds, double pivot) { if (is_increase(seconds, pivot) || is_decrease(seconds, pivot)) { if (seconds < min_seconds_) *segments_per_thread *= 2; else { double factor = pivot / rsd_; factor = in_between(0.5, factor, 2); double segments = *segments_per_thread * factor; segments = max(1.0, segments); *segments_per_thread = (int64_t) segments; } } } } // namespace <|endoftext|>
<commit_before>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Each thread sieves a distance of /// segment_size * segments_per_thread. Once all threads have /// processed their intervals we calculate a new interval size /// based on the ideas below. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval size. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_avg(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } /// Relative standard deviation double rel_std_dev(aligned_vector<double>& timings) { size_t n = timings.size(); double avg = get_avg(timings); double sum = 0; if (avg == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - avg; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / avg; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } void S2LoadBalancer::init(maxint_t x, int64_t y, int64_t threads) { // determined by benchmarking double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; double divisor = log(log(x_)) * log(x_); update_min_size(divisor); double alpha = get_alpha(x, y); smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * iroot<6>(x))); } double S2LoadBalancer::get_rsd() const { return rsd_; } double S2LoadBalancer::get_avg_seconds() const { return total_seconds_ / count_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } /// Increase if relative std dev < pivot. /// Decrease if relative std dev > pivot. /// double S2LoadBalancer::get_pivot(double seconds) const { double log_seconds = log(seconds); log_seconds = max(min_seconds_, log_seconds); double dont_decrease = decrease_dividend_ / (seconds * log_seconds); dont_decrease = min(dont_decrease, rsd_); return rsd_ + dont_decrease; } bool S2LoadBalancer::is_increase(double seconds, double pivot) const { return seconds < get_avg_seconds() && !is_decrease(seconds, pivot); } bool S2LoadBalancer::is_decrease(double seconds, double pivot) const { return seconds > min_seconds_ && rsd_ > pivot; } void S2LoadBalancer::update_min_size(double divisor) { int64_t min_size = 1 << 9; int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { count_++; double seconds = get_avg(timings); total_seconds_ += seconds; double pivot = get_pivot(seconds); rsd_ = max(0.1, rel_std_dev(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (is_increase(seconds, pivot)) *segment_size <<= 1; else if (is_decrease(seconds, pivot)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) update(segments_per_thread, seconds, pivot); int64_t thread_distance = *segment_size * *segments_per_thread; int64_t high = low + thread_distance * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; thread_distance = *segment_size * *segments_per_thread; high = low + thread_distance * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } /// Increases the number of segments per thread if the previous /// thread run-times are close, otherwise decreases the /// number of segments per thread. /// void S2LoadBalancer::update(int64_t* segments_per_thread, double seconds, double pivot) { double factor = pivot / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < get_avg_seconds())) { *segments_per_thread = (int64_t) n; } } } // namespace <commit_msg>Refactor<commit_after>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Each thread sieves a distance of /// segment_size * segments_per_thread. Once all threads have /// processed their intervals we calculate a new interval size /// based on the ideas below. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval size. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_avg(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } /// Relative standard deviation double rel_std_dev(aligned_vector<double>& timings) { size_t n = timings.size(); double avg = get_avg(timings); double sum = 0; if (avg == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - avg; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / avg; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), count_(0), total_seconds_(0), sqrtz_(isqrt(z)) { init(x, y, threads); } void S2LoadBalancer::init(maxint_t x, int64_t y, int64_t threads) { // determined by benchmarking double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; double divisor = log(log(x_)) * log(x_); update_min_size(divisor); double alpha = get_alpha(x, y); smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * iroot<6>(x))); } double S2LoadBalancer::get_rsd() const { return rsd_; } double S2LoadBalancer::get_avg_seconds() const { return total_seconds_ / count_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } /// Increase if relative std dev < pivot. /// Decrease if relative std dev > pivot. /// double S2LoadBalancer::get_pivot(double seconds) const { double log_seconds = log(seconds); log_seconds = max(min_seconds_, log_seconds); double dont_decrease = decrease_dividend_ / (seconds * log_seconds); dont_decrease = min(dont_decrease, rsd_); return rsd_ + dont_decrease; } bool S2LoadBalancer::is_increase(double seconds, double pivot) const { return seconds < get_avg_seconds() && !is_decrease(seconds, pivot); } bool S2LoadBalancer::is_decrease(double seconds, double pivot) const { return seconds > min_seconds_ && rsd_ > pivot; } void S2LoadBalancer::update_min_size(double divisor) { int64_t min_size = 1 << 9; int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { count_++; double seconds = get_avg(timings); total_seconds_ += seconds; double pivot = get_pivot(seconds); rsd_ = max(0.1, rel_std_dev(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (is_increase(seconds, pivot)) *segment_size <<= 1; else if (is_decrease(seconds, pivot)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) update(segments_per_thread, seconds, pivot); int64_t thread_distance = *segment_size * *segments_per_thread; int64_t high = low + thread_distance * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; thread_distance = *segment_size * *segments_per_thread; high = low + thread_distance * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } /// Increase the segments_per_thread if the relative standard /// deviation of the thread run times is small, or /// decrease the segments_per_thread if the relative standard /// deviation of the thread run times is large. /// void S2LoadBalancer::update(int64_t* segments_per_thread, double seconds, double pivot) { if (is_increase(seconds, pivot) || is_decrease(seconds, pivot)) { if (seconds < min_seconds_) *segments_per_thread *= 2; else { double factor = pivot / rsd_; factor = in_between(0.5, factor, 2); double segments = *segments_per_thread * factor; segments = max(1.0, segments); *segments_per_thread = (int64_t) segments; } } } } // namespace <|endoftext|>
<commit_before>// // ScrollingLabel.cpp // Kepler // // Created by Tom Carden on 5/25/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "ScrollingLabel.h" #include "cinder/app/AppCocoaTouch.h" // app::getElapsedSeconds() #include "cinder/gl/gl.h" #include "cinder/Text.h" using namespace std; using namespace ci; using namespace ci::app; void ScrollingLabel::setText(string text) { if (mText != text) { mIsScrolling = false; mText = text; updateTexture(); mLastTrackChangeTime = app::getElapsedSeconds(); } } void ScrollingLabel::updateTexture() { if (mText == "") { mTexture.reset(); } else { TextLayout layout; layout.setFont( mFont ); layout.setColor( mColor ); layout.addLine( mText ); bool PREMULT = false; mTexture = gl::Texture( layout.render( true, PREMULT ) ); } } void ScrollingLabel::update() { float ctSpaceWidth = mRect.x2 - mRect.x1; float ctTexWidth = mTexture.getWidth(); if( ctTexWidth < ctSpaceWidth ){ mIsScrolling = false; } else { // if the texture is too wide, animate the u coords... float elapsedSeconds = ci::app::getElapsedSeconds(); float x1; if( elapsedSeconds - mLastTrackChangeTime > 5.0f ) { // but wait 5 seconds first mIsScrolling = true; x1 = fmodf( ( elapsedSeconds - ( mLastTrackChangeTime + 5.0f ) ) * 20.0f, ctTexWidth + 10.0f ) - ctTexWidth-10.0f; } else { x1 = -ctTexWidth-10.0f; } mFirstArea = Area( x1, 0.0f, x1 + ctSpaceWidth, mTexture.getHeight() ); mSecondArea = Area( x1 + ctTexWidth + 10.0f, 0.0f, x1 + ctTexWidth + 10.0f + ctSpaceWidth, mTexture.getHeight() ); } } void ScrollingLabel::draw() { if (mTexture) { // force texture height to be correct: float restoreY2 = mRect.y2; mRect.y2 = mRect.y1 + mTexture.getHeight(); float ctSpaceWidth = mRect.x2 - mRect.x1; float ctTexWidth = mTexture.getWidth(); if( ctTexWidth < ctSpaceWidth ){ // if the texture width is less than the rect to fit it in... gl::draw(mTexture, mRect.getUpperLeft()); } else { gl::draw( mTexture, mFirstArea, mRect ); gl::draw( mTexture, mSecondArea, mRect ); } // restore mRect // (this is a hack because mRect is also used for hit testing) mRect.y2 = restoreY2; } } bool ScrollingLabel::touchBegan( TouchEvent::Touch touch ) { return mRect.contains( globalToLocal( touch.getPos() ) ); } bool ScrollingLabel::touchEnded( TouchEvent::Touch touch ) { return mRect.contains( globalToLocal( touch.getPos() ) ); } <commit_msg>fixing scrolling label<commit_after>// // ScrollingLabel.cpp // Kepler // // Created by Tom Carden on 5/25/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "ScrollingLabel.h" #include "cinder/app/AppCocoaTouch.h" // app::getElapsedSeconds() #include "cinder/gl/gl.h" #include "cinder/Text.h" using namespace std; using namespace ci; using namespace ci::app; void ScrollingLabel::setText(string text) { if (mText != text) { mIsScrolling = false; mText = text; updateTexture(); mLastChangeTime = app::getElapsedSeconds(); } } void ScrollingLabel::updateTexture() { if (mText == "") { mTexture.reset(); } else { TextLayout layout; layout.setFont( mFont ); layout.setColor( mColor ); layout.addLine( mText ); bool PREMULT = false; mTexture = gl::Texture( layout.render( true, PREMULT ) ); } } void ScrollingLabel::update() { float ctSpaceWidth = mRect.x2 - mRect.x1; float ctTexWidth = mTexture.getWidth(); if( ctTexWidth < ctSpaceWidth ){ mIsScrolling = false; } else { // if the texture is too wide, animate the u coords... float elapsedSeconds = ci::app::getElapsedSeconds(); float x1; if( elapsedSeconds - mLastChangeTime > 5.0f ) { // but wait 5 seconds first mIsScrolling = true; x1 = fmodf( ( elapsedSeconds - ( mLastChangeTime + 5.0f ) ) * 20.0f, ctTexWidth + 10.0f ) - ctTexWidth-10.0f; } else { x1 = -ctTexWidth-10.0f; } mFirstArea = Area( x1, 0.0f, x1 + ctSpaceWidth, mTexture.getHeight() ); mSecondArea = Area( x1 + ctTexWidth + 10.0f, 0.0f, x1 + ctTexWidth + 10.0f + ctSpaceWidth, mTexture.getHeight() ); } } void ScrollingLabel::draw() { if (mTexture) { // force texture height to be correct: float restoreY2 = mRect.y2; mRect.y2 = mRect.y1 + mTexture.getHeight(); float ctSpaceWidth = mRect.x2 - mRect.x1; float ctTexWidth = mTexture.getWidth(); if( ctTexWidth < ctSpaceWidth ){ // if the texture width is less than the rect to fit it in... gl::draw(mTexture, mRect.getUpperLeft()); } else { gl::draw( mTexture, mFirstArea, mRect ); gl::draw( mTexture, mSecondArea, mRect ); } // restore mRect // (this is a hack because mRect is also used for hit testing) mRect.y2 = restoreY2; } } bool ScrollingLabel::touchBegan( TouchEvent::Touch touch ) { return mRect.contains( globalToLocal( touch.getPos() ) ); } bool ScrollingLabel::touchEnded( TouchEvent::Touch touch ) { return mRect.contains( globalToLocal( touch.getPos() ) ); } <|endoftext|>
<commit_before>#include "CameraBase.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR) { m_nFlush = 0; m_vPosition = Vec3_zero; m_fPhiAngle = 0.0f; m_fThetaAngle = 0.0f; m_pLastPlayer = NULL; m_nEnabelMouse = 1; SetRadius(1.0f); SetMinThetaAngle(-90.0f); SetMaxThetaAngle(90.0f); SetTurning(90.0f); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetEnabled(0); SetHMDEnabled(1); } CCameraBase::~CCameraBase() { Leave(); } void CCameraBase::SetEnabled(int nEnable) { if(nEnable) { m_pLastPlayer = g_Engine.pGame->GetPlayer(); CPlayer::SetEnabled(nEnable); } else { if (m_pLastPlayer) { g_Engine.pGame->SetPlayer(m_pLastPlayer); CPlayer::SetEnabled(nEnable); } } } int CCameraBase::IsEnabled() const { return CPlayer::IsEnabled(); }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "CameraBase.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR) { m_nFlush = 0; m_vPosition = Vec3_zero; m_fPhiAngle = 0.0f; m_fThetaAngle = 0.0f; m_pLastPlayer = NULL; m_nEnabelMouse = 1; SetRadius(1.0f); SetMinThetaAngle(-90.0f); SetMaxThetaAngle(90.0f); SetTurning(90.0f); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetEnabled(0); SetHMDEnabled(1); } CCameraBase::~CCameraBase() { Leave(); } void CCameraBase::SetEnabled(int nEnable) { if(nEnable) { m_pLastPlayer = g_Engine.pGame->GetPlayer(); CPlayer::SetEnabled(nEnable); } else { if (m_pLastPlayer) { g_Engine.pGame->SetPlayer(m_pLastPlayer); CPlayer::SetEnabled(nEnable); } } } int CCameraBase::IsEnabled() const { return CPlayer::IsEnabled(); } void CCameraBase::SetHMDEnabled(int nEnable) { m_nHMDEnable = nEnable; } <|endoftext|>
<commit_before>/** * @file * * @brief This file contains a basic YAML to `KeySet` converter function. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <cstdio> #include <fstream> #include <iostream> #include <sstream> #include <yaep.h> #include <kdberrors.h> #include "convert.hpp" #include "error_listener.hpp" #include "lexer.hpp" #include "listener.hpp" #include "walk.hpp" #ifdef ENABLE_ASAN #include <sanitizer/lsan_interface.h> #endif using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::string; using std::stringstream; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using ckdb::keyNew; using yawn::ErrorListener; using yawn::Lexer; namespace { // -- Globals ------------------------------------------------------------------------------------------------------------------------------ ErrorListener * errorListenerAdress; Lexer * lexerAddress; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function returns the next token produced by the lexer. * * If the lexer found the end of the input, then this function returns `-1`. * * @param attribute The parser uses this parameter to store auxiliary data for * the returned token. * * @return A number specifying the type of the first token the parser has not * emitted yet */ int nextToken (void ** attribute) { return lexerAddress->nextToken (attribute); } /** * @brief This function reacts to syntax errors reported by YAEP’s parsing * engine. * * @param errorToken This number specifies the token where the error occurred. * @param errorTokenData This variable stores the data contained in * `errorToken`. * @param ignoredToken This number specifies the first token that was ignored * during error recovery. * @param ignoredTokenData This variable stores the data contained in * `ignoredToken`. * @param recoveredToken This number specifies the first included token after * the error recovery has taken place. * @param recoveredTokenData This variable stores the data contained in * `recoveredToken`. */ void syntaxError (int errorToken, void * errorTokenData, int ignoredToken, void * ignoredTokenData, int recoveredToken, void * recoveredTokenData) { return errorListenerAdress->syntaxError (errorToken, errorTokenData, ignoredToken, ignoredTokenData, recoveredToken, recoveredTokenData); } /** * This function allocates a memory region of the given size. * * @param size This variable specifies the amount of data this method should * allocate. * * @return A pointer to a memory region of the specified size */ inline void * alloc (int size) { return elektraMalloc (size); } /** * @brief This function parses the YAML grammar contained in `yaml.bnf`. * * @param parser This variable stores the YAEP parser that uses the YAML grammar contained in `yaml.bnf` to parse input. * @param error This function stores error information in this key, if it was unable to parse the grammar. * * @return A string containing the content of `yaml.bnf`, if parsing of the grammar was successful, or an empty string otherwise */ string parseGrammar (yaep & parser, CppKey & error) { string grammar = #include "yaml_grammar.h" ; if (parser.parse_grammar (1, grammar.c_str ()) != 0) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, error.getKey (), "Unable to parse grammar: %s", parser.error_message ()); return ""; } return grammar; } /** * @brief This function creates a stream containing the content of a given file. * * @param filename This variable stores location of the file for which this function creates an input stream * @param error This function stores an error message in this key, if it was unable to access `filename`. * * @return A input stream that contains the content of `filename`, if creating the stream was successful */ ifstream openFile (string const & filename, CppKey & error) { ifstream input{ filename }; if (!input.good ()) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, error.getKey (), "Unable to open file “%s”", filename.c_str ()); } return input; } /** * @brief This function stores error information in `error`, if parsing was unsuccessful. * * @param ambiguousOutput This variable is true, when YAEP was unable to create a unique syntax tree from the given input. * @param errorListener This object stores information about errors that occurred while YAEP parsed the input. * @param filename This variable stores the location of the file YAEP parsed. * @param grammar This argument stores the YAML grammar used to parse the input. * @param error This function will use this variable to store information about errors that occurred while parsing. * * @retval -1 If there was an error parsing the last input * @retval 0 Otherwise */ int handleErrors (int const ambiguousOutput, ErrorListener const & errorListener, string const & filename, string const & grammar, CppKey & error) { if (ambiguousOutput) { ELEKTRA_SET_ERRORF ( ELEKTRA_ERROR_PARSE, error.getKey (), "The content of file “%s” showed that the grammar:\n%s\nproduces ambiguous output!\n" "Please fix the grammar, to make sure it produces only one unique syntax tree for every kind of YAML input.", filename.c_str (), grammar.c_str ()); return -1; } if (errorListener.getNumberOfErrors () > 0) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_PARSE, error.getKey (), errorListener.getErrorMessage ().c_str ()); return -1; } return 0; } } // namespace namespace yawn { /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -2 if the file could not be opened for reading * @retval -1 if there was a error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given key set * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (CppKeySet & keySet, CppKey & parent, string const & filename) { #ifdef ENABLE_ASAN __lsan_disable (); #endif yaep parser; #ifdef ENABLE_ASAN __lsan_enable (); #endif auto grammar = parseGrammar (parser, parent); if (grammar.size () <= 0) return -1; auto input = openFile (filename, parent); if (!input.good ()) return -1; ErrorListener errorListener; errorListenerAdress = &errorListener; Lexer lexer{ input }; lexerAddress = &lexer; int ambiguousOutput; struct yaep_tree_node * root = nullptr; #ifdef ENABLE_ASAN __lsan_disable (); #endif parser.parse (nextToken, syntaxError, alloc, nullptr, &root, &ambiguousOutput); #ifdef ENABLE_ASAN __lsan_enable (); #endif if (handleErrors (ambiguousOutput, errorListener, filename, grammar, parent) < 0) return -1; Listener listener{ parent }; walk (listener, root); keySet.append (listener.getKeySet ()); return listener.getKeySet ().size () > 0; } } // namespace yawn <commit_msg>YAwn: Specify deallocation function for parser<commit_after>/** * @file * * @brief This file contains a basic YAML to `KeySet` converter function. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <cstdio> #include <fstream> #include <iostream> #include <sstream> #include <yaep.h> #include <kdberrors.h> #include "convert.hpp" #include "error_listener.hpp" #include "lexer.hpp" #include "listener.hpp" #include "walk.hpp" #ifdef ENABLE_ASAN #include <sanitizer/lsan_interface.h> #endif using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::string; using std::stringstream; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using ckdb::keyNew; using yawn::ErrorListener; using yawn::Lexer; namespace { // -- Globals ------------------------------------------------------------------------------------------------------------------------------ ErrorListener * errorListenerAdress; Lexer * lexerAddress; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function returns the next token produced by the lexer. * * If the lexer found the end of the input, then this function returns `-1`. * * @param attribute The parser uses this parameter to store auxiliary data for * the returned token. * * @return A number specifying the type of the first token the parser has not * emitted yet */ int nextToken (void ** attribute) { return lexerAddress->nextToken (attribute); } /** * @brief This function reacts to syntax errors reported by YAEP’s parsing * engine. * * @param errorToken This number specifies the token where the error occurred. * @param errorTokenData This variable stores the data contained in * `errorToken`. * @param ignoredToken This number specifies the first token that was ignored * during error recovery. * @param ignoredTokenData This variable stores the data contained in * `ignoredToken`. * @param recoveredToken This number specifies the first included token after * the error recovery has taken place. * @param recoveredTokenData This variable stores the data contained in * `recoveredToken`. */ void syntaxError (int errorToken, void * errorTokenData, int ignoredToken, void * ignoredTokenData, int recoveredToken, void * recoveredTokenData) { return errorListenerAdress->syntaxError (errorToken, errorTokenData, ignoredToken, ignoredTokenData, recoveredToken, recoveredTokenData); } /** * This function allocates a memory region of the given size. * * @param size This variable specifies the amount of data this method should * allocate. * * @return A pointer to a memory region of the specified size */ inline void * alloc (int size) { return elektraMalloc (size); } /** * @brief This function parses the YAML grammar contained in `yaml.bnf`. * * @param parser This variable stores the YAEP parser that uses the YAML grammar contained in `yaml.bnf` to parse input. * @param error This function stores error information in this key, if it was unable to parse the grammar. * * @return A string containing the content of `yaml.bnf`, if parsing of the grammar was successful, or an empty string otherwise */ string parseGrammar (yaep & parser, CppKey & error) { string grammar = #include "yaml_grammar.h" ; if (parser.parse_grammar (1, grammar.c_str ()) != 0) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, error.getKey (), "Unable to parse grammar: %s", parser.error_message ()); return ""; } return grammar; } /** * @brief This function creates a stream containing the content of a given file. * * @param filename This variable stores location of the file for which this function creates an input stream * @param error This function stores an error message in this key, if it was unable to access `filename`. * * @return A input stream that contains the content of `filename`, if creating the stream was successful */ ifstream openFile (string const & filename, CppKey & error) { ifstream input{ filename }; if (!input.good ()) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, error.getKey (), "Unable to open file “%s”", filename.c_str ()); } return input; } /** * @brief This function stores error information in `error`, if parsing was unsuccessful. * * @param ambiguousOutput This variable is true, when YAEP was unable to create a unique syntax tree from the given input. * @param errorListener This object stores information about errors that occurred while YAEP parsed the input. * @param filename This variable stores the location of the file YAEP parsed. * @param grammar This argument stores the YAML grammar used to parse the input. * @param error This function will use this variable to store information about errors that occurred while parsing. * * @retval -1 If there was an error parsing the last input * @retval 0 Otherwise */ int handleErrors (int const ambiguousOutput, ErrorListener const & errorListener, string const & filename, string const & grammar, CppKey & error) { if (ambiguousOutput) { ELEKTRA_SET_ERRORF ( ELEKTRA_ERROR_PARSE, error.getKey (), "The content of file “%s” showed that the grammar:\n%s\nproduces ambiguous output!\n" "Please fix the grammar, to make sure it produces only one unique syntax tree for every kind of YAML input.", filename.c_str (), grammar.c_str ()); return -1; } if (errorListener.getNumberOfErrors () > 0) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_PARSE, error.getKey (), errorListener.getErrorMessage ().c_str ()); return -1; } return 0; } } // namespace namespace yawn { /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -2 if the file could not be opened for reading * @retval -1 if there was a error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given key set * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (CppKeySet & keySet, CppKey & parent, string const & filename) { #ifdef ENABLE_ASAN __lsan_disable (); #endif yaep parser; #ifdef ENABLE_ASAN __lsan_enable (); #endif auto grammar = parseGrammar (parser, parent); if (grammar.size () <= 0) return -1; auto input = openFile (filename, parent); if (!input.good ()) return -1; ErrorListener errorListener; errorListenerAdress = &errorListener; Lexer lexer{ input }; lexerAddress = &lexer; int ambiguousOutput; struct yaep_tree_node * root = nullptr; #ifdef ENABLE_ASAN __lsan_disable (); #endif // TODO: Free parse tree after YAEP provides a function to do that parser.parse (nextToken, syntaxError, alloc, elektraFree, &root, &ambiguousOutput); #ifdef ENABLE_ASAN __lsan_enable (); #endif if (handleErrors (ambiguousOutput, errorListener, filename, grammar, parent) < 0) return -1; Listener listener{ parent }; walk (listener, root); keySet.append (listener.getKeySet ()); return listener.getKeySet ().size () > 0; } } // namespace yawn <|endoftext|>
<commit_before>// @(#)root/pyroot:$Id$ // Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "PyStrings.h" #include "ObjectProxy.h" #include "Utility.h" // ROOT #include "TObject.h" #include "TBufferFile.h" // for pickling //- data _______________________________________________________________________ R__EXTERN PyObject* gRootModule; //____________________________________________________________________________ void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) { // Destroy the held C++ object, if owned; does not deallocate the proxy. if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) { pyobj->ObjectIsA()->Destructor( pyobj->fObject ); } pyobj->fObject = NULL; } //____________________________________________________________________________ namespace PyROOT { namespace { //= PyROOT object proxy null-ness checking =================================== PyObject* op_nonzero( ObjectProxy* self ) { // Null of the proxy is determined by null-ness of the held C++ object. PyObject* result = self->GetObject() ? Py_True : Py_False; Py_INCREF( result ); return result; } //= PyROOT object proxy pickle support ======================================= PyObject* op_reduce( ObjectProxy* self ) { // Turn the object proxy instance into a character stream and return for // pickle, together with the callable object that can restore the stream // into the object proxy instance. // keep a borrowed reference around to the callable function for expanding; // because it is borrowed, it means that there can be no pickling during the // shutdown of the libPyROOT module static PyObject* s_expand = PyDict_GetItemString( PyModule_GetDict( gRootModule ), const_cast< char* >( "_ObjectProxy__expand__" ) ); // TBuffer and its derived classes can't write themselves, but can be created // directly from the buffer, so handle them in a special case static TClassRef s_bfClass( "TBufferFile" ); TBufferFile* buff = 0; if ( s_bfClass == self->ObjectIsA() ) { buff = (TBufferFile*)self->GetObject(); } else { // no cast is needed, but WriteObject taking a TClass argument is protected, // so use WriteObjectAny() static TBufferFile s_buff( TBuffer::kWrite ); s_buff.Reset(); if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) { PyErr_Format( PyExc_IOError, "could not stream object of type %s", self->ObjectIsA()->GetName() ); return 0; } buff = &s_buff; } // use a string for the serialized result, as a python buffer will not copy // the buffer contents; use a string for the class name, used when casting // on reading back in (see RootModule.cxx:TObjectExpand) PyObject* res2 = PyTuple_New( 2 ); PyTuple_SET_ITEM( res2, 0, PyBytes_FromStringAndSize( buff->Buffer(), buff->Length() ) ); PyTuple_SET_ITEM( res2, 1, PyBytes_FromString( self->ObjectIsA()->GetName() ) ); PyObject* result = PyTuple_New( 2 ); Py_INCREF( s_expand ); PyTuple_SET_ITEM( result, 0, s_expand ); PyTuple_SET_ITEM( result, 1, res2 ); return result; } //____________________________________________________________________________ PyMethodDef op_methods[] = { { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, { (char*)"__bool__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, // for p3 { (char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS, NULL }, { (char*)NULL, NULL, 0, NULL } }; //= PyROOT object proxy construction/destruction ============================= ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* ) { // Create a new object proxy (holder only). ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 ); pyobj->fObject = NULL; pyobj->fFlags = 0; return pyobj; } //____________________________________________________________________________ void op_dealloc( ObjectProxy* pyobj ) { // Remove memory held by the object proxy. op_dealloc_nofree( pyobj ); Py_TYPE(pyobj)->tp_free( (PyObject*)pyobj ); } //____________________________________________________________________________ PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op ) { // Rich set of comparison objects; only equals and not-equals are defined. if ( op != Py_EQ && op != Py_NE ) { Py_INCREF( Py_NotImplemented ); return Py_NotImplemented; } Bool_t bIsEq = false; // special case for None to compare True to a null-pointer if ( (PyObject*)other == Py_None && ! self->fObject ) bIsEq = true; // type + held pointer value defines identity (will cover if other is not // actually an ObjectProxy, as ob_type will be unequal) else if ( Py_TYPE(self) == Py_TYPE(other) && self->fObject == other->fObject ) bIsEq = true; if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) { Py_INCREF( Py_True ); return Py_True; } Py_INCREF( Py_False ); return Py_False; } //____________________________________________________________________________ PyObject* op_repr( ObjectProxy* pyobj ) { // Build a representation string of the object proxy that shows the address // of the C++ object that is held, as well as its type. TClass* klass = pyobj->ObjectIsA(); if ( pyobj->GetObject() ) { TClass* clActual = klass->GetActualClass( pyobj->GetObject() ); if ( clActual ) klass = clActual; } std::string clName = klass ? klass->GetName() : "<unknown>"; if ( pyobj->fFlags & ObjectProxy::kIsReference ) clName.append( "*" ); // need to prevent accidental derefs when just printing (usually unsafe) if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) { PyObject* name = PyObject_CallMethod( (PyObject*)pyobj, const_cast< char* >( "GetName" ), const_cast< char* >( "" ) ); if ( name ) { if ( PyROOT_PyUnicode_GET_SIZE( name ) != 0 ) { PyObject* repr = PyROOT_PyUnicode_FromFormat( "<ROOT.%s object (\"%s\") at %p>", clName.c_str(), PyROOT_PyUnicode_AsString( name ), pyobj->GetObject() ); Py_DECREF( name ); return repr; } Py_DECREF( name ); } else PyErr_Clear(); } // get here if object has no method GetName() or name = "" return PyROOT_PyUnicode_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ), clName.c_str(), pyobj->GetObject() ); } //= PyROOT type number stubs to allow dynamic overrides ====================== #define PYROOT_STUB( name, op, pystring ) \ PyObject* op_##name##_stub( PyObject* self, PyObject* other ) \ { \ /* place holder to lazily install __name__ if a global overload is available */ \ if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\ Py_INCREF( Py_NotImplemented ); \ return Py_NotImplemented; \ } \ \ /* redo the call, which will now go to the newly installed method */ \ return PyObject_CallMethodObjArgs( self, pystring, other, NULL ); \ } PYROOT_STUB( add, +, PyStrings::gAdd ) PYROOT_STUB( sub, -, PyStrings::gSub ) PYROOT_STUB( mul, *, PyStrings::gMul ) PYROOT_STUB( div, /, PyStrings::gDiv ) //____________________________________________________________________________ PyNumberMethods op_as_number = { (binaryfunc)op_add_stub, // nb_add (binaryfunc)op_sub_stub, // nb_subtract (binaryfunc)op_mul_stub, // nb_multiply #if PY_VERSION_HEX < 0x03000000 (binaryfunc)op_div_stub, // nb_divide #endif 0, // nb_remainder 0, // nb_divmod 0, // nb_power 0, // nb_negative 0, // nb_positive 0, // nb_absolute 0, // tp_nonzero (nb_bool in p3) 0, // nb_invert 0, // nb_lshift 0, // nb_rshift 0, // nb_and 0, // nb_xor 0, // nb_or #if PY_VERSION_HEX < 0x03000000 0, // nb_coerce #endif 0, // nb_int 0, // nb_long (nb_reserved in p3) 0, // nb_float #if PY_VERSION_HEX < 0x03000000 0, // nb_oct 0, // nb_hex #endif 0, // nb_inplace_add 0, // nb_inplace_subtract 0, // nb_inplace_multiply #if PY_VERSION_HEX < 0x03000000 0, // nb_inplace_divide #endif 0, // nb_inplace_remainder 0, // nb_inplace_power 0, // nb_inplace_lshift 0, // nb_inplace_rshift 0, // nb_inplace_and 0, // nb_inplace_xor 0 // nb_inplace_or #if PY_VERSION_HEX >= 0x02020000 , 0 // nb_floor_divide #if PY_VERSION_HEX < 0x03000000 , 0 // nb_true_divide #else , (binaryfunc)op_div_stub // nb_true_divide #endif , 0 // nb_inplace_floor_divide , 0 // nb_inplace_true_divide #endif #if PY_VERSION_HEX >= 0x02050000 , 0 // nb_index #endif }; } // unnamed namespace //= PyROOT object proxy type ================================================= PyTypeObject ObjectProxy_Type = { PyVarObject_HEAD_INIT( &PyRootType_Type, 0 ) (char*)"ROOT.ObjectProxy", // tp_name sizeof(ObjectProxy), // tp_basicsize 0, // tp_itemsize (destructor)op_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)op_repr, // tp_repr &op_as_number, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES, // tp_flags (char*)"PyROOT object proxy (internal)", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)op_richcompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext op_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)op_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0 // tp_weaklist #if PY_VERSION_HEX >= 0x02030000 , 0 // tp_del #endif #if PY_VERSION_HEX >= 0x02060000 , 0 // tp_version_tag #endif }; } // namespace PyROOT <commit_msg>don't get actual class for printing: if the object does not already carry the actual class, this is usually for good reasons<commit_after>// @(#)root/pyroot:$Id$ // Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "PyStrings.h" #include "ObjectProxy.h" #include "Utility.h" // ROOT #include "TObject.h" #include "TBufferFile.h" // for pickling //- data _______________________________________________________________________ R__EXTERN PyObject* gRootModule; //____________________________________________________________________________ void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) { // Destroy the held C++ object, if owned; does not deallocate the proxy. if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) { pyobj->ObjectIsA()->Destructor( pyobj->fObject ); } pyobj->fObject = NULL; } //____________________________________________________________________________ namespace PyROOT { namespace { //= PyROOT object proxy null-ness checking =================================== PyObject* op_nonzero( ObjectProxy* self ) { // Null of the proxy is determined by null-ness of the held C++ object. PyObject* result = self->GetObject() ? Py_True : Py_False; Py_INCREF( result ); return result; } //= PyROOT object proxy pickle support ======================================= PyObject* op_reduce( ObjectProxy* self ) { // Turn the object proxy instance into a character stream and return for // pickle, together with the callable object that can restore the stream // into the object proxy instance. // keep a borrowed reference around to the callable function for expanding; // because it is borrowed, it means that there can be no pickling during the // shutdown of the libPyROOT module static PyObject* s_expand = PyDict_GetItemString( PyModule_GetDict( gRootModule ), const_cast< char* >( "_ObjectProxy__expand__" ) ); // TBuffer and its derived classes can't write themselves, but can be created // directly from the buffer, so handle them in a special case static TClassRef s_bfClass( "TBufferFile" ); TBufferFile* buff = 0; if ( s_bfClass == self->ObjectIsA() ) { buff = (TBufferFile*)self->GetObject(); } else { // no cast is needed, but WriteObject taking a TClass argument is protected, // so use WriteObjectAny() static TBufferFile s_buff( TBuffer::kWrite ); s_buff.Reset(); if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) { PyErr_Format( PyExc_IOError, "could not stream object of type %s", self->ObjectIsA()->GetName() ); return 0; } buff = &s_buff; } // use a string for the serialized result, as a python buffer will not copy // the buffer contents; use a string for the class name, used when casting // on reading back in (see RootModule.cxx:TObjectExpand) PyObject* res2 = PyTuple_New( 2 ); PyTuple_SET_ITEM( res2, 0, PyBytes_FromStringAndSize( buff->Buffer(), buff->Length() ) ); PyTuple_SET_ITEM( res2, 1, PyBytes_FromString( self->ObjectIsA()->GetName() ) ); PyObject* result = PyTuple_New( 2 ); Py_INCREF( s_expand ); PyTuple_SET_ITEM( result, 0, s_expand ); PyTuple_SET_ITEM( result, 1, res2 ); return result; } //____________________________________________________________________________ PyMethodDef op_methods[] = { { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, { (char*)"__bool__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, // for p3 { (char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS, NULL }, { (char*)NULL, NULL, 0, NULL } }; //= PyROOT object proxy construction/destruction ============================= ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* ) { // Create a new object proxy (holder only). ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 ); pyobj->fObject = NULL; pyobj->fFlags = 0; return pyobj; } //____________________________________________________________________________ void op_dealloc( ObjectProxy* pyobj ) { // Remove memory held by the object proxy. op_dealloc_nofree( pyobj ); Py_TYPE(pyobj)->tp_free( (PyObject*)pyobj ); } //____________________________________________________________________________ PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op ) { // Rich set of comparison objects; only equals and not-equals are defined. if ( op != Py_EQ && op != Py_NE ) { Py_INCREF( Py_NotImplemented ); return Py_NotImplemented; } Bool_t bIsEq = false; // special case for None to compare True to a null-pointer if ( (PyObject*)other == Py_None && ! self->fObject ) bIsEq = true; // type + held pointer value defines identity (will cover if other is not // actually an ObjectProxy, as ob_type will be unequal) else if ( Py_TYPE(self) == Py_TYPE(other) && self->fObject == other->fObject ) bIsEq = true; if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) { Py_INCREF( Py_True ); return Py_True; } Py_INCREF( Py_False ); return Py_False; } //____________________________________________________________________________ PyObject* op_repr( ObjectProxy* pyobj ) { // Build a representation string of the object proxy that shows the address // of the C++ object that is held, as well as its type. TClass* klass = pyobj->ObjectIsA(); std::string clName = klass ? klass->GetName() : "<unknown>"; if ( pyobj->fFlags & ObjectProxy::kIsReference ) clName.append( "*" ); // need to prevent accidental derefs when just printing (usually unsafe) if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) { PyObject* name = PyObject_CallMethod( (PyObject*)pyobj, const_cast< char* >( "GetName" ), const_cast< char* >( "" ) ); if ( name ) { if ( PyROOT_PyUnicode_GET_SIZE( name ) != 0 ) { PyObject* repr = PyROOT_PyUnicode_FromFormat( "<ROOT.%s object (\"%s\") at %p>", clName.c_str(), PyROOT_PyUnicode_AsString( name ), pyobj->GetObject() ); Py_DECREF( name ); return repr; } Py_DECREF( name ); } else PyErr_Clear(); } // get here if object has no method GetName() or name = "" return PyROOT_PyUnicode_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ), clName.c_str(), pyobj->GetObject() ); } //= PyROOT type number stubs to allow dynamic overrides ====================== #define PYROOT_STUB( name, op, pystring ) \ PyObject* op_##name##_stub( PyObject* self, PyObject* other ) \ { \ /* place holder to lazily install __name__ if a global overload is available */ \ if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\ Py_INCREF( Py_NotImplemented ); \ return Py_NotImplemented; \ } \ \ /* redo the call, which will now go to the newly installed method */ \ return PyObject_CallMethodObjArgs( self, pystring, other, NULL ); \ } PYROOT_STUB( add, +, PyStrings::gAdd ) PYROOT_STUB( sub, -, PyStrings::gSub ) PYROOT_STUB( mul, *, PyStrings::gMul ) PYROOT_STUB( div, /, PyStrings::gDiv ) //____________________________________________________________________________ PyNumberMethods op_as_number = { (binaryfunc)op_add_stub, // nb_add (binaryfunc)op_sub_stub, // nb_subtract (binaryfunc)op_mul_stub, // nb_multiply #if PY_VERSION_HEX < 0x03000000 (binaryfunc)op_div_stub, // nb_divide #endif 0, // nb_remainder 0, // nb_divmod 0, // nb_power 0, // nb_negative 0, // nb_positive 0, // nb_absolute 0, // tp_nonzero (nb_bool in p3) 0, // nb_invert 0, // nb_lshift 0, // nb_rshift 0, // nb_and 0, // nb_xor 0, // nb_or #if PY_VERSION_HEX < 0x03000000 0, // nb_coerce #endif 0, // nb_int 0, // nb_long (nb_reserved in p3) 0, // nb_float #if PY_VERSION_HEX < 0x03000000 0, // nb_oct 0, // nb_hex #endif 0, // nb_inplace_add 0, // nb_inplace_subtract 0, // nb_inplace_multiply #if PY_VERSION_HEX < 0x03000000 0, // nb_inplace_divide #endif 0, // nb_inplace_remainder 0, // nb_inplace_power 0, // nb_inplace_lshift 0, // nb_inplace_rshift 0, // nb_inplace_and 0, // nb_inplace_xor 0 // nb_inplace_or #if PY_VERSION_HEX >= 0x02020000 , 0 // nb_floor_divide #if PY_VERSION_HEX < 0x03000000 , 0 // nb_true_divide #else , (binaryfunc)op_div_stub // nb_true_divide #endif , 0 // nb_inplace_floor_divide , 0 // nb_inplace_true_divide #endif #if PY_VERSION_HEX >= 0x02050000 , 0 // nb_index #endif }; } // unnamed namespace //= PyROOT object proxy type ================================================= PyTypeObject ObjectProxy_Type = { PyVarObject_HEAD_INIT( &PyRootType_Type, 0 ) (char*)"ROOT.ObjectProxy", // tp_name sizeof(ObjectProxy), // tp_basicsize 0, // tp_itemsize (destructor)op_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)op_repr, // tp_repr &op_as_number, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES, // tp_flags (char*)"PyROOT object proxy (internal)", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)op_richcompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext op_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)op_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0 // tp_weaklist #if PY_VERSION_HEX >= 0x02030000 , 0 // tp_del #endif #if PY_VERSION_HEX >= 0x02060000 , 0 // tp_version_tag #endif }; } // namespace PyROOT <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include <boost/test/unit_test.hpp> #include "mutation_reader.hh" #include "mutation_assertions.hh" // Intended to be called in a seastar thread class reader_assertions { mutation_reader _reader; public: reader_assertions(mutation_reader reader) : _reader(std::move(reader)) { } reader_assertions& produces(mutation m) { _reader().then([this, m = std::move(m)] (mutation_opt&& mo) mutable { BOOST_REQUIRE(bool(mo)); assert_that(*mo).is_equal_to(m); }).get0(); return *this; } reader_assertions& produces_end_of_stream() { _reader().then([this] (mutation_opt&& mo) mutable { if (bool(mo)) { BOOST_FAIL(sprint("Expected end of stream, got %s", *mo)); } }).get0(); return *this; } }; inline reader_assertions assert_that(mutation_reader r) { return { std::move(r) }; } <commit_msg>tests: Introduce reader_assertions::produces() which takes a vector<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include <boost/test/unit_test.hpp> #include "mutation_reader.hh" #include "mutation_assertions.hh" // Intended to be called in a seastar thread class reader_assertions { mutation_reader _reader; public: reader_assertions(mutation_reader reader) : _reader(std::move(reader)) { } reader_assertions& produces(mutation m) { _reader().then([this, m = std::move(m)] (mutation_opt&& mo) mutable { BOOST_REQUIRE(bool(mo)); assert_that(*mo).is_equal_to(m); }).get0(); return *this; } reader_assertions& produces(const std::vector<mutation>& mutations) { for (auto&& m : mutations) { produces(m); } return *this; } reader_assertions& produces_end_of_stream() { _reader().then([this] (mutation_opt&& mo) mutable { if (bool(mo)) { BOOST_FAIL(sprint("Expected end of stream, got %s", *mo)); } }).get0(); return *this; } }; inline reader_assertions assert_that(mutation_reader r) { return { std::move(r) }; } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2015 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 <stdio.h> #include <string.h> #include <getopt.h> #include <assert.h> #include <iostream> #include <fstream> #include "ClusterMetrics.h" #include "Context.h" #include "Cycles.h" #include "Dispatch.h" #include "ShortMacros.h" #include "Crc32C.h" #include "ObjectFinder.h" #include "OptionParser.h" #include "RamCloud.h" #include "Tub.h" #include "IndexLookup.h" #include "TableEnumerator.h" using namespace RAMCloud; int main(int argc, char *argv[]) try { int clientIndex; int numClients; string tableName; string imageFileName; // Set line buffering for stdout so that printf's and log messages // interleave properly. setvbuf(stdout, NULL, _IOLBF, 1024); // need external context to set log levels with OptionParser Context context(false); OptionsDescription clientOptions("TableDownloader"); clientOptions.add_options() // These first two options are currently ignored. They're here so that // this script can be run with cluster.py. ("clientIndex", ProgramOptions::value<int>(&clientIndex)-> default_value(0), "Index of this client (first client is 0; currently ignored)") ("numClients", ProgramOptions::value<int>(&numClients)-> default_value(1), "Total number of clients running (currently ignored)") ("tableName", ProgramOptions::value<string>(&tableName), "Name of the table to image.") ("imageFile", ProgramOptions::value<string>(&imageFileName), "Name of the image file to create."); OptionParser optionParser(clientOptions, argc, argv); context.transportManager->setSessionTimeout( optionParser.options.getSessionTimeout()); LOG(NOTICE, "Connecting to %s", optionParser.options.getCoordinatorLocator().c_str()); string locator = optionParser.options.getExternalStorageLocator(); if (locator.size() == 0) { locator = optionParser.options.getCoordinatorLocator(); } RamCloud client(&context, locator.c_str(), optionParser.options.getClusterName().c_str()); LOG(NOTICE, "Downloading table %s to file %s", tableName.c_str(), imageFileName.c_str()); std::ofstream imageFile; imageFile.open(imageFileName.c_str(), std::ios::binary); uint64_t tableId; tableId = client.getTableId(tableName.c_str()); TableEnumerator iter(client, tableId, false); uint32_t keyLength = 0; const void* key = 0; uint32_t dataLength = 0; const void* data = 0; long objCount = 0; long byteCount = 0; while (true) { if (objCount > 1220940) LOG(NOTICE, "%d ", objCount); if (!iter.hasNext()) break; if (objCount > 1220940) LOG(NOTICE, "%d ", objCount); iter.nextKeyAndData(&keyLength, &key, &dataLength, &data); if (objCount > 1220940) LOG(NOTICE, "%d ", objCount); imageFile.write((char*) &keyLength, sizeof(uint32_t)); imageFile.write((char*) key, keyLength); imageFile.write((char*) &dataLength, sizeof(uint32_t)); imageFile.write((char*) data, dataLength); if (objCount > 1220940) LOG(NOTICE, "%d \n", objCount); objCount++; byteCount += keyLength + dataLength; if (objCount % 100000 == 0) { LOG(NOTICE, "Downloaded %d objects totalling %d bytes.", objCount, byteCount); } } LOG(NOTICE, "writing out file..."); imageFile.close(); LOG(NOTICE, "Table downloaded."); return 0; } catch (RAMCloud::ClientException& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } catch (RAMCloud::Exception& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } <commit_msg>Removed logging statements from TableDownloader.<commit_after>/* Copyright (c) 2009-2015 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 <stdio.h> #include <string.h> #include <getopt.h> #include <assert.h> #include <iostream> #include <fstream> #include "ClusterMetrics.h" #include "Context.h" #include "Cycles.h" #include "Dispatch.h" #include "ShortMacros.h" #include "Crc32C.h" #include "ObjectFinder.h" #include "OptionParser.h" #include "RamCloud.h" #include "Tub.h" #include "IndexLookup.h" #include "TableEnumerator.h" using namespace RAMCloud; int main(int argc, char *argv[]) try { int clientIndex; int numClients; string tableName; string imageFileName; // Set line buffering for stdout so that printf's and log messages // interleave properly. setvbuf(stdout, NULL, _IOLBF, 1024); // need external context to set log levels with OptionParser Context context(false); OptionsDescription clientOptions("TableDownloader"); clientOptions.add_options() // These first two options are currently ignored. They're here so that // this script can be run with cluster.py. ("clientIndex", ProgramOptions::value<int>(&clientIndex)-> default_value(0), "Index of this client (first client is 0; currently ignored)") ("numClients", ProgramOptions::value<int>(&numClients)-> default_value(1), "Total number of clients running (currently ignored)") ("tableName", ProgramOptions::value<string>(&tableName), "Name of the table to image.") ("imageFile", ProgramOptions::value<string>(&imageFileName), "Name of the image file to create."); OptionParser optionParser(clientOptions, argc, argv); context.transportManager->setSessionTimeout( optionParser.options.getSessionTimeout()); LOG(NOTICE, "Connecting to %s", optionParser.options.getCoordinatorLocator().c_str()); string locator = optionParser.options.getExternalStorageLocator(); if (locator.size() == 0) { locator = optionParser.options.getCoordinatorLocator(); } RamCloud client(&context, locator.c_str(), optionParser.options.getClusterName().c_str()); LOG(NOTICE, "Downloading table %s to file %s", tableName.c_str(), imageFileName.c_str()); std::ofstream imageFile; imageFile.open(imageFileName.c_str(), std::ios::binary); uint64_t tableId; tableId = client.getTableId(tableName.c_str()); TableEnumerator iter(client, tableId, false); uint32_t keyLength = 0; const void* key = 0; uint32_t dataLength = 0; const void* data = 0; long objCount = 0; long byteCount = 0; while (true) { if (!iter.hasNext()) break; iter.nextKeyAndData(&keyLength, &key, &dataLength, &data); imageFile.write((char*) &keyLength, sizeof(uint32_t)); imageFile.write((char*) key, keyLength); imageFile.write((char*) &dataLength, sizeof(uint32_t)); imageFile.write((char*) data, dataLength); objCount++; byteCount += keyLength + dataLength; if (objCount % 100000 == 0) { LOG(NOTICE, "Downloaded %d objects totalling %d bytes.", objCount, byteCount); } } LOG(NOTICE, "Closing file..."); imageFile.close(); LOG(NOTICE, "Table downloaded."); return 0; } catch (RAMCloud::ClientException& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } catch (RAMCloud::Exception& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } <|endoftext|>
<commit_before>//================================================== // Copyright (c) 2015 Deividas Kazlauskas // // See the file license.txt for copying permission. //================================================== /* * ===================================================================================== * * Filename: Sugar.hpp * * Description: Syntax sugar * * Version: 1.0 * Created: 07/07/2014 07:13:15 PM * Compiler: gcc * * Author: David Kazlauskas (dk), david@templatious.org * * ===================================================================================== */ #ifndef SUGAR_RISZR4GH #define SUGAR_RISZR4GH #include <templatious/CollectionAdapter.hpp> #include <templatious/adapters/PtrAdapter.hpp> #include <templatious/StaticFactory.hpp> #include <templatious/StaticManipulator.hpp> namespace templatious { template <class T> struct __ForeachCounter { typedef T Iter; Iter _i; bool _keepGoing; __ForeachCounter(const Iter i) : _i(i), _keepGoing(true) {} Iter operator++() { flipGoing(); return ++_i; } void flipGoing() { _keepGoing = !_keepGoing; } Iter operator--() { flipGoing(); return --_i; } }; /** * Templatious foreach macro. * @param var Loop variable name. * @param col Collection to traverse. * * Example: * ~~~~~~~ * std::vector<int> v; * SA::add(v,1,3,5); * // v contains {1,3,5} * * TEMPLATIOUS_FOREACH(auto& i,v) { * std::cout << i << " "; * i *= 2; * } * * // prints out * // 1 3 5 * // v now contains {2,6,10} * ~~~~~~~ */ #define TEMPLATIOUS_FOREACH(var,col) \ for (::templatious::__ForeachCounter<decltype(::templatious::StaticAdapter::begin(col))> \ __tmp_i(::templatious::StaticAdapter::begin(col)); \ __tmp_i._i != ::templatious::StaticAdapter::end(col) \ && __tmp_i._keepGoing; \ ++__tmp_i) \ for (var = *__tmp_i._i; ; ({__tmp_i.flipGoing();break;})) /** * 0 to N traversal. * @param var Loop variable name (type is long) * @param to Number to traverse to * * Example: * ~~~~~~~ * int sumA = 0; * int sumB = 0; * * for (int i = 0; i < 10; ++i) { * sumA += i; * } * * TEMPLATIOUS_0_TO_N(i,10) { * sumB += i; * } * * assert( sumA == sumB ); * ~~~~~~~ */ #define TEMPLATIOUS_0_TO_N(var,to) \ for (long var = 0; var < to; ++var) /** * Repeat underlying block of code n times. * * Example: * ~~~~~~~ * int count = 0; * TEMPLATIOUS_REPEAT( 7 ) { * ++count; * } * assert( count == 7 ); * ~~~~~~~ */ #define TEMPLATIOUS_REPEAT(n) \ for (long __tmp_i = 0; __tmp_i < n; ++__tmp_i) #define TEMPLATIOUS_TRIPLET(AdName,FactName,ManipName) \ typedef templatious::StaticAdapter AdName;\ typedef templatious::StaticFactory FactName;\ typedef templatious::StaticManipulator ManipName; #define TEMPLATIOUS_TRIPLET_STD TEMPLATIOUS_TRIPLET(SA,SF,SM) #define TEMPLATIOUS_VPCORE templatious::VirtualPackCore #define TEMPLATIOUS_CALLEACH_FCTOR(name, expr) \ TEMPLATIOUS_TRIPLET_STD;\ struct name {\ template <class T>\ void operator()(T&& i) {\ expr;\ }\ }; #define TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(name, expr) \ TEMPLATIOUS_TRIPLET_STD;\ template <class StorType>\ struct name {\ name(const StorType& t) : _c(t) {}\ name() {}\ template <class T>\ bool operator()(T&& i) {\ expr;\ return true;\ }\ StorType _c;\ }; } #endif /* end of include guard: SUGAR_RISZR4GH */ <commit_msg>triplet docs<commit_after>//================================================== // Copyright (c) 2015 Deividas Kazlauskas // // See the file license.txt for copying permission. //================================================== /* * ===================================================================================== * * Filename: Sugar.hpp * * Description: Syntax sugar * * Version: 1.0 * Created: 07/07/2014 07:13:15 PM * Compiler: gcc * * Author: David Kazlauskas (dk), david@templatious.org * * ===================================================================================== */ #ifndef SUGAR_RISZR4GH #define SUGAR_RISZR4GH #include <templatious/CollectionAdapter.hpp> #include <templatious/adapters/PtrAdapter.hpp> #include <templatious/StaticFactory.hpp> #include <templatious/StaticManipulator.hpp> namespace templatious { template <class T> struct __ForeachCounter { typedef T Iter; Iter _i; bool _keepGoing; __ForeachCounter(const Iter i) : _i(i), _keepGoing(true) {} Iter operator++() { flipGoing(); return ++_i; } void flipGoing() { _keepGoing = !_keepGoing; } Iter operator--() { flipGoing(); return --_i; } }; /** * Templatious foreach macro. * @param var Loop variable name. * @param col Collection to traverse. * * Example: * ~~~~~~~ * std::vector<int> v; * SA::add(v,1,3,5); * // v contains {1,3,5} * * TEMPLATIOUS_FOREACH(auto& i,v) { * std::cout << i << " "; * i *= 2; * } * * // prints out * // 1 3 5 * // v now contains {2,6,10} * ~~~~~~~ */ #define TEMPLATIOUS_FOREACH(var,col) \ for (::templatious::__ForeachCounter<decltype(::templatious::StaticAdapter::begin(col))> \ __tmp_i(::templatious::StaticAdapter::begin(col)); \ __tmp_i._i != ::templatious::StaticAdapter::end(col) \ && __tmp_i._keepGoing; \ ++__tmp_i) \ for (var = *__tmp_i._i; ; ({__tmp_i.flipGoing();break;})) /** * 0 to N traversal. * @param var Loop variable name (type is long) * @param to Number to traverse to * * Example: * ~~~~~~~ * int sumA = 0; * int sumB = 0; * * for (int i = 0; i < 10; ++i) { * sumA += i; * } * * TEMPLATIOUS_0_TO_N(i,10) { * sumB += i; * } * * assert( sumA == sumB ); * ~~~~~~~ */ #define TEMPLATIOUS_0_TO_N(var,to) \ for (long var = 0; var < to; ++var) /** * Repeat underlying block of code n times. * * Example: * ~~~~~~~ * int count = 0; * TEMPLATIOUS_REPEAT( 7 ) { * ++count; * } * assert( count == 7 ); * ~~~~~~~ */ #define TEMPLATIOUS_REPEAT(n) \ for (long __tmp_i = 0; __tmp_i < n; ++__tmp_i) #define TEMPLATIOUS_TRIPLET(AdName,FactName,ManipName) \ typedef templatious::StaticAdapter AdName;\ typedef templatious::StaticFactory FactName;\ typedef templatious::StaticManipulator ManipName; /** * Macro to define main three templatious classes: * templatious::StaticAdapter * templatious::StaticFactory * templatious::StaticManipulator * * Expands to: * ~~~~~~~ * typedef templatious::StaticAdapter SA; * typedef templatious::StaticFactory SF; * typedef templatious::StaticManipulator SM; * ~~~~~~~ */ #define TEMPLATIOUS_TRIPLET_STD TEMPLATIOUS_TRIPLET(SA,SF,SM) #define TEMPLATIOUS_VPCORE templatious::VirtualPackCore #define TEMPLATIOUS_CALLEACH_FCTOR(name, expr) \ TEMPLATIOUS_TRIPLET_STD;\ struct name {\ template <class T>\ void operator()(T&& i) {\ expr;\ }\ }; #define TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(name, expr) \ TEMPLATIOUS_TRIPLET_STD;\ template <class StorType>\ struct name {\ name(const StorType& t) : _c(t) {}\ name() {}\ template <class T>\ bool operator()(T&& i) {\ expr;\ return true;\ }\ StorType _c;\ }; } #endif /* end of include guard: SUGAR_RISZR4GH */ <|endoftext|>
<commit_before>#include "TaskbarNotificationAreaIcon.h" #include "Res.h" #include <cstdio> #include <cwchar> #include <iostream> #include <windows.h> #ifdef OBSOLETE_WWINMAIN int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR, int nCmdShow) { LPWSTR lpCmdLine=GetCommandLineW(); #else int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { #endif TskbrNtfAreaIcon::OnWmCommand=[](TskbrNtfAreaIcon* sender, WPARAM wParam, LPARAM lParam){ switch (LOWORD(wParam)) { case ID_EXIT: MessageBox(NULL, L"ID_EXIT", L"SNK_HS", MB_OK); PostQuitMessage(0); return true; case ID_STOP_START: MessageBox(NULL, L"ID_STOP_START", L"SNK_HS", MB_OK); return true; case ID_EDIT_SHK: MessageBox(NULL, L"ID_EDIT_SHK", L"SNK_HS", MB_OK); return true; case ID_EDIT_LHK: MessageBox(NULL, L"ID_EDIT_LHK", L"SNK_HS", MB_OK); return true; default: return false; } }; if (!TskbrNtfAreaIcon::MakeInstance(hInstance, WM_HSTNAICO, L"SNK_HS", IDI_HSTNAICO, L"SnK_HotkeySuite_IconClass", IDR_ICONMENU, ID_EXIT)->IsValid()) { MessageBox(NULL, L"Failed to create icon!", L"SNK_HS", MB_OK); return 0; } //At this point taskbar icon is already visible but unusable - it doesn't respond to any clicks and can't show popup menu //So it's ok to customize menu here MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }<commit_msg>Unnecessary includes<commit_after>#include "TaskbarNotificationAreaIcon.h" #include "Res.h" #include <iostream> #include <windows.h> #ifdef OBSOLETE_WWINMAIN int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR, int nCmdShow) { LPWSTR lpCmdLine=GetCommandLineW(); #else int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { #endif TskbrNtfAreaIcon::OnWmCommand=[](TskbrNtfAreaIcon* sender, WPARAM wParam, LPARAM lParam){ switch (LOWORD(wParam)) { case ID_EXIT: MessageBox(NULL, L"ID_EXIT", L"SNK_HS", MB_OK); PostQuitMessage(0); return true; case ID_STOP_START: MessageBox(NULL, L"ID_STOP_START", L"SNK_HS", MB_OK); return true; case ID_EDIT_SHK: MessageBox(NULL, L"ID_EDIT_SHK", L"SNK_HS", MB_OK); return true; case ID_EDIT_LHK: MessageBox(NULL, L"ID_EDIT_LHK", L"SNK_HS", MB_OK); return true; default: return false; } }; if (!TskbrNtfAreaIcon::MakeInstance(hInstance, WM_HSTNAICO, L"SNK_HS", IDI_HSTNAICO, L"SnK_HotkeySuite_IconClass", IDR_ICONMENU, ID_EXIT)->IsValid()) { MessageBox(NULL, L"Failed to create icon!", L"SNK_HS", MB_OK); return 0; } //At this point taskbar icon is already visible but unusable - it doesn't respond to any clicks and can't show popup menu //So it's ok to customize menu here MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }<|endoftext|>
<commit_before>/* * Copyright 2011-2012 Gregory Banks * * 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 "np/spiegel/spiegel.hxx" #include "np/spiegel/dwarf/state.hxx" #include <libintl.h> #include "fw.h" using namespace std; using namespace np::util; #if 0 static unsigned long top_of_stack; static void __dump_stack(unsigned long ebp, unsigned long eip) { unsigned int n = 0; while (ebp < top_of_stack) { printf("%u EBP 0x%08lx EIP 0x%08lx", n, ebp, eip); np::spiegel::location_t loc; if (np::spiegel::describe_address(eip, loc)) printf(" <%s+0x%x> at %s:%u", loc.function_ ? loc.function_->get_name().c_str() : "???", loc.offset_, loc.compile_unit_->get_absolute_path().basename().c_str(), loc.line_); printf("\n"); eip = ((unsigned long *)ebp)[1]; ebp = ((unsigned long *)ebp)[0]; n++; } } #define DUMP_STACK \ { \ register unsigned long ebp; \ register unsigned long eip; \ __asm__ volatile("mov %%ebp,%0" : "=r"(ebp)); \ __asm__ volatile("call .Lxx; .Lxx: popl %0" : "=r"(eip)); \ __dump_stack(ebp, eip); \ } #endif static int the_function_count = 0; int the_function(int x, int y) { int i; if (is_verbose()) printf("Start of the_function, x=%d y=%d\n", x, y); the_function_count++; for (i = 0 ; i < x ; i++) { y *= 5; y--; } if (is_verbose()) printf("End of the_function, returning %d\n", y); return y; } static int another_function_count = 0; int another_function(int x, int y) { int i; if (is_verbose()) printf("Start of another_function, x=%d y=%d\n", x, y); another_function_count++; for (i = 0 ; i < x ; i++) { y *= 2; y++; } if (is_verbose()) printf("End of another_function, returning %d\n", y); return y; } class intercept_tester_t : public np::spiegel::intercept_t { public: intercept_tester_t(); ~intercept_tester_t(); void before(np::spiegel::call_t &); void after(np::spiegel::call_t &); unsigned int after_count; unsigned int before_count; int x, y, r; bool test_skip; bool test_redirect; }; intercept_tester_t::intercept_tester_t() : intercept_t((np::spiegel::addr_t)&the_function) // we don't initialise the counts to 0 because the // inherited operator new does that. { } intercept_tester_t::~intercept_tester_t() { } void intercept_tester_t::before(np::spiegel::call_t &call) { x = call.get_arg(0); y = call.get_arg(1); before_count++; if (is_verbose()) printf("BEFORE x=%d y=%d\n", x, y); if (test_skip) { if (is_verbose()) printf("SKIPPING r=%d\n", r); call.skip(r); } if (test_redirect) { if (is_verbose()) printf("REDIRECTING\n"); call.redirect((np::spiegel::addr_t)&another_function); } } void intercept_tester_t::after(np::spiegel::call_t &call) { r = call.get_retval(); after_count++; if (is_verbose()) printf("AFTER, returning %d\n", r); } int moe(int x, int y) { int r = the_function(x+1, y+1); return r-1; } int curly(int x, int y) { int r = moe(x+1, y+1); return r-1; } int larry(int x, int y) { int r = curly(x+1, y+1); return r-1; } int wide_call(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12) { return a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12; } class wide_intercept_tester_t : public np::spiegel::intercept_t { public: wide_intercept_tester_t() : intercept_t((np::spiegel::addr_t)&wide_call) { } ~wide_intercept_tester_t() { } int x[12], r; void before(np::spiegel::call_t &call) { int i; for (i = 0 ; i < 12 ; i++) x[i] = call.get_arg(i); if (is_verbose()) printf("BEFORE\n"); } void after(np::spiegel::call_t &call) { r = call.get_retval(); if (is_verbose()) printf("AFTER, returning %d\n", r); } }; class plt_intercept_tester_t : public np::spiegel::intercept_t { public: plt_intercept_tester_t() : intercept_t((np::spiegel::addr_t)&gettext) { } ~plt_intercept_tester_t() { } unsigned int after_count; unsigned int before_count; void before(np::spiegel::call_t &call) { if (is_verbose()) printf("BEFORE, arg0 \"%s\"\n", (const char *)call.get_arg(0)); before_count++; } void after(np::spiegel::call_t &call) { const char *s = (const char *)call.get_retval(); if (is_verbose()) printf("AFTER, returning \"%s\"\n", s); after_count++; call.set_retval((unsigned long)"world"); } }; int main(int argc, char **argv __attribute__((unused))) { #if 0 top_of_stack = (unsigned long)&argc; #endif if (argc > 1) { fatal("Usage: testrunner intercept\n"); } np::spiegel::dwarf::state_t state; if (!state.add_self()) return 1; intercept_tester_t *it; int r; BEGIN("basic"); it = new intercept_tester_t(); it->install(); CHECK(it->x == 0); CHECK(it->y == 0); CHECK(it->r == 0); CHECK(it->before_count == 0); CHECK(it->after_count == 0); CHECK(the_function_count == 0); CHECK(another_function_count == 0); r = larry(0, 39); CHECK(r == 5216); CHECK(it->x == 3); CHECK(it->y == 42); CHECK(it->r == 5219); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); r = larry(4, 24); CHECK(r == 2089841); CHECK(it->x == 7); CHECK(it->y == 27); CHECK(it->r == 2089844); CHECK(it->before_count == 2); CHECK(it->after_count == 2); CHECK(the_function_count == 2); CHECK(another_function_count == 0); END; BEGIN("skip"); it->test_skip = true; it->r = 327; r = larry(1, 53); it->test_skip = false; CHECK(r == 324); CHECK(it->x == 4); CHECK(it->y == 56); CHECK(it->r == 327); CHECK(it->before_count == 3); CHECK(it->after_count == 2); CHECK(the_function_count == 2); CHECK(another_function_count == 0); END; BEGIN("redirect"); it->test_redirect = true; r = larry(0, 39); it->test_redirect = false; CHECK(r == 340); CHECK(it->x == 3); CHECK(it->y == 42); CHECK(it->r == 343); CHECK(it->before_count == 4); CHECK(it->after_count == 3); CHECK(the_function_count == 2); CHECK(another_function_count == 1); END; intercept_tester_t *it2; BEGIN("two intercepts"); it2 = new intercept_tester_t(); it2->install(); r = larry(5, 23); CHECK(r == 10058591); CHECK(it->x == 8); CHECK(it->y == 26); CHECK(it->r == 10058594); CHECK(it->before_count == 5); CHECK(it->after_count == 4); CHECK(it2->x == 8); CHECK(it2->y == 26); CHECK(it2->r == 10058594); CHECK(it2->before_count == 1); CHECK(it2->after_count == 1); CHECK(the_function_count == 3); CHECK(another_function_count == 1); END; BEGIN("uninstall"); it2->uninstall(); delete it2; r = larry(7, 11); CHECK(r == 134277341); CHECK(it->x == 10); CHECK(it->y == 14); CHECK(it->r == 134277344); CHECK(it->before_count == 6); CHECK(it->after_count == 5); CHECK(the_function_count == 4); CHECK(another_function_count == 1); END; // fprintf(stderr, "About to SEGV\n"); // *(char *)0 = 0; // fprintf(stderr, "Done doing SEGV\n"); BEGIN("uninstall last"); it->uninstall(); delete it; r = larry(3, 7); CHECK(r == 152341); CHECK(the_function_count == 5); CHECK(another_function_count == 1); END; BEGIN("larger stack frame"); wide_intercept_tester_t *it3 = new wide_intercept_tester_t; it3->install(); r = wide_call(1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144); CHECK(it3->x[0] == 1); CHECK(it3->x[1] == 4); CHECK(it3->x[2] == 9); CHECK(it3->x[3] == 16); CHECK(it3->x[4] == 25); CHECK(it3->x[5] == 36); CHECK(it3->x[6] == 49); CHECK(it3->x[7] == 64); CHECK(it3->x[8] == 81); CHECK(it3->x[9] == 100); CHECK(it3->x[10] == 121); CHECK(it3->x[11] == 144); CHECK(it3->r == 650); it3->uninstall(); delete it3; END; BEGIN("plt"); plt_intercept_tester_t *it4 = new plt_intercept_tester_t(); it4->install(); CHECK(it4->before_count == 0); CHECK(it4->after_count == 0); const char *s = gettext("hello"); CHECK(!strcmp(s, "world")); CHECK(it4->before_count == 1); CHECK(it4->after_count == 1); it4->uninstall(); END; return 0; } <commit_msg>Improve intercept tests<commit_after>/* * Copyright 2011-2012 Gregory Banks * * 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 "np/spiegel/spiegel.hxx" #include "np/spiegel/dwarf/state.hxx" #include <libintl.h> #include "fw.h" using namespace std; using namespace np::util; #if 0 static unsigned long top_of_stack; static void __dump_stack(unsigned long ebp, unsigned long eip) { unsigned int n = 0; while (ebp < top_of_stack) { printf("%u EBP 0x%08lx EIP 0x%08lx", n, ebp, eip); np::spiegel::location_t loc; if (np::spiegel::describe_address(eip, loc)) printf(" <%s+0x%x> at %s:%u", loc.function_ ? loc.function_->get_name().c_str() : "???", loc.offset_, loc.compile_unit_->get_absolute_path().basename().c_str(), loc.line_); printf("\n"); eip = ((unsigned long *)ebp)[1]; ebp = ((unsigned long *)ebp)[0]; n++; } } #define DUMP_STACK \ { \ register unsigned long ebp; \ register unsigned long eip; \ __asm__ volatile("mov %%ebp,%0" : "=r"(ebp)); \ __asm__ volatile("call .Lxx; .Lxx: popl %0" : "=r"(eip)); \ __dump_stack(ebp, eip); \ } #endif static int the_function_count = 0; int the_function(int x, int y) { int i; if (is_verbose()) printf("Start of the_function, x=%d y=%d\n", x, y); the_function_count++; for (i = 0 ; i < x ; i++) { y *= 5; y--; } if (is_verbose()) printf("End of the_function, returning %d\n", y); return y; } static int another_function_count = 0; int another_function(int x, int y) { int i; if (is_verbose()) printf("Start of another_function, x=%d y=%d\n", x, y); another_function_count++; for (i = 0 ; i < x ; i++) { y *= 2; y++; } if (is_verbose()) printf("End of another_function, returning %d\n", y); return y; } class intercept_tester_t : public np::spiegel::intercept_t { public: intercept_tester_t(); ~intercept_tester_t(); void before(np::spiegel::call_t &); void after(np::spiegel::call_t &); void reset_counters(); unsigned int after_count; unsigned int before_count; int x, y, r, nr; bool test_skip; bool test_redirect; bool test_set_retval; }; intercept_tester_t::intercept_tester_t() : intercept_t((np::spiegel::addr_t)&the_function) // we don't initialise the counts to 0 because the // inherited operator new does that. { } intercept_tester_t::~intercept_tester_t() { } void intercept_tester_t::before(np::spiegel::call_t &call) { x = call.get_arg(0); y = call.get_arg(1); before_count++; if (is_verbose()) printf("BEFORE x=%d y=%d\n", x, y); if (test_skip) { if (is_verbose()) printf("SKIPPING r=%d\n", nr); call.skip(nr); } if (test_redirect) { if (is_verbose()) printf("REDIRECTING to another_function\n"); call.redirect((np::spiegel::addr_t)&another_function); } } void intercept_tester_t::after(np::spiegel::call_t &call) { r = call.get_retval(); after_count++; if (is_verbose()) printf("AFTER, returned %d\n", r); if (test_set_retval) { if (is_verbose()) printf("SETTING RETVAL to %d\n", nr); call.set_retval((unsigned long)nr); } } void intercept_tester_t::reset_counters() { x = 0; y = 0; r = 0; nr = 0; before_count = 0; after_count = 0; the_function_count = 0; another_function_count = 0; test_skip = false; test_redirect = false; test_set_retval = false; } int moe(int x, int y) { int r = the_function(x+1, y+1); return r-1; } int curly(int x, int y) { int r = moe(x+1, y+1); return r-1; } int larry(int x, int y) { int r = curly(x+1, y+1); return r-1; } int wide_call(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12) { return a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12; } class wide_intercept_tester_t : public np::spiegel::intercept_t { public: wide_intercept_tester_t() : intercept_t((np::spiegel::addr_t)&wide_call) { } ~wide_intercept_tester_t() { } int x[12], r; void before(np::spiegel::call_t &call) { int i; for (i = 0 ; i < 12 ; i++) x[i] = call.get_arg(i); if (is_verbose()) printf("BEFORE\n"); } void after(np::spiegel::call_t &call) { r = call.get_retval(); if (is_verbose()) printf("AFTER, returning %d\n", r); } }; typedef void (*fn_t)(void); class libc_intercept_tester_t : public np::spiegel::intercept_t { public: libc_intercept_tester_t(fn_t addr, const char *name) : intercept_t((np::spiegel::addr_t)addr, name) { } ~libc_intercept_tester_t() { } unsigned int after_count; unsigned int before_count; void before(np::spiegel::call_t &call) { if (is_verbose()) printf("BEFORE %s\n", get_name()); before_count++; } void after(np::spiegel::call_t &call) { if (is_verbose()) printf("AFTER %s\n", get_name()); after_count++; } }; int main(int argc, char **argv __attribute__((unused))) { #if 0 top_of_stack = (unsigned long)&argc; #endif if (argc > 1) { fatal("Usage: testrunner intercept\n"); } np::spiegel::dwarf::state_t state; if (!state.add_self()) return 1; intercept_tester_t *it; int r; BEGIN("install"); it = new intercept_tester_t(); it->install(); END; BEGIN("basic"); it->reset_counters(); r = larry(0, 39); CHECK(r == 5216); CHECK(it->x == 3); CHECK(it->y == 42); CHECK(it->r == 5219); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; BEGIN("basic2"); it->reset_counters(); r = larry(4, 24); CHECK(r == 2089841); CHECK(it->x == 7); CHECK(it->y == 27); CHECK(it->r == 2089844); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; BEGIN("skip"); it->reset_counters(); it->test_skip = true; it->nr = 327; r = larry(1, 53); CHECK(r == 324); CHECK(it->x == 4); CHECK(it->y == 56); CHECK(it->r == 0); CHECK(it->before_count == 1); CHECK(it->after_count == 0); CHECK(the_function_count == 0); CHECK(another_function_count == 0); END; BEGIN("redirect"); it->reset_counters(); it->test_redirect = true; r = larry(0, 39); CHECK(r == 340); CHECK(it->x == 3); CHECK(it->y == 42); CHECK(it->r == 343); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 0); CHECK(another_function_count == 1); END; BEGIN("set retval"); it->reset_counters(); it->test_set_retval = true; it->nr = 271828; r = larry(0, 39); CHECK(r == 271825); CHECK(it->x == 3); CHECK(it->y == 42); CHECK(it->r == 5219); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; intercept_tester_t *it2; BEGIN("two intercepts"); it2 = new intercept_tester_t(); it2->install(); it->reset_counters(); it2->reset_counters(); r = larry(5, 23); CHECK(r == 10058591); CHECK(it->x == 8); CHECK(it->y == 26); CHECK(it->r == 10058594); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(it2->x == 8); CHECK(it2->y == 26); CHECK(it2->r == 10058594); CHECK(it2->before_count == 1); CHECK(it2->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; BEGIN("uninstall second"); it2->uninstall(); delete it2; it->reset_counters(); r = larry(7, 11); CHECK(r == 134277341); CHECK(it->x == 10); CHECK(it->y == 14); CHECK(it->r == 134277344); CHECK(it->before_count == 1); CHECK(it->after_count == 1); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; BEGIN("uninstall last"); it->reset_counters(); it->uninstall(); delete it; r = larry(3, 7); CHECK(r == 152341); CHECK(the_function_count == 1); CHECK(another_function_count == 0); END; BEGIN("larger stack frame"); wide_intercept_tester_t *it3 = new wide_intercept_tester_t; it3->install(); r = wide_call(1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144); CHECK(it3->x[0] == 1); CHECK(it3->x[1] == 4); CHECK(it3->x[2] == 9); CHECK(it3->x[3] == 16); CHECK(it3->x[4] == 25); CHECK(it3->x[5] == 36); CHECK(it3->x[6] == 49); CHECK(it3->x[7] == 64); CHECK(it3->x[8] == 81); CHECK(it3->x[9] == 100); CHECK(it3->x[10] == 121); CHECK(it3->x[11] == 144); CHECK(it3->r == 650); it3->uninstall(); delete it3; END; /* * Test interception of functions in libc. There are several issues: * * - the functions are in a shared library and are accessed via the PLT * - the code is heavily optimised which affects function prologues * - function prologues are more predictable on some ABIs * * So we try to cover all of these by testing specific functions * known to exhibit specific properties in one libc or another. */ const char *s; /* textdomain uses the 0x55 prologue on x86 and x86_64 */ BEGIN("libc textdomain"); libc_intercept_tester_t *it4 = new libc_intercept_tester_t((fn_t)textdomain, "textdomain"); it4->install(); CHECK(it4->before_count == 0); CHECK(it4->after_count == 0); const char *s = textdomain("locavore"); CHECK(!strcmp(s, "locavore")); CHECK(it4->before_count == 1); CHECK(it4->after_count == 1); it4->uninstall(); END; /* gettext doesn't use the 0x55 prologue on x86_64 */ BEGIN("libc gettext"); libc_intercept_tester_t *it5 = new libc_intercept_tester_t((fn_t)gettext, "gettext"); it5->install(); CHECK(it5->before_count == 0); CHECK(it5->after_count == 0); s = gettext("hello"); CHECK(!strcmp(s, "hello")); CHECK(it5->before_count == 1); CHECK(it5->after_count == 1); it5->uninstall(); END; return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file * \brief C adapter to DTK Maps. */ #ifndef DTK_C_API_MAP_HPP #define DTK_C_API_MAP_HPP #include <DTK_C_API.h> #include <DTK_C_API.hpp> #include <DTK_DBC.hpp> #include <DTK_MovingLeastSquaresOperator.hpp> #include <DTK_NearestNeighborOperator.hpp> #include <DTK_ParallelTraits.hpp> #include <DTK_PointCloudOperator.hpp> #include <DTK_UserApplication.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <mpi.h> #include <memory> #include <string> #include <tuple> namespace DataTransferKit { //---------------------------------------------------------------------------// // Map interface base class. This allows us to hide the device template // parameter in MapImpl when we do the casting in the C interface // implementation. We won't know what device type we have in a template when // calling the C interface and we don't need to - the apply function // implementation details will dispatch to the correct device type based on // the construction. struct DTK_Map { virtual ~DTK_Map() = default; virtual void apply( const std::string &source_field_name, const std::string &target_field_name ) = 0; }; //---------------------------------------------------------------------------// template <class MapExecSpace, class SourceMemSpace, class TargetMemSpace> struct DTK_MapImpl : public DTK_Map { using map_device_type = typename MapExecSpace::device_type; DTK_MapImpl( MPI_Comm comm, DTK_UserApplicationHandle source, DTK_UserApplicationHandle target, boost::property_tree::ptree const &ptree ) : _source( reinterpret_cast<DTK_Registry *>( source )->_registry ) , _target( reinterpret_cast<DTK_Registry *>( target )->_registry ) { // Create a Teuchos comm from the MPI comm. auto teuchos_comm = Teuchos::rcp( new Teuchos::MpiComm<int>( comm ) ); // FOR NOW JUST CREATE A NEAREST NEIGHBOR OPERATOR FOR DEMONSTRATION // PURPOSES. THIS WILL BE REPLACED BY A PROPER FACTORY. // Get coordinates from the source and target. auto source_nodes = _source.getNodeList().coordinates; auto target_nodes = _target.getNodeList().coordinates; // For now things are layout left in the interface so copy to a // matching layout that is compatible with the operator. Kokkos::View<Coordinate **, map_device_type> source_nodes_copy( "src_nodes_copy", source_nodes.extent( 0 ), source_nodes.extent( 1 ) ); Kokkos::deep_copy( source_nodes_copy, source_nodes ); Kokkos::View<Coordinate **, map_device_type> target_nodes_copy( "tgt_nodes_copy", target_nodes.extent( 0 ), target_nodes.extent( 1 ) ); Kokkos::deep_copy( target_nodes_copy, target_nodes ); auto const which_map = ptree.get<std::string>( "Map Type" ); if ( which_map == "Nearest Neighbor" || which_map == "NN" ) _map = std::unique_ptr<NearestNeighborOperator<map_device_type>>( new NearestNeighborOperator<map_device_type>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else if ( which_map == "Moving Least Squares" || which_map == "MLS" ) { auto const order = ptree.get<std::string>( "Order", "Linear" ); if ( order == "Linear" || order == "1" ) _map = std::unique_ptr<MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Linear, 3>>>( new MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Linear, 3>>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else if ( order == "Quadratic" || order == "2" ) _map = std::unique_ptr<MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Quadratic, 3>>>( new MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Quadratic, 3>>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else throw DataTransferKitException( "Invalid order \"" + order + "\" for creating a moving least squares map" ); } else throw DataTransferKitException( "Invalid map type \"" + which_map + "\"" ); } void apply( const std::string &source_field_name, const std::string &target_field_name ) override { // Create fields. auto source_field = _source.getField( source_field_name ); auto target_field = _target.getField( target_field_name ); // Pull the data from the source. _source.pullField( source_field_name, source_field ); // Copy to a compatible layout. Nearest neighbor operator needs a // compatible layout and only 1 dimension int num_src = source_field.dofs.extent( 0 ); Kokkos::View<double *, map_device_type> source_field_copy( "source_field_copy", num_src ); Kokkos::deep_copy( source_field_copy, Kokkos::subview( source_field.dofs, Kokkos::ALL, 0 ) ); int num_tgt = target_field.dofs.extent( 0 ); Kokkos::View<double *, map_device_type> target_field_copy( "target_field_copy", num_tgt ); // Apply the map. _map->apply( source_field_copy, target_field_copy ); // Copy the transferred field back to the original target layout. Kokkos::deep_copy( Kokkos::subview( target_field.dofs, Kokkos::ALL, 0 ), target_field_copy ); // Push the data to the target. _target.pushField( target_field_name, target_field ); } UserApplication<double, SourceMemSpace> _source; UserApplication<double, TargetMemSpace> _target; std::unique_ptr<PointCloudOperator<map_device_type>> _map; }; //---------------------------------------------------------------------------// // Execution space validation. bool validExecutionSpace( DTK_ExecutionSpace space ) { switch ( space ) { case DTK_SERIAL: #if defined( KOKKOS_ENABLE_SERIAL ) return true; break; #else return false; break; #endif case DTK_OPENMP: #if defined( KOKKOS_ENABLE_OPENMP ) return true; break; #else return false; break; #endif case DTK_CUDA: #if defined( KOKKOS_ENABLE_CUDA ) return true; break; #else return false; break; #endif default: return false; break; } } // Memory space validation. bool validMemorySpace( DTK_MemorySpace space ) { switch ( space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) return true; break; #else return false; break; #endif case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) return true; break; #else return false; break; #endif default: return false; break; } } // Map space validation. bool validMapSpaces( DTK_ExecutionSpace map_space, DTK_MemorySpace source_space, DTK_MemorySpace target_space ) { return validExecutionSpace( map_space ) && validMemorySpace( source_space ) && validMemorySpace( target_space ); } //---------------------------------------------------------------------------// // Create a map. DTK_Map *createMap( DTK_ExecutionSpace map_space, MPI_Comm comm, DTK_UserApplicationHandle source, DTK_UserApplicationHandle target, const char *options ) { // Parse options. std::stringstream ss; ss.str( options ); boost::property_tree::ptree ptree; boost::property_tree::read_json( ss, ptree ); // Get the user source and target memory spaces. DTK_MemorySpace src_space = reinterpret_cast<DataTransferKit::DTK_Registry *>( source )->_space; DTK_MemorySpace tgt_space = reinterpret_cast<DataTransferKit::DTK_Registry *>( target )->_space; // Check up front that we have been asked for execution and memory spaces // that are available in the kokkos build. This lets use a little cleaner // macro logic below because we know we will get a valid map space // already. DTK_INSIST( validMapSpaces( map_space, src_space, tgt_space ) ); DTK_Map *map; switch ( map_space ) { case DTK_SERIAL: #if defined( KOKKOS_ENABLE_SERIAL ) switch ( src_space ) { case DTK_HOST_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Serial, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) map = new DTK_MapImpl<Serial, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); #endif break; } break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Serial, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Serial, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; } #endif break; case DTK_OPENMP: #if defined( KOKKOS_ENABLE_OPENMP ) switch ( src_space ) { case DTK_HOST_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<OpenMP, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) map = new DTK_MapImpl<OpenMP, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); #endif break; } break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<OpenMP, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<OpenMP, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; } #endif break; case DTK_CUDA: #if defined( KOKKOS_ENABLE_CUDA ) switch ( src_space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Cuda, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Cuda, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; case DTK_CUDAUVM_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) map = new DTK_MapImpl<Cuda, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); #endif break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Cuda, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } break; } #endif break; } return map; } //---------------------------------------------------------------------------// } // namespace DataTransferKit #endif // DTK_C_API_MAP_HPP <commit_msg>Catch boost exception if parsing json fails and throw DTK exception instead<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file * \brief C adapter to DTK Maps. */ #ifndef DTK_C_API_MAP_HPP #define DTK_C_API_MAP_HPP #include <DTK_C_API.h> #include <DTK_C_API.hpp> #include <DTK_DBC.hpp> #include <DTK_MovingLeastSquaresOperator.hpp> #include <DTK_NearestNeighborOperator.hpp> #include <DTK_ParallelTraits.hpp> #include <DTK_PointCloudOperator.hpp> #include <DTK_UserApplication.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <mpi.h> #include <memory> #include <string> #include <tuple> namespace DataTransferKit { //---------------------------------------------------------------------------// // Map interface base class. This allows us to hide the device template // parameter in MapImpl when we do the casting in the C interface // implementation. We won't know what device type we have in a template when // calling the C interface and we don't need to - the apply function // implementation details will dispatch to the correct device type based on // the construction. struct DTK_Map { virtual ~DTK_Map() = default; virtual void apply( const std::string &source_field_name, const std::string &target_field_name ) = 0; }; //---------------------------------------------------------------------------// template <class MapExecSpace, class SourceMemSpace, class TargetMemSpace> struct DTK_MapImpl : public DTK_Map { using map_device_type = typename MapExecSpace::device_type; DTK_MapImpl( MPI_Comm comm, DTK_UserApplicationHandle source, DTK_UserApplicationHandle target, boost::property_tree::ptree const &ptree ) : _source( reinterpret_cast<DTK_Registry *>( source )->_registry ) , _target( reinterpret_cast<DTK_Registry *>( target )->_registry ) { // Create a Teuchos comm from the MPI comm. auto teuchos_comm = Teuchos::rcp( new Teuchos::MpiComm<int>( comm ) ); // FOR NOW JUST CREATE A NEAREST NEIGHBOR OPERATOR FOR DEMONSTRATION // PURPOSES. THIS WILL BE REPLACED BY A PROPER FACTORY. // Get coordinates from the source and target. auto source_nodes = _source.getNodeList().coordinates; auto target_nodes = _target.getNodeList().coordinates; // For now things are layout left in the interface so copy to a // matching layout that is compatible with the operator. Kokkos::View<Coordinate **, map_device_type> source_nodes_copy( "src_nodes_copy", source_nodes.extent( 0 ), source_nodes.extent( 1 ) ); Kokkos::deep_copy( source_nodes_copy, source_nodes ); Kokkos::View<Coordinate **, map_device_type> target_nodes_copy( "tgt_nodes_copy", target_nodes.extent( 0 ), target_nodes.extent( 1 ) ); Kokkos::deep_copy( target_nodes_copy, target_nodes ); auto const which_map = ptree.get<std::string>( "Map Type" ); if ( which_map == "Nearest Neighbor" || which_map == "NN" ) _map = std::unique_ptr<NearestNeighborOperator<map_device_type>>( new NearestNeighborOperator<map_device_type>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else if ( which_map == "Moving Least Squares" || which_map == "MLS" ) { auto const order = ptree.get<std::string>( "Order", "Linear" ); if ( order == "Linear" || order == "1" ) _map = std::unique_ptr<MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Linear, 3>>>( new MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Linear, 3>>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else if ( order == "Quadratic" || order == "2" ) _map = std::unique_ptr<MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Quadratic, 3>>>( new MovingLeastSquaresOperator< map_device_type, Wendland<0>, MultivariatePolynomialBasis<Quadratic, 3>>( teuchos_comm, source_nodes_copy, target_nodes_copy ) ); else throw DataTransferKitException( "Invalid order \"" + order + "\" for creating a moving least squares map" ); } else throw DataTransferKitException( "Invalid map type \"" + which_map + "\"" ); } void apply( const std::string &source_field_name, const std::string &target_field_name ) override { // Create fields. auto source_field = _source.getField( source_field_name ); auto target_field = _target.getField( target_field_name ); // Pull the data from the source. _source.pullField( source_field_name, source_field ); // Copy to a compatible layout. Nearest neighbor operator needs a // compatible layout and only 1 dimension int num_src = source_field.dofs.extent( 0 ); Kokkos::View<double *, map_device_type> source_field_copy( "source_field_copy", num_src ); Kokkos::deep_copy( source_field_copy, Kokkos::subview( source_field.dofs, Kokkos::ALL, 0 ) ); int num_tgt = target_field.dofs.extent( 0 ); Kokkos::View<double *, map_device_type> target_field_copy( "target_field_copy", num_tgt ); // Apply the map. _map->apply( source_field_copy, target_field_copy ); // Copy the transferred field back to the original target layout. Kokkos::deep_copy( Kokkos::subview( target_field.dofs, Kokkos::ALL, 0 ), target_field_copy ); // Push the data to the target. _target.pushField( target_field_name, target_field ); } UserApplication<double, SourceMemSpace> _source; UserApplication<double, TargetMemSpace> _target; std::unique_ptr<PointCloudOperator<map_device_type>> _map; }; //---------------------------------------------------------------------------// // Execution space validation. bool validExecutionSpace( DTK_ExecutionSpace space ) { switch ( space ) { case DTK_SERIAL: #if defined( KOKKOS_ENABLE_SERIAL ) return true; break; #else return false; break; #endif case DTK_OPENMP: #if defined( KOKKOS_ENABLE_OPENMP ) return true; break; #else return false; break; #endif case DTK_CUDA: #if defined( KOKKOS_ENABLE_CUDA ) return true; break; #else return false; break; #endif default: return false; break; } } // Memory space validation. bool validMemorySpace( DTK_MemorySpace space ) { switch ( space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) return true; break; #else return false; break; #endif case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) return true; break; #else return false; break; #endif default: return false; break; } } // Map space validation. bool validMapSpaces( DTK_ExecutionSpace map_space, DTK_MemorySpace source_space, DTK_MemorySpace target_space ) { return validExecutionSpace( map_space ) && validMemorySpace( source_space ) && validMemorySpace( target_space ); } //---------------------------------------------------------------------------// // Create a map. DTK_Map *createMap( DTK_ExecutionSpace map_space, MPI_Comm comm, DTK_UserApplicationHandle source, DTK_UserApplicationHandle target, const char *options ) { // Parse options. std::stringstream ss; ss.str( options ); boost::property_tree::ptree ptree; try { boost::property_tree::read_json( ss, ptree ); } catch ( boost::property_tree::json_parser_error ) { throw DataTransferKitException( "Error while parsing JSON format in options string argument for " "map creation" ); } // Get the user source and target memory spaces. DTK_MemorySpace src_space = reinterpret_cast<DataTransferKit::DTK_Registry *>( source )->_space; DTK_MemorySpace tgt_space = reinterpret_cast<DataTransferKit::DTK_Registry *>( target )->_space; // Check up front that we have been asked for execution and memory spaces // that are available in the kokkos build. This lets use a little cleaner // macro logic below because we know we will get a valid map space // already. DTK_INSIST( validMapSpaces( map_space, src_space, tgt_space ) ); DTK_Map *map; switch ( map_space ) { case DTK_SERIAL: #if defined( KOKKOS_ENABLE_SERIAL ) switch ( src_space ) { case DTK_HOST_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Serial, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) map = new DTK_MapImpl<Serial, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); #endif break; } break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Serial, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Serial, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; } #endif break; case DTK_OPENMP: #if defined( KOKKOS_ENABLE_OPENMP ) switch ( src_space ) { case DTK_HOST_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<OpenMP, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) map = new DTK_MapImpl<OpenMP, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); #endif break; } break; case DTK_CUDAUVM_SPACE: #if defined( KOKKOS_ENABLE_CUDA ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<OpenMP, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<OpenMP, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; } #endif break; case DTK_CUDA: #if defined( KOKKOS_ENABLE_CUDA ) switch ( src_space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) switch ( tgt_space ) { case DTK_HOST_SPACE: map = new DTK_MapImpl<Cuda, HostSpace, HostSpace>( comm, source, target, ptree ); break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Cuda, HostSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } #endif break; case DTK_CUDAUVM_SPACE: switch ( tgt_space ) { case DTK_HOST_SPACE: #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) map = new DTK_MapImpl<Cuda, CudaUVMSpace, HostSpace>( comm, source, target, ptree ); #endif break; case DTK_CUDAUVM_SPACE: map = new DTK_MapImpl<Cuda, CudaUVMSpace, CudaUVMSpace>( comm, source, target, ptree ); break; } break; } #endif break; } return map; } //---------------------------------------------------------------------------// } // namespace DataTransferKit #endif // DTK_C_API_MAP_HPP <|endoftext|>
<commit_before>//===-- StringRef.cpp - Lightweight String References ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" using namespace llvm; const size_t StringRef::npos; //===----------------------------------------------------------------------===// // String Searching //===----------------------------------------------------------------------===// /// find - Search for the first string \arg Str in the string. /// /// \return - The index of the first occurence of \arg Str, or npos if not /// found. size_t StringRef::find(const StringRef &Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = 0, e = Length - N + 1; i != e; ++i) if (substr(i, N).equals(Str)) return i; return npos; } /// rfind - Search for the last string \arg Str in the string. /// /// \return - The index of the last occurence of \arg Str, or npos if not /// found. size_t StringRef::rfind(const StringRef &Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = Length - N + 1, e = 0; i != e;) { --i; if (substr(i, N).equals(Str)) return i; } return npos; } /// find_first_of - Find the first character from the string 'Chars' in the /// current string or return npos if not in string. StringRef::size_type StringRef::find_first_of(StringRef Chars) const { for (size_type i = 0, e = Length; i != e; ++i) if (Chars.find(Data[i]) != npos) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// in the string 'Chars' or return npos if all are in string. Same as find. StringRef::size_type StringRef::find_first_not_of(StringRef Chars) const { for (size_type i = 0, e = Length; i != e; ++i) if (Chars.find(Data[i]) == npos) return i; return npos; } //===----------------------------------------------------------------------===// // Helpful Algorithms //===----------------------------------------------------------------------===// /// count - Return the number of non-overlapped occurrences of \arg Str in /// the string. size_t StringRef::count(const StringRef &Str) const { size_t Count = 0; size_t N = Str.size(); if (N > Length) return 0; for (size_t i = 0, e = Length - N + 1; i != e; ++i) if (substr(i, N).equals(Str)) ++Count; return Count; } /// GetAsUnsignedInteger - Workhorse method that converts a integer character /// sequence of radix up to 36 to an unsigned long long value. static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result) { // Autosense radix if not specified. if (Radix == 0) { if (Str.startswith("0x")) { Str = Str.substr(2); Radix = 16; } else if (Str.startswith("0b")) { Str = Str.substr(2); Radix = 2; } else if (Str.startswith("0")) Radix = 8; else Radix = 10; } // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Parse all the bytes of the string given this radix. Watch for overflow. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. unsigned long long PrevResult = Result; Result = Result*Radix+CharVal; // Check for overflow. if (Result < PrevResult) return true; Str = Str.substr(1); } return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const { return GetAsUnsignedInteger(*this, Radix, Result); } bool StringRef::getAsInteger(unsigned Radix, long long &Result) const { unsigned long long ULLVal; // Handle positive strings first. if (empty() || front() != '-') { if (GetAsUnsignedInteger(*this, Radix, ULLVal) || // Check for value so large it overflows a signed value. (long long)ULLVal < 0) return true; Result = ULLVal; return false; } // Get the positive part of the value. if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) || // Reject values so large they'd overflow as negative signed, but allow // "-0". This negates the unsigned so that the negative isn't undefined // on signed overflow. (long long)-ULLVal > 0) return true; Result = -ULLVal; return false; } bool StringRef::getAsInteger(unsigned Radix, int &Result) const { long long Val; if (getAsInteger(Radix, Val) || (int)Val != Val) return true; Result = Val; return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const { unsigned long long Val; if (getAsInteger(Radix, Val) || (unsigned)Val != Val) return true; Result = Val; return false; } <commit_msg>Workaround what I believe is an MSVC bug where it emits a definition for a static const class member into each translation unit, with external linkage??? - If someone understands this issue better, please clue me in, I haven't consulted the standard yet.<commit_after>//===-- StringRef.cpp - Lightweight String References ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" using namespace llvm; // MSVC emits references to this into the translation units which reference it. #ifndef _MSC_VER const size_t StringRef::npos; #endif //===----------------------------------------------------------------------===// // String Searching //===----------------------------------------------------------------------===// /// find - Search for the first string \arg Str in the string. /// /// \return - The index of the first occurence of \arg Str, or npos if not /// found. size_t StringRef::find(const StringRef &Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = 0, e = Length - N + 1; i != e; ++i) if (substr(i, N).equals(Str)) return i; return npos; } /// rfind - Search for the last string \arg Str in the string. /// /// \return - The index of the last occurence of \arg Str, or npos if not /// found. size_t StringRef::rfind(const StringRef &Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = Length - N + 1, e = 0; i != e;) { --i; if (substr(i, N).equals(Str)) return i; } return npos; } /// find_first_of - Find the first character from the string 'Chars' in the /// current string or return npos if not in string. StringRef::size_type StringRef::find_first_of(StringRef Chars) const { for (size_type i = 0, e = Length; i != e; ++i) if (Chars.find(Data[i]) != npos) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// in the string 'Chars' or return npos if all are in string. Same as find. StringRef::size_type StringRef::find_first_not_of(StringRef Chars) const { for (size_type i = 0, e = Length; i != e; ++i) if (Chars.find(Data[i]) == npos) return i; return npos; } //===----------------------------------------------------------------------===// // Helpful Algorithms //===----------------------------------------------------------------------===// /// count - Return the number of non-overlapped occurrences of \arg Str in /// the string. size_t StringRef::count(const StringRef &Str) const { size_t Count = 0; size_t N = Str.size(); if (N > Length) return 0; for (size_t i = 0, e = Length - N + 1; i != e; ++i) if (substr(i, N).equals(Str)) ++Count; return Count; } /// GetAsUnsignedInteger - Workhorse method that converts a integer character /// sequence of radix up to 36 to an unsigned long long value. static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result) { // Autosense radix if not specified. if (Radix == 0) { if (Str.startswith("0x")) { Str = Str.substr(2); Radix = 16; } else if (Str.startswith("0b")) { Str = Str.substr(2); Radix = 2; } else if (Str.startswith("0")) Radix = 8; else Radix = 10; } // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Parse all the bytes of the string given this radix. Watch for overflow. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. unsigned long long PrevResult = Result; Result = Result*Radix+CharVal; // Check for overflow. if (Result < PrevResult) return true; Str = Str.substr(1); } return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const { return GetAsUnsignedInteger(*this, Radix, Result); } bool StringRef::getAsInteger(unsigned Radix, long long &Result) const { unsigned long long ULLVal; // Handle positive strings first. if (empty() || front() != '-') { if (GetAsUnsignedInteger(*this, Radix, ULLVal) || // Check for value so large it overflows a signed value. (long long)ULLVal < 0) return true; Result = ULLVal; return false; } // Get the positive part of the value. if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) || // Reject values so large they'd overflow as negative signed, but allow // "-0". This negates the unsigned so that the negative isn't undefined // on signed overflow. (long long)-ULLVal > 0) return true; Result = -ULLVal; return false; } bool StringRef::getAsInteger(unsigned Radix, int &Result) const { long long Val; if (getAsInteger(Radix, Val) || (int)Val != Val) return true; Result = Val; return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const { unsigned long long Val; if (getAsInteger(Radix, Val) || (unsigned)Val != Val) return true; Result = Val; return false; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Till Adam <adam@kde.org> * * * * This program 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 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 Library 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. * ***************************************************************************/ #include <QDebug> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "append.h" #include "response.h" using namespace Akonadi; Append::Append() : Handler(), m_size(-1) { } Append::~Append() { } static QDateTime parseDateTime( const QByteArray & s ) { // Syntax: // date-time = DQUOTE date-day-fixed "-" date-month "-" date-year // SP time SP zone DQUOTE // date-day-fixed = (SP DIGIT) / 2DIGIT // ; Fixed-format version of date-day // date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / // "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" // date-year = 4DIGIT // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT // ; Hours minutes seconds // zone = ("+" / "-") 4DIGIT // ; Signed four-digit value of hhmm representing // ; hours and minutes east of Greenwich (that is, // ; the amount that the given time differs from // ; Universal Time). Subtracting the timezone // ; from the given time will give the UT form. // ; The Universal Time zone is "+0000". // Example : "28-May-2006 01:03:35 +0200" // Position: 0123456789012345678901234567 // 1 2 QDateTime dateTime; bool ok = true; const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day : s.mid( 1, 2 ).toInt( &ok ) ); if ( !ok ) return dateTime; const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" ); int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() ); if ( month == -1 ) return dateTime; month = month / 3 + 1; const int year = s.mid( 8, 4 ).toInt( &ok ); if ( !ok ) return dateTime; const int hours = s.mid( 13, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int minutes = s.mid( 16, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int seconds = s.mid( 19, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int tzhh = s.mid( 23, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int tzmm = s.mid( 25, 2 ).toInt( &ok ); if ( !ok ) return dateTime; int tzsecs = tzhh*60*60 + tzmm*60; if ( s[22] == '-' ) tzsecs = -tzsecs; const QDate date( year, month, day ); const QTime time( hours, minutes, seconds ); dateTime = QDateTime( date, time, Qt::UTC ); if ( !dateTime.isValid() ) return dateTime; dateTime.addSecs( -tzsecs ); return dateTime; } bool Akonadi::Append::handleContinuation( const QByteArray& line ) { m_data += line; m_size -= line.size(); if ( !allDataRead() ) return false; return commit(); } bool Akonadi::Append::handleLine(const QByteArray& line ) { if ( inContinuation() ) return handleContinuation( line ); // Arguments: mailbox name // OPTIONAL flag parenthesized list // OPTIONAL date/time string // message literal // // Syntax: // append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal const int startOfCommand = line.indexOf( ' ' ) + 1; const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1; const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1; m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) ); // parse optional flag parenthesized list // Syntax: // flag-list = "(" [flag *(SP flag)] ")" // flag = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" / // "\Draft" / flag-keyword / flag-extension // ; Does not include "\Recent" // flag-extension = "\" atom // flag-keyword = atom int startOfDateTime = startOfFlags; if ( line[startOfFlags] == '(' ) { startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2; m_flags = line.mid( startOfFlags + 1, startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' '); } m_flags.append( "\\Recent" ); // the Recent flag always has to be set // parse optional date/time string int startOfLiteral = startOfDateTime; if ( line[startOfDateTime] == '"' ) { startOfLiteral = line.indexOf( '{', startOfDateTime + 1 ); m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) ); // FIXME Should we return an error if m_dateTime is invalid? } // if date/time is not given then it will be set to the current date/time // by the database // finally parse the message literal const int startOfSize = startOfLiteral + 1; m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt(); if ( !allDataRead() ) return startContinuation(); // otherwise it's a 0-size put, so we're done return commit(); } bool Akonadi::Append::commit() { Response response; DataStore *db = connection()->storageBackend(); Location l = db->locationByRawMailbox( m_mailbox ); QString mt; QByteArray remote_id; foreach( QByteArray flag, m_flags ) { if ( flag.startsWith( "\\MimeType" ) ) { int pos1 = flag.indexOf( '[' ); int pos2 = flag.indexOf( ']', pos1 ); mt = flag.mid( pos1 + 1, pos2 - pos1 - 1 ); } else if ( flag.startsWith( "\\RemoteId" ) ) { int pos1 = flag.indexOf( '[' ); int pos2 = flag.indexOf( ']', pos1 ); remote_id = flag.mid( pos1 + 1, pos2 - pos1 - 1 ); } } // standard imap does not know this attribute, so that's mail if ( mt.isEmpty() ) mt = "message/rfc822"; MimeType mimeType = db->mimeTypeByName( mt ); if ( !mimeType.isValid() ) { return failureResponse( QString( "Unknown mime type '%1'.").arg( mt ) ); } int itemId = 0; bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, remote_id, &itemId ); response.setTag( tag() ); if ( !ok ) { return failureResponse( "Append failed" ); } // set message flags ok = db->appendItemFlags( itemId, m_flags ); // TODO handle failure // the message was appended; now we have to update the counts const int existsChange = +1; const int recentChange = +1; int unseenChange = 0; if ( !m_flags.contains( "\\Seen" ) ) unseenChange = +1; // int firstUnseen = ?; // can't be updated atomically, so we probably have to // recalculate it each time it's needed ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange ); // TODO handle failure by removing the message again from the db // TODO if the mailbox is currently selected, the normal new message // actions SHOULD occur. Specifically, the server SHOULD notify the // client immediately via an untagged EXISTS response. response.setTag( tag() ); response.setSuccess(); response.setString( "Append completed" ); emit responseAvailable( response ); deleteLater(); return true; } bool Akonadi::Append::inContinuation( ) const { return m_size > -1; } bool Akonadi::Append::allDataRead( ) const { return ( m_size == 0 ); } bool Akonadi::Append::startContinuation() { Response response; response.setContinuation(); response.setString( "Ready for literal data" ); emit responseAvailable( response ); return false; } <commit_msg>Test if the location is valid before appending a new item.<commit_after>/*************************************************************************** * Copyright (C) 2006 by Till Adam <adam@kde.org> * * * * This program 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 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 Library 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. * ***************************************************************************/ #include <QDebug> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "append.h" #include "response.h" using namespace Akonadi; Append::Append() : Handler(), m_size(-1) { } Append::~Append() { } static QDateTime parseDateTime( const QByteArray & s ) { // Syntax: // date-time = DQUOTE date-day-fixed "-" date-month "-" date-year // SP time SP zone DQUOTE // date-day-fixed = (SP DIGIT) / 2DIGIT // ; Fixed-format version of date-day // date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / // "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" // date-year = 4DIGIT // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT // ; Hours minutes seconds // zone = ("+" / "-") 4DIGIT // ; Signed four-digit value of hhmm representing // ; hours and minutes east of Greenwich (that is, // ; the amount that the given time differs from // ; Universal Time). Subtracting the timezone // ; from the given time will give the UT form. // ; The Universal Time zone is "+0000". // Example : "28-May-2006 01:03:35 +0200" // Position: 0123456789012345678901234567 // 1 2 QDateTime dateTime; bool ok = true; const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day : s.mid( 1, 2 ).toInt( &ok ) ); if ( !ok ) return dateTime; const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" ); int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() ); if ( month == -1 ) return dateTime; month = month / 3 + 1; const int year = s.mid( 8, 4 ).toInt( &ok ); if ( !ok ) return dateTime; const int hours = s.mid( 13, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int minutes = s.mid( 16, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int seconds = s.mid( 19, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int tzhh = s.mid( 23, 2 ).toInt( &ok ); if ( !ok ) return dateTime; const int tzmm = s.mid( 25, 2 ).toInt( &ok ); if ( !ok ) return dateTime; int tzsecs = tzhh*60*60 + tzmm*60; if ( s[22] == '-' ) tzsecs = -tzsecs; const QDate date( year, month, day ); const QTime time( hours, minutes, seconds ); dateTime = QDateTime( date, time, Qt::UTC ); if ( !dateTime.isValid() ) return dateTime; dateTime.addSecs( -tzsecs ); return dateTime; } bool Akonadi::Append::handleContinuation( const QByteArray& line ) { m_data += line; m_size -= line.size(); if ( !allDataRead() ) return false; return commit(); } bool Akonadi::Append::handleLine(const QByteArray& line ) { if ( inContinuation() ) return handleContinuation( line ); // Arguments: mailbox name // OPTIONAL flag parenthesized list // OPTIONAL date/time string // message literal // // Syntax: // append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal const int startOfCommand = line.indexOf( ' ' ) + 1; const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1; const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1; m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) ); // parse optional flag parenthesized list // Syntax: // flag-list = "(" [flag *(SP flag)] ")" // flag = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" / // "\Draft" / flag-keyword / flag-extension // ; Does not include "\Recent" // flag-extension = "\" atom // flag-keyword = atom int startOfDateTime = startOfFlags; if ( line[startOfFlags] == '(' ) { startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2; m_flags = line.mid( startOfFlags + 1, startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' '); } m_flags.append( "\\Recent" ); // the Recent flag always has to be set // parse optional date/time string int startOfLiteral = startOfDateTime; if ( line[startOfDateTime] == '"' ) { startOfLiteral = line.indexOf( '{', startOfDateTime + 1 ); m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) ); // FIXME Should we return an error if m_dateTime is invalid? } // if date/time is not given then it will be set to the current date/time // by the database // finally parse the message literal const int startOfSize = startOfLiteral + 1; m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt(); if ( !allDataRead() ) return startContinuation(); // otherwise it's a 0-size put, so we're done return commit(); } bool Akonadi::Append::commit() { Response response; DataStore *db = connection()->storageBackend(); Location l = db->locationByRawMailbox( m_mailbox ); if ( !l.isValid() ) return failureResponse( QString("Unknown collection '%1'.").arg( m_mailbox.constData() ) ); QString mt; QByteArray remote_id; foreach( QByteArray flag, m_flags ) { if ( flag.startsWith( "\\MimeType" ) ) { int pos1 = flag.indexOf( '[' ); int pos2 = flag.indexOf( ']', pos1 ); mt = flag.mid( pos1 + 1, pos2 - pos1 - 1 ); } else if ( flag.startsWith( "\\RemoteId" ) ) { int pos1 = flag.indexOf( '[' ); int pos2 = flag.indexOf( ']', pos1 ); remote_id = flag.mid( pos1 + 1, pos2 - pos1 - 1 ); } } // standard imap does not know this attribute, so that's mail if ( mt.isEmpty() ) mt = "message/rfc822"; MimeType mimeType = db->mimeTypeByName( mt ); if ( !mimeType.isValid() ) { return failureResponse( QString( "Unknown mime type '%1'.").arg( mt ) ); } int itemId = 0; bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, remote_id, &itemId ); response.setTag( tag() ); if ( !ok ) { return failureResponse( "Append failed" ); } // set message flags ok = db->appendItemFlags( itemId, m_flags ); // TODO handle failure // the message was appended; now we have to update the counts const int existsChange = +1; const int recentChange = +1; int unseenChange = 0; if ( !m_flags.contains( "\\Seen" ) ) unseenChange = +1; // int firstUnseen = ?; // can't be updated atomically, so we probably have to // recalculate it each time it's needed ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange ); // TODO handle failure by removing the message again from the db // TODO if the mailbox is currently selected, the normal new message // actions SHOULD occur. Specifically, the server SHOULD notify the // client immediately via an untagged EXISTS response. response.setTag( tag() ); response.setSuccess(); response.setString( "Append completed" ); emit responseAvailable( response ); deleteLater(); return true; } bool Akonadi::Append::inContinuation( ) const { return m_size > -1; } bool Akonadi::Append::allDataRead( ) const { return ( m_size == 0 ); } bool Akonadi::Append::startContinuation() { Response response; response.setContinuation(); response.setString( "Ready for literal data" ); emit responseAvailable( response ); return false; } <|endoftext|>
<commit_before>#ifndef b_Tuple_hxx_ #define b_Tuple_hxx_ #include "b/If.hxx" #include "b/forward.hxx" #include "b/move.hxx" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" namespace b { /* * A small tuple implementation. */ template <typename...> struct Tuple; //------------------------------------------------------------------------------------------------// // N = 0 template <> struct Tuple<> { static const Unsigned N = 0; }; //------------------------------------------------------------------------------------------------// // N = 1 template <typename __X> struct Tuple<__X> { static const Unsigned N = 1; //--------------------------------------------------------------------------------------------// /* forward */ private: template <Unsigned> struct __Element; public: template <Unsigned __i> using Element = typename __Element<__i>::Result; //--------------------------------------------------------------------------------------------// constexpr explicit Tuple(__X&& x) : __x(move(x)) { } //--------------------------------------------------------------------------------------------// template <Unsigned __i> constexpr const Element<__i>& element() const noexcept { static_assert(__i == 0, "out of bounds"); return this->__x; } private: __X __x; //--------------------------------------------------------------------------------------------// template <Unsigned __i> struct __Element { static_assert(__i == 0, "out of bounds"); using Result = __X; }; }; //------------------------------------------------------------------------------------------------// // N > 1 template <typename __First, typename... __Rest> struct Tuple<__First, __Rest...> { static const Unsigned N = 1 + sizeof...(__Rest); //--------------------------------------------------------------------------------------------// /* forward */ private: template <Unsigned, typename=void> struct __Element; public: template <Unsigned __i> using Element = typename __Element<__i>::Result; //--------------------------------------------------------------------------------------------// constexpr Tuple(__First&& first, __Rest&&... rest) : __first(move(first)) , __rest(forward<__Rest>(rest)...) { } //--------------------------------------------------------------------------------------------// template <Unsigned __i> constexpr If<(__i == 0), const Element<__i>&> element() const noexcept { return this->__first; } template <Unsigned __i> constexpr If<(__i != 0), const Element<__i>&> element() const noexcept { return this->__rest.template element<(__i - 1)>(); } private: __First __first; Tuple<__Rest...> __rest; //--------------------------------------------------------------------------------------------// template <Unsigned __i, typename __Enable> struct __Element { using Result = typename Tuple<__Rest...>::template Element<(__i - 1)>; }; template <Unsigned __i> struct __Element<__i, If<(__i == 0)>> { using Result = __First; }; }; } // namespace b #pragma clang diagnostic pop #endif <commit_msg>missing #include<commit_after>#ifndef b_Tuple_hxx_ #define b_Tuple_hxx_ #include "b/If.hxx" #include "b/Unsigned.hxx" #include "b/forward.hxx" #include "b/move.hxx" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" namespace b { /* * A small tuple implementation. */ template <typename...> struct Tuple; //------------------------------------------------------------------------------------------------// // N = 0 template <> struct Tuple<> { static const Unsigned N = 0; }; //------------------------------------------------------------------------------------------------// // N = 1 template <typename __X> struct Tuple<__X> { static const Unsigned N = 1; //--------------------------------------------------------------------------------------------// /* forward */ private: template <Unsigned> struct __Element; public: template <Unsigned __i> using Element = typename __Element<__i>::Result; //--------------------------------------------------------------------------------------------// constexpr explicit Tuple(__X&& x) : __x(move(x)) { } //--------------------------------------------------------------------------------------------// template <Unsigned __i> constexpr const Element<__i>& element() const noexcept { static_assert(__i == 0, "out of bounds"); return this->__x; } private: __X __x; //--------------------------------------------------------------------------------------------// template <Unsigned __i> struct __Element { static_assert(__i == 0, "out of bounds"); using Result = __X; }; }; //------------------------------------------------------------------------------------------------// // N > 1 template <typename __First, typename... __Rest> struct Tuple<__First, __Rest...> { static const Unsigned N = 1 + sizeof...(__Rest); //--------------------------------------------------------------------------------------------// /* forward */ private: template <Unsigned, typename=void> struct __Element; public: template <Unsigned __i> using Element = typename __Element<__i>::Result; //--------------------------------------------------------------------------------------------// constexpr Tuple(__First&& first, __Rest&&... rest) : __first(move(first)) , __rest(forward<__Rest>(rest)...) { } //--------------------------------------------------------------------------------------------// template <Unsigned __i> constexpr If<(__i == 0), const Element<__i>&> element() const noexcept { return this->__first; } template <Unsigned __i> constexpr If<(__i != 0), const Element<__i>&> element() const noexcept { return this->__rest.template element<(__i - 1)>(); } private: __First __first; Tuple<__Rest...> __rest; //--------------------------------------------------------------------------------------------// template <Unsigned __i, typename __Enable> struct __Element { using Result = typename Tuple<__Rest...>::template Element<(__i - 1)>; }; template <Unsigned __i> struct __Element<__i, If<(__i == 0)>> { using Result = __First; }; }; } // namespace b #pragma clang diagnostic pop #endif <|endoftext|>
<commit_before>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "InitialState.h" #include "TransitionState.h" State* InitialState::action(bool &flip){ gfx()->load_image(NULL); gfx()->load_image("resources/splash.png"); gfx()->render(0.0); flip = true; return new TransitionState(this); } <commit_msg>validating whenever it succeded loading initial resources<commit_after>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "InitialState.h" #include "TransitionState.h" #include "Exceptions.h" #include "Log.h" State* InitialState::action(bool &flip){ try { gfx()->load_image(NULL); gfx()->load_image("resources/splash.png"); } catch ( exception &e ){ Log::message(Log::Warning, "%s\n", e.what()); Log::message(Log::Warning, "Failed to load initial resources, check your configuration\n"); } gfx()->render(0.0); flip = true; return new TransitionState(this); } <|endoftext|>
<commit_before>#include "adddossierdialog.h" #include "ui_adddossierdialog.h" #include "src/formation.hpp" #include "src/dossier.hpp" #include "addsemestredialog.h" #include <QMessageBox> #define FM FormationManager::getInstance() #define DM DossierManager::getInstance() //! Ouverture du Pop up création de dossier AddDossierDialog::AddDossierDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddDossierDialog) { ui->setupUi(this); ui->formationBox->addItems(FM->getItemNameList()); QStringList header; header << "Abbréviation" << "Nom"; ui->tableWidget->setColumnCount(2); ui->tableWidget->setHorizontalHeaderLabels(header); ui->tableWidget->setRowCount(0); ui->tableWidget->verticalHeader()->setVisible(true); ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); QStringList headerSemestre; headerSemestre << "Semestre" << "Date"; ui->tableSemestre->setColumnCount(2); ui->tableSemestre->setHorizontalHeaderLabels(headerSemestre); ui->tableSemestre->setRowCount(0); ui->tableSemestre->verticalHeader()->setVisible(true); ui->tableSemestre->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); } void AddDossierDialog::setDossier(const QString &name) { editionMode = true; dossier = DM->getItem(name); ui->loginEdit->setText(name); ui->loginEdit->setDisabled(true); refresh(); } void AddDossierDialog::formationRemoved() { QList<QTableWidgetSelectionRange> ranges = ui->tableWidget->selectedRanges(); if (ranges.length() == 0) { QMessageBox error(this); error.setText("Aucune ligne sélectionnée"); error.exec(); return; } std::cout<<ranges.length()<<std::endl; for(auto it=ranges.begin(); it!=ranges.end(); it++) { std::cout<<it->bottomRow()<<" "<<it->topRow()<<std::endl; for(int i=it->bottomRow(); i>=it->topRow(); --i) { QString nom = ui->tableWidget->item(i, 0)->text(); std::cout<<nom.toStdString()<<std::endl; try { dossier.removeFormation(nom); } catch (const Exception &e) { QMessageBox error(this); error.setText(e.getinfo()); error.exec(); return; } } } refresh(); } void AddDossierDialog::semestreRemoved() { QList<QTableWidgetSelectionRange> ranges = ui->tableSemestre->selectedRanges(); if (ranges.length() == 0) { QMessageBox error(this); error.setText("Aucune ligne sélectionnée"); error.exec(); return; } std::cout<<ranges.length()<<std::endl; for(auto it=ranges.begin(); it!=ranges.end(); it++) { for(int i=it->bottomRow(); i>=it->topRow(); --i) { QString nom = ui->tableSemestre->item(i, 0)->text(); dossier.removeSemestre(nom); dossier.removeEquivalence(nom); } } refresh(); } void AddDossierDialog::refresh() { std::vector<Semestre> semestres = dossier.getSemestres(); std::vector<Formation> formations = dossier.getFormations(); std::vector<Equivalence> equivalences = dossier.getEquivalences(); ui->tableSemestre->clearContents(); ui->tableSemestre->setRowCount(semestres.size() + equivalences.size()); ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(formations.size()); int semestreOffset = 0; for(auto it=semestres.begin(); it!=semestres.end(); it++) { ui->tableSemestre->setItem(semestreOffset, 0, getUneditableItem(it->getName())); ui->tableSemestre->setItem(semestreOffset, 1, getUneditableItem(it->getSemestre().representation)); semestreOffset++; } for(auto it=equivalences.begin(); it!=equivalences.end(); it++) { ui->tableSemestre->setItem(semestreOffset, 0, getUneditableItem(it->getName())); ui->tableSemestre->setItem(semestreOffset, 1, getUneditableItem(it->getSemestre().representation)); semestreOffset++; } int formationOffset = 0; for(auto it=formations.begin(); it!=formations.end(); it++) { ui->tableWidget->setItem(formationOffset, 0, getUneditableItem(it->getName())); ui->tableWidget->setItem(formationOffset, 1, getUneditableItem(it->getLongName())); formationOffset++; } } void AddDossierDialog::setDossier() { dossier = Dossier(); editionMode = false; } void AddDossierDialog::semestreAdded() { if (dossier.getFormations().size() == 0) { QMessageBox error(this); error.setText("Veuillez ajouter une formation"); error.exec(); return; } AddSemestreDialog *dialog = new AddSemestreDialog(this, &dossier); dialog->exec(); refresh(); } //! Création d'un nouveau dossier void AddDossierDialog::createDossier() { if (!editionMode) { dossier.setName(ui->loginEdit->text()); DM->addItem(dossier); } else { Dossier& concerned = DM->getItem(dossier.getName()); concerned = dossier; } close(); } //! Ajout d'une formation au dossier (ex : TC, GI, SRI) void AddDossierDialog::formationAdded() { QString formation = ui->formationBox->currentText(); Formation f = FM->getItem(formation); dossier.addFormation(f); ui->formationBox->removeItem(ui->formationBox->currentIndex()); refresh(); } AddDossierDialog::~AddDossierDialog() { delete ui; } <commit_msg>Tentative affichage contenus dossiers<commit_after>#include "adddossierdialog.h" #include "ui_adddossierdialog.h" #include "src/formation.hpp" #include "src/dossier.hpp" #include "addsemestredialog.h" #include <QMessageBox> #define FM FormationManager::getInstance() #define DM DossierManager::getInstance() //! Ouverture du Pop up création de dossier AddDossierDialog::AddDossierDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddDossierDialog) { ui->setupUi(this); ui->formationBox->addItems(FM->getItemNameList()); QStringList header; header << "Abbréviation" << "Nom"; ui->tableWidget->setColumnCount(2); ui->tableWidget->setHorizontalHeaderLabels(header); ui->tableWidget->setRowCount(0); ui->tableWidget->verticalHeader()->setVisible(true); ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); QStringList headerSemestre; headerSemestre << "Semestre" << "Date" << "UVs"; ui->tableSemestre->setColumnCount(3); ui->tableSemestre->setHorizontalHeaderLabels(headerSemestre); ui->tableSemestre->setRowCount(0); ui->tableSemestre->verticalHeader()->setVisible(true); ui->tableSemestre->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); } void AddDossierDialog::setDossier(const QString &name) { editionMode = true; dossier = DM->getItem(name); ui->loginEdit->setText(name); ui->loginEdit->setDisabled(true); refresh(); } void AddDossierDialog::formationRemoved() { QList<QTableWidgetSelectionRange> ranges = ui->tableWidget->selectedRanges(); if (ranges.length() == 0) { QMessageBox error(this); error.setText("Aucune ligne sélectionnée"); error.exec(); return; } std::cout<<ranges.length()<<std::endl; for(auto it=ranges.begin(); it!=ranges.end(); it++) { std::cout<<it->bottomRow()<<" "<<it->topRow()<<std::endl; for(int i=it->bottomRow(); i>=it->topRow(); --i) { QString nom = ui->tableWidget->item(i, 0)->text(); std::cout<<nom.toStdString()<<std::endl; try { dossier.removeFormation(nom); } catch (const Exception &e) { QMessageBox error(this); error.setText(e.getinfo()); error.exec(); return; } } } refresh(); } void AddDossierDialog::semestreRemoved() { QList<QTableWidgetSelectionRange> ranges = ui->tableSemestre->selectedRanges(); if (ranges.length() == 0) { QMessageBox error(this); error.setText("Aucune ligne sélectionnée"); error.exec(); return; } std::cout<<ranges.length()<<std::endl; for(auto it=ranges.begin(); it!=ranges.end(); it++) { for(int i=it->bottomRow(); i>=it->topRow(); --i) { QString nom = ui->tableSemestre->item(i, 0)->text(); dossier.removeSemestre(nom); dossier.removeEquivalence(nom); } } refresh(); } void AddDossierDialog::refresh() { std::vector<Semestre> semestres = dossier.getSemestres(); std::vector<Formation> formations = dossier.getFormations(); std::vector<Equivalence> equivalences = dossier.getEquivalences(); ui->tableSemestre->clearContents(); ui->tableSemestre->setRowCount(semestres.size() + equivalences.size()); ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(formations.size()); int semestreOffset = 0; for(auto it=semestres.begin(); it!=semestres.end(); it++) { ui->tableSemestre->setItem(semestreOffset, 0, getUneditableItem(it->getName())); ui->tableSemestre->setItem(semestreOffset, 1, getUneditableItem(it->getSemestre().representation)); ui->tableSemestre->setItem(semestreOffset, 2, getUneditableItem(it->getUvList().join(" "))); semestreOffset++; } for(auto it=equivalences.begin(); it!=equivalences.end(); it++) { ui->tableSemestre->setItem(semestreOffset, 0, getUneditableItem(it->getName())); ui->tableSemestre->setItem(semestreOffset, 1, getUneditableItem(it->getSemestre().representation)); ui->tableSemestre->setItem(semestreOffset, 2, getUneditableItem(it->getCreditsList().join(" "))); semestreOffset++; } int formationOffset = 0; for(auto it=formations.begin(); it!=formations.end(); it++) { ui->tableWidget->setItem(formationOffset, 0, getUneditableItem(it->getName())); ui->tableWidget->setItem(formationOffset, 1, getUneditableItem(it->getLongName())); formationOffset++; } } void AddDossierDialog::setDossier() { dossier = Dossier(); editionMode = false; } void AddDossierDialog::semestreAdded() { if (dossier.getFormations().size() == 0) { QMessageBox error(this); error.setText("Veuillez ajouter une formation"); error.exec(); return; } AddSemestreDialog *dialog = new AddSemestreDialog(this, &dossier); dialog->exec(); refresh(); } //! Création d'un nouveau dossier void AddDossierDialog::createDossier() { if (!editionMode) { dossier.setName(ui->loginEdit->text()); DM->addItem(dossier); } else { Dossier& concerned = DM->getItem(dossier.getName()); concerned = dossier; } close(); } //! Ajout d'une formation au dossier (ex : TC, GI, SRI) void AddDossierDialog::formationAdded() { QString formation = ui->formationBox->currentText(); Formation f = FM->getItem(formation); dossier.addFormation(f); ui->formationBox->removeItem(ui->formationBox->currentIndex()); refresh(); } AddDossierDialog::~AddDossierDialog() { delete ui; } <|endoftext|>
<commit_before>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/detail/config.h> #include <thrust/system/cuda/detail/trivial_copy.h> #include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h> #include <thrust/system_error.h> #include <thrust/system/cuda/error.h> #include <thrust/system/cuda/detail/throw_on_error.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/system/cpp/detail/execution_policy.h> #include <thrust/detail/raw_pointer_cast.h> #include <thrust/functional.h> #include <thrust/system/cuda/detail/execute_on_stream.h> namespace thrust { namespace system { namespace cuda { namespace detail { namespace trivial_copy_detail { inline void checked_cudaMemcpyAsync(void *dst, const void *src, size_t count, enum cudaMemcpyKind kind, cudaStream_t stream) { cudaError_t error = cudaMemcpyAsync(dst,src,count,kind,stream); if(error) { throw thrust::system_error(error, thrust::cuda_category()); } // end error } // end checked_cudaMemcpy() template<typename System1, typename System2> cudaMemcpyKind cuda_memcpy_kind(const thrust::cuda::execution_policy<System1> &, const thrust::cpp::execution_policy<System2> &) { return cudaMemcpyDeviceToHost; } // end cuda_memcpy_kind() template<typename System1, typename System2> cudaMemcpyKind cuda_memcpy_kind(const thrust::cpp::execution_policy<System1> &, const thrust::cuda::execution_policy<System2> &) { return cudaMemcpyHostToDevice; } // end cuda_memcpy_kind() } // end namespace trivial_copy_detail template<typename DerivedPolicy, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2> __host__ __device__ void trivial_copy_n(execution_policy<DerivedPolicy> &exec, RandomAccessIterator1 first, Size n, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type T; #ifndef __CUDA_ARCH__ void *dst = thrust::raw_pointer_cast(&*result); const void *src = thrust::raw_pointer_cast(&*first); trivial_copy_detail::checked_cudaMemcpyAsync(dst, src, n * sizeof(T), cudaMemcpyDeviceToDevice, stream(thrust::detail::derived_cast(exec))); #else thrust::transform(exec, first, first + n, result, thrust::identity<T>()); #endif } template<typename System1, typename System2, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2> void trivial_copy_n(cross_system<System1,System2> &systems, RandomAccessIterator1 first, Size n, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type T; void *dst = thrust::raw_pointer_cast(&*result); const void *src = thrust::raw_pointer_cast(&*first); cudaMemcpyKind kind = trivial_copy_detail::cuda_memcpy_kind(thrust::detail::derived_cast(systems.system1), thrust::detail::derived_cast(systems.system2)); // XXX use stream 0 for now // we may wish to enable async host <-> device copy in the future trivial_copy_detail::checked_cudaMemcpyAsync(dst, src, n * sizeof(T), kind, 0); } } // end namespace detail } // end namespace cuda } // end namespace system } // end namespace thrust <commit_msg>Infer the directionality of trivial_copy_n dynamically<commit_after>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/detail/config.h> #include <thrust/system/cuda/detail/trivial_copy.h> #include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h> #include <thrust/system_error.h> #include <thrust/system/cuda/error.h> #include <thrust/system/cuda/detail/throw_on_error.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/system/cpp/detail/execution_policy.h> #include <thrust/detail/raw_pointer_cast.h> #include <thrust/functional.h> #include <thrust/system/cuda/detail/execute_on_stream.h> namespace thrust { namespace system { namespace cuda { namespace detail { namespace trivial_copy_detail { inline void checked_cudaMemcpyAsync(void *dst, const void *src, size_t count, enum cudaMemcpyKind kind, cudaStream_t stream) { cudaError_t error = cudaMemcpyAsync(dst,src,count,kind,stream); if(error) { throw thrust::system_error(error, thrust::cuda_category()); } // end error } // end checked_cudaMemcpy() template<typename System1, typename System2> cudaMemcpyKind cuda_memcpy_kind(const thrust::cuda::execution_policy<System1> &, const thrust::cpp::execution_policy<System2> &) { return cudaMemcpyDeviceToHost; } // end cuda_memcpy_kind() template<typename System1, typename System2> cudaMemcpyKind cuda_memcpy_kind(const thrust::cpp::execution_policy<System1> &, const thrust::cuda::execution_policy<System2> &) { return cudaMemcpyHostToDevice; } // end cuda_memcpy_kind() } // end namespace trivial_copy_detail template<typename DerivedPolicy, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2> __host__ __device__ void trivial_copy_n(execution_policy<DerivedPolicy> &exec, RandomAccessIterator1 first, Size n, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type T; #ifndef __CUDA_ARCH__ void *dst = thrust::raw_pointer_cast(&*result); const void *src = thrust::raw_pointer_cast(&*first); // since the user may have given thrust::cuda::par to thrust::copy explicitly, // this copy may be a cross-space copy that has bypassed system dispatch // we need to have cudaMemcpyAsync figure out the directionality of the copy dynamically // using cudaMemcpyDefault trivial_copy_detail::checked_cudaMemcpyAsync(dst, src, n * sizeof(T), cudaMemcpyDefault, stream(thrust::detail::derived_cast(exec))); #else thrust::transform(exec, first, first + n, result, thrust::identity<T>()); #endif } template<typename System1, typename System2, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2> void trivial_copy_n(cross_system<System1,System2> &systems, RandomAccessIterator1 first, Size n, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator1>::type T; void *dst = thrust::raw_pointer_cast(&*result); const void *src = thrust::raw_pointer_cast(&*first); cudaMemcpyKind kind = trivial_copy_detail::cuda_memcpy_kind(thrust::detail::derived_cast(systems.system1), thrust::detail::derived_cast(systems.system2)); // XXX use stream 0 for now // we may wish to enable async host <-> device copy in the future trivial_copy_detail::checked_cudaMemcpyAsync(dst, src, n * sizeof(T), kind, 0); } } // end namespace detail } // end namespace cuda } // end namespace system } // end namespace thrust <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCLogicClassModule.h // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCLogicClassModule // // ------------------------------------------------------------------------- ////#include "stdafx.h" #include <algorithm> #include "NFConfigPlugin.h" #include "NFCElementInfoModule.h" #include "NFCLogicClassModule.h" //// bool NFCLogicClassModule::Init() { m_pElementInfoModule = dynamic_cast<NFCElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); assert(NULL != m_pElementInfoModule); Load(); return true; } bool NFCLogicClassModule::Shut() { NFILogicClass* pLogicClass = First(); while (pLogicClass) { pLogicClass->ClearAll(); delete pLogicClass; pLogicClass = NULL; pLogicClass = Next(); } ClearAll(); return true; } NFCLogicClassModule::NFCLogicClassModule(NFIPluginManager* p) { mnPropertyIndex = GetTickCount() % 10 + 1; pPluginManager = p; msConfigFileName = "../../NFDataCfg/Struct/LogicClass.xml"; } NFCLogicClassModule::~NFCLogicClassModule() { } TDATA_TYPE NFCLogicClassModule::ComputerType(const char* pstrTypeName, NFIValueList::TData& var) { if (0 == strcmp(pstrTypeName, "int")) { var.nType = TDATA_INT; var.variantData = (int)0; return TDATA_INT; } else if (0 == strcmp(pstrTypeName, "float")) { var.nType = TDATA_FLOAT; var.variantData = (float)0.0f; return TDATA_FLOAT; } else if (0 == strcmp(pstrTypeName, "string")) { var.nType = TDATA_STRING; var.variantData = NULL_STR; return TDATA_STRING; } else if (0 == strcmp(pstrTypeName, "double")) { var.nType = TDATA_DOUBLE; var.variantData = (double)0.0f; return TDATA_DOUBLE; } else if (0 == strcmp(pstrTypeName, "object")) { var.nType = TDATA_OBJECT; var.variantData = NFINT64(0); return TDATA_OBJECT; } return TDATA_UNKNOWN; } bool NFCLogicClassModule::AddPropertys(rapidxml::xml_node<>* pPropertyRootNode, NFCLogicClass* pClass) { for (rapidxml::xml_node<>* pPropertyNode = pPropertyRootNode->first_node(); pPropertyNode; pPropertyNode = pPropertyNode->next_sibling()) { if (pPropertyNode) { const char* strPropertyName = pPropertyNode->first_attribute("Id")->value(); if (pClass->GetPropertyManager()->GetElement(strPropertyName)) { //error NFASSERT(0, strPropertyName, __FILE__, __FUNCTION__); continue; } const char* pstrType = pPropertyNode->first_attribute("Type")->value(); const char* pstrPublic = pPropertyNode->first_attribute("Public")->value(); const char* pstrPrivate = pPropertyNode->first_attribute("Private")->value(); const char* pstrPropertyIndex = pPropertyNode->first_attribute("Index")->value(); const char* pstrSave = pPropertyNode->first_attribute("Save")->value(); const char* pstrRelationValue = NULL_STR.c_str(); if (pPropertyNode->first_attribute("RelationValue")) { pstrRelationValue = pPropertyNode->first_attribute("RelationValue")->value(); } bool bPublic = boost::lexical_cast<int>(pstrPublic); bool bPrivate = boost::lexical_cast<int>(pstrPrivate); bool bSave = boost::lexical_cast<int>(pstrSave); int nIndex = boost::lexical_cast<int>(pstrPropertyIndex); if (bPublic || bPrivate) { ++mnPropertyIndex; nIndex = mnPropertyIndex; mxPropertyIndexMap.insert(std::map<std::string, int>::value_type(strPropertyName, mnPropertyIndex)); } NFIValueList::TData varProperty; if (TDATA_UNKNOWN == ComputerType(pstrType, varProperty)) { //std::cout << "error:" << pClass->GetTypeName() << " " << pClass->GetInstancePath() << ": " << strPropertyName << " type error!!!" << std::endl; NFASSERT(0, strPropertyName, __FILE__, __FUNCTION__); } //printf( " Property:%s[%s]\n", pstrPropertyName, pstrType ); pClass->GetPropertyManager()->AddProperty(0, strPropertyName, varProperty.nType, bPublic, bPrivate, bSave, nIndex, pstrRelationValue); } } return true; } bool NFCLogicClassModule::AddRecords(rapidxml::xml_node<>* pRecordRootNode, NFCLogicClass* pClass) { for (rapidxml::xml_node<>* pRecordNode = pRecordRootNode->first_node(); pRecordNode; pRecordNode = pRecordNode->next_sibling()) { if (pRecordNode) { const char* pstrRecordName = pRecordNode->first_attribute("Id")->value(); if (pClass->GetRecordManager()->GetElement(pstrRecordName)) { //error //file << pClass->mstrType << ":" << pstrRecordName << std::endl; //assert(0); NFASSERT(0, pstrRecordName, __FILE__, __FUNCTION__); continue; } const char* pstrRow = pRecordNode->first_attribute("Row")->value(); const char* pstrCol = pRecordNode->first_attribute("Col")->value(); const char* pstrPublic = pRecordNode->first_attribute("Public")->value(); const char* pstrPrivate = pRecordNode->first_attribute("Private")->value(); const char* pstrSave = pRecordNode->first_attribute("Save")->value(); const char* pstrIndex = pRecordNode->first_attribute("Index")->value(); bool bPublic = boost::lexical_cast<int>(pstrPublic); bool bPrivate = boost::lexical_cast<int>(pstrPrivate); bool bSave = boost::lexical_cast<int>(pstrSave); int nIndex = boost::lexical_cast<int>(pstrIndex); NFCValueList recordVar; NFCValueList recordKey; NFCValueList recordDesc; NFCValueList recordTag; NFCValueList recordRelation; for (rapidxml::xml_node<>* recordColNode = pRecordNode->first_node(); recordColNode; recordColNode = recordColNode->next_sibling()) { //const char* pstrColName = recordColNode->first_attribute( "Id" )->value(); NFIValueList::TData TData; const char* pstrColType = recordColNode->first_attribute("Type")->value(); if (TDATA_UNKNOWN == ComputerType(pstrColType, TData)) { //assert(0); NFASSERT(0, pstrRecordName, __FILE__, __FUNCTION__); } recordVar.Append(TData); ////////////////////////////////////////////////////////////////////////// if (recordColNode->first_attribute("Key") != NULL) { const char* pstrKey = recordColNode->first_attribute("Key")->value(); bool bKey = boost::lexical_cast<int>(pstrKey); if (bKey) { recordKey.AddInt(1); } else { recordKey.AddInt(0); } } if (recordColNode->first_attribute("Tag") != NULL) { const char* pstrTag = recordColNode->first_attribute("Tag")->value(); recordTag.AddString(pstrTag); } else { recordTag.AddString(""); } if (recordColNode->first_attribute("RelateRecord") != NULL) { std::string strRelationRecord = recordColNode->first_attribute("RelatedRecord")->value(); recordRelation.AddString(strRelationRecord.c_str()); } else { recordRelation.AddString(""); } ////////////////////////////////////////////////////////////////////////// if (recordColNode->first_attribute("Desc")) { const char* pstrColDesc = recordColNode->first_attribute("Desc")->value(); recordDesc.AddString(pstrColDesc); } else { recordDesc.AddString(""); } ////////////////////////////////////////////////////////////////////////// } pClass->GetRecordManager()->AddRecord(0, pstrRecordName, recordVar, recordKey, recordDesc, recordTag, recordRelation, atoi(pstrRow), bPublic, bPrivate, bSave, nIndex); } } return true; } bool NFCLogicClassModule::AddComponents( rapidxml::xml_node<>* pComponentRootNode, NFCLogicClass* pClass ) { for (rapidxml::xml_node<>* pComponentNode = pComponentRootNode->first_node(); pComponentNode; pComponentNode = pComponentNode->next_sibling()) { if (pComponentNode) { const char* strComponentName = pComponentNode->first_attribute("Name")->value(); const char* strLanguage = pComponentNode->first_attribute("Language")->value(); const char* strEnable = pComponentNode->first_attribute("Enable")->value(); bool bEnable = boost::lexical_cast<int>(strEnable); if(bEnable) { if (pClass->GetComponentManager()->GetElement(strComponentName)) { //error NFASSERT(0, strComponentName, __FILE__, __FUNCTION__); continue; } pClass->GetComponentManager()->AddComponent(std::string(strComponentName), std::string(strLanguage)); } } } return true; } bool NFCLogicClassModule::AddClassInclude(const char* pstrClassFilePath, NFCLogicClass* pClass) { if (pClass->Find(pstrClassFilePath)) { return false; } rapidxml::file<> fdoc(pstrClassFilePath); //std::cout << fdoc.data() << std::endl; rapidxml::xml_document<> doc; doc.parse<0>(fdoc.data()); //support for unlimited layer class inherits rapidxml::xml_node<>* root = doc.first_node(); rapidxml::xml_node<>* pRropertyRootNode = root->first_node("Propertys"); if (pRropertyRootNode) { AddPropertys(pRropertyRootNode, pClass); } ////////////////////////////////////////////////////////////////////////// //and record rapidxml::xml_node<>* pRecordRootNode = root->first_node("Records"); if (pRecordRootNode) { AddRecords(pRecordRootNode, pClass); } rapidxml::xml_node<>* pComponentRootNode = root->first_node("Components"); if (pComponentRootNode) { AddComponents(pComponentRootNode, pClass); } //pClass->mvIncludeFile.push_back( pstrClassFilePath ); //and include file rapidxml::xml_node<>* pIncludeRootNode = root->first_node("Includes"); if (pIncludeRootNode) { for (rapidxml::xml_node<>* includeNode = pIncludeRootNode->first_node(); includeNode; includeNode = includeNode->next_sibling()) { const char* pstrIncludeFile = includeNode->first_attribute("Id")->value(); //std::vector<std::string>::iterator it = std::find( pClass->mvIncludeFile.begin(), pClass->mvIncludeFile..end(), pstrIncludeFile ); if (AddClassInclude(pstrIncludeFile, pClass)) { pClass->Add(pstrIncludeFile); } } } return true; } bool NFCLogicClassModule::AddClass(const char* pstrClassFilePath, NFCLogicClass* pClass) { std::ofstream file; file.open("./Log/NFLogicClass.log"); NFILogicClass* pParent = pClass->GetParent(); while (pParent) { //inherited some properties form class of parent std::string strFileName = ""; pParent->First(strFileName); while (!strFileName.empty()) { if (pClass->Find(strFileName)) { strFileName.clear(); continue; } if (AddClassInclude(strFileName.c_str(), pClass)) { pClass->Add(strFileName); } strFileName.clear(); pParent->Next(strFileName); } pParent = pParent->GetParent(); } ////////////////////////////////////////////////////////////////////////// if (AddClassInclude(pstrClassFilePath, pClass)) { pClass->Add(pstrClassFilePath); } file.close(); return true; } bool NFCLogicClassModule::AddClass(const std::string& strClassName, const std::string& strParentName) { NFILogicClass* pParentClass = GetElement(strParentName); NFILogicClass* pChildClass = GetElement(strClassName); if (!pChildClass) { pChildClass = new NFCLogicClass(strClassName); AddElement(strClassName, pChildClass); //pChildClass = CreateElement( strClassName ); pChildClass->SetTypeName(""); pChildClass->SetInstancePath(""); if (pParentClass) { pChildClass->SetParent(pParentClass); } } return true; } bool NFCLogicClassModule::Load(rapidxml::xml_node<>* attrNode, NFCLogicClass* pParentClass) { const char* pstrLogicClassName = attrNode->first_attribute("Id")->value(); const char* pstrType = attrNode->first_attribute("Type")->value(); const char* pstrPath = attrNode->first_attribute("Path")->value(); const char* pstrInstancePath = attrNode->first_attribute("InstancePath")->value(); //printf( "-----------------------------------------------------\n"); //printf( "%s:\n", pstrLogicClassName ); NFCLogicClass* pClass = new NFCLogicClass(pstrLogicClassName); AddElement(pstrLogicClassName, pClass); pClass->SetParent(pParentClass); pClass->SetTypeName(pstrType); pClass->SetInstancePath(pstrInstancePath); AddClass(pstrPath, pClass); for (rapidxml::xml_node<>* pDataNode = attrNode->first_node(); pDataNode; pDataNode = pDataNode->next_sibling()) { //her children Load(pDataNode, pClass); } //printf( "-----------------------------------------------------\n"); return true; } bool NFCLogicClassModule::Load() { rapidxml::file<> fdoc(msConfigFileName.c_str()); //std::cout << fdoc.data() << std::endl; rapidxml::xml_document<> doc; doc.parse<0>(fdoc.data()); //support for unlimited layer class inherits rapidxml::xml_node<>* root = doc.first_node(); for (rapidxml::xml_node<>* attrNode = root->first_node(); attrNode; attrNode = attrNode->next_sibling()) { Load(attrNode, NULL); } m_pElementInfoModule->Load(); return true; } bool NFCLogicClassModule::Save() { return true; } NFIPropertyManager* NFCLogicClassModule::GetClassPropertyManager(const std::string& strClassName) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetPropertyManager(); } return NULL; } NFIRecordManager* NFCLogicClassModule::GetClassRecordManager(const std::string& strClassName) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetRecordManager(); } return NULL; } NFIComponentManager* NFCLogicClassModule::GetClassComponentManager( const std::string& strClassName ) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetComponentManager(); } return NULL; } bool NFCLogicClassModule::Clear() { return true; }<commit_msg>modify boost::lexical_cast error type<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCLogicClassModule.h // @Author : LvSheng.Huang // @Date : 2012-12-15 // @Module : NFCLogicClassModule // // ------------------------------------------------------------------------- ////#include "stdafx.h" #include <algorithm> #include "NFConfigPlugin.h" #include "NFCElementInfoModule.h" #include "NFCLogicClassModule.h" //// bool NFCLogicClassModule::Init() { m_pElementInfoModule = dynamic_cast<NFCElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); assert(NULL != m_pElementInfoModule); Load(); return true; } bool NFCLogicClassModule::Shut() { NFILogicClass* pLogicClass = First(); while (pLogicClass) { pLogicClass->ClearAll(); delete pLogicClass; pLogicClass = NULL; pLogicClass = Next(); } ClearAll(); return true; } NFCLogicClassModule::NFCLogicClassModule(NFIPluginManager* p) { mnPropertyIndex = GetTickCount() % 10 + 1; pPluginManager = p; msConfigFileName = "../../NFDataCfg/Struct/LogicClass.xml"; } NFCLogicClassModule::~NFCLogicClassModule() { } TDATA_TYPE NFCLogicClassModule::ComputerType(const char* pstrTypeName, NFIValueList::TData& var) { if (0 == strcmp(pstrTypeName, "int")) { var.nType = TDATA_INT; var.variantData = (int)0; return TDATA_INT; } else if (0 == strcmp(pstrTypeName, "float")) { var.nType = TDATA_FLOAT; var.variantData = (float)0.0f; return TDATA_FLOAT; } else if (0 == strcmp(pstrTypeName, "string")) { var.nType = TDATA_STRING; var.variantData = NULL_STR; return TDATA_STRING; } else if (0 == strcmp(pstrTypeName, "double")) { var.nType = TDATA_DOUBLE; var.variantData = (double)0.0f; return TDATA_DOUBLE; } else if (0 == strcmp(pstrTypeName, "object")) { var.nType = TDATA_OBJECT; var.variantData = NFINT64(0); return TDATA_OBJECT; } return TDATA_UNKNOWN; } bool NFCLogicClassModule::AddPropertys(rapidxml::xml_node<>* pPropertyRootNode, NFCLogicClass* pClass) { for (rapidxml::xml_node<>* pPropertyNode = pPropertyRootNode->first_node(); pPropertyNode; pPropertyNode = pPropertyNode->next_sibling()) { if (pPropertyNode) { const char* strPropertyName = pPropertyNode->first_attribute("Id")->value(); if (pClass->GetPropertyManager()->GetElement(strPropertyName)) { //error NFASSERT(0, strPropertyName, __FILE__, __FUNCTION__); continue; } const char* pstrType = pPropertyNode->first_attribute("Type")->value(); const char* pstrPublic = pPropertyNode->first_attribute("Public")->value(); const char* pstrPrivate = pPropertyNode->first_attribute("Private")->value(); const char* pstrPropertyIndex = pPropertyNode->first_attribute("Index")->value(); const char* pstrSave = pPropertyNode->first_attribute("Save")->value(); const char* pstrRelationValue = NULL_STR.c_str(); if (pPropertyNode->first_attribute("RelationValue")) { pstrRelationValue = pPropertyNode->first_attribute("RelationValue")->value(); } bool bPublic = boost::lexical_cast<bool>(pstrPublic); bool bPrivate = boost::lexical_cast<bool>(pstrPrivate); bool bSave = boost::lexical_cast<bool>(pstrSave); int nIndex = boost::lexical_cast<int>(pstrPropertyIndex); if (bPublic || bPrivate) { ++mnPropertyIndex; nIndex = mnPropertyIndex; mxPropertyIndexMap.insert(std::map<std::string, int>::value_type(strPropertyName, mnPropertyIndex)); } NFIValueList::TData varProperty; if (TDATA_UNKNOWN == ComputerType(pstrType, varProperty)) { //std::cout << "error:" << pClass->GetTypeName() << " " << pClass->GetInstancePath() << ": " << strPropertyName << " type error!!!" << std::endl; NFASSERT(0, strPropertyName, __FILE__, __FUNCTION__); } //printf( " Property:%s[%s]\n", pstrPropertyName, pstrType ); pClass->GetPropertyManager()->AddProperty(0, strPropertyName, varProperty.nType, bPublic, bPrivate, bSave, nIndex, pstrRelationValue); } } return true; } bool NFCLogicClassModule::AddRecords(rapidxml::xml_node<>* pRecordRootNode, NFCLogicClass* pClass) { for (rapidxml::xml_node<>* pRecordNode = pRecordRootNode->first_node(); pRecordNode; pRecordNode = pRecordNode->next_sibling()) { if (pRecordNode) { const char* pstrRecordName = pRecordNode->first_attribute("Id")->value(); if (pClass->GetRecordManager()->GetElement(pstrRecordName)) { //error //file << pClass->mstrType << ":" << pstrRecordName << std::endl; //assert(0); NFASSERT(0, pstrRecordName, __FILE__, __FUNCTION__); continue; } const char* pstrRow = pRecordNode->first_attribute("Row")->value(); const char* pstrCol = pRecordNode->first_attribute("Col")->value(); const char* pstrPublic = pRecordNode->first_attribute("Public")->value(); const char* pstrPrivate = pRecordNode->first_attribute("Private")->value(); const char* pstrSave = pRecordNode->first_attribute("Save")->value(); const char* pstrIndex = pRecordNode->first_attribute("Index")->value(); bool bPublic = boost::lexical_cast<bool>(pstrPublic); bool bPrivate = boost::lexical_cast<bool>(pstrPrivate); bool bSave = boost::lexical_cast<bool>(pstrSave); int nIndex = boost::lexical_cast<int>(pstrIndex); NFCValueList recordVar; NFCValueList recordKey; NFCValueList recordDesc; NFCValueList recordTag; NFCValueList recordRelation; for (rapidxml::xml_node<>* recordColNode = pRecordNode->first_node(); recordColNode; recordColNode = recordColNode->next_sibling()) { //const char* pstrColName = recordColNode->first_attribute( "Id" )->value(); NFIValueList::TData TData; const char* pstrColType = recordColNode->first_attribute("Type")->value(); if (TDATA_UNKNOWN == ComputerType(pstrColType, TData)) { //assert(0); NFASSERT(0, pstrRecordName, __FILE__, __FUNCTION__); } recordVar.Append(TData); ////////////////////////////////////////////////////////////////////////// if (recordColNode->first_attribute("Key") != NULL) { const char* pstrKey = recordColNode->first_attribute("Key")->value(); bool bKey = boost::lexical_cast<int>(pstrKey); if (bKey) { recordKey.AddInt(1); } else { recordKey.AddInt(0); } } if (recordColNode->first_attribute("Tag") != NULL) { const char* pstrTag = recordColNode->first_attribute("Tag")->value(); recordTag.AddString(pstrTag); } else { recordTag.AddString(""); } if (recordColNode->first_attribute("RelateRecord") != NULL) { std::string strRelationRecord = recordColNode->first_attribute("RelatedRecord")->value(); recordRelation.AddString(strRelationRecord.c_str()); } else { recordRelation.AddString(""); } ////////////////////////////////////////////////////////////////////////// if (recordColNode->first_attribute("Desc")) { const char* pstrColDesc = recordColNode->first_attribute("Desc")->value(); recordDesc.AddString(pstrColDesc); } else { recordDesc.AddString(""); } ////////////////////////////////////////////////////////////////////////// } pClass->GetRecordManager()->AddRecord(0, pstrRecordName, recordVar, recordKey, recordDesc, recordTag, recordRelation, atoi(pstrRow), bPublic, bPrivate, bSave, nIndex); } } return true; } bool NFCLogicClassModule::AddComponents( rapidxml::xml_node<>* pComponentRootNode, NFCLogicClass* pClass ) { for (rapidxml::xml_node<>* pComponentNode = pComponentRootNode->first_node(); pComponentNode; pComponentNode = pComponentNode->next_sibling()) { if (pComponentNode) { const char* strComponentName = pComponentNode->first_attribute("Name")->value(); const char* strLanguage = pComponentNode->first_attribute("Language")->value(); const char* strEnable = pComponentNode->first_attribute("Enable")->value(); bool bEnable = boost::lexical_cast<int>(strEnable); if(bEnable) { if (pClass->GetComponentManager()->GetElement(strComponentName)) { //error NFASSERT(0, strComponentName, __FILE__, __FUNCTION__); continue; } pClass->GetComponentManager()->AddComponent(std::string(strComponentName), std::string(strLanguage)); } } } return true; } bool NFCLogicClassModule::AddClassInclude(const char* pstrClassFilePath, NFCLogicClass* pClass) { if (pClass->Find(pstrClassFilePath)) { return false; } rapidxml::file<> fdoc(pstrClassFilePath); //std::cout << fdoc.data() << std::endl; rapidxml::xml_document<> doc; doc.parse<0>(fdoc.data()); //support for unlimited layer class inherits rapidxml::xml_node<>* root = doc.first_node(); rapidxml::xml_node<>* pRropertyRootNode = root->first_node("Propertys"); if (pRropertyRootNode) { AddPropertys(pRropertyRootNode, pClass); } ////////////////////////////////////////////////////////////////////////// //and record rapidxml::xml_node<>* pRecordRootNode = root->first_node("Records"); if (pRecordRootNode) { AddRecords(pRecordRootNode, pClass); } rapidxml::xml_node<>* pComponentRootNode = root->first_node("Components"); if (pComponentRootNode) { AddComponents(pComponentRootNode, pClass); } //pClass->mvIncludeFile.push_back( pstrClassFilePath ); //and include file rapidxml::xml_node<>* pIncludeRootNode = root->first_node("Includes"); if (pIncludeRootNode) { for (rapidxml::xml_node<>* includeNode = pIncludeRootNode->first_node(); includeNode; includeNode = includeNode->next_sibling()) { const char* pstrIncludeFile = includeNode->first_attribute("Id")->value(); //std::vector<std::string>::iterator it = std::find( pClass->mvIncludeFile.begin(), pClass->mvIncludeFile..end(), pstrIncludeFile ); if (AddClassInclude(pstrIncludeFile, pClass)) { pClass->Add(pstrIncludeFile); } } } return true; } bool NFCLogicClassModule::AddClass(const char* pstrClassFilePath, NFCLogicClass* pClass) { std::ofstream file; file.open("./Log/NFLogicClass.log"); NFILogicClass* pParent = pClass->GetParent(); while (pParent) { //inherited some properties form class of parent std::string strFileName = ""; pParent->First(strFileName); while (!strFileName.empty()) { if (pClass->Find(strFileName)) { strFileName.clear(); continue; } if (AddClassInclude(strFileName.c_str(), pClass)) { pClass->Add(strFileName); } strFileName.clear(); pParent->Next(strFileName); } pParent = pParent->GetParent(); } ////////////////////////////////////////////////////////////////////////// if (AddClassInclude(pstrClassFilePath, pClass)) { pClass->Add(pstrClassFilePath); } file.close(); return true; } bool NFCLogicClassModule::AddClass(const std::string& strClassName, const std::string& strParentName) { NFILogicClass* pParentClass = GetElement(strParentName); NFILogicClass* pChildClass = GetElement(strClassName); if (!pChildClass) { pChildClass = new NFCLogicClass(strClassName); AddElement(strClassName, pChildClass); //pChildClass = CreateElement( strClassName ); pChildClass->SetTypeName(""); pChildClass->SetInstancePath(""); if (pParentClass) { pChildClass->SetParent(pParentClass); } } return true; } bool NFCLogicClassModule::Load(rapidxml::xml_node<>* attrNode, NFCLogicClass* pParentClass) { const char* pstrLogicClassName = attrNode->first_attribute("Id")->value(); const char* pstrType = attrNode->first_attribute("Type")->value(); const char* pstrPath = attrNode->first_attribute("Path")->value(); const char* pstrInstancePath = attrNode->first_attribute("InstancePath")->value(); //printf( "-----------------------------------------------------\n"); //printf( "%s:\n", pstrLogicClassName ); NFCLogicClass* pClass = new NFCLogicClass(pstrLogicClassName); AddElement(pstrLogicClassName, pClass); pClass->SetParent(pParentClass); pClass->SetTypeName(pstrType); pClass->SetInstancePath(pstrInstancePath); AddClass(pstrPath, pClass); for (rapidxml::xml_node<>* pDataNode = attrNode->first_node(); pDataNode; pDataNode = pDataNode->next_sibling()) { //her children Load(pDataNode, pClass); } //printf( "-----------------------------------------------------\n"); return true; } bool NFCLogicClassModule::Load() { rapidxml::file<> fdoc(msConfigFileName.c_str()); //std::cout << fdoc.data() << std::endl; rapidxml::xml_document<> doc; doc.parse<0>(fdoc.data()); //support for unlimited layer class inherits rapidxml::xml_node<>* root = doc.first_node(); for (rapidxml::xml_node<>* attrNode = root->first_node(); attrNode; attrNode = attrNode->next_sibling()) { Load(attrNode, NULL); } m_pElementInfoModule->Load(); return true; } bool NFCLogicClassModule::Save() { return true; } NFIPropertyManager* NFCLogicClassModule::GetClassPropertyManager(const std::string& strClassName) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetPropertyManager(); } return NULL; } NFIRecordManager* NFCLogicClassModule::GetClassRecordManager(const std::string& strClassName) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetRecordManager(); } return NULL; } NFIComponentManager* NFCLogicClassModule::GetClassComponentManager( const std::string& strClassName ) { NFILogicClass* pClass = GetElement(strClassName); if (pClass) { return pClass->GetComponentManager(); } return NULL; } bool NFCLogicClassModule::Clear() { return true; }<|endoftext|>
<commit_before>/* * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "stdafx.h" #include "dNewtonBody.h" #include "dNewtonWorld.h" #include "dNewtonCollision.h" #if 0 dNewtonCollision::dNewtonCollision(const dNewtonCollision& srcCollision, NewtonCollision* const shape) // :dNewtonAlloc() :dNewtonMaterial(srcCollision) ,m_shape (shape) ,m_userData(srcCollision.m_userData) ,m_type (srcCollision.m_type) { SetShape(shape); } void* dNewtonCollision::GetUserData() const { return m_userData; } void dNewtonCollision::SetUserData(void* const userData) { m_userData = userData; } dFloat dNewtonCollision::GetVolume () const { return NewtonConvexCollisionCalculateVolume (m_shape); } void dNewtonCollision::GetMatrix (dFloat* const matrix) const { NewtonCollisionGetMatrix(m_shape, matrix); } void dNewtonCollision::GetScale(dFloat& x, dFloat& y, dFloat& z) const { NewtonCollisionGetScale(m_shape, &x, &y, &z); } NewtonCollision* dNewtonCollision::GetShape() const { return m_shape; } void dNewtonCollision::CalculateAABB (const dFloat* const matrix, dFloat* const p0, dFloat* const p1) const { NewtonCollisionCalculateAABB (m_shape, matrix, p0, p1); } void dNewtonCollision::CalculateBuoyancyAcceleration (const dFloat* const matrix, const dFloat* const shapeOrigin, const dFloat* const gravityVector, const dFloat* const fluidPlane, dFloat fluidDensity, dFloat fluidViscosity, dFloat* const accel, dFloat* const alpha) { NewtonConvexCollisionCalculateBuoyancyAcceleration (m_shape, matrix, shapeOrigin, gravityVector, fluidPlane, fluidDensity, fluidViscosity, accel, alpha); } dNewtonCollisionMesh::dNewtonCollisionMesh(dNewton* const world, dLong collisionMask) :dNewtonCollision(m_mesh, collisionMask) { SetShape (NewtonCreateTreeCollision(world->GetNewton(), 0)); } dNewtonCollisionMesh::dNewtonCollisionMesh (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_mesh, collisionMask) { SetShape (NewtonCreateTreeCollisionFromMesh (world->GetNewton(), mesh.GetMesh(), 0)); } void dNewtonCollisionMesh::BeginFace() { NewtonTreeCollisionBeginBuild(m_shape); } void dNewtonCollisionMesh::AddFace(int vertexCount, const dFloat* const vertexPtr, int strideInBytes, int faceAttribute) { NewtonTreeCollisionAddFace (m_shape, vertexCount, vertexPtr, strideInBytes, faceAttribute); } void dNewtonCollisionMesh::EndFace() { //NewtonTreeCollisionEndBuild (m_shape, 1); NewtonTreeCollisionEndBuild (m_shape, 0); } dNewtonCollisionScene::dNewtonCollisionScene(dNewton* const world, dLong collisionMask) :dNewtonCollision(m_scene, collisionMask) { SetShape (NewtonCreateSceneCollision(world->GetNewton(), 0)); } void dNewtonCollisionScene::BeginAddRemoveCollision() { NewtonSceneCollisionBeginAddRemove (m_shape); } void* dNewtonCollisionScene::AddCollision(const dNewtonCollision* const collision) { return NewtonSceneCollisionAddSubCollision (m_shape, collision->GetShape()); } void dNewtonCollisionScene::RemoveCollision (void* const handle) { NewtonSceneCollisionRemoveSubCollision (m_shape, handle); } void dNewtonCollisionScene::EndAddRemoveCollision() { NewtonSceneCollisionEndAddRemove(m_shape); } void* dNewtonCollisionScene::GetFirstNode () const { return NewtonSceneCollisionGetFirstNode (m_shape); } void* dNewtonCollisionScene::GetNextNode (void* const collisionNode) const { return NewtonSceneCollisionGetNextNode (m_shape, collisionNode); } dNewtonCollision* dNewtonCollisionScene::GetChildFromNode(void* const collisionNode) const { NewtonCollision* const collision = NewtonSceneCollisionGetCollisionFromNode (m_shape, collisionNode); return (dNewtonCollision*) NewtonCollisionGetUserData (collision); } dNewtonCollisionConvexHull::dNewtonCollisionConvexHull (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_convex, collisionMask) { SetShape (NewtonCreateConvexHullFromMesh (world->GetNewton(), mesh.GetMesh(), 0.001f, 0)); } dNewtonCollisionCompound::dNewtonCollisionCompound (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_compound, collisionMask) { SetShape (NewtonCreateCompoundCollisionFromMesh (world->GetNewton(), mesh.GetMesh(), 0.001f, 0, 0)); for (void* node = GetFirstNode(); node; node = GetNextNode(node)) { NewtonCollision* const collision = NewtonCompoundCollisionGetCollisionFromNode (m_shape, node); dAssert (NewtonCollisionGetType (collision) == SERIALIZE_ID_CONVEXHULL); new dNewtonCollisionConvexHull (collision, collisionMask); } } void dNewtonCollisionCompound::BeginAddRemoveCollision() { NewtonCompoundCollisionBeginAddRemove (m_shape); } void* dNewtonCollisionCompound::AddCollision(const dNewtonCollision* const collision) { return NewtonCompoundCollisionAddSubCollision(m_shape, collision->GetShape()); } void dNewtonCollisionCompound::RemoveCollision (void* const handle) { NewtonCompoundCollisionRemoveSubCollision (m_shape, handle); } void dNewtonCollisionCompound::EndAddRemoveCollision() { NewtonCompoundCollisionEndAddRemove(m_shape); } void* dNewtonCollisionCompound::GetFirstNode () const { return NewtonCompoundCollisionGetFirstNode (m_shape); } void* dNewtonCollisionCompound::GetNextNode (void* const collisionNode) const { return NewtonCompoundCollisionGetNextNode (m_shape, collisionNode); } dNewtonCollision* dNewtonCollisionCompound::GetChildFromNode(void* const collisionNode) const { NewtonCollision* const collision = NewtonCompoundCollisionGetCollisionFromNode (m_shape, collisionNode); return (dNewtonCollision*) NewtonCollisionGetUserData (collision); } #endif dNewtonCollision::dNewtonCollision(dLong collisionMask) :dAlloc() ,m_shape(NULL) { } dNewtonCollision::~dNewtonCollision() { Cleanup(); } void dNewtonCollision::Cleanup() { if (m_shape) { NewtonCollisionSetUserData(m_shape, NULL); NewtonDestroyCollision(m_shape); m_shape = NULL; } } void dNewtonCollision::SetShape(NewtonCollision* const shape) { m_shape = shape; NewtonCollisionSetUserData(m_shape, this); } void dNewtonCollision::DebugRenderCallback(void* userData, int vertexCount, const dFloat* faceVertec, int id) { dPoints* const polygon = (dPoints*)faceVertec; DrawFaceCallback callback = (DrawFaceCallback)userData; callback(polygon, vertexCount); } void dNewtonCollision::DebugRender(DrawFaceCallback callback) { dMatrix matrix(dGetIdentityMatrix()); NewtonCollisionForEachPolygonDo(m_shape, &matrix[0][0], DebugRenderCallback, callback); } void dNewtonCollision::SetScale(dFloat x, dFloat y, dFloat z) { NewtonCollisionSetScale(m_shape, x, y, z); } void dNewtonCollision::SetMatrix(const void* const matrixPtr) { dMatrix matrix((dFloat*)matrixPtr); NewtonCollisionSetMatrix(m_shape, &matrix[0][0]); } dNewtonCollisionSphere::dNewtonCollisionSphere(dNewtonWorld* const world, dFloat r) :dNewtonCollision(0) { SetShape(NewtonCreateSphere(world->m_world, r, 0, NULL)); } dNewtonCollisionBox::dNewtonCollisionBox(dNewtonWorld* const world, dFloat x, dFloat y, dFloat z) :dNewtonCollision(0) { SetShape(NewtonCreateBox(world->m_world, x, y, z, 0, NULL)); } <commit_msg>clamp collision scale<commit_after>/* * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "stdafx.h" #include "dNewtonBody.h" #include "dNewtonWorld.h" #include "dNewtonCollision.h" #if 0 dNewtonCollision::dNewtonCollision(const dNewtonCollision& srcCollision, NewtonCollision* const shape) // :dNewtonAlloc() :dNewtonMaterial(srcCollision) ,m_shape (shape) ,m_userData(srcCollision.m_userData) ,m_type (srcCollision.m_type) { SetShape(shape); } void* dNewtonCollision::GetUserData() const { return m_userData; } void dNewtonCollision::SetUserData(void* const userData) { m_userData = userData; } dFloat dNewtonCollision::GetVolume () const { return NewtonConvexCollisionCalculateVolume (m_shape); } void dNewtonCollision::GetMatrix (dFloat* const matrix) const { NewtonCollisionGetMatrix(m_shape, matrix); } void dNewtonCollision::GetScale(dFloat& x, dFloat& y, dFloat& z) const { NewtonCollisionGetScale(m_shape, &x, &y, &z); } NewtonCollision* dNewtonCollision::GetShape() const { return m_shape; } void dNewtonCollision::CalculateAABB (const dFloat* const matrix, dFloat* const p0, dFloat* const p1) const { NewtonCollisionCalculateAABB (m_shape, matrix, p0, p1); } void dNewtonCollision::CalculateBuoyancyAcceleration (const dFloat* const matrix, const dFloat* const shapeOrigin, const dFloat* const gravityVector, const dFloat* const fluidPlane, dFloat fluidDensity, dFloat fluidViscosity, dFloat* const accel, dFloat* const alpha) { NewtonConvexCollisionCalculateBuoyancyAcceleration (m_shape, matrix, shapeOrigin, gravityVector, fluidPlane, fluidDensity, fluidViscosity, accel, alpha); } dNewtonCollisionMesh::dNewtonCollisionMesh(dNewton* const world, dLong collisionMask) :dNewtonCollision(m_mesh, collisionMask) { SetShape (NewtonCreateTreeCollision(world->GetNewton(), 0)); } dNewtonCollisionMesh::dNewtonCollisionMesh (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_mesh, collisionMask) { SetShape (NewtonCreateTreeCollisionFromMesh (world->GetNewton(), mesh.GetMesh(), 0)); } void dNewtonCollisionMesh::BeginFace() { NewtonTreeCollisionBeginBuild(m_shape); } void dNewtonCollisionMesh::AddFace(int vertexCount, const dFloat* const vertexPtr, int strideInBytes, int faceAttribute) { NewtonTreeCollisionAddFace (m_shape, vertexCount, vertexPtr, strideInBytes, faceAttribute); } void dNewtonCollisionMesh::EndFace() { //NewtonTreeCollisionEndBuild (m_shape, 1); NewtonTreeCollisionEndBuild (m_shape, 0); } dNewtonCollisionScene::dNewtonCollisionScene(dNewton* const world, dLong collisionMask) :dNewtonCollision(m_scene, collisionMask) { SetShape (NewtonCreateSceneCollision(world->GetNewton(), 0)); } void dNewtonCollisionScene::BeginAddRemoveCollision() { NewtonSceneCollisionBeginAddRemove (m_shape); } void* dNewtonCollisionScene::AddCollision(const dNewtonCollision* const collision) { return NewtonSceneCollisionAddSubCollision (m_shape, collision->GetShape()); } void dNewtonCollisionScene::RemoveCollision (void* const handle) { NewtonSceneCollisionRemoveSubCollision (m_shape, handle); } void dNewtonCollisionScene::EndAddRemoveCollision() { NewtonSceneCollisionEndAddRemove(m_shape); } void* dNewtonCollisionScene::GetFirstNode () const { return NewtonSceneCollisionGetFirstNode (m_shape); } void* dNewtonCollisionScene::GetNextNode (void* const collisionNode) const { return NewtonSceneCollisionGetNextNode (m_shape, collisionNode); } dNewtonCollision* dNewtonCollisionScene::GetChildFromNode(void* const collisionNode) const { NewtonCollision* const collision = NewtonSceneCollisionGetCollisionFromNode (m_shape, collisionNode); return (dNewtonCollision*) NewtonCollisionGetUserData (collision); } dNewtonCollisionConvexHull::dNewtonCollisionConvexHull (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_convex, collisionMask) { SetShape (NewtonCreateConvexHullFromMesh (world->GetNewton(), mesh.GetMesh(), 0.001f, 0)); } dNewtonCollisionCompound::dNewtonCollisionCompound (dNewton* const world, const dNewtonMesh& mesh, dLong collisionMask) :dNewtonCollision(m_compound, collisionMask) { SetShape (NewtonCreateCompoundCollisionFromMesh (world->GetNewton(), mesh.GetMesh(), 0.001f, 0, 0)); for (void* node = GetFirstNode(); node; node = GetNextNode(node)) { NewtonCollision* const collision = NewtonCompoundCollisionGetCollisionFromNode (m_shape, node); dAssert (NewtonCollisionGetType (collision) == SERIALIZE_ID_CONVEXHULL); new dNewtonCollisionConvexHull (collision, collisionMask); } } void dNewtonCollisionCompound::BeginAddRemoveCollision() { NewtonCompoundCollisionBeginAddRemove (m_shape); } void* dNewtonCollisionCompound::AddCollision(const dNewtonCollision* const collision) { return NewtonCompoundCollisionAddSubCollision(m_shape, collision->GetShape()); } void dNewtonCollisionCompound::RemoveCollision (void* const handle) { NewtonCompoundCollisionRemoveSubCollision (m_shape, handle); } void dNewtonCollisionCompound::EndAddRemoveCollision() { NewtonCompoundCollisionEndAddRemove(m_shape); } void* dNewtonCollisionCompound::GetFirstNode () const { return NewtonCompoundCollisionGetFirstNode (m_shape); } void* dNewtonCollisionCompound::GetNextNode (void* const collisionNode) const { return NewtonCompoundCollisionGetNextNode (m_shape, collisionNode); } dNewtonCollision* dNewtonCollisionCompound::GetChildFromNode(void* const collisionNode) const { NewtonCollision* const collision = NewtonCompoundCollisionGetCollisionFromNode (m_shape, collisionNode); return (dNewtonCollision*) NewtonCollisionGetUserData (collision); } #endif dNewtonCollision::dNewtonCollision(dLong collisionMask) :dAlloc() ,m_shape(NULL) { } dNewtonCollision::~dNewtonCollision() { Cleanup(); } void dNewtonCollision::Cleanup() { if (m_shape) { NewtonCollisionSetUserData(m_shape, NULL); NewtonDestroyCollision(m_shape); m_shape = NULL; } } void dNewtonCollision::SetShape(NewtonCollision* const shape) { m_shape = shape; NewtonCollisionSetUserData(m_shape, this); } void dNewtonCollision::DebugRenderCallback(void* userData, int vertexCount, const dFloat* faceVertec, int id) { dPoints* const polygon = (dPoints*)faceVertec; DrawFaceCallback callback = (DrawFaceCallback)userData; callback(polygon, vertexCount); } void dNewtonCollision::DebugRender(DrawFaceCallback callback) { dMatrix matrix(dGetIdentityMatrix()); NewtonCollisionForEachPolygonDo(m_shape, &matrix[0][0], DebugRenderCallback, callback); } void dNewtonCollision::SetScale(dFloat scaleX, dFloat scaleY, dFloat scaleZ) { scaleX = dMax(0.01f, dAbs(scaleX)); scaleY = dMax(0.01f, dAbs(scaleY)); scaleZ = dMax(0.01f, dAbs(scaleZ)); NewtonCollisionSetScale(m_shape, scaleX, scaleY, scaleZ); } void dNewtonCollision::SetMatrix(const void* const matrixPtr) { dMatrix matrix((dFloat*)matrixPtr); NewtonCollisionSetMatrix(m_shape, &matrix[0][0]); } dNewtonCollisionSphere::dNewtonCollisionSphere(dNewtonWorld* const world, dFloat r) :dNewtonCollision(0) { SetShape(NewtonCreateSphere(world->m_world, r, 0, NULL)); } dNewtonCollisionBox::dNewtonCollisionBox(dNewtonWorld* const world, dFloat x, dFloat y, dFloat z) :dNewtonCollision(0) { SetShape(NewtonCreateBox(world->m_world, x, y, z, 0, NULL)); } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/qoi_base.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" // GRINS #include "grins/assembly_context.h" namespace GRINS { QoIBase::QoIBase( const std::string& qoi_name ) : ParameterUser(qoi_name), _qoi_name(qoi_name), _qoi_value(0.0) { return; } QoIBase::~QoIBase() { return; } void QoIBase::init (const GetPot& input, const MultiphysicsSystem& system, unsigned int /*qoi_num*/ ) { } void QoIBase::init_context( AssemblyContext& /*context*/ ) { return; } void QoIBase::element_qoi( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::element_qoi_derivative( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::side_qoi( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::side_qoi_derivative( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::parallel_op( const libMesh::Parallel::Communicator& communicator, libMesh::Number& sys_qoi, libMesh::Number& local_qoi ) { communicator.sum(local_qoi); sys_qoi = local_qoi; _qoi_value = sys_qoi; return; } void QoIBase::thread_join( libMesh::Number& qoi, const libMesh::Number& other_qoi ) { qoi += other_qoi; return; } void QoIBase::output_qoi( std::ostream& out ) const { out << "==========================================================" << std::endl; out << _qoi_name+" = " << std::setprecision(16) << std::scientific << _qoi_value << std::endl; out << "==========================================================" << std::endl; return; } } // namespace GRINS <commit_msg>Comment out unused variable names<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/qoi_base.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" // GRINS #include "grins/assembly_context.h" namespace GRINS { QoIBase::QoIBase( const std::string& qoi_name ) : ParameterUser(qoi_name), _qoi_name(qoi_name), _qoi_value(0.0) { return; } QoIBase::~QoIBase() { return; } void QoIBase::init (const GetPot& /*input*/, const MultiphysicsSystem& /*system*/, unsigned int /*qoi_num*/ ) { } void QoIBase::init_context( AssemblyContext& /*context*/ ) { return; } void QoIBase::element_qoi( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::element_qoi_derivative( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::side_qoi( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::side_qoi_derivative( AssemblyContext& /*context*/, const unsigned int /*qoi_index*/ ) { return; } void QoIBase::parallel_op( const libMesh::Parallel::Communicator& communicator, libMesh::Number& sys_qoi, libMesh::Number& local_qoi ) { communicator.sum(local_qoi); sys_qoi = local_qoi; _qoi_value = sys_qoi; return; } void QoIBase::thread_join( libMesh::Number& qoi, const libMesh::Number& other_qoi ) { qoi += other_qoi; return; } void QoIBase::output_qoi( std::ostream& out ) const { out << "==========================================================" << std::endl; out << _qoi_name+" = " << std::setprecision(16) << std::scientific << _qoi_value << std::endl; out << "==========================================================" << std::endl; return; } } // namespace GRINS <|endoftext|>
<commit_before>#include "notificator.h" #include <QMetaType> #include <QVariant> #include <QIcon> #include <QApplication> #include <QStyle> #include <QByteArray> #include <QSystemTrayIcon> #include <QMessageBox> #include <QTemporaryFile> #include <QImageWriter> #ifdef USE_DBUS #include <QtDBus/QtDBus> #include <stdint.h> #endif #ifdef Q_OS_MAC #include <ApplicationServices/ApplicationServices.h> extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret); #endif #ifdef USE_DBUS // https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128 const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128; #endif Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent): QObject(parent), parent(parent), programName(programName), mode(None), trayIcon(trayicon) #ifdef USE_DBUS ,interface(0) #endif { if(trayicon && trayicon->supportsMessages()) { mode = QSystemTray; } #ifdef USE_DBUS interface = new QDBusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications"); if(interface->isValid()) { mode = Freedesktop; } #endif #ifdef Q_OS_MAC // Check if Growl is installed (based on Qt's tray icon implementation) CFURLRef cfurl; OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl); if (status != kLSApplicationNotFoundErr) { CFBundleRef bundle = CFBundleCreate(0, cfurl); if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) { if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/"))) mode = Growl13; else mode = Growl12; } CFRelease(cfurl); CFRelease(bundle); } #endif } Notificator::~Notificator() { #ifdef USE_DBUS delete interface; #endif } #ifdef USE_DBUS // Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html class FreedesktopImage { public: FreedesktopImage() {} FreedesktopImage(const QImage &img); static int metaType(); // Image to variant that can be marshalled over DBus static QVariant toVariant(const QImage &img); private: int width, height, stride; bool hasAlpha; int channels; int bitsPerSample; QByteArray image; friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i); friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i); }; Q_DECLARE_METATYPE(FreedesktopImage); // Image configuration settings const int CHANNELS = 4; const int BYTES_PER_PIXEL = 4; const int BITS_PER_SAMPLE = 8; FreedesktopImage::FreedesktopImage(const QImage &img): width(img.width()), height(img.height()), stride(img.width() * BYTES_PER_PIXEL), hasAlpha(true), channels(CHANNELS), bitsPerSample(BITS_PER_SAMPLE) { // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format QImage tmp = img.convertToFormat(QImage::Format_ARGB32); const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits()); unsigned int num_pixels = width * height; image.resize(num_pixels * BYTES_PER_PIXEL); for(unsigned int ptr = 0; ptr < num_pixels; ++ptr) { image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A } } QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i) { a.beginStructure(); a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image; a.endStructure(); return a; } const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i) { a.beginStructure(); a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image; a.endStructure(); return a; } int FreedesktopImage::metaType() { return qDBusRegisterMetaType<FreedesktopImage>(); } QVariant FreedesktopImage::toVariant(const QImage &img) { FreedesktopImage fimg(img); return QVariant(FreedesktopImage::metaType(), &fimg); } void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { Q_UNUSED(cls); // Arguments for DBus call: QList<QVariant> args; // Program Name: args.append(programName); // Unique ID of this notification type: args.append(0U); // Application Icon, empty string args.append(QString()); // Summary args.append(title); // Body args.append(text); // Actions (none, actions are deprecated) QStringList actions; args.append(actions); // Hints QVariantMap hints; // If no icon specified, set icon based on class QIcon tmpicon; if(icon.isNull()) { QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion; switch(cls) { case Information: sicon = QStyle::SP_MessageBoxInformation; break; case Warning: sicon = QStyle::SP_MessageBoxWarning; break; case Critical: sicon = QStyle::SP_MessageBoxCritical; break; default: break; } tmpicon = QApplication::style()->standardIcon(sicon); } else { tmpicon = icon; } hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage()); args.append(hints); // Timeout (in msec) args.append(millisTimeout); // "Fire and forget" interface->callWithArgumentList(QDBus::NoBlock, "Notify", args); } #endif void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { Q_UNUSED(icon); QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon; switch(cls) // Set icon based on class { case Information: sicon = QSystemTrayIcon::Information; break; case Warning: sicon = QSystemTrayIcon::Warning; break; case Critical: sicon = QSystemTrayIcon::Critical; break; } trayIcon->showMessage(title, text, sicon, millisTimeout); } // Based on Qt's tray icon implementation #ifdef Q_OS_MAC void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon) { const QString script( "tell application \"%5\"\n" " set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all) " set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled) " register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl " notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification "end tell" ); QString notificationApp(QApplication::applicationName()); if (notificationApp.isEmpty()) notificationApp = "Application"; QPixmap notificationIconPixmap; if (icon.isNull()) { // If no icon specified, set icon based on class QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion; switch (cls) { case Information: sicon = QStyle::SP_MessageBoxInformation; break; case Warning: sicon = QStyle::SP_MessageBoxWarning; break; case Critical: sicon = QStyle::SP_MessageBoxCritical; break; } notificationIconPixmap = QApplication::style()->standardPixmap(sicon); } else { QSize size = icon.actualSize(QSize(48, 48)); notificationIconPixmap = icon.pixmap(size); } QString notificationIcon; QTemporaryFile notificationIconFile; if (!notificationIconPixmap.isNull() && notificationIconFile.open()) { QImageWriter writer(&notificationIconFile, "PNG"); if (writer.write(notificationIconPixmap.toImage())) notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName()); } QString quotedTitle(title), quotedText(text); quotedTitle.replace("\\", "\\\\").replace("\"", "\\"); quotedText.replace("\\", "\\\\").replace("\"", "\\"); QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp"); qt_mac_execute_apple_script(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp), 0); } #endif void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { switch(mode) { #ifdef USE_DBUS case Freedesktop: notifyDBus(cls, title, text, icon, millisTimeout); break; #endif case QSystemTray: notifySystray(cls, title, text, icon, millisTimeout); break; #ifdef Q_OS_MAC case Growl12: case Growl13: notifyGrowl(cls, title, text, icon); break; #endif default: if(cls == Critical) { // Fall back to old fashioned pop-up dialog if critical and no other notification available QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok); } break; } } <commit_msg>Fix unresolved symbol<commit_after>#include "notificator.h" #include <QMetaType> #include <QVariant> #include <QIcon> #include <QApplication> #include <QStyle> #include <QByteArray> #include <QSystemTrayIcon> #include <QMessageBox> #include <QTemporaryFile> #include <QImageWriter> #ifdef USE_DBUS #include <QtDBus/QtDBus> #include <stdint.h> #endif #ifdef Q_OS_MAC #include <ApplicationServices/ApplicationServices.h> extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret); #endif #ifdef USE_DBUS // https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128 const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128; #endif Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent): QObject(parent), parent(parent), programName(programName), mode(None), trayIcon(trayicon) #ifdef USE_DBUS ,interface(0) #endif { if(trayicon && trayicon->supportsMessages()) { mode = QSystemTray; } #ifdef USE_DBUS interface = new QDBusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications"); if(interface->isValid()) { mode = Freedesktop; } #endif #ifdef Q_OS_MAC // Check if Growl is installed (based on Qt's tray icon implementation) CFURLRef cfurl; OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl); if (status != kLSApplicationNotFoundErr) { CFBundleRef bundle = CFBundleCreate(0, cfurl); if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) { if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/"))) mode = Growl13; else mode = Growl12; } CFRelease(cfurl); CFRelease(bundle); } #endif } Notificator::~Notificator() { #ifdef USE_DBUS delete interface; #endif } #ifdef USE_DBUS // Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html class FreedesktopImage { public: FreedesktopImage() {} FreedesktopImage(const QImage &img); static int metaType(); // Image to variant that can be marshalled over DBus static QVariant toVariant(const QImage &img); private: int width, height, stride; bool hasAlpha; int channels; int bitsPerSample; QByteArray image; friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i); friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i); }; Q_DECLARE_METATYPE(FreedesktopImage); // Image configuration settings const int CHANNELS = 4; const int BYTES_PER_PIXEL = 4; const int BITS_PER_SAMPLE = 8; FreedesktopImage::FreedesktopImage(const QImage &img): width(img.width()), height(img.height()), stride(img.width() * BYTES_PER_PIXEL), hasAlpha(true), channels(CHANNELS), bitsPerSample(BITS_PER_SAMPLE) { // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format QImage tmp = img.convertToFormat(QImage::Format_ARGB32); const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits()); unsigned int num_pixels = width * height; image.resize(num_pixels * BYTES_PER_PIXEL); for(unsigned int ptr = 0; ptr < num_pixels; ++ptr) { image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A } } QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i) { a.beginStructure(); a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image; a.endStructure(); return a; } const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i) { a.beginStructure(); a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image; a.endStructure(); return a; } int FreedesktopImage::metaType() { return qDBusRegisterMetaType<FreedesktopImage>(); } QVariant FreedesktopImage::toVariant(const QImage &img) { FreedesktopImage fimg(img); return QVariant(FreedesktopImage::metaType(), &fimg); } void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { Q_UNUSED(cls); // Arguments for DBus call: QList<QVariant> args; // Program Name: args.append(programName); // Unique ID of this notification type: args.append(0U); // Application Icon, empty string args.append(QString()); // Summary args.append(title); // Body args.append(text); // Actions (none, actions are deprecated) QStringList actions; args.append(actions); // Hints QVariantMap hints; // If no icon specified, set icon based on class QIcon tmpicon; if(icon.isNull()) { QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion; switch(cls) { case Information: sicon = QStyle::SP_MessageBoxInformation; break; case Warning: sicon = QStyle::SP_MessageBoxWarning; break; case Critical: sicon = QStyle::SP_MessageBoxCritical; break; default: break; } tmpicon = QApplication::style()->standardIcon(sicon); } else { tmpicon = icon; } hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage()); args.append(hints); // Timeout (in msec) args.append(millisTimeout); // "Fire and forget" interface->callWithArgumentList(QDBus::NoBlock, "Notify", args); } #endif void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { Q_UNUSED(icon); QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon; switch(cls) // Set icon based on class { case Information: sicon = QSystemTrayIcon::Information; break; case Warning: sicon = QSystemTrayIcon::Warning; break; case Critical: sicon = QSystemTrayIcon::Critical; break; } trayIcon->showMessage(title, text, sicon, millisTimeout); } // Based on Qt's tray icon implementation #ifdef Q_OS_MAC void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon) { const QString script( "tell application \"%5\"\n" " set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all) " set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled) " register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl " notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification "end tell" ); QString notificationApp(QApplication::applicationName()); if (notificationApp.isEmpty()) notificationApp = "Application"; QPixmap notificationIconPixmap; if (icon.isNull()) { // If no icon specified, set icon based on class QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion; switch (cls) { case Information: sicon = QStyle::SP_MessageBoxInformation; break; case Warning: sicon = QStyle::SP_MessageBoxWarning; break; case Critical: sicon = QStyle::SP_MessageBoxCritical; break; } notificationIconPixmap = QApplication::style()->standardPixmap(sicon); } else { QSize size = icon.actualSize(QSize(48, 48)); notificationIconPixmap = icon.pixmap(size); } QString notificationIcon; QTemporaryFile notificationIconFile; if (!notificationIconPixmap.isNull() && notificationIconFile.open()) { QImageWriter writer(&notificationIconFile, "PNG"); if (writer.write(notificationIconPixmap.toImage())) notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName()); } QString quotedTitle(title), quotedText(text); quotedTitle.replace("\\", "\\\\").replace("\"", "\\"); quotedText.replace("\\", "\\\\").replace("\"", "\\"); QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp"); // FIXME gives linker error //qt_mac_execute_apple_script(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp), 0); } #endif void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout) { switch(mode) { #ifdef USE_DBUS case Freedesktop: notifyDBus(cls, title, text, icon, millisTimeout); break; #endif case QSystemTray: notifySystray(cls, title, text, icon, millisTimeout); break; #ifdef Q_OS_MAC case Growl12: case Growl13: notifyGrowl(cls, title, text, icon); break; #endif default: if(cls == Critical) { // Fall back to old fashioned pop-up dialog if critical and no other notification available QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok); } break; } } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/op.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/minidriver.hpp" #include "debug.hpp" namespace ql { argspec_t::argspec_t(int n) : min(n), max(n), eval_flags(NO_FLAGS) { } argspec_t::argspec_t(int _min, int _max) : min(_min), max(_max), eval_flags(NO_FLAGS) { } argspec_t::argspec_t(int _min, int _max, eval_flags_t _eval_flags) : min(_min), max(_max), eval_flags(_eval_flags) { } std::string argspec_t::print() const { if (min == max) { return strprintf("%d argument%s", min, (min == 1 ? "" : "s")); } else if (max == -1) { return strprintf("%d or more arguments", min); } else { return strprintf("between %d and %d arguments", min, max); } } bool argspec_t::contains(int n) const { return min <= n && (max < 0 || n <= max); } optargspec_t::optargspec_t(std::initializer_list<const char *> args) { init(args.size(), args.begin()); } void optargspec_t::init(int num_args, const char *const *args) { for (int i = 0; i < num_args; ++i) { legal_args.insert(args[i]); } } bool optargspec_t::contains(const std::string &key) const { return legal_args.count(key) != 0; } optargspec_t optargspec_t::with(std::initializer_list<const char *> args) const { optargspec_t ret(args); ret.legal_args.insert(legal_args.begin(), legal_args.end()); return ret; } class faux_term_t : public runtime_term_t { public: faux_term_t(protob_t<const Backtrace> bt, datum_t _d) : runtime_term_t(std::move(bt)), d(std::move(_d)) { } const char *name() const final { return "<EXPANDED FROM r.args>"; } private: scoped_ptr_t<val_t> term_eval(scope_env_t *, eval_flags_t) const final { return new_val(d); } datum_t d; }; class arg_terms_t : public pb_rcheckable_t { public: arg_terms_t(protob_t<const Term> _src, argspec_t _argspec, std::vector<counted_t<const term_t> > _original_args); // Evals the r.args arguments, and returns the expanded argument list. argvec_t start_eval(scope_env_t *env, eval_flags_t flags) const; const std::vector<counted_t<const term_t> > &get_original_args() const { return original_args; } private: const protob_t<const Term> src; const argspec_t argspec; const std::vector<counted_t<const term_t> > original_args; DISABLE_COPYING(arg_terms_t); }; arg_terms_t::arg_terms_t(protob_t<const Term> _src, argspec_t _argspec, std::vector<counted_t<const term_t> > _original_args) : pb_rcheckable_t(get_backtrace(_src)), src(std::move(_src)), argspec(std::move(_argspec)), original_args(std::move(_original_args)) { for (auto it = original_args.begin(); it != original_args.end(); ++it) { if ((*it)->get_src()->type() == Term::ARGS) { return; } } // We check this here *and* in `start_eval` because if `r.args` isn't in // play we want to give a compile-time error. rcheck(argspec.contains(original_args.size()), base_exc_t::GENERIC, strprintf("Expected %s but found %zu.", argspec.print().c_str(), original_args.size())); } argvec_t arg_terms_t::start_eval(scope_env_t *env, eval_flags_t flags) const { eval_flags_t new_flags = static_cast<eval_flags_t>( flags | argspec.get_eval_flags()); std::vector<counted_t<const runtime_term_t> > args; for (auto it = original_args.begin(); it != original_args.end(); ++it) { if ((*it)->get_src()->type() == Term::ARGS) { scoped_ptr_t<val_t> v = (*it)->eval(env, new_flags); datum_t d = v->as_datum(); for (size_t i = 0; i < d.arr_size(); ++i) { args.push_back(make_counted<faux_term_t>(get_backtrace(src), d.get(i))); } } else { args.push_back(counted_t<const runtime_term_t>(*it)); } } rcheck(argspec.contains(args.size()), base_exc_t::GENERIC, strprintf("Expected %s but found %zu.", argspec.print().c_str(), args.size())); return argvec_t(std::move(args)); } argvec_t::argvec_t(std::vector<counted_t<const runtime_term_t> > &&v) : vec(std::move(v)) { } counted_t<const runtime_term_t> argvec_t::remove(size_t i) { r_sanity_check(i < vec.size()); r_sanity_check(vec[i].has()); counted_t<const runtime_term_t> ret; ret.swap(vec[i]); return ret; } size_t args_t::num_args() const { return argv.size(); } scoped_ptr_t<val_t> args_t::arg(scope_env_t *env, size_t i, eval_flags_t flags) { if (i == 0 && arg0.has()) { scoped_ptr_t<val_t> v = std::move(arg0); arg0.reset(); return v; } else { return argv.remove(i)->eval(env, flags); } } scoped_ptr_t<val_t> args_t::optarg(scope_env_t *env, const std::string &key) const { return op_term->optarg(env, key); } args_t::args_t(const op_term_t *_op_term, argvec_t _argv) : op_term(_op_term), argv(std::move(_argv)) { } args_t::args_t(const op_term_t *_op_term, argvec_t _argv, scoped_ptr_t<val_t> _arg0) : op_term(_op_term), argv(std::move(_argv)), arg0(std::move(_arg0)) { } op_term_t::op_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec, optargspec_t optargspec) : term_t(term) { std::vector<counted_t<const term_t> > original_args; original_args.reserve(term->args_size()); for (int i = 0; i < term->args_size(); ++i) { counted_t<const term_t> t = compile_term(env, term.make_child(&term->args(i))); original_args.push_back(t); } arg_terms.init(new arg_terms_t(term, std::move(argspec), std::move(original_args))); for (int i = 0; i < term->optargs_size(); ++i) { const Term_AssocPair *ap = &term->optargs(i); rcheck(optargspec.contains(ap->key()), base_exc_t::GENERIC, strprintf("Unrecognized optional argument `%s`.", ap->key().c_str())); counted_t<const term_t> t = compile_term(env, term.make_child(&ap->val())); auto res = optargs.insert(std::make_pair(ap->key(), std::move(t))); rcheck(res.second, base_exc_t::GENERIC, strprintf("Duplicate optional argument: %s", ap->key().c_str())); } } op_term_t::~op_term_t() { } scoped_ptr_t<val_t> op_term_t::term_eval(scope_env_t *env, eval_flags_t eval_flags) const { argvec_t argv = arg_terms->start_eval(env, eval_flags); if (can_be_grouped()) { counted_t<grouped_data_t> gd; scoped_ptr_t<val_t> arg0; maybe_grouped_data(env, &argv, eval_flags, &gd, &arg0); if (gd.has()) { // (arg0 is empty, because maybe_grouped_data sets at most one of gd and // arg0, so we don't have to worry about re-evaluating it. counted_t<grouped_data_t> out(new grouped_data_t()); // We're processing gd into another grouped_data_t -- so gd's order // doesn't matter. for (auto kv = gd->begin(grouped::order_doesnt_matter_t()); kv != gd->end(grouped::order_doesnt_matter_t()); ++kv) { arg_terms->start_eval(env, eval_flags); args_t args(this, argv, make_scoped<val_t>(kv->second, backtrace())); (*out)[kv->first] = eval_impl(env, &args, eval_flags)->as_datum(); } return make_scoped<val_t>(out, backtrace()); } else { args_t args(this, std::move(argv), std::move(arg0)); return eval_impl(env, &args, eval_flags); } } else { args_t args(this, std::move(argv)); return eval_impl(env, &args, eval_flags); } } bool op_term_t::can_be_grouped() const { return true; } bool op_term_t::is_grouped_seq_op() const { return false; } scoped_ptr_t<val_t> op_term_t::optarg(scope_env_t *env, const std::string &key) const { std::map<std::string, counted_t<const term_t> >::const_iterator it = optargs.find(key); if (it != optargs.end()) { return it->second->eval(env); } // returns scoped_ptr_t<val_t>() if the key isn't found return env->env->get_optarg(env->env, key); } counted_t<func_term_t> op_term_t::lazy_literal_optarg(compile_env_t *env, const std::string &key) const { std::map<std::string, counted_t<const term_t> >::const_iterator it = optargs.find(key); if (it != optargs.end()) { protob_t<Term> func(make_counted_term()); r::fun(r::expr(*it->second->get_src().get())).swap(*func.get()); return make_counted<func_term_t>(env, func); } return counted_t<func_term_t>(); } void accumulate_all_captures( const std::map<std::string, counted_t<const term_t> > &optargs, var_captures_t *captures) { for (auto it = optargs.begin(); it != optargs.end(); ++it) { it->second->accumulate_captures(captures); } } void op_term_t::accumulate_captures(var_captures_t *captures) const { const std::vector<counted_t<const term_t> > &original_args = arg_terms->get_original_args(); for (auto it = original_args.begin(); it != original_args.end(); ++it) { (*it)->accumulate_captures(captures); } accumulate_all_captures(optargs, captures); } bool all_are_deterministic( const std::map<std::string, counted_t<const term_t> > &optargs) { for (auto it = optargs.begin(); it != optargs.end(); ++it) { if (!it->second->is_deterministic()) { return false; } } return true; } bool op_term_t::is_deterministic() const { const std::vector<counted_t<const term_t> > &original_args = arg_terms->get_original_args(); for (size_t i = 0; i < original_args.size(); ++i) { if (!original_args[i]->is_deterministic()) { return false; } } return all_are_deterministic(optargs); } void op_term_t::maybe_grouped_data(scope_env_t *env, argvec_t *argv, eval_flags_t flags, counted_t<grouped_data_t> *grouped_data_out, scoped_ptr_t<val_t> *arg0_out) const { if (argv->empty()) { grouped_data_out->reset(); arg0_out->reset(); } else { scoped_ptr_t<val_t> arg0 = argv->remove(0)->eval(env, flags); counted_t<grouped_data_t> gd = is_grouped_seq_op() ? arg0->maybe_as_grouped_data() : arg0->maybe_as_promiscuous_grouped_data(env->env); if (gd.has()) { *grouped_data_out = std::move(gd); arg0_out->reset(); } else { grouped_data_out->reset(); *arg0_out = std::move(arg0); } } } bounded_op_term_t::bounded_op_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec, optargspec_t optargspec) : op_term_t(env, term, argspec, optargspec.with({"left_bound", "right_bound"})) { } bool bounded_op_term_t::is_left_open(scope_env_t *env, args_t *args) const { return open_bool(env, args, "left_bound", false); } bool bounded_op_term_t::is_right_open(scope_env_t *env, args_t *args) const { return open_bool(env, args, "right_bound", true); } bool bounded_op_term_t::open_bool( scope_env_t *env, args_t *args, const std::string &key, bool def/*ault*/) const { scoped_ptr_t<val_t> v = args->optarg(env, key); if (!v.has()) { return def; } const datum_string_t &s = v->as_str(); if (s == "open") { return true; } else if (s == "closed") { return false; } else { rfail(base_exc_t::GENERIC, "Expected `open` or `closed` for optarg `%s` (got `%s`).", key.c_str(), v->trunc_print().c_str()); } } } // namespace ql <commit_msg>Validate optargs against global list.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/op.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/minidriver.hpp" #include "rdb_protocol/validate.hpp" #include "debug.hpp" namespace ql { argspec_t::argspec_t(int n) : min(n), max(n), eval_flags(NO_FLAGS) { } argspec_t::argspec_t(int _min, int _max) : min(_min), max(_max), eval_flags(NO_FLAGS) { } argspec_t::argspec_t(int _min, int _max, eval_flags_t _eval_flags) : min(_min), max(_max), eval_flags(_eval_flags) { } std::string argspec_t::print() const { if (min == max) { return strprintf("%d argument%s", min, (min == 1 ? "" : "s")); } else if (max == -1) { return strprintf("%d or more arguments", min); } else { return strprintf("between %d and %d arguments", min, max); } } bool argspec_t::contains(int n) const { return min <= n && (max < 0 || n <= max); } optargspec_t::optargspec_t(std::initializer_list<const char *> args) { init(args.size(), args.begin()); for (auto i = legal_args.begin(); i!= legal_args.end(); ++i) validate_optarg(*i); } void optargspec_t::init(int num_args, const char *const *args) { for (int i = 0; i < num_args; ++i) { legal_args.insert(args[i]); } } bool optargspec_t::contains(const std::string &key) const { return legal_args.count(key) != 0; } optargspec_t optargspec_t::with(std::initializer_list<const char *> args) const { optargspec_t ret(args); ret.legal_args.insert(legal_args.begin(), legal_args.end()); return ret; } class faux_term_t : public runtime_term_t { public: faux_term_t(protob_t<const Backtrace> bt, datum_t _d) : runtime_term_t(std::move(bt)), d(std::move(_d)) { } const char *name() const final { return "<EXPANDED FROM r.args>"; } private: scoped_ptr_t<val_t> term_eval(scope_env_t *, eval_flags_t) const final { return new_val(d); } datum_t d; }; class arg_terms_t : public pb_rcheckable_t { public: arg_terms_t(protob_t<const Term> _src, argspec_t _argspec, std::vector<counted_t<const term_t> > _original_args); // Evals the r.args arguments, and returns the expanded argument list. argvec_t start_eval(scope_env_t *env, eval_flags_t flags) const; const std::vector<counted_t<const term_t> > &get_original_args() const { return original_args; } private: const protob_t<const Term> src; const argspec_t argspec; const std::vector<counted_t<const term_t> > original_args; DISABLE_COPYING(arg_terms_t); }; arg_terms_t::arg_terms_t(protob_t<const Term> _src, argspec_t _argspec, std::vector<counted_t<const term_t> > _original_args) : pb_rcheckable_t(get_backtrace(_src)), src(std::move(_src)), argspec(std::move(_argspec)), original_args(std::move(_original_args)) { for (auto it = original_args.begin(); it != original_args.end(); ++it) { if ((*it)->get_src()->type() == Term::ARGS) { return; } } // We check this here *and* in `start_eval` because if `r.args` isn't in // play we want to give a compile-time error. rcheck(argspec.contains(original_args.size()), base_exc_t::GENERIC, strprintf("Expected %s but found %zu.", argspec.print().c_str(), original_args.size())); } argvec_t arg_terms_t::start_eval(scope_env_t *env, eval_flags_t flags) const { eval_flags_t new_flags = static_cast<eval_flags_t>( flags | argspec.get_eval_flags()); std::vector<counted_t<const runtime_term_t> > args; for (auto it = original_args.begin(); it != original_args.end(); ++it) { if ((*it)->get_src()->type() == Term::ARGS) { scoped_ptr_t<val_t> v = (*it)->eval(env, new_flags); datum_t d = v->as_datum(); for (size_t i = 0; i < d.arr_size(); ++i) { args.push_back(make_counted<faux_term_t>(get_backtrace(src), d.get(i))); } } else { args.push_back(counted_t<const runtime_term_t>(*it)); } } rcheck(argspec.contains(args.size()), base_exc_t::GENERIC, strprintf("Expected %s but found %zu.", argspec.print().c_str(), args.size())); return argvec_t(std::move(args)); } argvec_t::argvec_t(std::vector<counted_t<const runtime_term_t> > &&v) : vec(std::move(v)) { } counted_t<const runtime_term_t> argvec_t::remove(size_t i) { r_sanity_check(i < vec.size()); r_sanity_check(vec[i].has()); counted_t<const runtime_term_t> ret; ret.swap(vec[i]); return ret; } size_t args_t::num_args() const { return argv.size(); } scoped_ptr_t<val_t> args_t::arg(scope_env_t *env, size_t i, eval_flags_t flags) { if (i == 0 && arg0.has()) { scoped_ptr_t<val_t> v = std::move(arg0); arg0.reset(); return v; } else { return argv.remove(i)->eval(env, flags); } } scoped_ptr_t<val_t> args_t::optarg(scope_env_t *env, const std::string &key) const { return op_term->optarg(env, key); } args_t::args_t(const op_term_t *_op_term, argvec_t _argv) : op_term(_op_term), argv(std::move(_argv)) { } args_t::args_t(const op_term_t *_op_term, argvec_t _argv, scoped_ptr_t<val_t> _arg0) : op_term(_op_term), argv(std::move(_argv)), arg0(std::move(_arg0)) { } op_term_t::op_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec, optargspec_t optargspec) : term_t(term) { std::vector<counted_t<const term_t> > original_args; original_args.reserve(term->args_size()); for (int i = 0; i < term->args_size(); ++i) { counted_t<const term_t> t = compile_term(env, term.make_child(&term->args(i))); original_args.push_back(t); } arg_terms.init(new arg_terms_t(term, std::move(argspec), std::move(original_args))); for (int i = 0; i < term->optargs_size(); ++i) { const Term_AssocPair *ap = &term->optargs(i); rcheck(optargspec.contains(ap->key()), base_exc_t::GENERIC, strprintf("Unrecognized optional argument `%s`.", ap->key().c_str())); counted_t<const term_t> t = compile_term(env, term.make_child(&ap->val())); auto res = optargs.insert(std::make_pair(ap->key(), std::move(t))); rcheck(res.second, base_exc_t::GENERIC, strprintf("Duplicate optional argument: %s", ap->key().c_str())); } } op_term_t::~op_term_t() { } scoped_ptr_t<val_t> op_term_t::term_eval(scope_env_t *env, eval_flags_t eval_flags) const { argvec_t argv = arg_terms->start_eval(env, eval_flags); if (can_be_grouped()) { counted_t<grouped_data_t> gd; scoped_ptr_t<val_t> arg0; maybe_grouped_data(env, &argv, eval_flags, &gd, &arg0); if (gd.has()) { // (arg0 is empty, because maybe_grouped_data sets at most one of gd and // arg0, so we don't have to worry about re-evaluating it. counted_t<grouped_data_t> out(new grouped_data_t()); // We're processing gd into another grouped_data_t -- so gd's order // doesn't matter. for (auto kv = gd->begin(grouped::order_doesnt_matter_t()); kv != gd->end(grouped::order_doesnt_matter_t()); ++kv) { arg_terms->start_eval(env, eval_flags); args_t args(this, argv, make_scoped<val_t>(kv->second, backtrace())); (*out)[kv->first] = eval_impl(env, &args, eval_flags)->as_datum(); } return make_scoped<val_t>(out, backtrace()); } else { args_t args(this, std::move(argv), std::move(arg0)); return eval_impl(env, &args, eval_flags); } } else { args_t args(this, std::move(argv)); return eval_impl(env, &args, eval_flags); } } bool op_term_t::can_be_grouped() const { return true; } bool op_term_t::is_grouped_seq_op() const { return false; } scoped_ptr_t<val_t> op_term_t::optarg(scope_env_t *env, const std::string &key) const { std::map<std::string, counted_t<const term_t> >::const_iterator it = optargs.find(key); if (it != optargs.end()) { return it->second->eval(env); } // returns scoped_ptr_t<val_t>() if the key isn't found return env->env->get_optarg(env->env, key); } counted_t<func_term_t> op_term_t::lazy_literal_optarg(compile_env_t *env, const std::string &key) const { std::map<std::string, counted_t<const term_t> >::const_iterator it = optargs.find(key); if (it != optargs.end()) { protob_t<Term> func(make_counted_term()); r::fun(r::expr(*it->second->get_src().get())).swap(*func.get()); return make_counted<func_term_t>(env, func); } return counted_t<func_term_t>(); } void accumulate_all_captures( const std::map<std::string, counted_t<const term_t> > &optargs, var_captures_t *captures) { for (auto it = optargs.begin(); it != optargs.end(); ++it) { it->second->accumulate_captures(captures); } } void op_term_t::accumulate_captures(var_captures_t *captures) const { const std::vector<counted_t<const term_t> > &original_args = arg_terms->get_original_args(); for (auto it = original_args.begin(); it != original_args.end(); ++it) { (*it)->accumulate_captures(captures); } accumulate_all_captures(optargs, captures); } bool all_are_deterministic( const std::map<std::string, counted_t<const term_t> > &optargs) { for (auto it = optargs.begin(); it != optargs.end(); ++it) { if (!it->second->is_deterministic()) { return false; } } return true; } bool op_term_t::is_deterministic() const { const std::vector<counted_t<const term_t> > &original_args = arg_terms->get_original_args(); for (size_t i = 0; i < original_args.size(); ++i) { if (!original_args[i]->is_deterministic()) { return false; } } return all_are_deterministic(optargs); } void op_term_t::maybe_grouped_data(scope_env_t *env, argvec_t *argv, eval_flags_t flags, counted_t<grouped_data_t> *grouped_data_out, scoped_ptr_t<val_t> *arg0_out) const { if (argv->empty()) { grouped_data_out->reset(); arg0_out->reset(); } else { scoped_ptr_t<val_t> arg0 = argv->remove(0)->eval(env, flags); counted_t<grouped_data_t> gd = is_grouped_seq_op() ? arg0->maybe_as_grouped_data() : arg0->maybe_as_promiscuous_grouped_data(env->env); if (gd.has()) { *grouped_data_out = std::move(gd); arg0_out->reset(); } else { grouped_data_out->reset(); *arg0_out = std::move(arg0); } } } bounded_op_term_t::bounded_op_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec, optargspec_t optargspec) : op_term_t(env, term, argspec, optargspec.with({"left_bound", "right_bound"})) { } bool bounded_op_term_t::is_left_open(scope_env_t *env, args_t *args) const { return open_bool(env, args, "left_bound", false); } bool bounded_op_term_t::is_right_open(scope_env_t *env, args_t *args) const { return open_bool(env, args, "right_bound", true); } bool bounded_op_term_t::open_bool( scope_env_t *env, args_t *args, const std::string &key, bool def/*ault*/) const { scoped_ptr_t<val_t> v = args->optarg(env, key); if (!v.has()) { return def; } const datum_string_t &s = v->as_str(); if (s == "open") { return true; } else if (s == "closed") { return false; } else { rfail(base_exc_t::GENERIC, "Expected `open` or `closed` for optarg `%s` (got `%s`).", key.c_str(), v->trunc_print().c_str()); } } } // namespace ql <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: mba $ $Date: 2001-09-13 11:49:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // includes -------------------------------------------------------------- #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig ) { INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); switch ( nProtocol ) { case INET_PROT_UNO : case INET_PROT_SLOT : { URL aTargetURL; SfxViewFrame* pViewFrame = NULL; Reference < XController > xController; if ( rFrame.is() ) xController = rFrame->getController(); Reference < XDispatchProvider > xProvider( xController, UNO_QUERY ); if ( xProvider.is() ) { aTargetURL.Complete = aURL; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( aTargetURL ); Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if ( xDisp.is() ) { Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY ); SfxOfficeDispatch* pDisp = NULL; if ( xTunnel.is() ) { sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier()); pDisp = (SfxOfficeDispatch*)(nImplementation); } if ( pDisp ) pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame(); } } USHORT nId; if ( nProtocol == INET_PROT_UNO ) { SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame ); const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path ); if ( pSlot ) nId = pSlot->GetSlotId(); } else nId = ( USHORT ) aTargetURL.Path.toInt32(); SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL; if ( nId ) { if ( pViewFrame ) return pViewFrame->GetImageManager()->GetImage( nId, pModule, bBig ); else { return SFX_APP()->GetImageManager_Impl()->GetImage( nId, NULL, bBig ); } } break; } case INET_PROT_NOT_VALID : { return Image(); break; } } return SvFileInformationManager::GetImageNoDefault( aObj, bBig ); } <commit_msg>#89485#: TargetURL is needed always<commit_after>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: mba $ $Date: 2001-09-18 15:45:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // includes -------------------------------------------------------------- #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig ) { INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); switch ( nProtocol ) { case INET_PROT_UNO : case INET_PROT_SLOT : { URL aTargetURL; aTargetURL.Complete = aURL; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( aTargetURL ); SfxViewFrame* pViewFrame = NULL; Reference < XController > xController; if ( rFrame.is() ) xController = rFrame->getController(); Reference < XDispatchProvider > xProvider( xController, UNO_QUERY ); if ( xProvider.is() ) { Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if ( xDisp.is() ) { Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY ); SfxOfficeDispatch* pDisp = NULL; if ( xTunnel.is() ) { sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier()); pDisp = (SfxOfficeDispatch*)(nImplementation); } if ( pDisp ) pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame(); } } USHORT nId; if ( nProtocol == INET_PROT_UNO ) { SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame ); const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path ); if ( pSlot ) nId = pSlot->GetSlotId(); } else nId = ( USHORT ) aTargetURL.Path.toInt32(); SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL; if ( nId ) { if ( pViewFrame ) return pViewFrame->GetImageManager()->GetImage( nId, pModule, bBig ); else { return SFX_APP()->GetImageManager_Impl()->GetImage( nId, NULL, bBig ); } } break; } case INET_PROT_NOT_VALID : { return Image(); break; } } return SvFileInformationManager::GetImageNoDefault( aObj, bBig ); } <|endoftext|>
<commit_before>#ifndef SLICE_HPP #define SLICE_HPP #include "iterbase.hpp" #include <iterator> #include <type_traits> #include <initializer_list> namespace iter { //Forward declarations of Slice and slice //template <typename Container, typename DifferenceType> //class Slice; //template <typename T> //Slice<std::initializer_list<T>> slice( std::initializer_list<T>); //template <typename Container, typename DifferenceType> //Slice<Container> slice(Container &&); template <typename T> class has_size { typedef char one; typedef long two; template <typename C> static one test( decltype(&C::size) ) ; template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template <typename Container> typename std::enable_if<has_size<Container>::value, std::size_t>::type size(const Container& container) { return container.size(); } template <typename Container> typename std::enable_if<!has_size<Container>::value, std::size_t>::type size(const Container& container) { return std::distance(std::begin(container), std::end(container)); } template <typename T, std::size_t N> std::size_t size(const T (&)[N]) { return N; } template <typename Container, typename DifferenceType> class Slice { private: Container container; DifferenceType start; DifferenceType stop; DifferenceType step; // The only thing allowed to directly instantiate an Slice is // the slice function //friend Slice slice<Container, DifferenceType>(Container &&); //template <typename T> //friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>); public: Slice(Container in_container, DifferenceType start, DifferenceType stop, DifferenceType step) : container(std::forward<Container>(in_container)), start{start}, stop{stop}, step{step} { // sets stop = start if the range is empty if ((start < stop && step <=0) || (start > stop && step >=0)){ this->stop = start; } if (this->stop > static_cast<DifferenceType>( size(this->container))) { this->stop = static_cast<DifferenceType>(size( this->container)); std::cout << "stop is too large\n"; std::cout << "stop is now: " << this->stop << '\n'; } if (this->start < 0) { this->start = 0; } } Slice() = delete; Slice& operator=(const Slice&) = delete; Slice(const Slice &) = default; class Iterator { private: iterator_type<Container> sub_iter; DifferenceType current; const DifferenceType stop; const DifferenceType step; public: Iterator (iterator_type<Container> si, DifferenceType start, DifferenceType stop, DifferenceType step) : sub_iter{si}, current{start}, stop{stop}, step{step} { } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { std::advance(this->sub_iter, this->step); this->current += this->step; return *this; } bool operator!=(const Iterator &) const { return (this->step > 0 && this->current < this->stop)|| (this->step < 0 && this->current > this->stop); } }; Iterator begin() { return {std::next(std::begin(this->container), this->start), this->start, this->stop, this->step}; } Iterator end() { return {std::next(std::begin(this->container), this->stop), this->stop, this->stop, this->step}; } }; // Helper function to instantiate a Slice template <typename Container, typename DifferenceType> Slice<Container, DifferenceType> slice( Container&& container, DifferenceType start, DifferenceType stop, DifferenceType step=1) { return {std::forward<Container>(container), start, stop, step}; } //only give the end as an arg and assume step is 1 and begin is 0 template <typename Container, typename DifferenceType> Slice<Container, DifferenceType> slice( Container&& container, DifferenceType stop) { return {std::forward<Container>(container), 0, stop, 1}; } template <typename T, typename DifferenceType> Slice<std::initializer_list<T>, DifferenceType> slice( std::initializer_list<T> il, DifferenceType start, DifferenceType stop, DifferenceType step=1) { return {il, start, stop, step}; } template <typename T, typename DifferenceType> Slice<std::initializer_list<T>, DifferenceType> slice( std::initializer_list<T> il, DifferenceType stop) { return {il, 0, stop, 1}; } } #endif //SLICE_HPP <commit_msg>removes couts that were still hanging around<commit_after>#ifndef SLICE_HPP #define SLICE_HPP #include "iterbase.hpp" #include <iterator> #include <type_traits> #include <initializer_list> namespace iter { //Forward declarations of Slice and slice //template <typename Container, typename DifferenceType> //class Slice; //template <typename T> //Slice<std::initializer_list<T>> slice( std::initializer_list<T>); //template <typename Container, typename DifferenceType> //Slice<Container> slice(Container &&); template <typename T> class has_size { typedef char one; typedef long two; template <typename C> static one test( decltype(&C::size) ) ; template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template <typename Container> typename std::enable_if<has_size<Container>::value, std::size_t>::type size(const Container& container) { return container.size(); } template <typename Container> typename std::enable_if<!has_size<Container>::value, std::size_t>::type size(const Container& container) { return std::distance(std::begin(container), std::end(container)); } template <typename T, std::size_t N> std::size_t size(const T (&)[N]) { return N; } template <typename Container, typename DifferenceType> class Slice { private: Container container; DifferenceType start; DifferenceType stop; DifferenceType step; // The only thing allowed to directly instantiate an Slice is // the slice function //friend Slice slice<Container, DifferenceType>(Container &&); //template <typename T> //friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>); public: Slice(Container in_container, DifferenceType start, DifferenceType stop, DifferenceType step) : container(std::forward<Container>(in_container)), start{start}, stop{stop}, step{step} { // sets stop = start if the range is empty if ((start < stop && step <=0) || (start > stop && step >=0)){ this->stop = start; } if (this->stop > static_cast<DifferenceType>( size(this->container))) { this->stop = static_cast<DifferenceType>(size( this->container)); } if (this->start < 0) { this->start = 0; } } Slice() = delete; Slice& operator=(const Slice&) = delete; Slice(const Slice &) = default; class Iterator { private: iterator_type<Container> sub_iter; DifferenceType current; const DifferenceType stop; const DifferenceType step; public: Iterator (iterator_type<Container> si, DifferenceType start, DifferenceType stop, DifferenceType step) : sub_iter{si}, current{start}, stop{stop}, step{step} { } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { std::advance(this->sub_iter, this->step); this->current += this->step; return *this; } bool operator!=(const Iterator &) const { return (this->step > 0 && this->current < this->stop)|| (this->step < 0 && this->current > this->stop); } }; Iterator begin() { return {std::next(std::begin(this->container), this->start), this->start, this->stop, this->step}; } Iterator end() { return {std::next(std::begin(this->container), this->stop), this->stop, this->stop, this->step}; } }; // Helper function to instantiate a Slice template <typename Container, typename DifferenceType> Slice<Container, DifferenceType> slice( Container&& container, DifferenceType start, DifferenceType stop, DifferenceType step=1) { return {std::forward<Container>(container), start, stop, step}; } //only give the end as an arg and assume step is 1 and begin is 0 template <typename Container, typename DifferenceType> Slice<Container, DifferenceType> slice( Container&& container, DifferenceType stop) { return {std::forward<Container>(container), 0, stop, 1}; } template <typename T, typename DifferenceType> Slice<std::initializer_list<T>, DifferenceType> slice( std::initializer_list<T> il, DifferenceType start, DifferenceType stop, DifferenceType step=1) { return {il, start, stop, step}; } template <typename T, typename DifferenceType> Slice<std::initializer_list<T>, DifferenceType> slice( std::initializer_list<T> il, DifferenceType stop) { return {il, 0, stop, 1}; } } #endif //SLICE_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: objmnctl.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:52:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/list.hxx> #ifndef _MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _PSEUDO_HXX //autogen #include <so3/pseudo.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #pragma hdrstop #include "sfxsids.hrc" #include "objmnctl.hxx" #include "dispatch.hxx" #include "viewsh.hxx" #include "viewfrm.hxx" // STATIC DATA ----------------------------------------------------------- SFX_IMPL_MENU_CONTROL(SfxObjectVerbsControl, SfxStringItem); //-------------------------------------------------------------------- /* Ctor; setzt Select-Handler am Menu und traegt Menu in seinen Parent ein. */ SfxObjectVerbsControl::SfxObjectVerbsControl(USHORT nId, Menu &rMenu, SfxBindings &rBindings) : SfxMenuControl( nId, rBindings ) , pMenu(new PopupMenu) , rParent(rMenu) { rMenu.SetPopupMenu(nId, pMenu); pMenu->SetSelectHdl(LINK(this, SfxObjectVerbsControl, MenuSelect)); FillMenu(); } //-------------------------------------------------------------------- /* Fuellt das Menu mit den aktuellen Verben aus der ViewShell. */ void SfxObjectVerbsControl::FillMenu() { pMenu->Clear(); SfxViewShell *pView = GetBindings().GetDispatcher()->GetFrame()->GetViewShell(); if (pView) { const SvVerbList *pList = pView->GetVerbs(); if (pList) { USHORT nId = SID_VERB_START; for (USHORT n=0; n<pList->Count(); n++) { const SvVerb& rVerb = (*pList)[n]; if (!rVerb.IsOnMenu()) continue; DBG_ASSERT(nId <= SID_VERB_END, "Zuviele Verben!"); if (nId > SID_VERB_END) break; pMenu->InsertItem(nId++, rVerb.GetName()); } } } rParent.EnableItem( GetId(), (BOOL)pMenu->GetItemCount() ); } //-------------------------------------------------------------------- /* Statusbenachrichtigung; fuellt gfs. das Menu mit den aktuellen Verben aus der ViewShell. der DocumentShell. Ist die Funktionalit"at disabled, wird der entsprechende Menueeintrag im Parentmenu disabled, andernfalls wird er enabled. */ void SfxObjectVerbsControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { rParent.EnableItem(GetId(), SFX_ITEM_AVAILABLE == eState ); if ( SFX_ITEM_AVAILABLE == eState ) FillMenu(); } //-------------------------------------------------------------------- /* Select-Handler des Menus; das selektierte Verb mit ausgef"uhrt, */ IMPL_LINK_INLINE_START( SfxObjectVerbsControl, MenuSelect, Menu *, pMenu ) { const USHORT nId = pMenu->GetCurItemId(); if( nId ) GetBindings().Execute(nId); return 1; } IMPL_LINK_INLINE_END( SfxObjectVerbsControl, MenuSelect, Menu *, pMenu ) //-------------------------------------------------------------------- /* Dtor; gibt das Menu frei. */ SfxObjectVerbsControl::~SfxObjectVerbsControl() { delete pMenu; } //-------------------------------------------------------------------- PopupMenu* SfxObjectVerbsControl::GetPopup() const { return pMenu; } <commit_msg>INTEGRATION: CWS ooo20040329 (1.1.1.1.480); FILE MERGED 2004/03/18 10:42:49 waratah 1.1.1.1.480.1: :#i1858# exclude pragma hdrstop by bracketting for gcc<commit_after>/************************************************************************* * * $RCSfile: objmnctl.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: svesik $ $Date: 2004-04-21 13:18:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/list.hxx> #ifndef _MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _PSEUDO_HXX //autogen #include <so3/pseudo.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef GCC #pragma hdrstop #endif #include "sfxsids.hrc" #include "objmnctl.hxx" #include "dispatch.hxx" #include "viewsh.hxx" #include "viewfrm.hxx" // STATIC DATA ----------------------------------------------------------- SFX_IMPL_MENU_CONTROL(SfxObjectVerbsControl, SfxStringItem); //-------------------------------------------------------------------- /* Ctor; setzt Select-Handler am Menu und traegt Menu in seinen Parent ein. */ SfxObjectVerbsControl::SfxObjectVerbsControl(USHORT nId, Menu &rMenu, SfxBindings &rBindings) : SfxMenuControl( nId, rBindings ) , pMenu(new PopupMenu) , rParent(rMenu) { rMenu.SetPopupMenu(nId, pMenu); pMenu->SetSelectHdl(LINK(this, SfxObjectVerbsControl, MenuSelect)); FillMenu(); } //-------------------------------------------------------------------- /* Fuellt das Menu mit den aktuellen Verben aus der ViewShell. */ void SfxObjectVerbsControl::FillMenu() { pMenu->Clear(); SfxViewShell *pView = GetBindings().GetDispatcher()->GetFrame()->GetViewShell(); if (pView) { const SvVerbList *pList = pView->GetVerbs(); if (pList) { USHORT nId = SID_VERB_START; for (USHORT n=0; n<pList->Count(); n++) { const SvVerb& rVerb = (*pList)[n]; if (!rVerb.IsOnMenu()) continue; DBG_ASSERT(nId <= SID_VERB_END, "Zuviele Verben!"); if (nId > SID_VERB_END) break; pMenu->InsertItem(nId++, rVerb.GetName()); } } } rParent.EnableItem( GetId(), (BOOL)pMenu->GetItemCount() ); } //-------------------------------------------------------------------- /* Statusbenachrichtigung; fuellt gfs. das Menu mit den aktuellen Verben aus der ViewShell. der DocumentShell. Ist die Funktionalit"at disabled, wird der entsprechende Menueeintrag im Parentmenu disabled, andernfalls wird er enabled. */ void SfxObjectVerbsControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { rParent.EnableItem(GetId(), SFX_ITEM_AVAILABLE == eState ); if ( SFX_ITEM_AVAILABLE == eState ) FillMenu(); } //-------------------------------------------------------------------- /* Select-Handler des Menus; das selektierte Verb mit ausgef"uhrt, */ IMPL_LINK_INLINE_START( SfxObjectVerbsControl, MenuSelect, Menu *, pMenu ) { const USHORT nId = pMenu->GetCurItemId(); if( nId ) GetBindings().Execute(nId); return 1; } IMPL_LINK_INLINE_END( SfxObjectVerbsControl, MenuSelect, Menu *, pMenu ) //-------------------------------------------------------------------- /* Dtor; gibt das Menu frei. */ SfxObjectVerbsControl::~SfxObjectVerbsControl() { delete pMenu; } //-------------------------------------------------------------------- PopupMenu* SfxObjectVerbsControl::GetPopup() const { return pMenu; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_INVERSE_POWER_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_GLOBAL_INVERSE_POWER_POTENTIAL_HPP #include <mjolnir/core/ExclusionList.hpp> #include <mjolnir/core/System.hpp> #include <algorithm> #include <numeric> #include <memory> #include <cmath> namespace mjolnir { // inverse power potential. template<typename traitsT> class InversePowerPotential { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using integer_type = std::int32_t; using parameter_type = real_type; using container_type = std::vector<parameter_type>; using pair_parameter_type = parameter_type; // ------------------------------------------------------------------------ // topology stuff using topology_type = Topology; using molecule_id_type = typename topology_type::molecule_id_type; using group_id_type = typename topology_type::group_id_type; using connection_kind_type = typename topology_type::connection_kind_type; using ignore_molecule_type = IgnoreMolecule<molecule_id_type>; using ignore_group_type = IgnoreGroup <group_id_type>; using exclusion_list_type = ExclusionList <traits_type>; static constexpr real_type default_cutoff(const integer_type n) noexcept { return std::pow(2.0, 12.0 / n); } static constexpr parameter_type default_parameter() noexcept { return parameter_type{0.0}; } public: InversePowerPotential(const real_type eps, const integer_type n, const real_type cutoff_ratio, const std::vector<std::pair<std::size_t, parameter_type>>& parameters, const std::map<connection_kind_type, std::size_t>& exclusions, ignore_molecule_type ignore_mol, ignore_group_type ignore_grp) :epsilon_(eps), n_(n), cutoff_ratio_(cutoff_ratio), coef_at_cutoff_(std::pow(1.0 / cutoff_ratio, n)), exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp)) { this->parameters_ .reserve(parameters.size()); this->participants_.reserve(parameters.size()); for(const auto& idxp : parameters) { const auto idx = idxp.first; this->participants_.push_back(idx); if(idx >= this->parameters_.size()) { this->parameters_.resize(idx+1, default_parameter()); } this->parameters_.at(idx) = idxp.second; } } ~InversePowerPotential() = default; InversePowerPotential(const InversePowerPotential&) = default; InversePowerPotential(InversePowerPotential&&) = default; InversePowerPotential& operator=(const InversePowerPotential&) = default; InversePowerPotential& operator=(InversePowerPotential&&) = default; // this value will be stored in NeighborList pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept { return this->parameters_[i] + this->parameters_[j]; } // forwarding function for clarity real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->potential(r, this->prepare_params(i, j)); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->derivative(r, this->prepare_params(i, j)); } real_type potential(const real_type r, const pair_parameter_type& d) const noexcept { MJOLNIR_GET_DEFAULT_LOGGER_DEBUG(); MJOLNIR_LOG_FUNCTION_DEBUG(); if(d * this->cutoff_ratio_ < r){return 0.0;} const real_type rinv = 1.0 / r; const real_type d_r = d * rinv; const real_type drn = std::pow(d_r, n_); return this->epsilon_ * (drn - this->coef_at_cutoff_); } real_type derivative(const real_type r, const pair_parameter_type& d) const noexcept { MJOLNIR_GET_DEFAULT_LOGGER_DEBUG(); MJOLNIR_LOG_FUNCTION_DEBUG(); if(d * this->cutoff_ratio_ < r){return 0.0;} const real_type rinv = 1.0 / r; const real_type d_r = d * rinv; const real_type drn = std::pow(d_r, n_); return -n_ * this->epsilon_ * drn * rinv; } void initialize(const System<traits_type>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); this->update(sys); return; } // nothing to be done if system parameter (e.g. temperature) do not changes void update(const System<traits_type>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); // update exclusion list based on sys.topology() exclusion_list_.make(sys); return; } real_type cutoff_ratio() const noexcept {return this->cutoff_ratio_;} real_type coef_at_cutoff() const noexcept {return this->coef_at_cutoff_;} real_type max_cutoff_length() const { const real_type max_sigma = * (std::max_element(parameters_.cbegin(), parameters_.cend())); return 2 * max_sigma * this->cutoff_ratio_; } // ----------------------------------------------------------------------- // for spatial partitions // // Here, the default implementation uses Newton's 3rd law to reduce // calculation. For an interacting pair (i, j), forces applied to i and j // are equal in magnitude and opposite in direction. So, if a pair (i, j) is // listed, (j, i) is not needed. // See implementation of VerletList, CellList and GlobalPairInteraction // for more details about the usage of these functions. std::vector<std::size_t> const& participants() const noexcept {return participants_;} range<typename std::vector<std::size_t>::const_iterator> leading_participants() const noexcept { return make_range(participants_.begin(), std::prev(participants_.end())); } range<typename std::vector<std::size_t>::const_iterator> possible_partners_of(const std::size_t participant_idx, const std::size_t /*particle_idx*/) const noexcept { return make_range(participants_.begin() + participant_idx + 1, participants_.end()); } bool has_interaction(const std::size_t i, const std::size_t j) const noexcept { return (i < j) && !exclusion_list_.is_excluded(i, j); } // ------------------------------------------------------------------------ // for testing exclusion_list_type const& exclusion_list() const noexcept { return exclusion_list_; } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "InversePower";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. real_type& epsilon() noexcept {return this->epsilon_;} real_type epsilon() const noexcept {return this->epsilon_;} integer_type& n() noexcept {return this->n_;} integer_type n() const noexcept {return this->n_;} std::vector<real_type>& parameters() noexcept {return this->parameters_;} std::vector<real_type> const& parameters() const noexcept {return this->parameters_;} private: real_type epsilon_; integer_type n_; real_type cutoff_ratio_; real_type coef_at_cutoff_; // correction of energy value at cutoff length std::vector<parameter_type> parameters_; std::vector<std::size_t> participants_; exclusion_list_type exclusion_list_; }; } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> namespace mjolnir { extern template class InversePowerPotential<SimulatorTraits<double, UnlimitedBoundary> >; extern template class InversePowerPotential<SimulatorTraits<float, UnlimitedBoundary> >; extern template class InversePowerPotential<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class InversePowerPotential<SimulatorTraits<float, CuboidalPeriodicBoundary>>; } // mjolnir #endif// MJOLNIR_SEPARATE_BUILD #endif /* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL */ <commit_msg>refactor: polish a bit<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_INVERSE_POWER_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_GLOBAL_INVERSE_POWER_POTENTIAL_HPP #include <mjolnir/core/ExclusionList.hpp> #include <mjolnir/core/System.hpp> #include <algorithm> #include <numeric> #include <memory> #include <cmath> namespace mjolnir { // inverse power potential. template<typename traitsT> class InversePowerPotential { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using integer_type = std::int32_t; using parameter_type = real_type; using container_type = std::vector<parameter_type>; using pair_parameter_type = parameter_type; // ------------------------------------------------------------------------ // topology stuff using topology_type = Topology; using molecule_id_type = typename topology_type::molecule_id_type; using group_id_type = typename topology_type::group_id_type; using connection_kind_type = typename topology_type::connection_kind_type; using ignore_molecule_type = IgnoreMolecule<molecule_id_type>; using ignore_group_type = IgnoreGroup <group_id_type>; using exclusion_list_type = ExclusionList <traits_type>; // std::pow is not marked constexpr static real_type default_cutoff(const integer_type n) noexcept { return std::pow(2.0, 12.0 / n); } static constexpr parameter_type default_parameter() noexcept { return parameter_type{0.0}; } public: InversePowerPotential(const real_type eps, const integer_type n, const real_type cutoff_ratio, const std::vector<std::pair<std::size_t, parameter_type>>& parameters, const std::map<connection_kind_type, std::size_t>& exclusions, ignore_molecule_type ignore_mol, ignore_group_type ignore_grp) :epsilon_(eps), n_(n), cutoff_ratio_(cutoff_ratio), coef_at_cutoff_(std::pow(1.0 / cutoff_ratio, n)), exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp)) { this->parameters_ .reserve(parameters.size()); this->participants_.reserve(parameters.size()); for(const auto& idxp : parameters) { const auto idx = idxp.first; this->participants_.push_back(idx); if(idx >= this->parameters_.size()) { this->parameters_.resize(idx+1, default_parameter()); } this->parameters_.at(idx) = idxp.second; } } ~InversePowerPotential() = default; InversePowerPotential(const InversePowerPotential&) = default; InversePowerPotential(InversePowerPotential&&) = default; InversePowerPotential& operator=(const InversePowerPotential&) = default; InversePowerPotential& operator=(InversePowerPotential&&) = default; // this value will be stored in NeighborList pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept { return this->parameters_[i] + this->parameters_[j]; } // forwarding function for clarity real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->potential(r, this->prepare_params(i, j)); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->derivative(r, this->prepare_params(i, j)); } real_type potential(const real_type r, const pair_parameter_type& d) const noexcept { MJOLNIR_GET_DEFAULT_LOGGER_DEBUG(); MJOLNIR_LOG_FUNCTION_DEBUG(); if(d * this->cutoff_ratio_ < r){return 0.0;} const real_type d_r = d / r; const real_type drn = std::pow(d_r, n_); return this->epsilon_ * (drn - this->coef_at_cutoff_); } real_type derivative(const real_type r, const pair_parameter_type& d) const noexcept { MJOLNIR_GET_DEFAULT_LOGGER_DEBUG(); MJOLNIR_LOG_FUNCTION_DEBUG(); if(d * this->cutoff_ratio_ < r){return 0.0;} const real_type rinv = 1.0 / r; const real_type d_r = d * rinv; const real_type drn = std::pow(d_r, n_); return -n_ * this->epsilon_ * drn * rinv; } void initialize(const System<traits_type>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); this->update(sys); return; } // nothing to be done if system parameter (e.g. temperature) do not changes void update(const System<traits_type>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); // update exclusion list based on sys.topology() exclusion_list_.make(sys); return; } real_type cutoff_ratio() const noexcept {return this->cutoff_ratio_;} real_type coef_at_cutoff() const noexcept {return this->coef_at_cutoff_;} real_type max_cutoff_length() const { const real_type max_sigma = * (std::max_element(parameters_.cbegin(), parameters_.cend())); return 2 * max_sigma * this->cutoff_ratio_; } // ----------------------------------------------------------------------- // for spatial partitions // // Here, the default implementation uses Newton's 3rd law to reduce // calculation. For an interacting pair (i, j), forces applied to i and j // are equal in magnitude and opposite in direction. So, if a pair (i, j) is // listed, (j, i) is not needed. // See implementation of VerletList, CellList and GlobalPairInteraction // for more details about the usage of these functions. std::vector<std::size_t> const& participants() const noexcept {return participants_;} range<typename std::vector<std::size_t>::const_iterator> leading_participants() const noexcept { return make_range(participants_.begin(), std::prev(participants_.end())); } range<typename std::vector<std::size_t>::const_iterator> possible_partners_of(const std::size_t participant_idx, const std::size_t /*particle_idx*/) const noexcept { return make_range(participants_.begin() + participant_idx + 1, participants_.end()); } bool has_interaction(const std::size_t i, const std::size_t j) const noexcept { return (i < j) && !exclusion_list_.is_excluded(i, j); } // ------------------------------------------------------------------------ // for testing exclusion_list_type const& exclusion_list() const noexcept { return exclusion_list_; } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "InversePower";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. real_type& epsilon() noexcept {return this->epsilon_;} real_type epsilon() const noexcept {return this->epsilon_;} integer_type& n() noexcept {return this->n_;} integer_type n() const noexcept {return this->n_;} std::vector<real_type>& parameters() noexcept {return this->parameters_;} std::vector<real_type> const& parameters() const noexcept {return this->parameters_;} private: real_type epsilon_; integer_type n_; real_type cutoff_ratio_; real_type coef_at_cutoff_; // correction of energy value at cutoff length std::vector<parameter_type> parameters_; std::vector<std::size_t> participants_; exclusion_list_type exclusion_list_; }; } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> namespace mjolnir { extern template class InversePowerPotential<SimulatorTraits<double, UnlimitedBoundary> >; extern template class InversePowerPotential<SimulatorTraits<float, UnlimitedBoundary> >; extern template class InversePowerPotential<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class InversePowerPotential<SimulatorTraits<float, CuboidalPeriodicBoundary>>; } // mjolnir #endif// MJOLNIR_SEPARATE_BUILD #endif /* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL */ <|endoftext|>
<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() { printf("Call to AliAnalysisVertexingHF parameters setting :\n"); vHF = new AliAnalysisVertexingHF(); //--- switch-off candidates finding (default: all on) //vHF->SetD0toKpiOff(); vHF->SetJPSItoEleOff(); //vHF->Set3ProngOff(); //vHF->SetLikeSignOn(); // like-sign pairs and triplets vHF->Set4ProngOff(); vHF->SetDstarOff(); vHF->SetFindVertexForDstar(kFALSE); //--- secondary vertex with KF? //vHF->SetSecVtxWithKF(); vHF->SetCascadesOff(); vHF->SetFindVertexForCascades(kFALSE); //--- set cuts for single-track selection // displaced tracks AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNClustersTPC(70); esdTrackCuts->SetRequireITSRefit(kTRUE); //esdTrackCuts->SetMinNClustersITS(4); esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); esdTrackCuts->SetMinDCAToVertexXY(0.0100); esdTrackCuts->SetPtRange(0.8,1.e10); esdTrackCuts->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter"); trkFilter->AddCuts(esdTrackCuts); vHF->SetTrackFilter(trkFilter); // D* soft pion tracks AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCutsSoftPi->SetMinNClustersITS(2); esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi"); trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi); vHF->SetTrackFilterSoftPi(trkFilterSoftPi); //--- set cuts for candidates selection AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi"); Float_t cutsArrayD0toKpi[9]={0.2,999999.,1.1,0.,0.,999999.,999999.,0.,0.5}; cutsD0toKpi->SetCuts(9,cutsArrayD0toKpi); cutsD0toKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpi(cutsD0toKpi); AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee"); Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1}; cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee); cutsJpsitoee->AddTrackCuts(esdTrackCuts); vHF->SetCutsJpsitoee(cutsJpsitoee); AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi"); Float_t cutsArrayDplustoKpipi[12]={0.2,0.8,0.8,0.,0.,0.01,0.06,0.03,0.,0.85,0.,10000000000.}; cutsDplustoKpipi->SetCuts(12,cutsArrayDplustoKpipi); cutsDplustoKpipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsDplustoKpipi(cutsDplustoKpipi); AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi"); Float_t cutsArrayDstoKKpi[14]={0.,999.,999.,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1}; cutsDstoKKpi->SetCuts(14,cutsArrayDstoKKpi); cutsDstoKKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsDstoKKpi(cutsDstoKKpi); AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi"); //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.}; Float_t cutsArrayLctopKpi[12]={0.,999.,999.,0.,0.,0.01,0.06,0.005,0.7,0.,0.,0.05}; cutsLctopKpi->SetCuts(12,cutsArrayLctopKpi); cutsLctopKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsLctopKpi(cutsLctopKpi); AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi"); Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.}; cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi); cutsD0toKpipipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpipipi(cutsD0toKpipipi); AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi"); Float_t cutsArrayDStartoKpipi[14]={0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.,0.3, 0.1, 0.05, 100000000000.0, 0.5}; // first 9 for D0 from D*, last 5 for D* cutsDStartoKpipi->SetCuts(14,cutsArrayDStartoKpipi); cutsDStartoKpipi->AddTrackCuts(esdTrackCuts); cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi); vHF->SetCutsDStartoKpipi(cutsDStartoKpipi); AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0"); Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.}; cutsLctoV0->SetCuts(9,cutsArrayLctoV0); cutsLctoV0->AddTrackCuts(esdTrackCuts); vHF->SetCutsLctoV0(cutsLctoV0); // //--- set this if you want to reconstruct primary vertex candidate by // candidate using other tracks in the event (for pp, broad // interaction region) //vHF->SetRecoPrimVtxSkippingTrks(); //--- OR set this if you want to remove the candidate daughters from // the primary vertex, without recostructing it from scratch //vHF->SetRmTrksFromPrimVtx(); //--- check the settings vHF->PrintStatus(); //--- verbose // AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2); return vHF; } <commit_msg>Update D* cuts (Alessandro)<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() { printf("Call to AliAnalysisVertexingHF parameters setting :\n"); vHF = new AliAnalysisVertexingHF(); //--- switch-off candidates finding (default: all on) //vHF->SetD0toKpiOff(); vHF->SetJPSItoEleOff(); //vHF->Set3ProngOff(); //vHF->SetLikeSignOn(); // like-sign pairs and triplets vHF->Set4ProngOff(); vHF->SetDstarOff(); vHF->SetFindVertexForDstar(kFALSE); //--- secondary vertex with KF? //vHF->SetSecVtxWithKF(); vHF->SetCascadesOff(); vHF->SetFindVertexForCascades(kFALSE); //--- set cuts for single-track selection // displaced tracks AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNClustersTPC(70); esdTrackCuts->SetRequireITSRefit(kTRUE); //esdTrackCuts->SetMinNClustersITS(4); esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); esdTrackCuts->SetMinDCAToVertexXY(0.0100); esdTrackCuts->SetPtRange(0.8,1.e10); esdTrackCuts->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter"); trkFilter->AddCuts(esdTrackCuts); vHF->SetTrackFilter(trkFilter); // D* soft pion tracks AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCutsSoftPi->SetMinNClustersITS(4); esdTrackCuts->SetPtRange(0.2,1.e10); esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi"); trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi); vHF->SetTrackFilterSoftPi(trkFilterSoftPi); //--- set cuts for candidates selection AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi"); Float_t cutsArrayD0toKpi[9]={0.2,999999.,1.1,0.,0.,999999.,999999.,0.,0.5}; cutsD0toKpi->SetCuts(9,cutsArrayD0toKpi); cutsD0toKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpi(cutsD0toKpi); AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee"); Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1}; cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee); cutsJpsitoee->AddTrackCuts(esdTrackCuts); vHF->SetCutsJpsitoee(cutsJpsitoee); AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi"); Float_t cutsArrayDplustoKpipi[12]={0.2,0.8,0.8,0.,0.,0.01,0.06,0.03,0.,0.85,0.,10000000000.}; cutsDplustoKpipi->SetCuts(12,cutsArrayDplustoKpipi); cutsDplustoKpipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsDplustoKpipi(cutsDplustoKpipi); AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi"); Float_t cutsArrayDstoKKpi[14]={0.,999.,999.,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1}; cutsDstoKKpi->SetCuts(14,cutsArrayDstoKKpi); cutsDstoKKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsDstoKKpi(cutsDstoKKpi); AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi"); //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.}; Float_t cutsArrayLctopKpi[12]={0.,999.,999.,0.,0.,0.01,0.06,0.005,0.7,0.,0.,0.05}; cutsLctopKpi->SetCuts(12,cutsArrayLctopKpi); cutsLctopKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsLctopKpi(cutsLctopKpi); AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi"); Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.}; cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi); cutsD0toKpipipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpipipi(cutsD0toKpipipi); AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi"); Float_t cutsArrayDStartoKpipi[14]={0.15,0.07.,0.85,0.8,0.8,0.06.,0.06.,0.001,0.6,0.15, 0.03, 0.2, 5, 0.5}; // first 9 for D0 from D*, last 5 for D* cutsDStartoKpipi->SetCuts(14,cutsArrayDStartoKpipi); cutsDStartoKpipi->AddTrackCuts(esdTrackCuts); cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi); vHF->SetCutsDStartoKpipi(cutsDStartoKpipi); AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0"); Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.}; cutsLctoV0->SetCuts(9,cutsArrayLctoV0); cutsLctoV0->AddTrackCuts(esdTrackCuts); vHF->SetCutsLctoV0(cutsLctoV0); // //--- set this if you want to reconstruct primary vertex candidate by // candidate using other tracks in the event (for pp, broad // interaction region) //vHF->SetRecoPrimVtxSkippingTrks(); //--- OR set this if you want to remove the candidate daughters from // the primary vertex, without recostructing it from scratch //vHF->SetRmTrksFromPrimVtx(); //--- check the settings vHF->PrintStatus(); //--- verbose // AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2); return vHF; } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER #include <stdlib.h> #include <SDL.h> #include <SDL_syswm.h> // Windows specific header + D3D11 SDK header #include <Windows.h> #include <d3d11.h> // link with D3D11.lib #pragma comment(lib, "D3D11.lib") // SDL2 hack. #ifdef main #undef main #endif // main // used to signify that the variable is being outputted #define OUT HWND getWindowHandle(SDL_Window *window); bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context); void render(ID3D11Device *device, ID3D11DeviceContext *context); int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // create window SDL_Window *window = SDL_CreateWindow("D3D11 Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1366, 768, SDL_WINDOW_SHOWN); if (window == nullptr) { SDL_Quit(); return 1; } // get window handle from the window HWND windowHandle = getWindowHandle(window); if (windowHandle == nullptr) { SDL_DestroyWindow(window); SDL_Quit(); return 2; } ID3D11Device *device = nullptr; IDXGISwapChain *swapChain = nullptr; ID3D11DeviceContext *context = nullptr; bool r = createD3D11DeviceAndSwapChain(windowHandle, device, swapChain, context); if (r == false) { SDL_DestroyWindow(window); SDL_Quit(); return 3; } // render target view ID3D11RenderTargetView *rtv = nullptr; { ID3D11Texture2D *backBuffer = nullptr; if (swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&backBuffer)) != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 4; } HRESULT check = device->CreateRenderTargetView(backBuffer, NULL, &rtv); // release back buffer texture as it already has been set. backBuffer->Release(); if (check != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 5; } context->OMSetRenderTargets(1, &rtv, NULL); } // set viewport D3D11_VIEWPORT vp; vp.Width = 1366.0f; vp.Height = 768.0f; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; context->RSSetViewports(1, &vp); // clear color static float clearColor[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } // set canvas clear color context->ClearRenderTargetView(rtv, clearColor); // perform any additional render logic render(device, context); // swap buffer swapChain->Present(0, 0); } // cleanup SDL_DestroyWindow(window); SDL_Quit(); return 0; } HWND getWindowHandle(SDL_Window *window) { SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(window, &info)) return nullptr; return info.info.win.window; } bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context) { // create swap chain description DXGI_SWAP_CHAIN_DESC swapDesc; ZeroMemory(&swapDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapDesc.BufferCount = 1; // how many back buffers swapDesc.BufferDesc.Width = 1366; // window width swapDesc.BufferDesc.Height = 768; // window height swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // standard backbuffer format swapDesc.BufferDesc.RefreshRate.Numerator = 60; // vsync swapDesc.BufferDesc.RefreshRate.Denominator = 1; // vsync swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // yes we are rendering to a window swapDesc.OutputWindow = window; // the window we are outputting to swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; // Antialiasing swapDesc.Windowed = true; // we are not in fullscreen // request feature level 11_0 D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; UINT featureLevelCount = 1; D3D_FEATURE_LEVEL featureLevelSupported; HRESULT r = D3D11CreateDeviceAndSwapChain( NULL, // adapter D3D_DRIVER_TYPE_HARDWARE, // device type NULL, // do we want software emulation for features not supported? 0, // device flags &featureLevel, // feature level(s) requested featureLevelCount, // amount of feature level(s) requested D3D11_SDK_VERSION, // version of the DX11 SDK &swapDesc, // swap chain description &swapChain, // OUT the swap chain pointer &device, // OUT the d3d11 device &featureLevelSupported, // OUT the d3d11 feature level that is supported on this computer. &context // OUT the d3d11 context ); if (r == S_OK) return true; return false; } void render(ID3D11Device *device, ID3D11DeviceContext *context) { }<commit_msg>cleanup<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER #include <stdlib.h> #include <SDL.h> #include <SDL_syswm.h> // Windows specific header + D3D11 SDK header #include <Windows.h> #include <d3d11.h> // link with D3D11.lib #pragma comment(lib, "D3D11.lib") // SDL2 hack. #ifdef main #undef main #endif // main // used to signify that the variable is being outputted #define OUT HWND getWindowHandle(SDL_Window *window); bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context); void render(ID3D11Device *device, ID3D11DeviceContext *context); int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // create window SDL_Window *window = SDL_CreateWindow("D3D11 Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1366, 768, SDL_WINDOW_SHOWN); if (window == nullptr) { SDL_Quit(); return 1; } // get window handle from the window HWND windowHandle = getWindowHandle(window); if (windowHandle == nullptr) { SDL_DestroyWindow(window); SDL_Quit(); return 2; } ID3D11Device *device = nullptr; IDXGISwapChain *swapChain = nullptr; ID3D11DeviceContext *context = nullptr; bool r = createD3D11DeviceAndSwapChain(windowHandle, device, swapChain, context); if (r == false) { SDL_DestroyWindow(window); SDL_Quit(); return 3; } // render target view ID3D11RenderTargetView *rtv = nullptr; { ID3D11Texture2D *backBuffer = nullptr; if (swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&backBuffer)) != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 4; } HRESULT check = device->CreateRenderTargetView(backBuffer, NULL, &rtv); // release back buffer texture as it already has been set. backBuffer->Release(); if (check != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 5; } context->OMSetRenderTargets(1, &rtv, NULL); } // set viewport D3D11_VIEWPORT vp; vp.Width = 1366.0f; vp.Height = 768.0f; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; context->RSSetViewports(1, &vp); // clear color const float clearColor[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } // set canvas clear color context->ClearRenderTargetView(rtv, clearColor); // perform any additional render logic render(device, context); // swap buffer swapChain->Present(0, 0); } // cleanup SDL_DestroyWindow(window); SDL_Quit(); return 0; } HWND getWindowHandle(SDL_Window *window) { SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(window, &info)) return nullptr; return info.info.win.window; } bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context) { // create swap chain description DXGI_SWAP_CHAIN_DESC swapDesc; ZeroMemory(&swapDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapDesc.BufferCount = 1; // how many back buffers swapDesc.BufferDesc.Width = 1366; // window width swapDesc.BufferDesc.Height = 768; // window height swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // standard backbuffer format swapDesc.BufferDesc.RefreshRate.Numerator = 60; // vsync swapDesc.BufferDesc.RefreshRate.Denominator = 1; // vsync swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // yes we are rendering to a window swapDesc.OutputWindow = window; // the window we are outputting to swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; // Antialiasing swapDesc.Windowed = true; // we are not in fullscreen // request feature level 11_0 D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; UINT featureLevelCount = 1; D3D_FEATURE_LEVEL featureLevelSupported; HRESULT r = D3D11CreateDeviceAndSwapChain( NULL, // adapter D3D_DRIVER_TYPE_HARDWARE, // device type NULL, // do we want software emulation for features not supported? 0, // device flags &featureLevel, // feature level(s) requested featureLevelCount, // amount of feature level(s) requested D3D11_SDK_VERSION, // version of the DX11 SDK &swapDesc, // swap chain description &swapChain, // OUT the swap chain pointer &device, // OUT the d3d11 device &featureLevelSupported, // OUT the d3d11 feature level that is supported on this computer. &context // OUT the d3d11 context ); if (r == S_OK) return true; return false; } void render(ID3D11Device *device, ID3D11DeviceContext *context) { }<|endoftext|>
<commit_before>// // Created by john on 9/12/15. // #include <argos3/core/simulator/simulator.h> #include <argos3/core/simulator/loop_functions.h> #include <source/ga/BasicGA.h> #include <source/ga/ChromosomeFactory.h> #include "iAnt_controller.h" #include "iAnt_loop_functions.h" #include "iAnt_pheromone.h" /****************************************/ /****************************************/ int main(int argc, char** argv) { static argos::CSimulator& cSimulator = argos::CSimulator::GetInstance(); cSimulator.SetExperimentFileName("experiments/iAnt.xml"); cSimulator.LoadExperiment(); static iAnt_loop_functions &cLoopFunctions = static_cast<iAnt_loop_functions&>(cSimulator.GetLoopFunctions()); BasicGA ga; ChromosomeFactory chromosomeFactory; vector<Chromosome*> chromosomes = chromosomeFactory.buildPopulation(10); for(int i = 0; i < 100; i++) { argos::LOG << "Generation #"; argos::LOG << i; argos::LOG << " started.\n"; // This file is created in the directory where you run ARGoS // it is always created or appended to, never overwritten, i.e. ios::app ofstream dataOutput("iAntTagData.txt", ios::app); dataOutput << "Generation #"; dataOutput << i; dataOutput << " started.\n"; dataOutput.close(); vector<BasicGA::FitnessChromosome> fitness; int fitsum = 0; for (int c = 0; c < chromosomes.size(); c++) { cLoopFunctions.setChromosome(chromosomes.at(c)); cSimulator.Reset(); cSimulator.Execute(); BasicGA::FitnessChromosome fitChromosome; fitChromosome.chromosome = chromosomes.at(c); fitChromosome.fitness = cLoopFunctions.getFitness(); fitsum += fitChromosome.fitness; fitness.push_back(fitChromosome); } argos::LOG << "Generation #"; argos::LOG << i; argos::LOG << " total: "; argos::LOG << fitsum; argos::LOG <<"done.\n"; // This file is created in the directory where you run ARGoS // it is always created or appended to, never overwritten, i.e. ios::app ofstream dataOutput2("iAntTagData.txt", ios::app); dataOutput2 << "Generation #"; dataOutput2 << i; dataOutput2 << " total: "; dataOutput2 << fitsum; dataOutput2 <<"done.\n"; chromosomes = ga.evolve(fitness); } /* * Dispose of ARGoS stuff */ cSimulator.Destroy(); /* All is OK */ return 0; } /****************************************/ /****************************************/ <commit_msg>Changed static cast to regular cast.<commit_after>// // Created by john on 9/12/15. // #include <argos3/core/simulator/simulator.h> #include <argos3/core/simulator/loop_functions.h> #include <source/ga/BasicGA.h> #include <source/ga/ChromosomeFactory.h> #include "iAnt_controller.h" #include "iAnt_loop_functions.h" #include "iAnt_pheromone.h" /****************************************/ /****************************************/ int main(int argc, char** argv) { static argos::CSimulator& cSimulator = argos::CSimulator::GetInstance(); cSimulator.SetExperimentFileName("experiments/iAnt.xml"); cSimulator.LoadExperiment(); iAnt_loop_functions &cLoopFunctions = (iAnt_loop_functions&)(cSimulator.GetLoopFunctions()); BasicGA ga; ChromosomeFactory chromosomeFactory; vector<Chromosome*> chromosomes = chromosomeFactory.buildPopulation(10); for(int i = 0; i < 100; i++) { argos::LOG << "Generation #"; argos::LOG << i; argos::LOG << " started.\n"; // This file is created in the directory where you run ARGoS // it is always created or appended to, never overwritten, i.e. ios::app ofstream dataOutput("iAntTagData.txt", ios::app); dataOutput << "Generation #"; dataOutput << i; dataOutput << " started.\n"; dataOutput.close(); vector<BasicGA::FitnessChromosome> fitness; int fitsum = 0; for (int c = 0; c < chromosomes.size(); c++) { cLoopFunctions.setChromosome(chromosomes.at(c)); cSimulator.Reset(); cSimulator.Execute(); BasicGA::FitnessChromosome fitChromosome; fitChromosome.chromosome = chromosomes.at(c); fitChromosome.fitness = cLoopFunctions.getFitness(); fitsum += fitChromosome.fitness; fitness.push_back(fitChromosome); } argos::LOG << "Generation #"; argos::LOG << i; argos::LOG << " total: "; argos::LOG << fitsum; argos::LOG <<"done.\n"; // This file is created in the directory where you run ARGoS // it is always created or appended to, never overwritten, i.e. ios::app ofstream dataOutput2("iAntTagData.txt", ios::app); dataOutput2 << "Generation #"; dataOutput2 << i; dataOutput2 << " total: "; dataOutput2 << fitsum; dataOutput2 <<"done.\n"; chromosomes = ga.evolve(fitness); } /* * Dispose of ARGoS stuff */ cSimulator.Destroy(); /* All is OK */ return 0; } /****************************************/ /****************************************/ <|endoftext|>
<commit_before><commit_msg>Changed the pseudorapidity interval to +/-0.6<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2021 The Orbit 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 "MoveFilesToDocuments/MoveFilesToDocuments.h" #include <QObject> #include <QString> #include <thread> #include "MoveFilesDialog.h" #include "MoveFilesProcess.h" #include "OrbitBase/File.h" #include "Path.h" #include "absl/strings/str_format.h" namespace orbit_move_files_to_documents { static bool IsDirectoryEmpty(const std::filesystem::path& directory) { auto exists_or_error = orbit_base::FileExists(directory); if (exists_or_error.has_error()) { ERROR("Unable to check for existence of \"%s\": %s", directory.string(), exists_or_error.error().message()); return false; } if (!exists_or_error.value()) { return true; } auto file_list_or_error = orbit_base::ListFilesInDirectory(directory); if (file_list_or_error.has_error()) { ERROR("Unable to list directory \"%s\": %s", directory.string(), file_list_or_error.error().message()); return false; } return file_list_or_error.value().empty(); } void TryMoveSavedDataLocationIfNeeded() { if (IsDirectoryEmpty(orbit_core::GetPresetDirPriorTo1_66()) && IsDirectoryEmpty(orbit_core::GetCaptureDirPriorTo1_66())) { return; } std::thread::id main_thread_id = std::this_thread::get_id(); MoveFilesDialog dialog; MoveFilesProcess process; QObject::connect(&process, &MoveFilesProcess::generalError, &dialog, [&dialog, main_thread_id](const QString& error_message) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat("Error: %s", error_message.toStdString())); }); QObject::connect( &process, &MoveFilesProcess::moveDirectoryStarted, &dialog, [&dialog, main_thread_id](const QString& from_dir_path, const QString& to_dir_path, quint64 number_of_files) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat(R"(Moving %d files from "%s" to "%s"...)", number_of_files, from_dir_path.toStdString(), to_dir_path.toStdString())); }); QObject::connect(&process, &MoveFilesProcess::moveDirectoryDone, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Done.\n"); }); QObject::connect( &process, &MoveFilesProcess::moveFileStarted, &dialog, [&dialog, main_thread_id](const QString& from_path) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat(" Moving \"%s\"...", from_path.toStdString())); }); QObject::connect(&process, &MoveFilesProcess::moveFileDone, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(" Done."); }); QObject::connect(&process, &MoveFilesProcess::processFinished, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Finished."); dialog.OnMoveFinished(); }); QObject::connect(&process, &MoveFilesProcess::processInterrupted, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Interrupted."); dialog.OnMoveInterrupted(); }); // Intentionally use the version of `QObject::connect` with three arguments, so that // `MoveFilesProcess::RequestInterruption` is called asynchronously to `MoveFilesProcess::Run`. // Otherwise, `MoveFilesProcess::RequestInterruption` would be queued on `MoveFilesProcess`, which // would cause `MoveFilesProcess::RequestInterruption` to be executed only after // `MoveFilesProcess::Run` has completed. QObject::connect(&dialog, &MoveFilesDialog::interruptionRequested, [&process]() { process.RequestInterruption(); }); process.Start(); dialog.exec(); } } // namespace orbit_move_files_to_documents <commit_msg>Add ORBIT_DONT_MOVE_FROM_APPDATA env var to avoid moving from %APPDATA%<commit_after>// Copyright (c) 2021 The Orbit 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 "MoveFilesToDocuments/MoveFilesToDocuments.h" #include <QObject> #include <QString> #include <thread> #include "MoveFilesDialog.h" #include "MoveFilesProcess.h" #include "OrbitBase/File.h" #include "Path.h" #include "absl/strings/ascii.h" #include "absl/strings/str_format.h" namespace orbit_move_files_to_documents { static bool IsDirectoryEmpty(const std::filesystem::path& directory) { auto exists_or_error = orbit_base::FileExists(directory); if (exists_or_error.has_error()) { ERROR("Unable to check for existence of \"%s\": %s", directory.string(), exists_or_error.error().message()); return false; } if (!exists_or_error.value()) { return true; } auto file_list_or_error = orbit_base::ListFilesInDirectory(directory); if (file_list_or_error.has_error()) { ERROR("Unable to list directory \"%s\": %s", directory.string(), file_list_or_error.error().message()); return false; } return file_list_or_error.value().empty(); } void TryMoveSavedDataLocationIfNeeded() { constexpr const char* kEnvDontMoveData = "ORBIT_DONT_MOVE_FROM_APPDATA"; if (char* value = std::getenv(kEnvDontMoveData); value != nullptr && value != std::string{"0"} && absl::AsciiStrToLower(value) != "false") { return; } if (IsDirectoryEmpty(orbit_core::GetPresetDirPriorTo1_66()) && IsDirectoryEmpty(orbit_core::GetCaptureDirPriorTo1_66())) { return; } std::thread::id main_thread_id = std::this_thread::get_id(); MoveFilesDialog dialog; MoveFilesProcess process; QObject::connect(&process, &MoveFilesProcess::generalError, &dialog, [&dialog, main_thread_id](const QString& error_message) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat("Error: %s", error_message.toStdString())); }); QObject::connect( &process, &MoveFilesProcess::moveDirectoryStarted, &dialog, [&dialog, main_thread_id](const QString& from_dir_path, const QString& to_dir_path, quint64 number_of_files) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat(R"(Moving %d files from "%s" to "%s"...)", number_of_files, from_dir_path.toStdString(), to_dir_path.toStdString())); }); QObject::connect(&process, &MoveFilesProcess::moveDirectoryDone, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Done.\n"); }); QObject::connect( &process, &MoveFilesProcess::moveFileStarted, &dialog, [&dialog, main_thread_id](const QString& from_path) { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(absl::StrFormat(" Moving \"%s\"...", from_path.toStdString())); }); QObject::connect(&process, &MoveFilesProcess::moveFileDone, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText(" Done."); }); QObject::connect(&process, &MoveFilesProcess::processFinished, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Finished."); dialog.OnMoveFinished(); }); QObject::connect(&process, &MoveFilesProcess::processInterrupted, &dialog, [&dialog, main_thread_id]() { CHECK(main_thread_id == std::this_thread::get_id()); dialog.AddText("Interrupted."); dialog.OnMoveInterrupted(); }); // Intentionally use the version of `QObject::connect` with three arguments, so that // `MoveFilesProcess::RequestInterruption` is called asynchronously to `MoveFilesProcess::Run`. // Otherwise, `MoveFilesProcess::RequestInterruption` would be queued on `MoveFilesProcess`, which // would cause `MoveFilesProcess::RequestInterruption` to be executed only after // `MoveFilesProcess::Run` has completed. QObject::connect(&dialog, &MoveFilesDialog::interruptionRequested, [&process]() { process.RequestInterruption(); }); process.Start(); dialog.exec(); } } // namespace orbit_move_files_to_documents <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/tile/tileprovidermanager.h> #include <modules/globebrowsing/tile/tileproviderfactory.h> #include <ghoul/logging/logmanager.h> #include "cpl_minixml.h" namespace { const std::string _loggerCat = "TileProviderManager"; } namespace openspace { ThreadPool TileProviderManager::tileRequestThreadPool(1); TileProviderManager::TileProviderManager( const ghoul::Dictionary& textureCategoriesDictionary, const ghoul::Dictionary& textureInitDictionary){ // Create all the categories of tile providers for (size_t i = 0; i < textureCategoriesDictionary.size(); i++) { ghoul::Dictionary texturesDict = textureCategoriesDictionary.value<ghoul::Dictionary>( LayeredTextures::TEXTURE_CATEGORY_NAMES[i]); ghoul_assert(texturesDict.size() <= LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY, "Too many textures! Number of textures per category must be less than or equal to " << LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY); TileProviderInitData initData; if (i == LayeredTextures::ColorTextures || i == LayeredTextures::NightTextures || i == LayeredTextures::WaterMasks || i == LayeredTextures::GrayScaleOverlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("ColorTextureMinimumSize"); } else if (i == LayeredTextures::Overlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("OverlayMinimumSize"); } else if (i == LayeredTextures::HeightMaps || i == LayeredTextures::HeightMapOverlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("HeightMapMinimumSize"); } else { initData.minimumPixelSize = 512; } initData.threads = 1; initData.cacheSize = 500; initData.framesUntilRequestQueueFlush = 60; initData.preprocessTiles = i == LayeredTextures::HeightMaps || i == LayeredTextures::HeightMapOverlays; // Only preprocess height maps. initTexures( _layerCategories[i], texturesDict, initData); // init level blending to be true levelBlendingEnabled[i] = true; } } TileProviderManager::~TileProviderManager() { } void TileProviderManager::initTexures(std::vector<TileProviderWithName>& dest, const ghoul::Dictionary& texturesDict, const TileProviderInitData& initData) { // Create TileProviders for all textures within this category for (size_t i = 0; i < texturesDict.size(); i++) { std::string name, path; std::string dictKey = std::to_string(i + 1); ghoul::Dictionary texDict = texturesDict.value<ghoul::Dictionary>(dictKey); texDict.getValue("Name", name); texDict.getValue("FilePath", path); std::string type = "LRUCaching"; // if type is unspecified texDict.getValue("Type", type); std::shared_ptr<TileProvider> tileProvider = TileProviderFactory::ref()->create(type, path, initData); if (tileProvider == nullptr) { continue; } bool enabled = false; // defaults to false if unspecified texDict.getValue("Enabled", enabled); dest.push_back({ name, tileProvider, enabled }); } } TileProviderManager::LayerCategory& TileProviderManager::getLayerCategory(LayeredTextures::TextureCategory category) { return _layerCategories[category]; } void TileProviderManager::update() { for (auto layerCategory : _layerCategories) { for (auto tileProviderWithName : layerCategory) { if (tileProviderWithName.isActive) { tileProviderWithName.tileProvider->update(); } } } } const std::vector<std::shared_ptr<TileProvider> > TileProviderManager::getActivatedLayerCategory( LayeredTextures::TextureCategory textureCategory) { std::vector<std::shared_ptr<TileProvider> > tileProviders; for (auto tileProviderWithName : _layerCategories[textureCategory]) { if (tileProviderWithName.isActive) { tileProviders.push_back(tileProviderWithName.tileProvider); } } return tileProviders; } } // namespace openspace <commit_msg>Increase default tile provider cache size<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/tile/tileprovidermanager.h> #include <modules/globebrowsing/tile/tileproviderfactory.h> #include <ghoul/logging/logmanager.h> #include "cpl_minixml.h" namespace { const std::string _loggerCat = "TileProviderManager"; } namespace openspace { ThreadPool TileProviderManager::tileRequestThreadPool(1); TileProviderManager::TileProviderManager( const ghoul::Dictionary& textureCategoriesDictionary, const ghoul::Dictionary& textureInitDictionary){ // Create all the categories of tile providers for (size_t i = 0; i < textureCategoriesDictionary.size(); i++) { ghoul::Dictionary texturesDict = textureCategoriesDictionary.value<ghoul::Dictionary>( LayeredTextures::TEXTURE_CATEGORY_NAMES[i]); ghoul_assert(texturesDict.size() <= LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY, "Too many textures! Number of textures per category must be less than or equal to " << LayeredTextures::MAX_NUM_TEXTURES_PER_CATEGORY); TileProviderInitData initData; if (i == LayeredTextures::ColorTextures || i == LayeredTextures::NightTextures || i == LayeredTextures::WaterMasks || i == LayeredTextures::GrayScaleOverlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("ColorTextureMinimumSize"); } else if (i == LayeredTextures::Overlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("OverlayMinimumSize"); } else if (i == LayeredTextures::HeightMaps || i == LayeredTextures::HeightMapOverlays) { initData.minimumPixelSize = textureInitDictionary.value<double>("HeightMapMinimumSize"); } else { initData.minimumPixelSize = 512; } initData.threads = 1; initData.cacheSize = 5000; initData.framesUntilRequestQueueFlush = 60; initData.preprocessTiles = i == LayeredTextures::HeightMaps || i == LayeredTextures::HeightMapOverlays; // Only preprocess height maps. initTexures( _layerCategories[i], texturesDict, initData); // init level blending to be true levelBlendingEnabled[i] = true; } } TileProviderManager::~TileProviderManager() { } void TileProviderManager::initTexures(std::vector<TileProviderWithName>& dest, const ghoul::Dictionary& texturesDict, const TileProviderInitData& initData) { // Create TileProviders for all textures within this category for (size_t i = 0; i < texturesDict.size(); i++) { std::string name, path; std::string dictKey = std::to_string(i + 1); ghoul::Dictionary texDict = texturesDict.value<ghoul::Dictionary>(dictKey); texDict.getValue("Name", name); texDict.getValue("FilePath", path); std::string type = "LRUCaching"; // if type is unspecified texDict.getValue("Type", type); std::shared_ptr<TileProvider> tileProvider = TileProviderFactory::ref()->create(type, path, initData); if (tileProvider == nullptr) { continue; } bool enabled = false; // defaults to false if unspecified texDict.getValue("Enabled", enabled); dest.push_back({ name, tileProvider, enabled }); } } TileProviderManager::LayerCategory& TileProviderManager::getLayerCategory(LayeredTextures::TextureCategory category) { return _layerCategories[category]; } void TileProviderManager::update() { for (auto layerCategory : _layerCategories) { for (auto tileProviderWithName : layerCategory) { if (tileProviderWithName.isActive) { tileProviderWithName.tileProvider->update(); } } } } const std::vector<std::shared_ptr<TileProvider> > TileProviderManager::getActivatedLayerCategory( LayeredTextures::TextureCategory textureCategory) { std::vector<std::shared_ptr<TileProvider> > tileProviders; for (auto tileProviderWithName : _layerCategories[textureCategory]) { if (tileProviderWithName.isActive) { tileProviders.push_back(tileProviderWithName.tileProvider); } } return tileProviders; } } // namespace openspace <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #define SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #include <sofa/component/mapping/IdentityMapping.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/core/Mapping.inl> namespace sofa { namespace component { namespace mapping { template<class T1, class T2> static inline void eq(T1& dest, const T2& src) { dest = src; } template<class T1, class T2> static inline void peq(T1& dest, const T2& src) { dest += src; } // float <-> double (to remove warnings) //template<> static inline void eq(float& dest, const double& src) { dest = (float)src; } //template<> static inline void peq(float& dest, const double& src) { dest += (float)src; } // Vec <-> Vec template<int N1, int N2, class T1, class T2> static inline void eq(defaulttype::Vec<N1,T1>& dest, const defaulttype::Vec<N2,T2>& src) { dest = src; } template<int N1, int N2, class T1, class T2> static inline void peq(defaulttype::Vec<N1,T1>& dest, const defaulttype::Vec<N2,T2>& src) { for (unsigned int i=0; i<(N1>N2?N2:N1); i++) dest[i] += (T1)src[i]; } // RigidDeriv <-> RigidDeriv template<int N, class T1, class T2> static inline void eq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest.getVCenter() = src.getVCenter(); dest.getVOrientation() = (typename defaulttype::RigidDeriv<N,T1>::Rot)src.getVOrientation(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest.getVCenter() += src.getVCenter(); dest.getVOrientation() += (typename defaulttype::RigidDeriv<N,T1>::Rot)src.getVOrientation(); } // RigidCoord <-> RigidCoord template<int N, class T1, class T2> static inline void eq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest.getCenter() = src.getCenter(); dest.getOrientation() = (typename defaulttype::RigidCoord<N,T1>::Rot)src.getOrientation(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest.getCenter() += src.getCenter(); dest.getOrientation() += src.getOrientation(); } // RigidDeriv <-> Vec template<int N, class T1, class T2> static inline void eq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest = src.getVCenter(); } template<int N, class T1, class T2> static inline void peq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest += src.getVCenter(); } template<int N, class T1, class T2> static inline void eq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getVCenter() = src; //dest.getVOrientation() = defaulttype::RigidDeriv<N,T1>::Rot(); //.clear(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getVCenter() += src; } // RigidCoord <-> Vec template<int N, class T1, class T2> static inline void eq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest = src.getCenter(); } template<int N, class T1, class T2> static inline void peq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest += src.getCenter(); } template<int N, class T1, class T2> static inline void eq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getCenter() = src; //dest.getOrientation() = defaulttype::RigidCoord<N,T1>::Rot(); //.clear(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getCenter() += src; } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::init() { if ((stateFrom = dynamic_cast< core::behavior::BaseMechanicalState *>(this->fromModel.get()))) maskFrom = &stateFrom->forceMask; if ((stateTo = dynamic_cast< core::behavior::BaseMechanicalState *>(this->toModel.get()))) maskTo = &stateTo->forceMask; Inherit::init(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::apply(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<VecCoord>& dOut, const Data<InVecCoord>& dIn) { helper::WriteAccessor< Data<VecCoord> > out = dOut; helper::ReadAccessor< Data<InVecCoord> > in = dIn; out.resize(in.size()); for(unsigned int i=0; i<out.size(); i++) { eq(out[i], in[i]); } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJ(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<VecDeriv>& dOut, const Data<InVecDeriv>& dIn) { helper::WriteAccessor< Data<VecDeriv> > out = dOut; helper::ReadAccessor< Data<InVecDeriv> > in = dIn; out.resize(in.size()); if ( !(maskTo->isInUse()) ) { for(unsigned int i=0; i<out.size(); i++) { eq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); eq(out[i], in[i]); } } } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<InVecDeriv>& dOut, const Data<VecDeriv>& dIn) { helper::WriteAccessor< Data<InVecDeriv> > out = dOut; helper::ReadAccessor< Data<VecDeriv> > in = dIn; if ( !(maskTo->isInUse()) ) { maskFrom->setInUse(false); for(unsigned int i=0; i<in.size(); i++) { peq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); peq(out[i], in[i]); maskFrom->insertEntry(i); } } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::ConstraintParams * /*cparams*/ /* PARAMS FIRST */, Data<InMatrixDeriv>& dOut, const Data<MatrixDeriv>& dIn) { InMatrixDeriv& out = *dOut.beginEdit(); const MatrixDeriv& in = dIn.getValue(); typename Out::MatrixDeriv::RowConstIterator rowItEnd = in.end(); for (typename Out::MatrixDeriv::RowConstIterator rowIt = in.begin(); rowIt != rowItEnd; ++rowIt) { typename Out::MatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename Out::MatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // Creates a constraints if the input constraint is not empty. if (colIt != colItEnd) { typename In::MatrixDeriv::RowIterator o = out.writeLine(rowIt.index()); while (colIt != colItEnd) { InDeriv data; eq(data, colIt.val()); o.addCol(colIt.index(), data); ++colIt; } } } dOut.endEdit(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::handleTopologyChange() { if ( stateTo && stateFrom && stateTo->getSize() != stateFrom->getSize()) this->init(); } template <class TIn, class TOut> const sofa::defaulttype::BaseMatrix* IdentityMapping<TIn, TOut>::getJ() { const unsigned int outStateSize = this->toModel->getX()->size(); const unsigned int inStateSize = this->fromModel->getX()->size(); assert(outStateSize == inStateSize); if (matrixJ.get() == 0 || updateJ) { updateJ = false; if (matrixJ.get() == 0 || matrixJ->rowBSize() != outStateSize || matrixJ->colBSize() != inStateSize) { matrixJ.reset(new MatrixType(outStateSize * NOut, inStateSize * NIn)); } else { matrixJ->clear(); } bool isMaskInUse = maskTo->isInUse(); typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage& indices = maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it = indices.begin(); for(unsigned i = 0; i < outStateSize && !(isMaskInUse && it == indices.end()); i++) { if (isMaskInUse) { if(i != *it) { continue; } ++it; } MBloc& block = *matrixJ->wbloc(i, i, true); IdentityMappingMatrixHelper<NOut, NIn, Real>::setMatrix(block); } } return matrixJ.get(); } template<int N, int M, class Real> struct IdentityMappingMatrixHelper { template <class Matrix> static void setMatrix(Matrix& mat) { for(int r = 0; r < N; ++r) { for(int c = 0; c < M; ++c) { mat[r][c] = (Real) 0; } if( r<M ) mat[r][r] = (Real) 1.0; } } }; #ifdef SOFA_HAVE_EIGEN2 template <class TIn, class TOut> const typename IdentityMapping<TIn, TOut>::js_type* IdentityMapping<TIn, TOut>::getJs() { if( !eigen.compressedMatrix.nonZeros() || updateJ ) { updateJ = false; const unsigned rowsBlock = this->toModel->getSize(); assert( rowsBlock == (unsigned)this->fromModel->getSize()/*colsBlock*/ ); const unsigned rows = rowsBlock * NOut; const unsigned cols = rowsBlock * NIn; eigen.compressedMatrix.resize( rows, cols ); eigen.compressedMatrix.setZero(); eigen.compressedMatrix.reserve( rows ); for( unsigned i = 0; i < rowsBlock; ++i) { for( unsigned j = 0; j < NOut; ++j) { eigen.compressedMatrix.startVec( i*NOut+j ); eigen.compressedMatrix.insertBack( i*NOut+j, i*NIn+j ) = 1.0; } } eigen.compressedMatrix.finalize(); } js.resize( 1 ); js[0] = &eigen; return &js; } #endif } // namespace mapping } // namespace component } // namespace sofa #endif <commit_msg>r11003/sofa : FIX: buggy IdentityMapping getJs() for Nout > Nin<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #define SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #include <sofa/component/mapping/IdentityMapping.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/core/Mapping.inl> namespace sofa { namespace component { namespace mapping { template<class T1, class T2> static inline void eq(T1& dest, const T2& src) { dest = src; } template<class T1, class T2> static inline void peq(T1& dest, const T2& src) { dest += src; } // float <-> double (to remove warnings) //template<> static inline void eq(float& dest, const double& src) { dest = (float)src; } //template<> static inline void peq(float& dest, const double& src) { dest += (float)src; } // Vec <-> Vec template<int N1, int N2, class T1, class T2> static inline void eq(defaulttype::Vec<N1,T1>& dest, const defaulttype::Vec<N2,T2>& src) { dest = src; } template<int N1, int N2, class T1, class T2> static inline void peq(defaulttype::Vec<N1,T1>& dest, const defaulttype::Vec<N2,T2>& src) { for (unsigned int i=0; i<(N1>N2?N2:N1); i++) dest[i] += (T1)src[i]; } // RigidDeriv <-> RigidDeriv template<int N, class T1, class T2> static inline void eq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest.getVCenter() = src.getVCenter(); dest.getVOrientation() = (typename defaulttype::RigidDeriv<N,T1>::Rot)src.getVOrientation(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest.getVCenter() += src.getVCenter(); dest.getVOrientation() += (typename defaulttype::RigidDeriv<N,T1>::Rot)src.getVOrientation(); } // RigidCoord <-> RigidCoord template<int N, class T1, class T2> static inline void eq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest.getCenter() = src.getCenter(); dest.getOrientation() = (typename defaulttype::RigidCoord<N,T1>::Rot)src.getOrientation(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest.getCenter() += src.getCenter(); dest.getOrientation() += src.getOrientation(); } // RigidDeriv <-> Vec template<int N, class T1, class T2> static inline void eq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest = src.getVCenter(); } template<int N, class T1, class T2> static inline void peq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidDeriv<N,T2>& src) { dest += src.getVCenter(); } template<int N, class T1, class T2> static inline void eq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getVCenter() = src; //dest.getVOrientation() = defaulttype::RigidDeriv<N,T1>::Rot(); //.clear(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidDeriv<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getVCenter() += src; } // RigidCoord <-> Vec template<int N, class T1, class T2> static inline void eq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest = src.getCenter(); } template<int N, class T1, class T2> static inline void peq(defaulttype::Vec<N,T1>& dest, const defaulttype::RigidCoord<N,T2>& src) { dest += src.getCenter(); } template<int N, class T1, class T2> static inline void eq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getCenter() = src; //dest.getOrientation() = defaulttype::RigidCoord<N,T1>::Rot(); //.clear(); } template<int N, class T1, class T2> static inline void peq(defaulttype::RigidCoord<N,T1>& dest, const defaulttype::Vec<N,T2>& src) { dest.getCenter() += src; } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::init() { if ((stateFrom = dynamic_cast< core::behavior::BaseMechanicalState *>(this->fromModel.get()))) maskFrom = &stateFrom->forceMask; if ((stateTo = dynamic_cast< core::behavior::BaseMechanicalState *>(this->toModel.get()))) maskTo = &stateTo->forceMask; Inherit::init(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::apply(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<VecCoord>& dOut, const Data<InVecCoord>& dIn) { helper::WriteAccessor< Data<VecCoord> > out = dOut; helper::ReadAccessor< Data<InVecCoord> > in = dIn; out.resize(in.size()); for(unsigned int i=0; i<out.size(); i++) { eq(out[i], in[i]); } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJ(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<VecDeriv>& dOut, const Data<InVecDeriv>& dIn) { helper::WriteAccessor< Data<VecDeriv> > out = dOut; helper::ReadAccessor< Data<InVecDeriv> > in = dIn; out.resize(in.size()); if ( !(maskTo->isInUse()) ) { for(unsigned int i=0; i<out.size(); i++) { eq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); eq(out[i], in[i]); } } } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::MechanicalParams * /*mparams*/ /* PARAMS FIRST */, Data<InVecDeriv>& dOut, const Data<VecDeriv>& dIn) { helper::WriteAccessor< Data<InVecDeriv> > out = dOut; helper::ReadAccessor< Data<VecDeriv> > in = dIn; if ( !(maskTo->isInUse()) ) { maskFrom->setInUse(false); for(unsigned int i=0; i<in.size(); i++) { peq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); peq(out[i], in[i]); maskFrom->insertEntry(i); } } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::ConstraintParams * /*cparams*/ /* PARAMS FIRST */, Data<InMatrixDeriv>& dOut, const Data<MatrixDeriv>& dIn) { InMatrixDeriv& out = *dOut.beginEdit(); const MatrixDeriv& in = dIn.getValue(); typename Out::MatrixDeriv::RowConstIterator rowItEnd = in.end(); for (typename Out::MatrixDeriv::RowConstIterator rowIt = in.begin(); rowIt != rowItEnd; ++rowIt) { typename Out::MatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename Out::MatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // Creates a constraints if the input constraint is not empty. if (colIt != colItEnd) { typename In::MatrixDeriv::RowIterator o = out.writeLine(rowIt.index()); while (colIt != colItEnd) { InDeriv data; eq(data, colIt.val()); o.addCol(colIt.index(), data); ++colIt; } } } dOut.endEdit(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::handleTopologyChange() { if ( stateTo && stateFrom && stateTo->getSize() != stateFrom->getSize()) this->init(); } template <class TIn, class TOut> const sofa::defaulttype::BaseMatrix* IdentityMapping<TIn, TOut>::getJ() { const unsigned int outStateSize = this->toModel->getX()->size(); const unsigned int inStateSize = this->fromModel->getX()->size(); assert(outStateSize == inStateSize); if (matrixJ.get() == 0 || updateJ) { updateJ = false; if (matrixJ.get() == 0 || matrixJ->rowBSize() != outStateSize || matrixJ->colBSize() != inStateSize) { matrixJ.reset(new MatrixType(outStateSize * NOut, inStateSize * NIn)); } else { matrixJ->clear(); } bool isMaskInUse = maskTo->isInUse(); typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage& indices = maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it = indices.begin(); for(unsigned i = 0; i < outStateSize && !(isMaskInUse && it == indices.end()); i++) { if (isMaskInUse) { if(i != *it) { continue; } ++it; } MBloc& block = *matrixJ->wbloc(i, i, true); IdentityMappingMatrixHelper<NOut, NIn, Real>::setMatrix(block); } } return matrixJ.get(); } template<int N, int M, class Real> struct IdentityMappingMatrixHelper { template <class Matrix> static void setMatrix(Matrix& mat) { for(int r = 0; r < N; ++r) { for(int c = 0; c < M; ++c) { mat[r][c] = (Real) 0; } if( r<M ) mat[r][r] = (Real) 1.0; } } }; #ifdef SOFA_HAVE_EIGEN2 template <class TIn, class TOut> const typename IdentityMapping<TIn, TOut>::js_type* IdentityMapping<TIn, TOut>::getJs() { if( !eigen.compressedMatrix.nonZeros() || updateJ ) { updateJ = false; assert( this->fromModel->getSize() == this->toModel->getSize()); const unsigned n = this->fromModel->getSize(); // each block (input i, output j) has only its top-left // principal submatrix filled with identity const unsigned rows = n * NOut; const unsigned cols = n * NIn; eigen.compressedMatrix.resize( rows, cols ); eigen.compressedMatrix.setZero(); eigen.compressedMatrix.reserve( rows ); for(unsigned i = 0 ; i < n; ++i) { for(unsigned r = 0; r < std::min<unsigned>(NIn, NOut); ++r) { const unsigned row = NOut * i + r; eigen.compressedMatrix.startVec( row ); const unsigned col = NIn * i + r; eigen.compressedMatrix.insertBack( row, col ) = 1; } } eigen.compressedMatrix.finalize(); } // std::cout << eigen.compressedMatrix << std::endl; js.resize( 1 ); js[0] = &eigen; return &js; } #endif } // namespace mapping } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before>#include <Game/Field/UnderGround/cBlock.h> #include <cinder/gl/gl.h> using namespace ci; namespace Game { namespace Field { namespace UnderGround { vec3 vertex0[] = { vec3(-0.50000, -0.50000, 0.50000), vec3(-0.50000, 0.50000, 0.50000), vec3(0.50000, 0.50000, 0.50000), vec3(0.50000, -0.50000, 0.50000), }; vec3 vertex1[] = { vec3(0.50000, -0.50000, -0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(-0.50000, -0.50000, -0.50000), }; vec3 vertex2[] = { vec3(-0.50000, -0.50000, -0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(-0.50000, 0.50000, 0.50000), vec3(-0.50000, -0.50000, 0.50000), }; vec3 vertex3[] = { vec3(0.50000, -0.50000, 0.50000), vec3(0.50000, 0.50000, 0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(0.50000, -0.50000, -0.50000), }; vec3 vertex4[] = { vec3(-0.50000, 0.50000, 0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(0.50000, 0.50000, 0.50000), }; vec3 vertex5[] = { vec3(-0.50000, -0.50000, -0.50000), vec3(-0.50000, -0.50000, 0.50000), vec3(0.50000, -0.50000, 0.50000), vec3(0.50000, -0.50000, -0.50000), }; std::vector<uint32_t> getIndices(int side_size) { std::vector<GLuint> indices = std::vector<GLuint>(side_size * 6); int c = 0; for (size_t i = 0; i < side_size * 4; i += 4) { indices[c++] = i; indices[c++] = i + 2; indices[c++] = i + 1; indices[c++] = i + 2; indices[c++] = i; indices[c++] = i + 3; } return indices; } std::vector<vec2> getUv(int side_num) { std::vector<vec2> uv = std::vector<vec2>(side_num * 4); int c = 0; for (size_t i = 0; i < side_num; i++) { uv[c++] = vec2(0.00000, 1.00000); uv[c++] = vec2(0.00000, 0.00000); uv[c++] = vec2(1.00000, 0.00000); uv[c++] = vec2(1.00000, 1.00000); } return uv; } vec3* getVertices(int side_num) { switch (side_num) { case 0: return vertex0; case 1: return vertex1; case 2: return vertex2; case 3: return vertex3; case 4: return vertex4; case 5: return vertex5; } } cBlock::cBlock(const ci::vec3 position, const float scale) { mPosition = position; mScale = scale; mIsActive = true; } cBlock::~cBlock() { } void cBlock::update() { } void cBlock::draw() { if (mIsActive == false) return; gl::pushModelView(); gl::translate(mPosition); gl::scale(vec3(mScale)); gl::drawCube(vec3(0), vec3(1)); gl::popModelView(); } void cBlock::drawMesh() { if (mIsActive == false) return; gl::pushModelView(); gl::translate(mPosition); gl::scale(vec3(mScale)); gl::draw(mVboMesh); gl::popModelView(); } void cBlock::setupDrawSide(std::vector<int>* draw_side) { for (size_t i = 0; i < draw_side->size(); i++) { vec3* temp = getVertices((*draw_side)[i]); for (size_t v = 0; v < 12; v++) mVertices.emplace_back(temp[v]); } mIndices = getIndices(draw_side->size()); mUv = getUv(draw_side->size()); // bV for (size_t i = 0; i < mVertices.size(); i++) mMesh.appendTriangle(mVertices[i].x, mVertices[i].y, mVertices[i].z); mMesh.appendIndices(&mIndices[0], mIndices.size()); mMesh.appendTexCoords0(&mUv[0], mUv.size()); mVboMesh = gl::VboMesh::create(mMesh); } void cBlock::toBreak() { } } } } <commit_msg>メッシュの未定義エラーを直しました<commit_after>#include <Game/Field/UnderGround/cBlock.h> #include <cinder/gl/gl.h> using namespace ci; namespace Game { namespace Field { namespace UnderGround { vec3 vertex0[] = { vec3(-0.50000, -0.50000, 0.50000), vec3(-0.50000, 0.50000, 0.50000), vec3(0.50000, 0.50000, 0.50000), vec3(0.50000, -0.50000, 0.50000), }; vec3 vertex1[] = { vec3(0.50000, -0.50000, -0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(-0.50000, -0.50000, -0.50000), }; vec3 vertex2[] = { vec3(-0.50000, -0.50000, -0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(-0.50000, 0.50000, 0.50000), vec3(-0.50000, -0.50000, 0.50000), }; vec3 vertex3[] = { vec3(0.50000, -0.50000, 0.50000), vec3(0.50000, 0.50000, 0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(0.50000, -0.50000, -0.50000), }; vec3 vertex4[] = { vec3(-0.50000, 0.50000, 0.50000), vec3(-0.50000, 0.50000, -0.50000), vec3(0.50000, 0.50000, -0.50000), vec3(0.50000, 0.50000, 0.50000), }; vec3 vertex5[] = { vec3(-0.50000, -0.50000, -0.50000), vec3(-0.50000, -0.50000, 0.50000), vec3(0.50000, -0.50000, 0.50000), vec3(0.50000, -0.50000, -0.50000), }; std::vector<uint32_t> getIndices(int side_size) { std::vector<GLuint> indices = std::vector<GLuint>(side_size * 6); int c = 0; for (size_t i = 0; i < side_size * 4; i += 4) { indices[c++] = i; indices[c++] = i + 2; indices[c++] = i + 1; indices[c++] = i + 2; indices[c++] = i; indices[c++] = i + 3; } return indices; } std::vector<vec2> getUv(int side_num) { std::vector<vec2> uv = std::vector<vec2>(side_num * 4); int c = 0; for (size_t i = 0; i < side_num; i++) { uv[c++] = vec2(0.00000, 1.00000); uv[c++] = vec2(0.00000, 0.00000); uv[c++] = vec2(1.00000, 0.00000); uv[c++] = vec2(1.00000, 1.00000); } return uv; } vec3* getVertices(int side_num) { switch (side_num) { case 0: return vertex0; case 1: return vertex1; case 2: return vertex2; case 3: return vertex3; case 4: return vertex4; case 5: return vertex5; } } cBlock::cBlock(const ci::vec3 position, const float scale) { mPosition = position; mScale = scale; mIsActive = true; } cBlock::~cBlock() { } void cBlock::update() { } void cBlock::draw() { if (mIsActive == false) return; gl::pushModelView(); gl::translate(mPosition); gl::scale(vec3(mScale)); gl::drawCube(vec3(0), vec3(1)); gl::popModelView(); } void cBlock::drawMesh() { if (mIsActive == false) return; gl::pushModelView(); gl::translate(mPosition); gl::scale(vec3(mScale)); gl::draw(mVboMesh); gl::popModelView(); } void cBlock::setupDrawSide(std::vector<int>* draw_side) { for (size_t i = 0; i < draw_side->size(); i++) { vec3* temp = getVertices((*draw_side)[i]); for (size_t v = 0; v < 12; v++) mVertices.emplace_back(temp[v]); } mIndices = getIndices(draw_side->size()); mUv = getUv(draw_side->size()); // bV if (mVertices.size() > 0) for (size_t i = 0; i < mVertices.size(); i++) mMesh.appendTriangle(mVertices[i].x, mVertices[i].y, mVertices[i].z); if (mIndices.size() > 0) mMesh.appendIndices(&mIndices[0], mIndices.size()); if (mUv.size() > 0) mMesh.appendTexCoords0(&mUv[0], mUv.size()); mVboMesh = gl::VboMesh::create(mMesh); } void cBlock::toBreak() { } } } } <|endoftext|>
<commit_before>#include <atlas/math/Coordinates.hpp> #include <atlas/core/Float.hpp> #include <catch2/catch.hpp> using atlas::core::areEqual; TEST_CASE("Checking Coordinate Functions", "[math]") { using namespace atlas::math; Point p1{ 1, 0, 0 }; Point p2{ 1, 1, 0 }; auto s1 = cartesianToSpherical(p1); auto s2 = cartesianToSpherical(p2); REQUIRE(areEqual(s1.x, 1.0f)); REQUIRE(areEqual(s1.y, 0.0f)); REQUIRE(areEqual(s1.z, glm::radians(90.0f))); REQUIRE(areEqual(s2.x, glm::sqrt(2.0f))); REQUIRE(areEqual(s2.y, glm::radians(45.0f))); REQUIRE(areEqual(s2.z, glm::radians(90.0f))); auto c1 = sphericalToCartesian(s1); auto c2 = sphericalToCartesian(s2); REQUIRE(areEqual(c1.x, 1.0f)); REQUIRE(areEqual(c1.y, 0.0f)); REQUIRE(areEqual(c1.z, 0.0f)); REQUIRE(areEqual(c2.x, 1.0f)); REQUIRE(areEqual(c2.y, 1.0f)); REQUIRE(areEqual(c2.z, 0.0f)); }<commit_msg>[brief] Finishes tests for Coordinates header.<commit_after>#include <atlas/math/Coordinates.hpp> #include <atlas/core/Float.hpp> #include <catch2/catch.hpp> using atlas::core::areEqual; TEST_CASE("Checking Spherical Functions", "[math]") { using namespace atlas::math; Point p1{ 1, 0, 0 }; Point p2{ 1, 1, 0 }; auto s1 = cartesianToSpherical(p1); auto s2 = cartesianToSpherical(p2); REQUIRE(areEqual(s1.x, 1.0f)); REQUIRE(areEqual(s1.y, 0.0f)); REQUIRE(areEqual(s1.z, glm::radians(90.0f))); REQUIRE(areEqual(s2.x, glm::sqrt(2.0f))); REQUIRE(areEqual(s2.y, glm::radians(45.0f))); REQUIRE(areEqual(s2.z, glm::radians(90.0f))); auto c1 = sphericalToCartesian(s1); auto c2 = sphericalToCartesian(s2); REQUIRE(areEqual(c1.x, 1.0f)); REQUIRE(areEqual(c1.y, 0.0f)); REQUIRE(areEqual(c1.z, glm::cos(glm::radians(90.0f)))); REQUIRE(areEqual(c2.x, 1.0f)); REQUIRE(areEqual(c2.y, 1.0f)); REQUIRE(areEqual(c2.z, glm::sqrt(2.0f) * glm::cos(glm::radians(90.0f)))); } TEST_CASE("Checking Cylindrical Functions", "[math]") { using namespace atlas::math; Point p1{ 1, 0, 0 }; Point p2{ 1, 1, 0 }; auto x1 = cartesianToCylindrical(p1); auto x2 = cartesianToCylindrical(p2); REQUIRE(areEqual(x1.x, 1.0f)); REQUIRE(areEqual(x1.y, 0.0f)); REQUIRE(areEqual(x1.z, 0.0f)); REQUIRE(areEqual(x2.x, glm::sqrt(2.0f))); REQUIRE(areEqual(x2.y, glm::radians(45.0f))); REQUIRE(areEqual(x2.z, 0.0f)); auto c1 = cylindricalToCartesian(x1); auto c2 = cylindricalToCartesian(x2); REQUIRE(areEqual(c1.x, 1.0f)); REQUIRE(areEqual(c1.y, 0.0f)); REQUIRE(areEqual(c1.z, 0.0f)); REQUIRE(areEqual(c2.x, 1.0f)); REQUIRE(areEqual(c2.y, 1.0f)); REQUIRE(areEqual(c2.z, 0.0f)); } TEST_CASE("Checking Polar Functions", "[math]") { using namespace atlas::math; Point2 p1{ 1, 0 }; Point2 p2{ 1, 1 }; auto x1 = cartesianToPolar(p1); auto x2 = cartesianToPolar(p2); REQUIRE(areEqual(x1.x, 1.0f)); REQUIRE(areEqual(x1.y, 0.0f)); REQUIRE(areEqual(x2.x, glm::sqrt(2.0f))); REQUIRE(areEqual(x2.y, glm::radians(45.0f))); auto c1 = polarToCartesian(x1); auto c2 = polarToCartesian(x2); REQUIRE(areEqual(c1.x, 1.0f)); REQUIRE(areEqual(c1.y, 0.0f)); REQUIRE(areEqual(c2.x, 1.0f)); REQUIRE(areEqual(c2.y, 1.0f)); }<|endoftext|>
<commit_before>// // Created by eele on 8-6-2015. // #include <iostream> #include <functional> #include "Controller.h" Controller::Controller() { state = State::MENU; lastState = State::GAP; //Dit doen we om de init aan te roepen bij het opstarten bool isRunning = true; SensorData sensorData; Monitor monitor(std::ref(sensorData)); ControlData controlData; BluetoothHandler bluetoothHandler(std::ref(controlData)); ServoDriver servoDriver; //ServerHandler server(std::ref(sensorData)); WalkCommand walkCommand(&servoDriver); std::cout << "Controller started!" << std::endl; while (isRunning) { switch (state) { case State::MENU : this->lastState = callCommand(state, lastState, &walkCommand); break; case State::LIMBO: break; case State::GRINDBAK: break; case State::RACE: break; case State::DANS: break; case State::GAP: break; case State::PRIK: break; case State::PAALDANS: break; case State::PAREN: break; default: std::cout << "U r a wizzart, how u get here? Bud how you leave here!??" << std::endl; break; } } } State Controller::callCommand(State currentState, State lastState, ICommand *command) { //Call the init for the current state if(currentState != lastState) { command->init(); // show new state std::cout << "State: " << stateNames[(int) state] << std::endl; } else //The init has been done lets do the run now { command->run(); } return currentState; }<commit_msg>monitor uit<commit_after>// // Created by eele on 8-6-2015. // #include <iostream> #include <functional> #include "Controller.h" Controller::Controller() { state = State::MENU; lastState = State::GAP; //Dit doen we om de init aan te roepen bij het opstarten bool isRunning = true; SensorData sensorData; //Monitor monitor(std::ref(sensorData)); ControlData controlData; BluetoothHandler bluetoothHandler(std::ref(controlData)); ServoDriver servoDriver; //ServerHandler server(std::ref(sensorData)); WalkCommand walkCommand(&servoDriver); std::cout << "Controller started!" << std::endl; while (isRunning) { switch (state) { case State::MENU : this->lastState = callCommand(state, lastState, &walkCommand); break; case State::LIMBO: break; case State::GRINDBAK: break; case State::RACE: break; case State::DANS: break; case State::GAP: break; case State::PRIK: break; case State::PAALDANS: break; case State::PAREN: break; default: std::cout << "U r a wizzart, how u get here? Bud how you leave here!??" << std::endl; break; } } } State Controller::callCommand(State currentState, State lastState, ICommand *command) { //Call the init for the current state if(currentState != lastState) { command->init(); // show new state std::cout << "State: " << stateNames[(int) state] << std::endl; } else //The init has been done lets do the run now { command->run(); } return currentState; }<|endoftext|>