text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw_base.h> #include <fclaw2d_map.h> #include <p4est_connectivity.h> #include <fclaw2d_map_query.h> #include <amr_forestclaw.H> #include <amr_utils.H> #include "no_solver_user.H" typedef struct user_options { int example; double alpha; int is_registered; } user_options_t; static void * options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt) { user_options_t* user = (user_options_t*) package; /* [user] User options */ sc_options_add_int (opt, 0, "example", &user->example, 0, "0 nomap (use [ax,bx]x[ay,by]; " \ "1 cart; 2 5-patch square [0]"); sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "Ratio of outer square to inner square [0.4]"); user->is_registered = 1; return NULL; } static fclaw_exit_type_t options_check_user (fclaw_app_t * app, void *package, void *registered) { user_options_t* user = (user_options_t*) package; if (user->example < 0 || user->example > 4) { fclaw_global_essentialf ("Option --user:example must be 0,1 or 2\n"); return FCLAW_EXIT_QUIET; } return FCLAW_NOEXIT; } static const fclaw_app_options_vtable_t options_vtable_user = { options_register_user, NULL, options_check_user, NULL }; static void register_user_options (fclaw_app_t * app, const char *configfile, user_options_t* user) { FCLAW_ASSERT (app != NULL); fclaw_app_options_register (app,"user", configfile, &options_vtable_user, user); } void run_program(fclaw_app_t* app, amr_options_t* gparms, user_options_t* user) { sc_MPI_Comm mpicomm; /* Mapped, multi-block domain */ p4est_connectivity_t *conn = NULL; fclaw2d_domain_t *domain; fclaw2d_map_context_t *cont = NULL; /* Used locally */ double pi = M_PI; double rotate[2]; mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL); rotate[0] = pi*gparms->theta/180.0; rotate[1] = pi*gparms->phi/180.0; switch (user->example) { case 0: /* Don't use a mapping. [ax,ay]x[ay,by] will be used instead */ conn = p4est_connectivity_new_unitsquare(); cont = fclaw2d_map_new_nomap (); break; case 1: /* Map unit square to disk using mapc2m_disk.f */ conn = p4est_connectivity_new_unitsquare(); cont = fclaw2d_map_new_cart (gparms->scale, gparms->shift,x rotate); break; case 2: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_fivepatch (gparms->scale,gparms->shift, rotate,user->alpha); break; case 3: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_pillowdisk (gparms->scale,gparms->shift, rotate); break; case 4: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift, rotate,user->alpha); break; default: SC_ABORT_NOT_REACHED (); } domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont); /* ---------------------------------------------------------- */ fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO); fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG); /* --------------------------------------------------------------- Set domain data. --------------------------------------------------------------- */ init_domain_data(domain); set_domain_parms(domain,gparms); /* --------------------------------------------------------------- Don't do any solve or run. This is just to test that we can compile without any solver routines. --------------------------------------------------------------- */ no_solver_linker(domain); /* --------------------------------------------------------------- Initialize and run (but with out updating anything) --------------------------------------------------------------- */ amrinit(&domain); amrrun(&domain); /* Nothing should happen */ amrreset(&domain); fclaw2d_map_destroy(cont); /* This destroys the brick as well */ } int main (int argc, char **argv) { fclaw_app_t *app; int first_arg; fclaw_exit_type_t vexit; /* Options */ sc_options_t *options; amr_options_t samr_options, *gparms = &samr_options; user_options_t suser_options, *user = &suser_options; int retval; /* Initialize application */ app = fclaw_app_new (&argc, &argv, user); options = fclaw_app_get_options (app); fclaw_options_register_general (app, "fclaw_options.ini", gparms); /* User defined options (defined above) */ register_user_options (app, "fclaw_options.ini", user); /* Read configuration file(s) */ retval = fclaw_options_read_from_file(options); vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used"); /* ------------------------------------------------------------- - Run program ------------------------------------------------------------- */ if (!retval & !vexit) { run_program(app, gparms,user); } fclaw_app_destroy (app); return 0; } <commit_msg>(no_solver) Minor fix<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw_base.h> #include <fclaw2d_map.h> #include <p4est_connectivity.h> #include <fclaw2d_map_query.h> #include <amr_forestclaw.H> #include <amr_utils.H> #include "no_solver_user.H" typedef struct user_options { int example; double alpha; int is_registered; } user_options_t; static void * options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt) { user_options_t* user = (user_options_t*) package; /* [user] User options */ sc_options_add_int (opt, 0, "example", &user->example, 0, "0 nomap (use [ax,bx]x[ay,by]; " \ "1 cart; 2 5-patch square [0]"); sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "Ratio of outer square to inner square [0.4]"); user->is_registered = 1; return NULL; } static fclaw_exit_type_t options_check_user (fclaw_app_t * app, void *package, void *registered) { user_options_t* user = (user_options_t*) package; if (user->example < 0 || user->example > 4) { fclaw_global_essentialf ("Option --user:example must be 0,1 or 2\n"); return FCLAW_EXIT_QUIET; } return FCLAW_NOEXIT; } static const fclaw_app_options_vtable_t options_vtable_user = { options_register_user, NULL, options_check_user, NULL }; static void register_user_options (fclaw_app_t * app, const char *configfile, user_options_t* user) { FCLAW_ASSERT (app != NULL); fclaw_app_options_register (app,"user", configfile, &options_vtable_user, user); } void run_program(fclaw_app_t* app, amr_options_t* gparms, user_options_t* user) { sc_MPI_Comm mpicomm; /* Mapped, multi-block domain */ p4est_connectivity_t *conn = NULL; fclaw2d_domain_t *domain; fclaw2d_map_context_t *cont = NULL; /* Used locally */ double pi = M_PI; double rotate[2]; mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL); rotate[0] = pi*gparms->theta/180.0; rotate[1] = pi*gparms->phi/180.0; switch (user->example) { case 0: /* Don't use a mapping. [ax,ay]x[ay,by] will be used instead */ conn = p4est_connectivity_new_unitsquare(); cont = fclaw2d_map_new_nomap (); break; case 1: /* Map unit square to disk using mapc2m_disk.f */ conn = p4est_connectivity_new_unitsquare(); cont = fclaw2d_map_new_cart (gparms->scale, gparms->shift, rotate); break; case 2: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_fivepatch (gparms->scale,gparms->shift, rotate,user->alpha); break; case 3: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_pillowdisk (gparms->scale,gparms->shift, rotate); break; case 4: conn = p4est_connectivity_new_disk (); cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift, rotate,user->alpha); break; default: SC_ABORT_NOT_REACHED (); } domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont); /* ---------------------------------------------------------- */ fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO); fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG); /* --------------------------------------------------------------- Set domain data. --------------------------------------------------------------- */ init_domain_data(domain); set_domain_parms(domain,gparms); /* --------------------------------------------------------------- Don't do any solve or run. This is just to test that we can compile without any solver routines. --------------------------------------------------------------- */ no_solver_linker(domain); /* --------------------------------------------------------------- Initialize and run (but with out updating anything) --------------------------------------------------------------- */ amrinit(&domain); amrrun(&domain); /* Nothing should happen */ amrreset(&domain); fclaw2d_map_destroy(cont); /* This destroys the brick as well */ } int main (int argc, char **argv) { fclaw_app_t *app; int first_arg; fclaw_exit_type_t vexit; /* Options */ sc_options_t *options; amr_options_t samr_options, *gparms = &samr_options; user_options_t suser_options, *user = &suser_options; int retval; /* Initialize application */ app = fclaw_app_new (&argc, &argv, user); options = fclaw_app_get_options (app); fclaw_options_register_general (app, "fclaw_options.ini", gparms); /* User defined options (defined above) */ register_user_options (app, "fclaw_options.ini", user); /* Read configuration file(s) */ retval = fclaw_options_read_from_file(options); vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used"); /* ------------------------------------------------------------- - Run program ------------------------------------------------------------- */ if (!retval & !vexit) { run_program(app, gparms,user); } fclaw_app_destroy (app); return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief https communication /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HttpsCommTask.h" #include <openssl/err.h> #include "Basics/logging.h" #include "Basics/socket-utils.h" #include "Basics/ssl-helper.h" #include "Basics/StringBuffer.h" #include "HttpServer/HttpsServer.h" #include "Scheduler/Scheduler.h" using namespace triagens::rest; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new task with a given socket //////////////////////////////////////////////////////////////////////////////// HttpsCommTask::HttpsCommTask (HttpsServer* server, TRI_socket_t socket, ConnectionInfo const& info, double keepAliveTimeout, SSL_CTX* ctx, int verificationMode, int (*verificationCallback)(int, X509_STORE_CTX*)) : Task("HttpsCommTask"), HttpCommTask(server, socket, info, keepAliveTimeout), _accepted(false), _readBlockedOnWrite(false), _writeBlockedOnRead(false), _tmpReadBuffer(nullptr), _ssl(nullptr), _ctx(ctx), _verificationMode(verificationMode), _verificationCallback(verificationCallback) { _tmpReadBuffer = new char[READ_BLOCK_SIZE]; } //////////////////////////////////////////////////////////////////////////////// /// @brief destructs a task //////////////////////////////////////////////////////////////////////////////// HttpsCommTask::~HttpsCommTask () { shutdownSsl(true); delete[] _tmpReadBuffer; } // ----------------------------------------------------------------------------- // --SECTION-- Task methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::setup (Scheduler* scheduler, EventLoop loop) { // setup base class bool ok = HttpCommTask::setup(scheduler, loop); if (! ok) { return false; } // build a new connection TRI_ASSERT(_ssl == nullptr); ERR_clear_error(); _ssl = SSL_new(_ctx); _connectionInfo.sslContext = _ssl; if (_ssl == nullptr) { LOG_DEBUG("cannot build new SSL connection: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; // terminate ourselves, ssl is nullptr } // enforce verification ERR_clear_error(); SSL_set_verify(_ssl, _verificationMode, _verificationCallback); // with the file descriptor ERR_clear_error(); SSL_set_fd(_ssl, (int) TRI_get_fd_or_handle_of_socket(_commSocket)); // accept might need writes _scheduler->startSocketEvents(_writeWatcher); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::handleEvent (EventToken token, EventType revents) { // try to accept the SSL connection if (! _accepted) { bool result = false; // be pessimistic if ((token == _readWatcher && (revents & EVENT_SOCKET_READ)) || (token == _writeWatcher && (revents & EVENT_SOCKET_WRITE))) { // must do the SSL handshake first result = trySSLAccept(); } if (! result) { // status is somehow invalid. we got here even though no accept was ever successful _clientClosed = true; _server->handleCommunicationFailure(this); _scheduler->destroyTask(this); } return result; } // if we blocked on write, read can be called when the socket is writeable if (_readBlockedOnWrite && token == _writeWatcher && (revents & EVENT_SOCKET_WRITE)) { _readBlockedOnWrite = false; revents &= ~EVENT_SOCKET_WRITE; revents |= EVENT_SOCKET_READ; token = _readWatcher; } // handle normal socket operation bool result = HttpCommTask::handleEvent(token, revents); // warning: if _clientClosed is true here, the task (this) is already deleted! // we might need to start listing for writes (even we only want to READ) if (result && ! _clientClosed) { if (_readBlockedOnWrite || _writeBlockedOnRead) { _scheduler->startSocketEvents(_writeWatcher); } } return result; } // ----------------------------------------------------------------------------- // --SECTION-- Socket methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::fillReadBuffer () { if (nullptr == _ssl) { _clientClosed = true; return false; } // is the handshake already done? if (! _accepted) { return false; } return trySSLRead(); } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::handleWrite () { if (nullptr == _ssl) { _clientClosed = true; return false; } // is the handshake already done? if (! _accepted) { return false; } return trySSLWrite(); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief accepts SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLAccept () { if (nullptr == _ssl) { _clientClosed = true; return false; } ERR_clear_error(); int res = SSL_accept(_ssl); // accept successful if (res == 1) { LOG_DEBUG("established SSL connection"); _accepted = true; // accept done, remove write events _scheduler->stopSocketEvents(_writeWatcher); return true; } // shutdown of connection if (res == 0) { LOG_DEBUG("SSL_accept failed: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } // maybe we need more data int err = SSL_get_error(_ssl, res); if (err == SSL_ERROR_WANT_READ) { return true; } else if (err == SSL_ERROR_WANT_WRITE) { return true; } LOG_TRACE("error in SSL handshake: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief reads from SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLRead () { _readBlockedOnWrite = false; again: ERR_clear_error(); int nr = SSL_read(_ssl, _tmpReadBuffer, READ_BLOCK_SIZE); if (nr <= 0) { int res = SSL_get_error(_ssl, nr); switch (res) { case SSL_ERROR_NONE: return true; case SSL_ERROR_SSL: LOG_DEBUG("received SSL error (bytes read %d, socket %d): %s", nr, (int) TRI_get_fd_or_handle_of_socket(_commSocket), triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; case SSL_ERROR_ZERO_RETURN: shutdownSsl(true); _clientClosed = true; return false; case SSL_ERROR_WANT_READ: // we must retry with the EXACT same parameters later return true; case SSL_ERROR_WANT_WRITE: _readBlockedOnWrite = true; return true; case SSL_ERROR_WANT_CONNECT: LOG_DEBUG("received SSL_ERROR_WANT_CONNECT"); break; case SSL_ERROR_WANT_ACCEPT: LOG_DEBUG("received SSL_ERROR_WANT_ACCEPT"); break; case SSL_ERROR_SYSCALL: if (res != 0) { LOG_DEBUG("SSL_read returned syscall error with: %s", triagens::basics::lastSSLError().c_str()); } else if (nr == 0) { LOG_DEBUG("SSL_read returned syscall error because an EOF was received"); } else { LOG_DEBUG("SSL_read return syscall error: %d: %s", (int) errno, strerror(errno)); } shutdownSsl(false); return false; default: LOG_DEBUG("received error with %d and %d: %s", res, nr, triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } } else { _readBuffer->appendText(_tmpReadBuffer, nr); // we might have more data to read // if we do not iterate again, the reading process would stop goto again; } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief writes from SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLWrite () { _writeBlockedOnRead = false; size_t len = 0; if (nullptr != _writeBuffer) { TRI_ASSERT(_writeBuffer->length() >= _writeLength); // size_t is unsigned, should never get < 0 len = _writeBuffer->length() - _writeLength; } // write buffer to SSL connection int nr = 0; if (0 < len) { ERR_clear_error(); nr = SSL_write(_ssl, _writeBuffer->begin() + _writeLength, (int) len); if (nr <= 0) { int res = SSL_get_error(_ssl, nr); switch (res) { case SSL_ERROR_NONE: return true; case SSL_ERROR_ZERO_RETURN: shutdownSsl(true); _clientClosed = true; return false; case SSL_ERROR_WANT_CONNECT: LOG_DEBUG("received SSL_ERROR_WANT_CONNECT"); break; case SSL_ERROR_WANT_ACCEPT: LOG_DEBUG("received SSL_ERROR_WANT_ACCEPT"); break; case SSL_ERROR_WANT_WRITE: // we must retry with the EXACT same parameters later return true; case SSL_ERROR_WANT_READ: _writeBlockedOnRead = true; return true; case SSL_ERROR_SYSCALL: if (res != 0) { LOG_DEBUG("SSL_write returned syscall error with: %s", triagens::basics::lastSSLError().c_str()); } else if (nr == 0) { LOG_DEBUG("SSL_write returned syscall error because an EOF was received"); } else { LOG_DEBUG("SSL_write return syscall error: %d: %s", errno, strerror(errno)); } shutdownSsl(false); return false; default: LOG_DEBUG("received error with %d and %d: %s", res, nr, triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } } else { len -= nr; } } if (len == 0) { delete _writeBuffer; _writeBuffer = nullptr; completedWriteBuffer(); } else if (nr > 0) { // nr might have been negative here _writeLength += nr; } // return immediately, everything is closed down if (_clientClosed) { return false; } // we might have a new write buffer _scheduler->sendAsync(SocketTask::_asyncWatcher); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief shuts down the SSL connection //////////////////////////////////////////////////////////////////////////////// void HttpsCommTask::shutdownSsl (bool initShutdown) { static int const SHUTDOWN_ITERATIONS = 10; if (nullptr != _ssl) { if (initShutdown) { bool ok = false; for (int i = 0; i < SHUTDOWN_ITERATIONS; ++i) { ERR_clear_error(); int res = SSL_shutdown(_ssl); if (res == 1) { ok = true; break; } if (res == -1) { int err = SSL_get_error(_ssl, res); if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) { LOG_DEBUG("received shutdown error with %d, %d: %s", res, err, triagens::basics::lastSSLError().c_str()); break; } } } if (! ok) { LOG_DEBUG("cannot complete SSL shutdown in socket %d", (int) TRI_get_fd_or_handle_of_socket(_commSocket)); } } else { ERR_clear_error(); SSL_clear(_ssl); } ERR_clear_error(); SSL_free(_ssl); // this will free bio as well _ssl = nullptr; } if (TRI_isvalidsocket(_commSocket)) { TRI_CLOSE_SOCKET(_commSocket); TRI_invalidatesocket(&_commSocket); } } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>added comment<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief https communication /// /// @file /// /// DISCLAIMER /// /// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt /// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HttpsCommTask.h" #include <openssl/err.h> #include "Basics/logging.h" #include "Basics/socket-utils.h" #include "Basics/ssl-helper.h" #include "Basics/StringBuffer.h" #include "HttpServer/HttpsServer.h" #include "Scheduler/Scheduler.h" using namespace triagens::rest; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new task with a given socket //////////////////////////////////////////////////////////////////////////////// HttpsCommTask::HttpsCommTask (HttpsServer* server, TRI_socket_t socket, ConnectionInfo const& info, double keepAliveTimeout, SSL_CTX* ctx, int verificationMode, int (*verificationCallback)(int, X509_STORE_CTX*)) : Task("HttpsCommTask"), HttpCommTask(server, socket, info, keepAliveTimeout), _accepted(false), _readBlockedOnWrite(false), _writeBlockedOnRead(false), _tmpReadBuffer(nullptr), _ssl(nullptr), _ctx(ctx), _verificationMode(verificationMode), _verificationCallback(verificationCallback) { _tmpReadBuffer = new char[READ_BLOCK_SIZE]; } //////////////////////////////////////////////////////////////////////////////// /// @brief destructs a task //////////////////////////////////////////////////////////////////////////////// HttpsCommTask::~HttpsCommTask () { shutdownSsl(true); delete[] _tmpReadBuffer; } // ----------------------------------------------------------------------------- // --SECTION-- Task methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::setup (Scheduler* scheduler, EventLoop loop) { // setup base class bool ok = HttpCommTask::setup(scheduler, loop); if (! ok) { return false; } // build a new connection TRI_ASSERT(_ssl == nullptr); ERR_clear_error(); _ssl = SSL_new(_ctx); _connectionInfo.sslContext = _ssl; if (_ssl == nullptr) { LOG_DEBUG("cannot build new SSL connection: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; // terminate ourselves, ssl is nullptr } // enforce verification ERR_clear_error(); SSL_set_verify(_ssl, _verificationMode, _verificationCallback); // with the file descriptor ERR_clear_error(); SSL_set_fd(_ssl, (int) TRI_get_fd_or_handle_of_socket(_commSocket)); // accept might need writes _scheduler->startSocketEvents(_writeWatcher); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::handleEvent (EventToken token, EventType revents) { // try to accept the SSL connection if (! _accepted) { bool result = false; // be pessimistic if ((token == _readWatcher && (revents & EVENT_SOCKET_READ)) || (token == _writeWatcher && (revents & EVENT_SOCKET_WRITE))) { // must do the SSL handshake first result = trySSLAccept(); } if (! result) { // status is somehow invalid. we got here even though no accept was ever successful _clientClosed = true; // this will remove the corresponding chunkedTask from the global list // if we would leave it in there, then the server may crash on shutdown _server->handleCommunicationFailure(this); _scheduler->destroyTask(this); } return result; } // if we blocked on write, read can be called when the socket is writeable if (_readBlockedOnWrite && token == _writeWatcher && (revents & EVENT_SOCKET_WRITE)) { _readBlockedOnWrite = false; revents &= ~EVENT_SOCKET_WRITE; revents |= EVENT_SOCKET_READ; token = _readWatcher; } // handle normal socket operation bool result = HttpCommTask::handleEvent(token, revents); // warning: if _clientClosed is true here, the task (this) is already deleted! // we might need to start listing for writes (even we only want to READ) if (result && ! _clientClosed) { if (_readBlockedOnWrite || _writeBlockedOnRead) { _scheduler->startSocketEvents(_writeWatcher); } } return result; } // ----------------------------------------------------------------------------- // --SECTION-- Socket methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::fillReadBuffer () { if (nullptr == _ssl) { _clientClosed = true; return false; } // is the handshake already done? if (! _accepted) { return false; } return trySSLRead(); } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::handleWrite () { if (nullptr == _ssl) { _clientClosed = true; return false; } // is the handshake already done? if (! _accepted) { return false; } return trySSLWrite(); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief accepts SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLAccept () { if (nullptr == _ssl) { _clientClosed = true; return false; } ERR_clear_error(); int res = SSL_accept(_ssl); // accept successful if (res == 1) { LOG_DEBUG("established SSL connection"); _accepted = true; // accept done, remove write events _scheduler->stopSocketEvents(_writeWatcher); return true; } // shutdown of connection if (res == 0) { LOG_DEBUG("SSL_accept failed: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } // maybe we need more data int err = SSL_get_error(_ssl, res); if (err == SSL_ERROR_WANT_READ) { return true; } else if (err == SSL_ERROR_WANT_WRITE) { return true; } LOG_TRACE("error in SSL handshake: %s", triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief reads from SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLRead () { _readBlockedOnWrite = false; again: ERR_clear_error(); int nr = SSL_read(_ssl, _tmpReadBuffer, READ_BLOCK_SIZE); if (nr <= 0) { int res = SSL_get_error(_ssl, nr); switch (res) { case SSL_ERROR_NONE: return true; case SSL_ERROR_SSL: LOG_DEBUG("received SSL error (bytes read %d, socket %d): %s", nr, (int) TRI_get_fd_or_handle_of_socket(_commSocket), triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; case SSL_ERROR_ZERO_RETURN: shutdownSsl(true); _clientClosed = true; return false; case SSL_ERROR_WANT_READ: // we must retry with the EXACT same parameters later return true; case SSL_ERROR_WANT_WRITE: _readBlockedOnWrite = true; return true; case SSL_ERROR_WANT_CONNECT: LOG_DEBUG("received SSL_ERROR_WANT_CONNECT"); break; case SSL_ERROR_WANT_ACCEPT: LOG_DEBUG("received SSL_ERROR_WANT_ACCEPT"); break; case SSL_ERROR_SYSCALL: if (res != 0) { LOG_DEBUG("SSL_read returned syscall error with: %s", triagens::basics::lastSSLError().c_str()); } else if (nr == 0) { LOG_DEBUG("SSL_read returned syscall error because an EOF was received"); } else { LOG_DEBUG("SSL_read return syscall error: %d: %s", (int) errno, strerror(errno)); } shutdownSsl(false); return false; default: LOG_DEBUG("received error with %d and %d: %s", res, nr, triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } } else { _readBuffer->appendText(_tmpReadBuffer, nr); // we might have more data to read // if we do not iterate again, the reading process would stop goto again; } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief writes from SSL connection //////////////////////////////////////////////////////////////////////////////// bool HttpsCommTask::trySSLWrite () { _writeBlockedOnRead = false; size_t len = 0; if (nullptr != _writeBuffer) { TRI_ASSERT(_writeBuffer->length() >= _writeLength); // size_t is unsigned, should never get < 0 len = _writeBuffer->length() - _writeLength; } // write buffer to SSL connection int nr = 0; if (0 < len) { ERR_clear_error(); nr = SSL_write(_ssl, _writeBuffer->begin() + _writeLength, (int) len); if (nr <= 0) { int res = SSL_get_error(_ssl, nr); switch (res) { case SSL_ERROR_NONE: return true; case SSL_ERROR_ZERO_RETURN: shutdownSsl(true); _clientClosed = true; return false; case SSL_ERROR_WANT_CONNECT: LOG_DEBUG("received SSL_ERROR_WANT_CONNECT"); break; case SSL_ERROR_WANT_ACCEPT: LOG_DEBUG("received SSL_ERROR_WANT_ACCEPT"); break; case SSL_ERROR_WANT_WRITE: // we must retry with the EXACT same parameters later return true; case SSL_ERROR_WANT_READ: _writeBlockedOnRead = true; return true; case SSL_ERROR_SYSCALL: if (res != 0) { LOG_DEBUG("SSL_write returned syscall error with: %s", triagens::basics::lastSSLError().c_str()); } else if (nr == 0) { LOG_DEBUG("SSL_write returned syscall error because an EOF was received"); } else { LOG_DEBUG("SSL_write return syscall error: %d: %s", errno, strerror(errno)); } shutdownSsl(false); return false; default: LOG_DEBUG("received error with %d and %d: %s", res, nr, triagens::basics::lastSSLError().c_str()); shutdownSsl(false); return false; } } else { len -= nr; } } if (len == 0) { delete _writeBuffer; _writeBuffer = nullptr; completedWriteBuffer(); } else if (nr > 0) { // nr might have been negative here _writeLength += nr; } // return immediately, everything is closed down if (_clientClosed) { return false; } // we might have a new write buffer _scheduler->sendAsync(SocketTask::_asyncWatcher); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief shuts down the SSL connection //////////////////////////////////////////////////////////////////////////////// void HttpsCommTask::shutdownSsl (bool initShutdown) { static int const SHUTDOWN_ITERATIONS = 10; if (nullptr != _ssl) { if (initShutdown) { bool ok = false; for (int i = 0; i < SHUTDOWN_ITERATIONS; ++i) { ERR_clear_error(); int res = SSL_shutdown(_ssl); if (res == 1) { ok = true; break; } if (res == -1) { int err = SSL_get_error(_ssl, res); if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) { LOG_DEBUG("received shutdown error with %d, %d: %s", res, err, triagens::basics::lastSSLError().c_str()); break; } } } if (! ok) { LOG_DEBUG("cannot complete SSL shutdown in socket %d", (int) TRI_get_fd_or_handle_of_socket(_commSocket)); } } else { ERR_clear_error(); SSL_clear(_ssl); } ERR_clear_error(); SSL_free(_ssl); // this will free bio as well _ssl = nullptr; } if (TRI_isvalidsocket(_commSocket)) { TRI_CLOSE_SOCKET(_commSocket); TRI_invalidatesocket(&_commSocket); } } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>#include <plasp/pddl/TranslatorASP.h> #include <plasp/utils/IO.h> #include <plasp/utils/TranslatorException.h> namespace plasp { namespace pddl { //////////////////////////////////////////////////////////////////////////////////////////////////// // // TranslatorASP // //////////////////////////////////////////////////////////////////////////////////////////////////// TranslatorASP::TranslatorASP(const Description &description, std::ostream &ostream) : m_description(description), m_ostream(ostream) { } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::checkSupport() const { // Check for "either" types const auto &predicates = m_description.domain().predicates(); std::for_each(predicates.cbegin(), predicates.cend(), [&](const auto &predicate) { const auto &arguments = predicate->arguments(); std::for_each(arguments.cbegin(), arguments.cend(), [&](const auto &parameter) { if (parameter->type()->expressionType() != Expression::Type::PrimitiveType) throw utils::TranslatorException("Only primitive types supported currently"); }); }); const auto &actions = m_description.domain().actions(); std::for_each(actions.cbegin(), actions.cend(), [&](const auto &action) { const auto &parameters = action->parameters(); std::for_each(parameters.cbegin(), parameters.cend(), [&](const auto &parameter) { if (parameter->type()->expressionType() != Expression::Type::PrimitiveType) throw utils::TranslatorException("Only primitive types supported currently"); }); }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translate() const { checkSupport(); translateDomain(); if (m_description.containsProblem()) { m_ostream << std::endl; translateProblem(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateDomain() const { m_ostream << "%---------------------------------------" << std::endl << "% domain" << std::endl << "%---------------------------------------" << std::endl; const auto &domain = m_description.domain(); // Types if (!domain.types().empty()) { m_ostream << std::endl; translateTypes(); } // Constants if (!domain.constants().empty()) { m_ostream << std::endl; translateConstants(); } // Predicates if (!domain.predicates().empty()) { m_ostream << std::endl; translatePredicates(); } // Actions if (!domain.actions().empty()) { m_ostream << std::endl; translateActions(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateTypes() const { // TODO: escape ASP identifiers m_ostream << "% types"; const auto &types = m_description.domain().types(); std::for_each(types.cbegin(), types.cend(), [&](const auto &type) { m_ostream << std::endl; m_ostream << "type(" << type->name() << ")." << std::endl; const auto &parentTypes = type->parentTypes(); std::for_each(parentTypes.cbegin(), parentTypes.cend(), [&](const auto &parentType) { m_ostream << "inherits(type(" << type->name() << "), type(" << parentType->name() << "))." << std::endl; }); }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateConstants() const { m_ostream << "% constants"; const auto &constants = m_description.domain().constants(); std::for_each(constants.cbegin(), constants.cend(), [&](const auto &constant) { m_ostream << std::endl; m_ostream << "constant(" << constant->name() << ")." << std::endl; const auto *type = constant->type(); if (type == nullptr) return; m_ostream << "hasType(constant(" << constant->name() << "), type(" << type->name() << "))." << std::endl; }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translatePredicates() const { m_ostream << "% predicates"; const auto &predicates = m_description.domain().predicates(); std::for_each(predicates.cbegin(), predicates.cend(), [&](const auto &predicate) { m_ostream << std::endl; m_ostream << "predicate(" << predicate->name(); translateVariables(predicate->arguments()); m_ostream << ")."; }); m_ostream << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateActions() const { m_ostream << "% actions"; const auto &actions = m_description.domain().actions(); std::for_each(actions.cbegin(), actions.cend(), [&](const auto &action) { m_ostream << std::endl; m_ostream << "action(" << action->name(); translateVariables(action->parameters()); m_ostream << ")."; }); m_ostream << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateVariables(const expressions::Variables &variables) const { if (variables.empty()) return; m_ostream << "("; for (auto i = variables.cbegin(); i != variables.cend(); i++) { if (i != variables.cbegin()) m_ostream << ", "; const auto &variable = *dynamic_cast<const expressions::Variable *>(i->get()); m_ostream << utils::escapeASPVariable(variable.name()); } m_ostream << ")) :- "; for (auto i = variables.cbegin(); i != variables.cend(); i++) { if (i != variables.cbegin()) m_ostream << ", "; const auto &variable = *dynamic_cast<const expressions::Variable *>(i->get()); const auto &type = *dynamic_cast<const expressions::PrimitiveType *>(variable.type()); m_ostream << "hasType(" << utils::escapeASPVariable(variable.name()) << ", type(" << type.name() << "))"; } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateProblem() const { m_ostream << "%---------------------------------------" << std::endl << "% problem" << std::endl << "%---------------------------------------" << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <commit_msg>Fixes lambda issue with gcc.<commit_after>#include <plasp/pddl/TranslatorASP.h> #include <plasp/utils/IO.h> #include <plasp/utils/TranslatorException.h> namespace plasp { namespace pddl { //////////////////////////////////////////////////////////////////////////////////////////////////// // // TranslatorASP // //////////////////////////////////////////////////////////////////////////////////////////////////// TranslatorASP::TranslatorASP(const Description &description, std::ostream &ostream) : m_description(description), m_ostream(ostream) { } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::checkSupport() const { // Check for "either" types const auto &predicates = m_description.domain().predicates(); std::for_each(predicates.cbegin(), predicates.cend(), [&](const auto &predicate) { const auto &arguments = predicate->arguments(); std::for_each(arguments.cbegin(), arguments.cend(), [&](const auto &parameter) { if (parameter->type()->expressionType() != Expression::Type::PrimitiveType) throw utils::TranslatorException("Only primitive types supported currently"); }); }); const auto &actions = m_description.domain().actions(); std::for_each(actions.cbegin(), actions.cend(), [&](const auto &action) { const auto &parameters = action->parameters(); std::for_each(parameters.cbegin(), parameters.cend(), [&](const auto &parameter) { if (parameter->type()->expressionType() != Expression::Type::PrimitiveType) throw utils::TranslatorException("Only primitive types supported currently"); }); }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translate() const { checkSupport(); translateDomain(); if (m_description.containsProblem()) { m_ostream << std::endl; translateProblem(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateDomain() const { m_ostream << "%---------------------------------------" << std::endl << "% domain" << std::endl << "%---------------------------------------" << std::endl; const auto &domain = m_description.domain(); // Types if (!domain.types().empty()) { m_ostream << std::endl; translateTypes(); } // Constants if (!domain.constants().empty()) { m_ostream << std::endl; translateConstants(); } // Predicates if (!domain.predicates().empty()) { m_ostream << std::endl; translatePredicates(); } // Actions if (!domain.actions().empty()) { m_ostream << std::endl; translateActions(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateTypes() const { // TODO: escape ASP identifiers m_ostream << "% types"; const auto &types = m_description.domain().types(); std::for_each(types.cbegin(), types.cend(), [&](const auto &type) { m_ostream << std::endl; m_ostream << "type(" << type->name() << ")." << std::endl; const auto &parentTypes = type->parentTypes(); std::for_each(parentTypes.cbegin(), parentTypes.cend(), [&](const auto &parentType) { m_ostream << "inherits(type(" << type->name() << "), type(" << parentType->name() << "))." << std::endl; }); }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateConstants() const { m_ostream << "% constants"; const auto &constants = m_description.domain().constants(); std::for_each(constants.cbegin(), constants.cend(), [&](const auto &constant) { m_ostream << std::endl; m_ostream << "constant(" << constant->name() << ")." << std::endl; const auto *type = constant->type(); if (type == nullptr) return; m_ostream << "hasType(constant(" << constant->name() << "), type(" << type->name() << "))." << std::endl; }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translatePredicates() const { m_ostream << "% predicates"; const auto &predicates = m_description.domain().predicates(); std::for_each(predicates.cbegin(), predicates.cend(), [&](const auto &predicate) { m_ostream << std::endl; m_ostream << "predicate(" << predicate->name(); this->translateVariables(predicate->arguments()); m_ostream << ")."; }); m_ostream << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateActions() const { m_ostream << "% actions"; const auto &actions = m_description.domain().actions(); std::for_each(actions.cbegin(), actions.cend(), [&](const auto &action) { m_ostream << std::endl; m_ostream << "action(" << action->name(); this->translateVariables(action->parameters()); m_ostream << ")."; }); m_ostream << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateVariables(const expressions::Variables &variables) const { if (variables.empty()) return; m_ostream << "("; for (auto i = variables.cbegin(); i != variables.cend(); i++) { if (i != variables.cbegin()) m_ostream << ", "; const auto &variable = *dynamic_cast<const expressions::Variable *>(i->get()); m_ostream << utils::escapeASPVariable(variable.name()); } m_ostream << ")) :- "; for (auto i = variables.cbegin(); i != variables.cend(); i++) { if (i != variables.cbegin()) m_ostream << ", "; const auto &variable = *dynamic_cast<const expressions::Variable *>(i->get()); const auto &type = *dynamic_cast<const expressions::PrimitiveType *>(variable.type()); m_ostream << "hasType(" << utils::escapeASPVariable(variable.name()) << ", type(" << type.name() << "))"; } } //////////////////////////////////////////////////////////////////////////////////////////////////// void TranslatorASP::translateProblem() const { m_ostream << "%---------------------------------------" << std::endl << "% problem" << std::endl << "%---------------------------------------" << std::endl; } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <|endoftext|>
<commit_before>// Copyright 2015 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. #include "bindings/event.h" #include <algorithm> #include <unordered_map> #include "base/encoding.h" #include "base/logging.h" #include "base/string_piece.h" #include "bindings/utilities.h" #include "plugin/arguments.h" #include <include/v8.h> namespace bindings { namespace { // Index in the instance object's internal fields for the DefaultPrevented flag. int kInternalEventDefaultPreventedIndex = 0; // Map from SA-MP callback name to idiomatic JavaScript event type. std::unordered_map<std::string, std::string> g_callback_type_map_; // Converts |callback| to an idiomatic JavaScript event type. This means we remove the "On" // prefix and lowercase the rest of the event, e.g. OnPlayerConnect -> playerconnect. std::string CreateEventType(base::StringPiece callback) { if (callback.starts_with("On")) callback.remove_prefix(2 /** strlen("On") **/); std::string event_type = callback.as_string(); std::transform(event_type.begin(), event_type.end(), event_type.begin(), ::tolower); return event_type; } // Converts |callback| to an idiomatic JavaScript interface name. This means we remove the "On" // prefix and append "Event", e.g. OnPlayerConnect -> PlayerConnectEvent. std::string CreateEventInterfaceName(base::StringPiece callback) { if (callback.starts_with("On")) callback.remove_prefix(2 /** strlen("On") **/); return callback.as_string() + "Event"; } // Updates the internal DefaultPrevented flag for the holder to |true|. Note that this method // does not have very sophisticated checks to prevent it from being bound to other internal // objects, so let's hope people don't play weird tricks. void PreventDefaultCallback(const v8::FunctionCallbackInfo<v8::Value>& arguments) { if (arguments.Holder().IsEmpty() || !arguments.Holder()->IsObject()) return; v8::Local<v8::Object> object_value = v8::Local<v8::Object>::Cast(arguments.Holder()); if (!object_value->InternalFieldCount()) return; object_value->SetInternalField(kInternalEventDefaultPreventedIndex, v8::True(v8::Isolate::GetCurrent())); } // Returns whether the default action of the holder has been prevented. void DefaultPreventedCallback(const v8::FunctionCallbackInfo<v8::Value>& arguments) { arguments.GetReturnValue().Set(Event::DefaultPrevented(arguments.Holder())); } } // namespace // static std::unique_ptr<Event> Event::Create(const plugin::Callback& callback) { return std::unique_ptr<Event>(new Event(callback)); } // static bool Event::DefaultPrevented(v8::Local<v8::Value> value) { if (value.IsEmpty() || !value->IsObject()) return false; v8::Local<v8::Object> object_value = v8::Local<v8::Object>::Cast(value); if (!object_value->InternalFieldCount()) return false; v8::Local<v8::Value> internal_flag = object_value->GetInternalField(kInternalEventDefaultPreventedIndex); if (internal_flag.IsEmpty() || !internal_flag->IsBoolean()) return false; return internal_flag->BooleanValue(GetIsolate()); } // static const std::string& Event::ToEventType(const std::string& callback) { if (!g_callback_type_map_.count(callback)) g_callback_type_map_[callback] = CreateEventType(callback); return g_callback_type_map_[callback]; } Event::Event(const plugin::Callback& callback) : callback_(callback), event_type_(CreateEventInterfaceName(callback.name)) {} Event::~Event() {} void Event::InstallPrototype(v8::Local<v8::ObjectTemplate> global) const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(isolate); v8::Local<v8::ObjectTemplate> object_template = function_template->InstanceTemplate(); // TODO: Special-case "playerid", "vehicleid" and so on. for (const auto& pair : callback_.arguments) object_template->Set(v8String(pair.first), v8::Undefined(isolate)); // If the event is cancelable, we create the property "defaultPrevented" (a readonly boolean) // and the method preventDefault() to set it to true. This effect is irreversible. if (callback_.cancelable) { v8::Local<v8::ObjectTemplate> prototype_template = function_template->PrototypeTemplate(); // Make sure that there is a location to store the DefaultPrevented flag. object_template->SetInternalFieldCount(1 /** kInternalEventDefaultPreventedIndex **/); prototype_template->Set(v8String("preventDefault"), v8::FunctionTemplate::New(isolate, PreventDefaultCallback)); object_template->SetAccessorProperty( v8String("defaultPrevented"), v8::FunctionTemplate::New(isolate, DefaultPreventedCallback), v8::Local<v8::FunctionTemplate>(), v8::PropertyAttribute::ReadOnly); } global->Set(v8String(event_type_), function_template); } v8::Local<v8::Object> Event::NewInstance(const plugin::Arguments& arguments) const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Value> function_value = context->Global()->Get(context, v8String(event_type_)).ToLocalChecked(); DCHECK(function_value->IsFunction()); v8::Local<v8::Function> function = v8::Local<v8::Function>::Cast(function_value); v8::Local<v8::Object> instance = function->NewInstance(context).ToLocalChecked(); for (const auto& argument : callback_.arguments) { v8::Local<v8::String> property = v8String(argument.first); switch (argument.second) { case plugin::ARGUMENT_TYPE_INT: instance->Set(context, property, v8::Number::New(isolate, arguments.GetInteger(argument.first))); break; case plugin::ARGUMENT_TYPE_FLOAT: instance->Set(context, property, v8::Number::New(isolate, arguments.GetFloat(argument.first))); break; case plugin::ARGUMENT_TYPE_STRING: instance->Set(context, property, v8String(fromAnsi(arguments.GetString(argument.first)))); break; } } return instance; } } // namespace bindings <commit_msg>Output debugging information when converting strings for events<commit_after>// Copyright 2015 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. #include "bindings/event.h" #include <algorithm> #include <unordered_map> #include "base/encoding.h" #include "base/logging.h" #include "base/string_piece.h" #include "bindings/utilities.h" #include "plugin/arguments.h" #include <include/v8.h> namespace bindings { namespace { // Index in the instance object's internal fields for the DefaultPrevented flag. int kInternalEventDefaultPreventedIndex = 0; // Map from SA-MP callback name to idiomatic JavaScript event type. std::unordered_map<std::string, std::string> g_callback_type_map_; // Converts |callback| to an idiomatic JavaScript event type. This means we remove the "On" // prefix and lowercase the rest of the event, e.g. OnPlayerConnect -> playerconnect. std::string CreateEventType(base::StringPiece callback) { if (callback.starts_with("On")) callback.remove_prefix(2 /** strlen("On") **/); std::string event_type = callback.as_string(); std::transform(event_type.begin(), event_type.end(), event_type.begin(), ::tolower); return event_type; } // Converts |callback| to an idiomatic JavaScript interface name. This means we remove the "On" // prefix and append "Event", e.g. OnPlayerConnect -> PlayerConnectEvent. std::string CreateEventInterfaceName(base::StringPiece callback) { if (callback.starts_with("On")) callback.remove_prefix(2 /** strlen("On") **/); return callback.as_string() + "Event"; } // Updates the internal DefaultPrevented flag for the holder to |true|. Note that this method // does not have very sophisticated checks to prevent it from being bound to other internal // objects, so let's hope people don't play weird tricks. void PreventDefaultCallback(const v8::FunctionCallbackInfo<v8::Value>& arguments) { if (arguments.Holder().IsEmpty() || !arguments.Holder()->IsObject()) return; v8::Local<v8::Object> object_value = v8::Local<v8::Object>::Cast(arguments.Holder()); if (!object_value->InternalFieldCount()) return; object_value->SetInternalField(kInternalEventDefaultPreventedIndex, v8::True(v8::Isolate::GetCurrent())); } // Returns whether the default action of the holder has been prevented. void DefaultPreventedCallback(const v8::FunctionCallbackInfo<v8::Value>& arguments) { arguments.GetReturnValue().Set(Event::DefaultPrevented(arguments.Holder())); } } // namespace // static std::unique_ptr<Event> Event::Create(const plugin::Callback& callback) { return std::unique_ptr<Event>(new Event(callback)); } // static bool Event::DefaultPrevented(v8::Local<v8::Value> value) { if (value.IsEmpty() || !value->IsObject()) return false; v8::Local<v8::Object> object_value = v8::Local<v8::Object>::Cast(value); if (!object_value->InternalFieldCount()) return false; v8::Local<v8::Value> internal_flag = object_value->GetInternalField(kInternalEventDefaultPreventedIndex); if (internal_flag.IsEmpty() || !internal_flag->IsBoolean()) return false; return internal_flag->BooleanValue(GetIsolate()); } // static const std::string& Event::ToEventType(const std::string& callback) { if (!g_callback_type_map_.count(callback)) g_callback_type_map_[callback] = CreateEventType(callback); return g_callback_type_map_[callback]; } Event::Event(const plugin::Callback& callback) : callback_(callback), event_type_(CreateEventInterfaceName(callback.name)) {} Event::~Event() {} void Event::InstallPrototype(v8::Local<v8::ObjectTemplate> global) const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(isolate); v8::Local<v8::ObjectTemplate> object_template = function_template->InstanceTemplate(); // TODO: Special-case "playerid", "vehicleid" and so on. for (const auto& pair : callback_.arguments) object_template->Set(v8String(pair.first), v8::Undefined(isolate)); // If the event is cancelable, we create the property "defaultPrevented" (a readonly boolean) // and the method preventDefault() to set it to true. This effect is irreversible. if (callback_.cancelable) { v8::Local<v8::ObjectTemplate> prototype_template = function_template->PrototypeTemplate(); // Make sure that there is a location to store the DefaultPrevented flag. object_template->SetInternalFieldCount(1 /** kInternalEventDefaultPreventedIndex **/); prototype_template->Set(v8String("preventDefault"), v8::FunctionTemplate::New(isolate, PreventDefaultCallback)); object_template->SetAccessorProperty( v8String("defaultPrevented"), v8::FunctionTemplate::New(isolate, DefaultPreventedCallback), v8::Local<v8::FunctionTemplate>(), v8::PropertyAttribute::ReadOnly); } global->Set(v8String(event_type_), function_template); } v8::Local<v8::Object> Event::NewInstance(const plugin::Arguments& arguments) const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Value> function_value = context->Global()->Get(context, v8String(event_type_)).ToLocalChecked(); DCHECK(function_value->IsFunction()); v8::Local<v8::Function> function = v8::Local<v8::Function>::Cast(function_value); v8::Local<v8::Object> instance = function->NewInstance(context).ToLocalChecked(); for (const auto& argument : callback_.arguments) { v8::Local<v8::String> property = v8String(argument.first); switch (argument.second) { case plugin::ARGUMENT_TYPE_INT: instance->Set(context, property, v8::Number::New(isolate, arguments.GetInteger(argument.first))); break; case plugin::ARGUMENT_TYPE_FLOAT: instance->Set(context, property, v8::Number::New(isolate, arguments.GetFloat(argument.first))); break; case plugin::ARGUMENT_TYPE_STRING: { const std::string before = arguments.GetString(argument.first); const std::string after = fromAnsi(before); LOG(INFO) << "Before: [" << before << "]"; LOG(INFO) << "After: [" << after << "]"; instance->Set(context, property, v8String(after)); } break; } } return instance; } } // namespace bindings <|endoftext|>
<commit_before>/* * Discrete Logarithm Parameters * (C) 1999-2008 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dl_group.h> #include <botan/libstate.h> #include <botan/parsing.h> #include <botan/numthry.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/pipe.h> #include <botan/pem.h> #include <botan/internal/workfactor.h> #include <botan/internal/assert.h> namespace Botan { /* * DL_Group Constructor */ DL_Group::DL_Group() { initialized = false; } /* * DL_Group Constructor */ DL_Group::DL_Group(const std::string& type) { const std::string grp_contents = global_state().get("dl", type); if(grp_contents == "") throw Invalid_Argument("DL_Group: Unknown group " + type); PEM_decode(grp_contents); } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, PrimeType type, size_t pbits, size_t qbits) { if(pbits < 512) throw Invalid_Argument("DL_Group: prime size " + std::to_string(pbits) + " is too small"); if(type == Strong) { p = random_safe_prime(rng, pbits); q = (p - 1) / 2; g = 2; } else if(type == Prime_Subgroup) { if(!qbits) qbits = 2 * dl_work_factor(pbits); q = random_prime(rng, qbits); BigInt X; while(p.bits() != pbits || !check_prime(p, rng)) { X.randomize(rng, pbits); p = X - (X % (2*q) - 1); } g = make_dsa_generator(p, q); } else if(type == DSA_Kosherizer) { qbits = qbits ? qbits : ((pbits <= 1024) ? 160 : 256); generate_dsa_primes(rng, global_state().algorithm_factory(), p, q, pbits, qbits); g = make_dsa_generator(p, q); } initialized = true; } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, const std::vector<byte>& seed, size_t pbits, size_t qbits) { if(!generate_dsa_primes(rng, global_state().algorithm_factory(), p, q, pbits, qbits, seed)) throw Invalid_Argument("DL_Group: The seed given does not " "generate a DSA group"); g = make_dsa_generator(p, q); initialized = true; } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p1, const BigInt& g1) { initialize(p1, 0, g1); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p1, const BigInt& q1, const BigInt& g1) { initialize(p1, q1, g1); } /* * DL_Group Initializer */ void DL_Group::initialize(const BigInt& p1, const BigInt& q1, const BigInt& g1) { if(p1 < 3) throw Invalid_Argument("DL_Group: Prime invalid"); if(g1 < 2 || g1 >= p1) throw Invalid_Argument("DL_Group: Generator invalid"); if(q1 < 0 || q1 >= p1) throw Invalid_Argument("DL_Group: Subgroup invalid"); p = p1; g = g1; q = q1; initialized = true; } /* * Verify that the group has been set */ void DL_Group::init_check() const { if(!initialized) throw Invalid_State("DLP group cannot be used uninitialized"); } /* * Verify the parameters */ bool DL_Group::verify_group(RandomNumberGenerator& rng, bool strong) const { init_check(); if(g < 2 || p < 3 || q < 0) return false; if((q != 0) && ((p - 1) % q != 0)) return false; if(!strong) return true; if(!check_prime(p, rng)) return false; if((q > 0) && !check_prime(q, rng)) return false; return true; } /* * Return the prime */ const BigInt& DL_Group::get_p() const { init_check(); return p; } /* * Return the generator */ const BigInt& DL_Group::get_g() const { init_check(); return g; } /* * Return the subgroup */ const BigInt& DL_Group::get_q() const { init_check(); if(q == 0) throw Invalid_State("DLP group has no q prime specified"); return q; } /* * DER encode the parameters */ std::vector<byte> DL_Group::DER_encode(Format format) const { init_check(); if((q == 0) && (format != PKCS_3)) throw Encoding_Error("The ANSI DL parameter formats require a subgroup"); if(format == ANSI_X9_57) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(q) .encode(g) .end_cons() .get_contents_unlocked(); } else if(format == ANSI_X9_42) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(g) .encode(q) .end_cons() .get_contents_unlocked(); } else if(format == PKCS_3) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(g) .end_cons() .get_contents_unlocked(); } throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * PEM encode the parameters */ std::string DL_Group::PEM_encode(Format format) const { const std::vector<byte> encoding = DER_encode(format); if(format == PKCS_3) return PEM_Code::encode(encoding, "DH PARAMETERS"); else if(format == ANSI_X9_57) return PEM_Code::encode(encoding, "DSA PARAMETERS"); else if(format == ANSI_X9_42) return PEM_Code::encode(encoding, "X942 DH PARAMETERS"); else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * Decode BER encoded parameters */ void DL_Group::BER_decode(const std::vector<byte>& data, Format format) { BigInt new_p, new_q, new_g; BER_Decoder decoder(data); BER_Decoder ber = decoder.start_cons(SEQUENCE); if(format == ANSI_X9_57) { ber.decode(new_p) .decode(new_q) .decode(new_g) .verify_end(); } else if(format == ANSI_X9_42) { ber.decode(new_p) .decode(new_g) .decode(new_q) .discard_remaining(); } else if(format == PKCS_3) { ber.decode(new_p) .decode(new_g) .discard_remaining(); } else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); initialize(new_p, new_q, new_g); } /* * Decode PEM encoded parameters */ void DL_Group::PEM_decode(const std::string& pem) { std::string label; auto ber = unlock(PEM_Code::decode(pem, label)); if(label == "DH PARAMETERS") BER_decode(ber, PKCS_3); else if(label == "DSA PARAMETERS") BER_decode(ber, ANSI_X9_57); else if(label == "X942 DH PARAMETERS") BER_decode(ber, ANSI_X9_42); else throw Decoding_Error("DL_Group: Invalid PEM label " + label); } /* * Create generator of the q-sized subgroup (DSA style generator) */ BigInt DL_Group::make_dsa_generator(const BigInt& p, const BigInt& q) { BigInt g, e = (p - 1) / q; BOTAN_ASSERT(e > 0, "q divides p-1"); for(size_t i = 0; i != PRIME_TABLE_SIZE; ++i) { g = power_mod(PRIMES[i], e, p); if(g > 1) return g; } throw Internal_Error("DL_Group: Couldn't create a suitable generator"); } } <commit_msg>Fix divisibility check in DL_Group::make_dsa_generator<commit_after>/* * Discrete Logarithm Parameters * (C) 1999-2008 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dl_group.h> #include <botan/libstate.h> #include <botan/parsing.h> #include <botan/numthry.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/pipe.h> #include <botan/pem.h> #include <botan/internal/workfactor.h> #include <botan/internal/assert.h> namespace Botan { /* * DL_Group Constructor */ DL_Group::DL_Group() { initialized = false; } /* * DL_Group Constructor */ DL_Group::DL_Group(const std::string& type) { const std::string grp_contents = global_state().get("dl", type); if(grp_contents == "") throw Invalid_Argument("DL_Group: Unknown group " + type); PEM_decode(grp_contents); } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, PrimeType type, size_t pbits, size_t qbits) { if(pbits < 512) throw Invalid_Argument("DL_Group: prime size " + std::to_string(pbits) + " is too small"); if(type == Strong) { p = random_safe_prime(rng, pbits); q = (p - 1) / 2; g = 2; } else if(type == Prime_Subgroup) { if(!qbits) qbits = 2 * dl_work_factor(pbits); q = random_prime(rng, qbits); BigInt X; while(p.bits() != pbits || !check_prime(p, rng)) { X.randomize(rng, pbits); p = X - (X % (2*q) - 1); } g = make_dsa_generator(p, q); } else if(type == DSA_Kosherizer) { qbits = qbits ? qbits : ((pbits <= 1024) ? 160 : 256); generate_dsa_primes(rng, global_state().algorithm_factory(), p, q, pbits, qbits); g = make_dsa_generator(p, q); } initialized = true; } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, const std::vector<byte>& seed, size_t pbits, size_t qbits) { if(!generate_dsa_primes(rng, global_state().algorithm_factory(), p, q, pbits, qbits, seed)) throw Invalid_Argument("DL_Group: The seed given does not " "generate a DSA group"); g = make_dsa_generator(p, q); initialized = true; } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p1, const BigInt& g1) { initialize(p1, 0, g1); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p1, const BigInt& q1, const BigInt& g1) { initialize(p1, q1, g1); } /* * DL_Group Initializer */ void DL_Group::initialize(const BigInt& p1, const BigInt& q1, const BigInt& g1) { if(p1 < 3) throw Invalid_Argument("DL_Group: Prime invalid"); if(g1 < 2 || g1 >= p1) throw Invalid_Argument("DL_Group: Generator invalid"); if(q1 < 0 || q1 >= p1) throw Invalid_Argument("DL_Group: Subgroup invalid"); p = p1; g = g1; q = q1; initialized = true; } /* * Verify that the group has been set */ void DL_Group::init_check() const { if(!initialized) throw Invalid_State("DLP group cannot be used uninitialized"); } /* * Verify the parameters */ bool DL_Group::verify_group(RandomNumberGenerator& rng, bool strong) const { init_check(); if(g < 2 || p < 3 || q < 0) return false; if((q != 0) && ((p - 1) % q != 0)) return false; if(!strong) return true; if(!check_prime(p, rng)) return false; if((q > 0) && !check_prime(q, rng)) return false; return true; } /* * Return the prime */ const BigInt& DL_Group::get_p() const { init_check(); return p; } /* * Return the generator */ const BigInt& DL_Group::get_g() const { init_check(); return g; } /* * Return the subgroup */ const BigInt& DL_Group::get_q() const { init_check(); if(q == 0) throw Invalid_State("DLP group has no q prime specified"); return q; } /* * DER encode the parameters */ std::vector<byte> DL_Group::DER_encode(Format format) const { init_check(); if((q == 0) && (format != PKCS_3)) throw Encoding_Error("The ANSI DL parameter formats require a subgroup"); if(format == ANSI_X9_57) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(q) .encode(g) .end_cons() .get_contents_unlocked(); } else if(format == ANSI_X9_42) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(g) .encode(q) .end_cons() .get_contents_unlocked(); } else if(format == PKCS_3) { return DER_Encoder() .start_cons(SEQUENCE) .encode(p) .encode(g) .end_cons() .get_contents_unlocked(); } throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * PEM encode the parameters */ std::string DL_Group::PEM_encode(Format format) const { const std::vector<byte> encoding = DER_encode(format); if(format == PKCS_3) return PEM_Code::encode(encoding, "DH PARAMETERS"); else if(format == ANSI_X9_57) return PEM_Code::encode(encoding, "DSA PARAMETERS"); else if(format == ANSI_X9_42) return PEM_Code::encode(encoding, "X942 DH PARAMETERS"); else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * Decode BER encoded parameters */ void DL_Group::BER_decode(const std::vector<byte>& data, Format format) { BigInt new_p, new_q, new_g; BER_Decoder decoder(data); BER_Decoder ber = decoder.start_cons(SEQUENCE); if(format == ANSI_X9_57) { ber.decode(new_p) .decode(new_q) .decode(new_g) .verify_end(); } else if(format == ANSI_X9_42) { ber.decode(new_p) .decode(new_g) .decode(new_q) .discard_remaining(); } else if(format == PKCS_3) { ber.decode(new_p) .decode(new_g) .discard_remaining(); } else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); initialize(new_p, new_q, new_g); } /* * Decode PEM encoded parameters */ void DL_Group::PEM_decode(const std::string& pem) { std::string label; auto ber = unlock(PEM_Code::decode(pem, label)); if(label == "DH PARAMETERS") BER_decode(ber, PKCS_3); else if(label == "DSA PARAMETERS") BER_decode(ber, ANSI_X9_57); else if(label == "X942 DH PARAMETERS") BER_decode(ber, ANSI_X9_42); else throw Decoding_Error("DL_Group: Invalid PEM label " + label); } /* * Create generator of the q-sized subgroup (DSA style generator) */ BigInt DL_Group::make_dsa_generator(const BigInt& p, const BigInt& q) { const BigInt e = (p - 1) / q; if(e == 0 || (p - 1) % q > 0) throw std::invalid_argument("make_dsa_generator q does not divide p-1"); for(size_t i = 0; i != PRIME_TABLE_SIZE; ++i) { BigInt g = power_mod(PRIMES[i], e, p); if(g > 1) return g; } throw Internal_Error("DL_Group: Couldn't create a suitable generator"); } } <|endoftext|>
<commit_before>#pragma once #include <memory> #include "modifier_flag.hpp" class modifier_flag_manager { public: modifier_flag_manager(void) { // left control modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 0, "control", "⌃")); // left shift modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 1, "shift", "⇧")); // left option modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 2, "option", "⌥")); // left command modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 3, "command", "⌘")); // right control modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 4, "control", "⌃")); // right shift modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 5, "shift", "⇧")); // right option modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 6, "option", "⌥")); // right command modifier_flags_.push(std::make_unique<modifier_flag>(0x1 << 7, "command", "⌘")); } private: std::vector<std::unique_ptr<modifier_flag>> modifier_flags_; }; <commit_msg>fix modifier_flag_manager<commit_after>#pragma once #include <memory> #include <vector> #include "modifier_flag.hpp" class modifier_flag_manager { public: modifier_flag_manager(void) { // left control modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 0, "control", "⌃")); // left shift modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 1, "shift", "⇧")); // left option modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 2, "option", "⌥")); // left command modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 3, "command", "⌘")); // right control modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 4, "control", "⌃")); // right shift modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 5, "shift", "⇧")); // right option modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 6, "option", "⌥")); // right command modifier_flags_.push_back(std::make_unique<modifier_flag>(0x1 << 7, "command", "⌘")); } private: std::vector<std::unique_ptr<modifier_flag>> modifier_flags_; }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i_typedef.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:47:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <ary/idl/i_typedef.hxx> #include <ary/idl/ik_typedef.hxx> // NOT FULLY DECLARED SERVICES #include <ary/idl/ihost_ce.hxx> #include <sci_impl.hxx> #include "ipi_2s.hxx" namespace ary { namespace idl { Typedef::Typedef( const String & i_sName, Ce_id i_nOwner, Type_id i_nDefiningType ) : sName(i_sName), nOwner(i_nOwner), nDefiningType(i_nDefiningType) { } Typedef::~Typedef() { } void Typedef::do_Visit_CeHost( CeHost & o_rHost ) const { o_rHost.Do_Typedef(*this); } RCid Typedef::inq_ClassId() const { return class_id; } const String & Typedef::inq_LocalName() const { return sName; } Ce_id Typedef::inq_NameRoom() const { return nOwner; } Ce_id Typedef::inq_Owner() const { return nOwner; } E_SightLevel Typedef::inq_SightLevel() const { return sl_File; } namespace ifc_typedef { inline const Typedef & typedef_cast( const CodeEntity & i_ce ) { csv_assert( i_ce.ClassId() == Typedef::class_id ); return static_cast< const Typedef& >(i_ce); } Type_id attr::DefiningType( const CodeEntity & i_ce ) { return typedef_cast(i_ce).nDefiningType; } void xref::Get_SynonymTypedefs( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_SynonymTypedefs)); } void xref::Get_AsReturns( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsReturns)); } void xref::Get_AsParameters( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsParameters)); } void xref::Get_AsDataTypes( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsDataTypes)); } } // namespace ifc_typedef } // namespace idl } // namespace ary <commit_msg>INTEGRATION: CWS pchfix02 (1.3.30); FILE MERGED 2006/09/01 17:15:21 kaib 1.3.30.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i_typedef.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 16:25:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_autodoc.hxx" #include <precomp.h> #include <ary/idl/i_typedef.hxx> #include <ary/idl/ik_typedef.hxx> // NOT FULLY DECLARED SERVICES #include <ary/idl/ihost_ce.hxx> #include <sci_impl.hxx> #include "ipi_2s.hxx" namespace ary { namespace idl { Typedef::Typedef( const String & i_sName, Ce_id i_nOwner, Type_id i_nDefiningType ) : sName(i_sName), nOwner(i_nOwner), nDefiningType(i_nDefiningType) { } Typedef::~Typedef() { } void Typedef::do_Visit_CeHost( CeHost & o_rHost ) const { o_rHost.Do_Typedef(*this); } RCid Typedef::inq_ClassId() const { return class_id; } const String & Typedef::inq_LocalName() const { return sName; } Ce_id Typedef::inq_NameRoom() const { return nOwner; } Ce_id Typedef::inq_Owner() const { return nOwner; } E_SightLevel Typedef::inq_SightLevel() const { return sl_File; } namespace ifc_typedef { inline const Typedef & typedef_cast( const CodeEntity & i_ce ) { csv_assert( i_ce.ClassId() == Typedef::class_id ); return static_cast< const Typedef& >(i_ce); } Type_id attr::DefiningType( const CodeEntity & i_ce ) { return typedef_cast(i_ce).nDefiningType; } void xref::Get_SynonymTypedefs( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_SynonymTypedefs)); } void xref::Get_AsReturns( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsReturns)); } void xref::Get_AsParameters( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsParameters)); } void xref::Get_AsDataTypes( Dyn_CeIterator & o_result, const CodeEntity & i_ce ) { o_result = new SCI_Vector<Ce_id>(i_ce.Secondaries().List(typedef_2s_AsDataTypes)); } } // namespace ifc_typedef } // namespace idl } // namespace ary <|endoftext|>
<commit_before>// // refract/RenderJSONVisitor.cc // librefract // // Created by Pavan Kumar Sunkara on 17/06/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "Element.h" #include "Visitors.h" #include "sosJSON.h" #include <sstream> #include <iostream> namespace refract { RenderJSONVisitor::RenderJSONVisitor(const sos::Base::Type& type_) : type(type_), isExtend(false) {} RenderJSONVisitor::RenderJSONVisitor() : type(sos::Base::UndefinedType), isExtend(false) {} void RenderJSONVisitor::assign(sos::Base value) { if (isExtend) { extend(value); } else if (type == sos::Base::ArrayType) { pArr.push(value); } else if (type == sos::Base::UndefinedType) { result = value; } } void RenderJSONVisitor::assign(std::string key, sos::Base value) { if (!key.empty() && type == sos::Base::ObjectType) { pObj.set(key, value); } } void RenderJSONVisitor::extend(sos::Base value) { if (type == sos::Base::ObjectType) { for (sos::KeyValues::iterator it = value.object().begin(); it != value.object().end(); ++it) { pObj.set(it->first, it->second); } } else if (type == sos::Base::ArrayType) { for (sos::Bases::iterator it = value.array().begin(); it != value.array().end(); ++it) { pArr.push(*it); } } } void RenderJSONVisitor::visit(const IElement& e) { e.content(*this); } template<typename T> bool IsTypeAttribute(const T& e, std::string typeAttribute) { IElement::MemberElementCollection::const_iterator ta = e.attributes.find("typeAttributes"); if (ta == e.attributes.end()) { return false; } ArrayElement* attrs = TypeQueryVisitor::as<ArrayElement>((*ta)->value.second); if (!attrs) { return false; } for (ArrayElement::ValueType::const_iterator it = attrs->value.begin() ; it != attrs->value.end() ; ++it ) { StringElement* attr = TypeQueryVisitor::as<StringElement>(*it); if (!attr) { continue; } if (attr->value == typeAttribute) { return true; } } return false; } void RenderJSONVisitor::visit(const MemberElement& e) { RenderJSONVisitor renderer; if (e.value.second) { if (IsTypeAttribute(e, "nullable") && e.value.second->empty()) { renderer.result = sos::Null(); } else if (IsTypeAttribute(e, "optional") && e.value.second->empty()) { return; } else { renderer.visit(*e.value.second); } } if (StringElement* str = TypeQueryVisitor::as<StringElement>(e.value.first)) { assign(str->value, renderer.get()); } else { throw std::logic_error("A property's key in the object is not of type string"); } } template<typename T> const T* getDefault(const T& e) { IElement::MemberElementCollection::const_iterator i = e.attributes.find("default"); if (i == e.attributes.end()) { return NULL; } return TypeQueryVisitor::as<T>((*i)->value.second); } template<typename T> const T* getSample(const T& e) { IElement::MemberElementCollection::const_iterator i = e.attributes.find("samples"); if (i == e.attributes.end()) { return NULL; } ArrayElement* a = TypeQueryVisitor::as<ArrayElement>((*i)->value.second); if (!a || a->value.empty()) { return NULL; } return TypeQueryVisitor::as<T>(*(a->value.begin())); } template<typename T, typename R = typename T::ValueType> struct getValue { const T& element; getValue(const T& e) : element(e) {} operator const R*() { // FIXME: if value is propageted as first // following example will be rendered w/ empty members // ``` // - o // - m1 // - m2 // - sample // - m1: a // - m2: b // ``` // because `o` has members `m1` and `m2` , but members has no sed value if (!element.empty()) { return &element.value; } if (const T* s = getSample(element)) { return &s->value; } if (const T* d = getDefault(element)) { return &d->value; } if (element.empty() && IsTypeAttribute(element, "nullable")) { return NULL; } return &element.value; } }; void RenderJSONVisitor::visit(const ObjectElement& e) { // If the element is a mixin reference if (e.element() == "ref") { IElement::MemberElementCollection::const_iterator resolved = e.attributes.find("resolved"); if (resolved == e.attributes.end()) { return; } RenderJSONVisitor renderer; if ((*resolved)->value.second) { renderer.visit(*(*resolved)->value.second); } // Imitate an extend object isExtend = true; assign(renderer.get()); isExtend = false; return; } RenderJSONVisitor renderer(sos::Base::ObjectType); const ObjectElement::ValueType* val = getValue<ObjectElement>(e); if (!val) { return; } if (e.element() == "extend") { renderer.isExtend = true; } for (std::vector<refract::IElement*>::const_iterator it = val->begin(); it != val->end(); ++it) { if (*it) { renderer.visit(*(*it)); } } assign(renderer.get()); } namespace { void FetchArray(const ArrayElement::ValueType* val, RenderJSONVisitor& renderer) { for (ArrayElement::ValueType::const_iterator it = val->begin(); it != val->end(); ++it) { if (*it && !(*it)->empty()) { renderer.visit(*(*it)); } } } IElement* getEnumValue(const ArrayElement::ValueType* extend) { if (!extend || extend->empty()) { return NULL; } for (ArrayElement::ValueType::const_reverse_iterator it = extend->rbegin(); it != extend->rend(); ++it) { const ArrayElement* element = TypeQueryVisitor::as<ArrayElement>(*it); if (!element) { continue; } const ArrayElement::ValueType* items = getValue<ArrayElement>(*element); if (!items->empty()) { return *items->begin(); } } return NULL; } bool isEnum(const ArrayElement::ValueType* val) { for (ArrayElement::ValueType::const_iterator it = val->begin(); it != val->end(); ++it) { if ((*it)->element() == "enum") { return true; } } return false; } } void RenderJSONVisitor::visit(const ArrayElement& e) { RenderJSONVisitor renderer(sos::Base::ArrayType); const ArrayElement::ValueType* val = getValue<ArrayElement>(e); if (!val) { return; } if (e.element() == "extend") { if (isEnum(val)) { IElement* value = getEnumValue(val); if (!value) { assign(sos::String()); return; } RenderJSONVisitor renderer; value->content(renderer); assign(renderer.get()); return; } renderer.isExtend = true; } FetchArray(val, renderer); assign(renderer.get()); } void RenderJSONVisitor::visit(const NullElement& e) {} void RenderJSONVisitor::visit(const StringElement& e) { const StringElement::ValueType* v = getValue<StringElement>(e); if (v) { assign(sos::String(*v)); } } void RenderJSONVisitor::visit(const NumberElement& e) { const NumberElement::ValueType* v = getValue<NumberElement>(e); if (v) { assign(sos::Number(*v)); } } void RenderJSONVisitor::visit(const BooleanElement& e) { const BooleanElement::ValueType* v = getValue<BooleanElement>(e); if (v) { assign(sos::Boolean(*v)); } } sos::Base RenderJSONVisitor::get() const { if (type == sos::Base::ArrayType) { return pArr; } else if (type == sos::Base::ObjectType) { return pObj; } return result; } std::string RenderJSONVisitor::getString() const { sos::SerializeJSON serializer; std::stringstream ss; serializer.process(get(), ss); return ss.str(); } } <commit_msg>Enclose local function into anonymous space<commit_after>// // refract/RenderJSONVisitor.cc // librefract // // Created by Pavan Kumar Sunkara on 17/06/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "Element.h" #include "Visitors.h" #include "sosJSON.h" #include <sstream> namespace refract { RenderJSONVisitor::RenderJSONVisitor(const sos::Base::Type& type_) : type(type_), isExtend(false) {} RenderJSONVisitor::RenderJSONVisitor() : type(sos::Base::UndefinedType), isExtend(false) {} void RenderJSONVisitor::assign(sos::Base value) { if (isExtend) { extend(value); } else if (type == sos::Base::ArrayType) { pArr.push(value); } else if (type == sos::Base::UndefinedType) { result = value; } } void RenderJSONVisitor::assign(std::string key, sos::Base value) { if (!key.empty() && type == sos::Base::ObjectType) { pObj.set(key, value); } } void RenderJSONVisitor::extend(sos::Base value) { if (type == sos::Base::ObjectType) { for (sos::KeyValues::iterator it = value.object().begin(); it != value.object().end(); ++it) { pObj.set(it->first, it->second); } } else if (type == sos::Base::ArrayType) { for (sos::Bases::iterator it = value.array().begin(); it != value.array().end(); ++it) { pArr.push(*it); } } } void RenderJSONVisitor::visit(const IElement& e) { e.content(*this); } namespace { template<typename T> bool IsTypeAttribute(const T& e, std::string typeAttribute) { IElement::MemberElementCollection::const_iterator ta = e.attributes.find("typeAttributes"); if (ta == e.attributes.end()) { return false; } ArrayElement* attrs = TypeQueryVisitor::as<ArrayElement>((*ta)->value.second); if (!attrs) { return false; } for (ArrayElement::ValueType::const_iterator it = attrs->value.begin() ; it != attrs->value.end() ; ++it ) { StringElement* attr = TypeQueryVisitor::as<StringElement>(*it); if (!attr) { continue; } if (attr->value == typeAttribute) { return true; } } return false; } template<typename T> const T* getDefault(const T& e) { IElement::MemberElementCollection::const_iterator i = e.attributes.find("default"); if (i == e.attributes.end()) { return NULL; } return TypeQueryVisitor::as<T>((*i)->value.second); } template<typename T> const T* getSample(const T& e) { IElement::MemberElementCollection::const_iterator i = e.attributes.find("samples"); if (i == e.attributes.end()) { return NULL; } ArrayElement* a = TypeQueryVisitor::as<ArrayElement>((*i)->value.second); if (!a || a->value.empty()) { return NULL; } return TypeQueryVisitor::as<T>(*(a->value.begin())); } template<typename T, typename R = typename T::ValueType> struct getValue { const T& element; getValue(const T& e) : element(e) {} operator const R*() { // FIXME: if value is propageted as first // following example will be rendered w/ empty members // ``` // - o // - m1 // - m2 // - sample // - m1: a // - m2: b // ``` // because `o` has members `m1` and `m2` , but members has no sed value if (!element.empty()) { return &element.value; } if (const T* s = getSample(element)) { return &s->value; } if (const T* d = getDefault(element)) { return &d->value; } if (element.empty() && IsTypeAttribute(element, "nullable")) { return NULL; } return &element.value; } }; } void RenderJSONVisitor::visit(const MemberElement& e) { RenderJSONVisitor renderer; if (e.value.second) { if (IsTypeAttribute(e, "nullable") && e.value.second->empty()) { renderer.result = sos::Null(); } else if (IsTypeAttribute(e, "optional") && e.value.second->empty()) { return; } else { renderer.visit(*e.value.second); } } if (StringElement* str = TypeQueryVisitor::as<StringElement>(e.value.first)) { assign(str->value, renderer.get()); } else { throw std::logic_error("A property's key in the object is not of type string"); } } void RenderJSONVisitor::visit(const ObjectElement& e) { // If the element is a mixin reference if (e.element() == "ref") { IElement::MemberElementCollection::const_iterator resolved = e.attributes.find("resolved"); if (resolved == e.attributes.end()) { return; } RenderJSONVisitor renderer; if ((*resolved)->value.second) { renderer.visit(*(*resolved)->value.second); } // Imitate an extend object isExtend = true; assign(renderer.get()); isExtend = false; return; } RenderJSONVisitor renderer(sos::Base::ObjectType); const ObjectElement::ValueType* val = getValue<ObjectElement>(e); if (!val) { return; } if (e.element() == "extend") { renderer.isExtend = true; } for (std::vector<refract::IElement*>::const_iterator it = val->begin(); it != val->end(); ++it) { if (*it) { renderer.visit(*(*it)); } } assign(renderer.get()); } namespace { void FetchArray(const ArrayElement::ValueType* val, RenderJSONVisitor& renderer) { for (ArrayElement::ValueType::const_iterator it = val->begin(); it != val->end(); ++it) { if (*it && !(*it)->empty()) { renderer.visit(*(*it)); } } } IElement* getEnumValue(const ArrayElement::ValueType* extend) { if (!extend || extend->empty()) { return NULL; } for (ArrayElement::ValueType::const_reverse_iterator it = extend->rbegin(); it != extend->rend(); ++it) { const ArrayElement* element = TypeQueryVisitor::as<ArrayElement>(*it); if (!element) { continue; } const ArrayElement::ValueType* items = getValue<ArrayElement>(*element); if (!items->empty()) { return *items->begin(); } } return NULL; } bool isEnum(const ArrayElement::ValueType* val) { for (ArrayElement::ValueType::const_iterator it = val->begin(); it != val->end(); ++it) { if ((*it)->element() == "enum") { return true; } } return false; } } void RenderJSONVisitor::visit(const ArrayElement& e) { RenderJSONVisitor renderer(sos::Base::ArrayType); const ArrayElement::ValueType* val = getValue<ArrayElement>(e); if (!val) { return; } if (e.element() == "extend") { if (isEnum(val)) { IElement* value = getEnumValue(val); if (!value) { assign(sos::String()); return; } RenderJSONVisitor renderer; value->content(renderer); assign(renderer.get()); return; } renderer.isExtend = true; } FetchArray(val, renderer); assign(renderer.get()); } void RenderJSONVisitor::visit(const NullElement& e) {} void RenderJSONVisitor::visit(const StringElement& e) { const StringElement::ValueType* v = getValue<StringElement>(e); if (v) { assign(sos::String(*v)); } } void RenderJSONVisitor::visit(const NumberElement& e) { const NumberElement::ValueType* v = getValue<NumberElement>(e); if (v) { assign(sos::Number(*v)); } } void RenderJSONVisitor::visit(const BooleanElement& e) { const BooleanElement::ValueType* v = getValue<BooleanElement>(e); if (v) { assign(sos::Boolean(*v)); } } sos::Base RenderJSONVisitor::get() const { if (type == sos::Base::ArrayType) { return pArr; } else if (type == sos::Base::ObjectType) { return pObj; } return result; } std::string RenderJSONVisitor::getString() const { sos::SerializeJSON serializer; std::stringstream ss; serializer.process(get(), ss); return ss.str(); } } <|endoftext|>
<commit_before>/** * @file sparse_coding_main.cpp * @author Nishant Mehta * * Executable for Sparse Coding. */ #include <mlpack/core.hpp> #include "sparse_coding.hpp" PROGRAM_INFO("Sparse Coding", "An implementation of Sparse Coding with " "Dictionary Learning, which achieves sparsity via an l1-norm regularizer on" " the codes (LASSO) or an (l1+l2)-norm regularizer on the codes (the " "Elastic Net). Given a dense data matrix X with n points and d dimensions," " sparse coding seeks to find a dense dictionary matrix D with k atoms in " "d dimensions, and a sparse coding matrix Z with n points in k dimensions." "\n\n" "The original data matrix X can then be reconstructed as D * Z. Therefore," " this program finds a representation of each point in X as a sparse linear" " combination of atoms in the dictionary D." "\n\n" "The sparse coding is found with an algorithm which alternates between a " "dictionary step, which updates the dictionary D, and a sparse coding step," " which updates the sparse coding matrix." "\n\n" "To run this program, the input matrix X must be specified (with -i), along" " with the number of atoms in the dictionary (-k). An initial dictionary " "may also be specified with the --initial_dictionary option. The l1 and l2" " norm regularization parameters may be specified with -l and -L, " "respectively. For example, to run sparse coding on the dataset in " "data.csv using 200 atoms and an l1-regularization parameter of 0.1, saving" " the dictionary into dict.csv and the codes into codes.csv, use " "\n\n" "$ sparse_coding -i data.csv -k 200 -l 0.1 -d dict.csv -c codes.csv" "\n\n" "The maximum number of iterations may be specified with the -n option. " "Optionally, the input data matrix X can be normalized before coding with " "the -N option."); PARAM_STRING_REQ("input_file", "Filename of the input data.", "i"); PARAM_INT_REQ("atoms", "Number of atoms in the dictionary.", "k"); PARAM_DOUBLE("lambda1", "Sparse coding l1-norm regularization parameter.", "l", 0); PARAM_DOUBLE("lambda2", "Sparse coding l2-norm regularization parameter.", "L", 0); PARAM_INT("max_iterations", "Maximum number of iterations for sparse coding (0 " "indicates no limit).", "n", 0); PARAM_STRING("initial_dictionary", "Filename for optional initial dictionary.", "D", ""); PARAM_STRING("dictionary_file", "Filename to save the output dictionary to.", "d", "dictionary.csv"); PARAM_STRING("codes_file", "Filename to save the output sparse codes to.", "c", "codes.csv"); PARAM_FLAG("normalize", "If set, the input data matrix will be normalized " "before coding.", "N"); PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL) is used.", "s", 0); using namespace arma; using namespace std; using namespace mlpack; using namespace mlpack::math; using namespace mlpack::sparse_coding; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); if (CLI::GetParam<int>("seed") != 0) RandomSeed((size_t) CLI::GetParam<int>("seed")); else RandomSeed((size_t) std::time(NULL)); const double lambda1 = CLI::GetParam<double>("lambda1"); const double lambda2 = CLI::GetParam<double>("lambda2"); const string inputFile = CLI::GetParam<string>("input_file"); const string dictionaryFile = CLI::GetParam<string>("dictionary_file"); const string codesFile = CLI::GetParam<string>("codes_file"); const string initialDictionaryFile = CLI::GetParam<string>("initial_dictionary"); const size_t maxIterations = CLI::GetParam<int>("max_iterations"); const size_t atoms = CLI::GetParam<int>("atoms"); const bool normalize = CLI::HasParam("normalize"); mat matX; data::Load(inputFile, matX, true); Log::Info << "Loaded " << matX.n_cols << " points in " << matX.n_rows << " dimensions." << endl; // Normalize each point if the user asked for it. if (normalize) { Log::Info << "Normalizing data before coding..." << std::endl; for (size_t i = 0; i < matX.n_cols; ++i) matX.col(i) /= norm(matX.col(i), 2); } // If there is an initial dictionary, be sure we do not initialize one. if (initialDictionaryFile != "") { SparseCoding<NothingInitializer> sc(matX, atoms, lambda1, lambda2); // Load initial dictionary directly into sparse coding object. data::Load(initialDictionaryFile, sc.Dictionary(), true); // Validate size of initial dictionary. if (sc.Dictionary().n_cols != atoms) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_cols << " atoms, but the number of atoms was specified to be " << atoms << "!" << endl; } if (sc.Dictionary().n_rows != matX.n_rows) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_rows << " dimensions, but the data has " << matX.n_rows << " dimensions!" << endl; } // Run sparse coding. sc.Encode(maxIterations); // Save the results. Log::Info << "Saving dictionary matrix to '" << dictionaryFile << "'.\n"; data::Save(dictionaryFile, sc.Dictionary()); Log::Info << "Saving sparse codes to '" << codesFile << "'.\n"; data::Save(codesFile, sc.Codes()); } else { // No initial dictionary. SparseCoding<> sc(matX, atoms, lambda1, lambda2); // Run sparse coding. sc.Encode(maxIterations); // Save the results. Log::Info << "Saving dictionary matrix to '" << dictionaryFile << "'.\n"; data::Save(dictionaryFile, sc.Dictionary()); Log::Info << "Saving sparse codes to '" << codesFile << "'.\n"; data::Save(codesFile, sc.Codes()); } } <commit_msg>Fix unclosed '<commit_after>/** * @file sparse_coding_main.cpp * @author Nishant Mehta * * Executable for Sparse Coding. */ #include <mlpack/core.hpp> #include "sparse_coding.hpp" PROGRAM_INFO("Sparse Coding", "An implementation of Sparse Coding with " "Dictionary Learning, which achieves sparsity via an l1-norm regularizer on" " the codes (LASSO) or an (l1+l2)-norm regularizer on the codes (the " "Elastic Net). Given a dense data matrix X with n points and d dimensions," " sparse coding seeks to find a dense dictionary matrix D with k atoms in " "d dimensions, and a sparse coding matrix Z with n points in k dimensions." "\n\n" "The original data matrix X can then be reconstructed as D * Z. Therefore," " this program finds a representation of each point in X as a sparse linear" " combination of atoms in the dictionary D." "\n\n" "The sparse coding is found with an algorithm which alternates between a " "dictionary step, which updates the dictionary D, and a sparse coding step," " which updates the sparse coding matrix." "\n\n" "To run this program, the input matrix X must be specified (with -i), along" " with the number of atoms in the dictionary (-k). An initial dictionary " "may also be specified with the --initial_dictionary option. The l1 and l2" " norm regularization parameters may be specified with -l and -L, " "respectively. For example, to run sparse coding on the dataset in " "data.csv using 200 atoms and an l1-regularization parameter of 0.1, saving" " the dictionary into dict.csv and the codes into codes.csv, use " "\n\n" "$ sparse_coding -i data.csv -k 200 -l 0.1 -d dict.csv -c codes.csv" "\n\n" "The maximum number of iterations may be specified with the -n option. " "Optionally, the input data matrix X can be normalized before coding with " "the -N option."); PARAM_STRING_REQ("input_file", "Filename of the input data.", "i"); PARAM_INT_REQ("atoms", "Number of atoms in the dictionary.", "k"); PARAM_DOUBLE("lambda1", "Sparse coding l1-norm regularization parameter.", "l", 0); PARAM_DOUBLE("lambda2", "Sparse coding l2-norm regularization parameter.", "L", 0); PARAM_INT("max_iterations", "Maximum number of iterations for sparse coding (0 " "indicates no limit).", "n", 0); PARAM_STRING("initial_dictionary", "Filename for optional initial dictionary.", "D", ""); PARAM_STRING("dictionary_file", "Filename to save the output dictionary to.", "d", "dictionary.csv"); PARAM_STRING("codes_file", "Filename to save the output sparse codes to.", "c", "codes.csv"); PARAM_FLAG("normalize", "If set, the input data matrix will be normalized " "before coding.", "N"); PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0); using namespace arma; using namespace std; using namespace mlpack; using namespace mlpack::math; using namespace mlpack::sparse_coding; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); if (CLI::GetParam<int>("seed") != 0) RandomSeed((size_t) CLI::GetParam<int>("seed")); else RandomSeed((size_t) std::time(NULL)); const double lambda1 = CLI::GetParam<double>("lambda1"); const double lambda2 = CLI::GetParam<double>("lambda2"); const string inputFile = CLI::GetParam<string>("input_file"); const string dictionaryFile = CLI::GetParam<string>("dictionary_file"); const string codesFile = CLI::GetParam<string>("codes_file"); const string initialDictionaryFile = CLI::GetParam<string>("initial_dictionary"); const size_t maxIterations = CLI::GetParam<int>("max_iterations"); const size_t atoms = CLI::GetParam<int>("atoms"); const bool normalize = CLI::HasParam("normalize"); mat matX; data::Load(inputFile, matX, true); Log::Info << "Loaded " << matX.n_cols << " points in " << matX.n_rows << " dimensions." << endl; // Normalize each point if the user asked for it. if (normalize) { Log::Info << "Normalizing data before coding..." << std::endl; for (size_t i = 0; i < matX.n_cols; ++i) matX.col(i) /= norm(matX.col(i), 2); } // If there is an initial dictionary, be sure we do not initialize one. if (initialDictionaryFile != "") { SparseCoding<NothingInitializer> sc(matX, atoms, lambda1, lambda2); // Load initial dictionary directly into sparse coding object. data::Load(initialDictionaryFile, sc.Dictionary(), true); // Validate size of initial dictionary. if (sc.Dictionary().n_cols != atoms) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_cols << " atoms, but the number of atoms was specified to be " << atoms << "!" << endl; } if (sc.Dictionary().n_rows != matX.n_rows) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_rows << " dimensions, but the data has " << matX.n_rows << " dimensions!" << endl; } // Run sparse coding. sc.Encode(maxIterations); // Save the results. Log::Info << "Saving dictionary matrix to '" << dictionaryFile << "'.\n"; data::Save(dictionaryFile, sc.Dictionary()); Log::Info << "Saving sparse codes to '" << codesFile << "'.\n"; data::Save(codesFile, sc.Codes()); } else { // No initial dictionary. SparseCoding<> sc(matX, atoms, lambda1, lambda2); // Run sparse coding. sc.Encode(maxIterations); // Save the results. Log::Info << "Saving dictionary matrix to '" << dictionaryFile << "'.\n"; data::Save(dictionaryFile, sc.Dictionary()); Log::Info << "Saving sparse codes to '" << codesFile << "'.\n"; data::Save(codesFile, sc.Codes()); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/metrics/stats_counters.h" #include "base/metrics/stats_table.h" #include "base/shared_memory.h" #include "base/stringprintf.h" #include "base/string_piece.h" #include "base/test/multiprocess_test.h" #include "base/threading/platform_thread.h" #include "base/threading/simple_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" namespace base { class StatsTableTest : public MultiProcessTest { public: void DeleteShmem(const std::string& name) { SharedMemory mem; mem.Delete(name); } }; // Open a StatsTable and verify that we can write to each of the // locations in the table. TEST_F(StatsTableTest, VerifySlots) { const std::string kTableName = "VerifySlotsStatTable"; const int kMaxThreads = 1; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); // Register a single thread. std::string thread_name = "mainThread"; int slot_id = table.RegisterThread(thread_name); EXPECT_NE(slot_id, 0); // Fill up the table with counters. std::string counter_base_name = "counter"; for (int index = 0; index < kMaxCounter; index++) { std::string counter_name = counter_base_name; base::StringAppendF(&counter_name, "counter.ctr%d", index); int counter_id = table.FindCounter(counter_name); EXPECT_GT(counter_id, 0); } // Try to allocate an additional thread. Verify it fails. slot_id = table.RegisterThread("too many threads"); EXPECT_EQ(slot_id, 0); // Try to allocate an additional counter. Verify it fails. int counter_id = table.FindCounter(counter_base_name); EXPECT_EQ(counter_id, 0); DeleteShmem(kTableName); } // CounterZero will continually be set to 0. const std::string kCounterZero = "CounterZero"; // Counter1313 will continually be set to 1313. const std::string kCounter1313 = "Counter1313"; // CounterIncrement will be incremented each time. const std::string kCounterIncrement = "CounterIncrement"; // CounterDecrement will be decremented each time. const std::string kCounterDecrement = "CounterDecrement"; // CounterMixed will be incremented by odd numbered threads and // decremented by even threads. const std::string kCounterMixed = "CounterMixed"; // The number of thread loops that we will do. const int kThreadLoops = 100; class StatsTableThread : public SimpleThread { public: StatsTableThread(std::string name, int id) : SimpleThread(name), id_(id) {} virtual void Run() OVERRIDE; private: int id_; }; void StatsTableThread::Run() { // Each thread will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the thread scheduling. StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { StatsCounter mixed_counter(kCounterMixed); // create this one in the loop zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); if (id_ % 2) mixed_counter.Decrement(); else mixed_counter.Increment(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } } // Create a few threads and have them poke on their counters. // See http://crbug.com/10611 for more information. #if defined(OS_MACOSX) #define MAYBE_MultipleThreads DISABLED_MultipleThreads #else #define MAYBE_MultipleThreads MultipleThreads #endif TEST_F(StatsTableTest, MAYBE_MultipleThreads) { // Create a stats table. const std::string kTableName = "MultipleThreadStatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of threads to go bang on the various counters. // After we join the threads, we'll make sure the counters // contain the values we expected. StatsTableThread* threads[kMaxThreads]; // Spawn the threads. for (int index = 0; index < kMaxThreads; index++) { threads[index] = new StatsTableThread("MultipleThreadsTest", index); threads[index]->Start(); } // Wait for the threads to finish. for (int index = 0; index < kMaxThreads; index++) { threads[index]->Join(); delete threads[index]; } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); StatsCounter mixed_counter(kCounterMixed); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxThreads, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterMixed; EXPECT_EQ((kMaxThreads % 2) * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kTableName); } const std::string kMPTableName = "MultipleProcessStatTable"; MULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) { // Each process will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the scheduling. StatsTable table(kMPTableName, 0, 0); StatsTable::set_current(&table); StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } return 0; } // Create a few processes and have them poke on their counters. // This test is slow and flaky http://crbug.com/10611 TEST_F(StatsTableTest, DISABLED_MultipleProcesses) { // Create a stats table. const int kMaxProcs = 20; const int kMaxCounter = 5; DeleteShmem(kMPTableName); StatsTable table(kMPTableName, kMaxProcs, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of processes to go bang on the various counters. // After we join the processes, we'll make sure the counters // contain the values we expected. ProcessHandle procs[kMaxProcs]; // Spawn the processes. for (int16 index = 0; index < kMaxProcs; index++) { procs[index] = this->SpawnChild("StatsTableMultipleProcessMain", false); EXPECT_NE(kNullProcessHandle, procs[index]); } // Wait for the processes to finish. for (int index = 0; index < kMaxProcs; index++) { EXPECT_TRUE(WaitForSingleProcess(procs[index], 60 * 1000)); CloseProcessHandle(procs[index]); } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxProcs, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxProcs * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxProcs * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kMPTableName); } class MockStatsCounter : public StatsCounter { public: explicit MockStatsCounter(const std::string& name) : StatsCounter(name) {} int* Pointer() { return GetPtr(); } }; // Test some basic StatsCounter operations TEST_F(StatsTableTest, StatsCounter) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounter foo("foo"); // Test initial state. EXPECT_TRUE(foo.Enabled()); ASSERT_NE(foo.Pointer(), static_cast<int*>(0)); EXPECT_EQ(0, *(foo.Pointer())); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Increment. while (*(foo.Pointer()) < 123) foo.Increment(); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(0); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(-1); EXPECT_EQ(122, table.GetCounterValue("c:foo")); // Test Set. foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); foo.Set(100); EXPECT_EQ(100, table.GetCounterValue("c:foo")); foo.Set(-1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Decrement. foo.Subtract(1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(0); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(-1); EXPECT_EQ(0, table.GetCounterValue("c:foo")); DeleteShmem(kTableName); } class MockStatsCounterTimer : public StatsCounterTimer { public: explicit MockStatsCounterTimer(const std::string& name) : StatsCounterTimer(name) {} TimeTicks start_time() { return start_time_; } TimeTicks stop_time() { return stop_time_; } }; // Test some basic StatsCounterTimer operations TEST_F(StatsTableTest, StatsCounterTimer) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounterTimer bar("bar"); // Test initial state. EXPECT_FALSE(bar.Running()); EXPECT_TRUE(bar.start_time().is_null()); EXPECT_TRUE(bar.stop_time().is_null()); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); // Verify that timing again is additive. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); DeleteShmem(kTableName); } // Test some basic StatsRate operations TEST_F(StatsTableTest, StatsRate) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsRate baz("baz"); // Test initial state. EXPECT_FALSE(baz.Running()); EXPECT_EQ(0, table.GetCounterValue("c:baz")); EXPECT_EQ(0, table.GetCounterValue("t:baz")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(1, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:baz")); // Verify that timing again is additive. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(2, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:baz")); DeleteShmem(kTableName); } // Test some basic StatsScope operations TEST_F(StatsTableTest, StatsScope) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsCounterTimer foo("foo"); StatsRate bar("bar"); // Test initial state. EXPECT_EQ(0, table.GetCounterValue("t:foo")); EXPECT_EQ(0, table.GetCounterValue("t:bar")); EXPECT_EQ(0, table.GetCounterValue("c:bar")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Try a scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); EXPECT_EQ(1, table.GetCounterValue("c:bar")); // Try a second scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); EXPECT_EQ(2, table.GetCounterValue("c:bar")); DeleteShmem(kTableName); } } // namespace base <commit_msg>Switch to TimeDelta interface for WaitForSingleProcess in metrics unit test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/metrics/stats_counters.h" #include "base/metrics/stats_table.h" #include "base/shared_memory.h" #include "base/stringprintf.h" #include "base/string_piece.h" #include "base/test/multiprocess_test.h" #include "base/threading/platform_thread.h" #include "base/threading/simple_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" namespace base { class StatsTableTest : public MultiProcessTest { public: void DeleteShmem(const std::string& name) { SharedMemory mem; mem.Delete(name); } }; // Open a StatsTable and verify that we can write to each of the // locations in the table. TEST_F(StatsTableTest, VerifySlots) { const std::string kTableName = "VerifySlotsStatTable"; const int kMaxThreads = 1; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); // Register a single thread. std::string thread_name = "mainThread"; int slot_id = table.RegisterThread(thread_name); EXPECT_NE(slot_id, 0); // Fill up the table with counters. std::string counter_base_name = "counter"; for (int index = 0; index < kMaxCounter; index++) { std::string counter_name = counter_base_name; base::StringAppendF(&counter_name, "counter.ctr%d", index); int counter_id = table.FindCounter(counter_name); EXPECT_GT(counter_id, 0); } // Try to allocate an additional thread. Verify it fails. slot_id = table.RegisterThread("too many threads"); EXPECT_EQ(slot_id, 0); // Try to allocate an additional counter. Verify it fails. int counter_id = table.FindCounter(counter_base_name); EXPECT_EQ(counter_id, 0); DeleteShmem(kTableName); } // CounterZero will continually be set to 0. const std::string kCounterZero = "CounterZero"; // Counter1313 will continually be set to 1313. const std::string kCounter1313 = "Counter1313"; // CounterIncrement will be incremented each time. const std::string kCounterIncrement = "CounterIncrement"; // CounterDecrement will be decremented each time. const std::string kCounterDecrement = "CounterDecrement"; // CounterMixed will be incremented by odd numbered threads and // decremented by even threads. const std::string kCounterMixed = "CounterMixed"; // The number of thread loops that we will do. const int kThreadLoops = 100; class StatsTableThread : public SimpleThread { public: StatsTableThread(std::string name, int id) : SimpleThread(name), id_(id) {} virtual void Run() OVERRIDE; private: int id_; }; void StatsTableThread::Run() { // Each thread will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the thread scheduling. StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { StatsCounter mixed_counter(kCounterMixed); // create this one in the loop zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); if (id_ % 2) mixed_counter.Decrement(); else mixed_counter.Increment(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } } // Create a few threads and have them poke on their counters. // See http://crbug.com/10611 for more information. #if defined(OS_MACOSX) #define MAYBE_MultipleThreads DISABLED_MultipleThreads #else #define MAYBE_MultipleThreads MultipleThreads #endif TEST_F(StatsTableTest, MAYBE_MultipleThreads) { // Create a stats table. const std::string kTableName = "MultipleThreadStatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of threads to go bang on the various counters. // After we join the threads, we'll make sure the counters // contain the values we expected. StatsTableThread* threads[kMaxThreads]; // Spawn the threads. for (int index = 0; index < kMaxThreads; index++) { threads[index] = new StatsTableThread("MultipleThreadsTest", index); threads[index]->Start(); } // Wait for the threads to finish. for (int index = 0; index < kMaxThreads; index++) { threads[index]->Join(); delete threads[index]; } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); StatsCounter mixed_counter(kCounterMixed); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxThreads, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterMixed; EXPECT_EQ((kMaxThreads % 2) * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kTableName); } const std::string kMPTableName = "MultipleProcessStatTable"; MULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) { // Each process will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the scheduling. StatsTable table(kMPTableName, 0, 0); StatsTable::set_current(&table); StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } return 0; } // Create a few processes and have them poke on their counters. // This test is slow and flaky http://crbug.com/10611 TEST_F(StatsTableTest, DISABLED_MultipleProcesses) { // Create a stats table. const int kMaxProcs = 20; const int kMaxCounter = 5; DeleteShmem(kMPTableName); StatsTable table(kMPTableName, kMaxProcs, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of processes to go bang on the various counters. // After we join the processes, we'll make sure the counters // contain the values we expected. ProcessHandle procs[kMaxProcs]; // Spawn the processes. for (int16 index = 0; index < kMaxProcs; index++) { procs[index] = this->SpawnChild("StatsTableMultipleProcessMain", false); EXPECT_NE(kNullProcessHandle, procs[index]); } // Wait for the processes to finish. for (int index = 0; index < kMaxProcs; index++) { EXPECT_TRUE(WaitForSingleProcess( procs[index], base::TimeDelta::FromMinutes(1))); CloseProcessHandle(procs[index]); } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxProcs, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxProcs * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxProcs * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kMPTableName); } class MockStatsCounter : public StatsCounter { public: explicit MockStatsCounter(const std::string& name) : StatsCounter(name) {} int* Pointer() { return GetPtr(); } }; // Test some basic StatsCounter operations TEST_F(StatsTableTest, StatsCounter) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounter foo("foo"); // Test initial state. EXPECT_TRUE(foo.Enabled()); ASSERT_NE(foo.Pointer(), static_cast<int*>(0)); EXPECT_EQ(0, *(foo.Pointer())); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Increment. while (*(foo.Pointer()) < 123) foo.Increment(); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(0); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(-1); EXPECT_EQ(122, table.GetCounterValue("c:foo")); // Test Set. foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); foo.Set(100); EXPECT_EQ(100, table.GetCounterValue("c:foo")); foo.Set(-1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Decrement. foo.Subtract(1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(0); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(-1); EXPECT_EQ(0, table.GetCounterValue("c:foo")); DeleteShmem(kTableName); } class MockStatsCounterTimer : public StatsCounterTimer { public: explicit MockStatsCounterTimer(const std::string& name) : StatsCounterTimer(name) {} TimeTicks start_time() { return start_time_; } TimeTicks stop_time() { return stop_time_; } }; // Test some basic StatsCounterTimer operations TEST_F(StatsTableTest, StatsCounterTimer) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounterTimer bar("bar"); // Test initial state. EXPECT_FALSE(bar.Running()); EXPECT_TRUE(bar.start_time().is_null()); EXPECT_TRUE(bar.stop_time().is_null()); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); // Verify that timing again is additive. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); DeleteShmem(kTableName); } // Test some basic StatsRate operations TEST_F(StatsTableTest, StatsRate) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsRate baz("baz"); // Test initial state. EXPECT_FALSE(baz.Running()); EXPECT_EQ(0, table.GetCounterValue("c:baz")); EXPECT_EQ(0, table.GetCounterValue("t:baz")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(1, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:baz")); // Verify that timing again is additive. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(2, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:baz")); DeleteShmem(kTableName); } // Test some basic StatsScope operations TEST_F(StatsTableTest, StatsScope) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsCounterTimer foo("foo"); StatsRate bar("bar"); // Test initial state. EXPECT_EQ(0, table.GetCounterValue("t:foo")); EXPECT_EQ(0, table.GetCounterValue("t:bar")); EXPECT_EQ(0, table.GetCounterValue("c:bar")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Try a scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); EXPECT_EQ(1, table.GetCounterValue("c:bar")); // Try a second scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); EXPECT_EQ(2, table.GetCounterValue("c:bar")); DeleteShmem(kTableName); } } // namespace base <|endoftext|>
<commit_before>#ifndef RUNNER_INTERPRETER_VISIT_HXX # define RUNNER_INTERPRETER_VISIT_HXX # include <boost/bind.hpp> # include <libport/compiler.hh> # include <libport/finally.hh> # include <libport/foreach.hh> # include <ast/all.hh> # include <ast/print.hh> # include <kernel/exception.hh> # include <kernel/uconnection.hh> # include <object/code-class.hh> # include <object/global-class.hh> # include <object/list-class.hh> # include <object/tag-class.hh> # include <object/symbols.hh> # include <runner/interpreter.hh> # include <libport/compilation.hh> /// Job echo. #define JECHO(Title, Content) \ ECHO ("job " << ME << ", " Title ": " << Content) /// Job & astecho. #define JAECHO(Title, Ast) \ JECHO (Title, AST(Ast)) /* Yield and trace. */ #define YIELD() \ do \ { \ ECHO ("job " << ME << " yielding on AST: " \ << &e << ' ' << AST(e)); \ yield (); \ } while (0) namespace runner { using boost::bind; using libport::Finally; LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::And* e) { // Collect all subrunners scheduler::jobs_type jobs; // Create separate runners for every child but the first foreach (const ast::rConstExp& child, boost::make_iterator_range(e->children_get(), 1, 0)) { Interpreter* job = new Interpreter(*this, eval(child)); // Propagate errors from subrunners. link(job); jobs.push_back(job); job->start_job(); } // Evaluate the first child in this runner rRoutine code = eval(e->children_get().front()).unsafe_cast<object::Code>(); assert(code); // This is a closure, it won't use its 'this' object::objects_type args; args.push_back(rObject()); apply_urbi(code, SYMBOL(), args, 0); // Wait for all other jobs to terminate yield_until_terminated(jobs); return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Assignment* e) { rObject val = eval(e->value_get()); stacks_.set(e, val); return val; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Call* e) { // The invoked slot (probably a function). const ast::rConstExp& ast_tgt = e->target_get(); rObject tgt = ast_tgt->implicit() ? stacks_.self() : eval(ast_tgt); return apply(tgt, e->name_get(), e->arguments_get(), e->location_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::CallMsg*) { return stacks_.call(); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Declaration* d) { rObject val = eval(d->value_get()); stacks_.def(d, val); return val; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Float* e) { return new object::Float(e->value_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Foreach* e) { (void)e; pabort(e); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Routine* e, bool closure) { rRoutine res = make_routine(e); // Capture variables foreach (const ast::rDeclaration& dec, *e->captured_variables_get()) { ast::rLocal local = dec->value_get().unsafe_cast<ast::Local>(); assert(local); res->captures_get().push_back(stacks_.rget(local)); } // Capture 'this' and 'call' in closures if (closure) { res->self_get() = stacks_.self(); res->call_get() = stacks_.call(); } return res; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Function* e) { return visit(e, false); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Closure* e) { return visit(e, true); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::If* e) { // Evaluate the test. JAECHO ("test", e->test_get ()); rObject cond = operator()(e->test_get().get()); if (object::is_true(cond, SYMBOL(if))) { JAECHO ("then", e->thenclause_get()); return operator()(e->thenclause_get().get()); } else { JAECHO ("else", e->elseclause_get()); return operator()(e->elseclause_get().get()); } } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::List* e) { object::List::value_type res; // Evaluate every expression in the list foreach (const ast::rConstExp& c, e->value_get()) { rObject v = eval(c); // Refuse void in literal lists if (v == object::void_class) { object::WrongArgumentType e(SYMBOL(new)); e.location_set(c->location_get()); throw e; } res.push_back(v); } return new object::List(res); //ECHO ("result: " << *result_); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Lazy* e) { return operator()(e->strict_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Local* e) { const rObject& value = stacks_.get(e); passert("Local variable read before being set", value); if (e->arguments_get()) // FIXME: Register in the call stack return apply(stacks_.self(), value, e->name_get(), e->arguments_get(), e->location_get()); else return value; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Message* e) { send_message(e->tag_get(), e->text_get()); return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Nary* e) { // List of runners for Stmt flavored by a comma. scheduler::jobs_type runners; // In case we're empty, {} evaluates to void. rObject res = object::void_class; bool tail = false; foreach (const ast::rConstExp& c, e->children_get()) { // Allow some time to pass before we execute what follows. If // we don't do this, the ;-operator would act almost like the // |-operator because it would always start to execute its RHS // immediately. However, we don't want to do it before the first // statement or if we only have one statement in the scope. if (tail++) YIELD(); JAECHO("child", c); if (c.unsafe_cast<const ast::Stmt>() && c.unsafe_cast<const ast::Stmt>()->flavor_get() == ast::flavor_comma) { // The new runners are attached to the same tags as we are. Interpreter* subrunner = new Interpreter(*this, eval(c)); // If the subrunner throws an exception, propagate it here ASAP, unless // we are at the top level. if (!e->toplevel_get()) link(subrunner); runners.push_back(subrunner); subrunner->start_job (); } else { // If at toplevel, print errors and continue, else rethrow them try { // We do not use operator() to avoid duplicating the catch // of UrbiExceptions res = c->eval(*this); // We need to keep checking for void here because it can not be passed // to the << function if (e->toplevel_get() && res.get() // FIXME: What's that for? && res != object::void_class) { try { assertion(res); ECHO("toplevel: returning a result to the connection."); // Display the value using the topLevel channel. // If it is not (yet) defined, do nothing, unless the environment // variable TOPLEVEL_DEBUG is set. static bool toplevel_debug = getenv("TOPLEVEL_DEBUG"); if (rObject topLevel = object::global_class->slot_locate(SYMBOL(topLevel), false, true)) { rObject e = topLevel->slot_get(SYMBOL(LT_LT)); objects_type args; args.push_back(topLevel); args.push_back(res); apply(e, SYMBOL(topLevel), args); } else if (toplevel_debug) lobby_->value_get().connection.new_result(res); } catch (std::exception &ke) { std::cerr << "Exception when printing result: " << ke.what() << std::endl; } catch (object::UrbiException& e) { throw; } catch (...) { std::cerr << "Unknown exception when printing result" << std::endl; } } } catch (object::UrbiException& ue) { propagate_error_(ue, c->location_get()); if (e->toplevel_get()) show_error_(ue); else throw; } } } // If the Nary is not the toplevel one, all subrunners must be finished when // the runner exits the Nary node. However, it we have a scopeTag, we must // issue a "stop" which may interrupt subrunners. if (!e->toplevel_get() && !runners.empty()) { const scheduler::rTag& tag = scope_tag_get(); if (tag) tag->stop(scheduler_get(), object::void_class); yield_until_terminated(runners); } return res; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Noop*) { return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Pipe* e) { // lhs JAECHO ("lhs", e->lhs_get ()); operator() (e->lhs_get().get()); // rhs: start the execution immediately. JAECHO ("rhs", e->rhs_get ()); return operator() (e->rhs_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Scope* e) { libport::Finally finally; create_scope_tag(); finally << boost::bind(&Interpreter::cleanup_scope_tag, this); finally << libport::restore(non_interruptible_); return operator()(e->body_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Do* e) { Finally finally; rObject tgt = eval(e->target_get()); finally << stacks_.switch_self(tgt); const ast::Scope* scope = reinterpret_cast<const ast::Scope*>(e); visit(scope); // This is arguable. Do, just like Scope, should maybe return // their last inner value. return tgt; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Stmt* e) { JAECHO ("expression", e->expression_get()); return operator()(e->expression_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::String* e) { return new object::String(libport::Symbol(e->value_get())); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Tag* t) { return eval_tag(t->exp_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::TaggedStmt* t) { int result_depth = tags_get().size(); try { // FIXME: might be simplified after type checking code is moved // to Object object::rObject unchecked_tag = eval(t->tag_get()); object::type_check<object::Tag>(unchecked_tag, SYMBOL(tagged_stmt)); const object::rTag& urbi_tag = unchecked_tag->as<object::Tag>(); const scheduler::rTag& tag = urbi_tag->value_get(); // If tag is blocked, do not start and ignore the // statement completely but use the provided payload. if (tag->blocked()) return boost::any_cast<rObject>(tag->payload_get()); push_tag (tag); Finally finally(bind(&Interpreter::pop_tag, this)); // If the latest tag causes us to be frozen, let the // scheduler handle this properly to avoid duplicating the // logic. if (tag->frozen()) yield(); urbi_tag->triggerEnter(*this); rObject res = eval (t->exp_get()); urbi_tag->triggerLeave(*this); return res; } catch (scheduler::StopException& e) { // Rewind up to the appropriate depth. if (e.depth_get() < result_depth) throw; // Extract the value from the exception. return boost::any_cast<rObject>(e.payload_get()); // If we are frozen, reenter the scheduler for a while. if (frozen()) yield(); } } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::This*) { return stacks_.self(); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::While* e) { const bool must_yield = e->flavor_get() == ast::flavor_semicolon; bool tail = false; // Evaluate the test. while (true) { if (must_yield && tail++) YIELD(); JAECHO ("while test", e->test_get()); rObject cond = operator()(e->test_get().get()); if (!object::is_true(cond, SYMBOL(while))) break; JAECHO ("while body", e->body_get()); operator()(e->body_get().get()); } return object::void_class; } // Invalid nodes #define INVALID(Node) \ LIBPORT_SPEED_INLINE object::rObject \ Interpreter::visit(const ast::Node* n) \ { \ static_cast<void>(n); \ pabort("Invalid node in the Interpreter: " << *n); \ } \ INVALID(Binding); INVALID(Break); INVALID(Continue); INVALID(Implicit); INVALID(MetaExp); INVALID(Return); #undef INVALID } #endif <commit_msg>Handle Foreach like other invalid nodes in the interpreter.<commit_after>#ifndef RUNNER_INTERPRETER_VISIT_HXX # define RUNNER_INTERPRETER_VISIT_HXX # include <boost/bind.hpp> # include <libport/compiler.hh> # include <libport/finally.hh> # include <libport/foreach.hh> # include <ast/all.hh> # include <ast/print.hh> # include <kernel/exception.hh> # include <kernel/uconnection.hh> # include <object/code-class.hh> # include <object/global-class.hh> # include <object/list-class.hh> # include <object/tag-class.hh> # include <object/symbols.hh> # include <runner/interpreter.hh> # include <libport/compilation.hh> /// Job echo. #define JECHO(Title, Content) \ ECHO ("job " << ME << ", " Title ": " << Content) /// Job & astecho. #define JAECHO(Title, Ast) \ JECHO (Title, AST(Ast)) /* Yield and trace. */ #define YIELD() \ do \ { \ ECHO ("job " << ME << " yielding on AST: " \ << &e << ' ' << AST(e)); \ yield (); \ } while (0) namespace runner { using boost::bind; using libport::Finally; LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::And* e) { // Collect all subrunners scheduler::jobs_type jobs; // Create separate runners for every child but the first foreach (const ast::rConstExp& child, boost::make_iterator_range(e->children_get(), 1, 0)) { Interpreter* job = new Interpreter(*this, eval(child)); // Propagate errors from subrunners. link(job); jobs.push_back(job); job->start_job(); } // Evaluate the first child in this runner rRoutine code = eval(e->children_get().front()).unsafe_cast<object::Code>(); assert(code); // This is a closure, it won't use its 'this' object::objects_type args; args.push_back(rObject()); apply_urbi(code, SYMBOL(), args, 0); // Wait for all other jobs to terminate yield_until_terminated(jobs); return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Assignment* e) { rObject val = eval(e->value_get()); stacks_.set(e, val); return val; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Call* e) { // The invoked slot (probably a function). const ast::rConstExp& ast_tgt = e->target_get(); rObject tgt = ast_tgt->implicit() ? stacks_.self() : eval(ast_tgt); return apply(tgt, e->name_get(), e->arguments_get(), e->location_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::CallMsg*) { return stacks_.call(); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Declaration* d) { rObject val = eval(d->value_get()); stacks_.def(d, val); return val; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Float* e) { return new object::Float(e->value_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Routine* e, bool closure) { rRoutine res = make_routine(e); // Capture variables foreach (const ast::rDeclaration& dec, *e->captured_variables_get()) { ast::rLocal local = dec->value_get().unsafe_cast<ast::Local>(); assert(local); res->captures_get().push_back(stacks_.rget(local)); } // Capture 'this' and 'call' in closures if (closure) { res->self_get() = stacks_.self(); res->call_get() = stacks_.call(); } return res; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Function* e) { return visit(e, false); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Closure* e) { return visit(e, true); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::If* e) { // Evaluate the test. JAECHO ("test", e->test_get ()); rObject cond = operator()(e->test_get().get()); if (object::is_true(cond, SYMBOL(if))) { JAECHO ("then", e->thenclause_get()); return operator()(e->thenclause_get().get()); } else { JAECHO ("else", e->elseclause_get()); return operator()(e->elseclause_get().get()); } } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::List* e) { object::List::value_type res; // Evaluate every expression in the list foreach (const ast::rConstExp& c, e->value_get()) { rObject v = eval(c); // Refuse void in literal lists if (v == object::void_class) { object::WrongArgumentType e(SYMBOL(new)); e.location_set(c->location_get()); throw e; } res.push_back(v); } return new object::List(res); //ECHO ("result: " << *result_); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Lazy* e) { return operator()(e->strict_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Local* e) { const rObject& value = stacks_.get(e); passert("Local variable read before being set", value); if (e->arguments_get()) // FIXME: Register in the call stack return apply(stacks_.self(), value, e->name_get(), e->arguments_get(), e->location_get()); else return value; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Message* e) { send_message(e->tag_get(), e->text_get()); return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Nary* e) { // List of runners for Stmt flavored by a comma. scheduler::jobs_type runners; // In case we're empty, {} evaluates to void. rObject res = object::void_class; bool tail = false; foreach (const ast::rConstExp& c, e->children_get()) { // Allow some time to pass before we execute what follows. If // we don't do this, the ;-operator would act almost like the // |-operator because it would always start to execute its RHS // immediately. However, we don't want to do it before the first // statement or if we only have one statement in the scope. if (tail++) YIELD(); JAECHO("child", c); if (c.unsafe_cast<const ast::Stmt>() && c.unsafe_cast<const ast::Stmt>()->flavor_get() == ast::flavor_comma) { // The new runners are attached to the same tags as we are. Interpreter* subrunner = new Interpreter(*this, eval(c)); // If the subrunner throws an exception, propagate it here ASAP, unless // we are at the top level. if (!e->toplevel_get()) link(subrunner); runners.push_back(subrunner); subrunner->start_job (); } else { // If at toplevel, print errors and continue, else rethrow them try { // We do not use operator() to avoid duplicating the catch // of UrbiExceptions res = c->eval(*this); // We need to keep checking for void here because it can not be passed // to the << function if (e->toplevel_get() && res.get() // FIXME: What's that for? && res != object::void_class) { try { assertion(res); ECHO("toplevel: returning a result to the connection."); // Display the value using the topLevel channel. // If it is not (yet) defined, do nothing, unless the environment // variable TOPLEVEL_DEBUG is set. static bool toplevel_debug = getenv("TOPLEVEL_DEBUG"); if (rObject topLevel = object::global_class->slot_locate(SYMBOL(topLevel), false, true)) { rObject e = topLevel->slot_get(SYMBOL(LT_LT)); objects_type args; args.push_back(topLevel); args.push_back(res); apply(e, SYMBOL(topLevel), args); } else if (toplevel_debug) lobby_->value_get().connection.new_result(res); } catch (std::exception &ke) { std::cerr << "Exception when printing result: " << ke.what() << std::endl; } catch (object::UrbiException& e) { throw; } catch (...) { std::cerr << "Unknown exception when printing result" << std::endl; } } } catch (object::UrbiException& ue) { propagate_error_(ue, c->location_get()); if (e->toplevel_get()) show_error_(ue); else throw; } } } // If the Nary is not the toplevel one, all subrunners must be finished when // the runner exits the Nary node. However, it we have a scopeTag, we must // issue a "stop" which may interrupt subrunners. if (!e->toplevel_get() && !runners.empty()) { const scheduler::rTag& tag = scope_tag_get(); if (tag) tag->stop(scheduler_get(), object::void_class); yield_until_terminated(runners); } return res; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Noop*) { return object::void_class; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Pipe* e) { // lhs JAECHO ("lhs", e->lhs_get ()); operator() (e->lhs_get().get()); // rhs: start the execution immediately. JAECHO ("rhs", e->rhs_get ()); return operator() (e->rhs_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Scope* e) { libport::Finally finally; create_scope_tag(); finally << boost::bind(&Interpreter::cleanup_scope_tag, this); finally << libport::restore(non_interruptible_); return operator()(e->body_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Do* e) { Finally finally; rObject tgt = eval(e->target_get()); finally << stacks_.switch_self(tgt); const ast::Scope* scope = reinterpret_cast<const ast::Scope*>(e); visit(scope); // This is arguable. Do, just like Scope, should maybe return // their last inner value. return tgt; } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Stmt* e) { JAECHO ("expression", e->expression_get()); return operator()(e->expression_get().get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::String* e) { return new object::String(libport::Symbol(e->value_get())); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::Tag* t) { return eval_tag(t->exp_get()); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::TaggedStmt* t) { int result_depth = tags_get().size(); try { // FIXME: might be simplified after type checking code is moved // to Object object::rObject unchecked_tag = eval(t->tag_get()); object::type_check<object::Tag>(unchecked_tag, SYMBOL(tagged_stmt)); const object::rTag& urbi_tag = unchecked_tag->as<object::Tag>(); const scheduler::rTag& tag = urbi_tag->value_get(); // If tag is blocked, do not start and ignore the // statement completely but use the provided payload. if (tag->blocked()) return boost::any_cast<rObject>(tag->payload_get()); push_tag (tag); Finally finally(bind(&Interpreter::pop_tag, this)); // If the latest tag causes us to be frozen, let the // scheduler handle this properly to avoid duplicating the // logic. if (tag->frozen()) yield(); urbi_tag->triggerEnter(*this); rObject res = eval (t->exp_get()); urbi_tag->triggerLeave(*this); return res; } catch (scheduler::StopException& e) { // Rewind up to the appropriate depth. if (e.depth_get() < result_depth) throw; // Extract the value from the exception. return boost::any_cast<rObject>(e.payload_get()); // If we are frozen, reenter the scheduler for a while. if (frozen()) yield(); } } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::This*) { return stacks_.self(); } LIBPORT_SPEED_INLINE object::rObject Interpreter::visit(const ast::While* e) { const bool must_yield = e->flavor_get() == ast::flavor_semicolon; bool tail = false; // Evaluate the test. while (true) { if (must_yield && tail++) YIELD(); JAECHO ("while test", e->test_get()); rObject cond = operator()(e->test_get().get()); if (!object::is_true(cond, SYMBOL(while))) break; JAECHO ("while body", e->body_get()); operator()(e->body_get().get()); } return object::void_class; } // Invalid nodes #define INVALID(Node) \ LIBPORT_SPEED_INLINE object::rObject \ Interpreter::visit(const ast::Node* n) \ { \ static_cast<void>(n); \ pabort("Invalid node in the Interpreter: " << *n); \ } \ INVALID(Binding); INVALID(Break); INVALID(Continue); INVALID(Foreach); INVALID(Implicit); INVALID(MetaExp); INVALID(Return); #undef INVALID } #endif <|endoftext|>
<commit_before>#include "regiondataremote.h" #include "regionmatrixproxy.h" #include "workerthread.h" using namespace petabricks; using namespace petabricks::RegionDataRemoteMessage; RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) { init(dimensions, size, remoteObject); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHostPtr host) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg size_t size_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(CreateRegionDataInitialMessage) + size_sz; char buf[msg_len]; CreateRegionDataInitialMessage* msg = (CreateRegionDataInitialMessage*)buf; msg->type = MessageTypes::CREATEREGIONDATA; msg->dimensions = _D; memcpy(msg->size, size, size_sz); host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, buf, msg_len); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const IndexT* partOffset, RemoteHostPtr host) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg CreateRegionDataPartInitialMessage msg; msg.type = MessageTypes::CREATEREGIONDATAPART; msg.dimensions = _D; memcpy(msg.size, size, sizeof(msg.size)); if (partOffset) { memcpy(msg.partOffset, partOffset, sizeof(msg.partOffset)); } int len = sizeof(CreateRegionDataPartInitialMessage); host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHost& host, const MessageType initialMessageType, const EncodedPtr encodePtr) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg EncodedPtrInitialMessage msg; msg.type = initialMessageType; msg.encodedPtr = encodePtr; int len = sizeof(EncodedPtrInitialMessage); host.createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len); } void RegionDataRemote::init(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) { _D = dimensions; _type = RegionDataTypes::REGIONDATAREMOTE; _remoteObject = remoteObject; memcpy(_size, size, sizeof(IndexT) * _D); } int RegionDataRemote::allocData() { void* data; size_t len; this->fetchData(0, MessageTypes::ALLOCDATA, 0, &data, &len); AllocDataReplyMessage* reply = (AllocDataReplyMessage*)data; ElementT result = reply->result; free(reply); return result; } void RegionDataRemote::randomize() { void* data; size_t len; this->fetchData(0, MessageTypes::RANDOMIZEDATA, 0, &data, &len); free(data); } IRegionCachePtr RegionDataRemote::cacheGenerator() const { IndexT multipliers[_D]; multipliers[0] = 1; for (int i = 1; i < _D; i++) { multipliers[i] = multipliers[i - 1] * _size[i - 1]; } return new RegionDataRemoteCache(this, _D, multipliers); } IRegionCachePtr RegionDataRemote::cache() const { #ifdef DISTRIBUTED_CACHE return WorkerThread::self()->cache()->get(this); #else return NULL; #endif } void RegionDataRemote::invalidateCache() { #ifdef DISTRIBUTED_CACHE cache()->invalidate(); #endif } ElementT RegionDataRemote::readCell(const IndexT* coord) const { #ifdef DISTRIBUTED_CACHE return cache()->readCell(coord); #else return readNoCache(coord); #endif } ElementT RegionDataRemote::readNoCache(const IndexT* coord) const { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(ReadCellMessage) + coord_sz; char buf[msg_len]; ReadCellMessage* msg = (ReadCellMessage*)buf; memcpy(msg->coord, coord, coord_sz); void* data; size_t len; this->fetchData(buf, MessageTypes::READCELL, msg_len, &data, &len); ReadCellReplyMessage* reply = (ReadCellReplyMessage*)data; ElementT value = reply->value; free(reply); return value; } void RegionDataRemote::readByCache(void* request, size_t request_len, void* reply, size_t &/*reply_len*/) const { ReadCellCacheMessage* msg = (ReadCellCacheMessage*)request; void* data; size_t len; this->fetchData(request, MessageTypes::READCELLCACHE, request_len, &data, &len); ReadCellCacheReplyMessage* r = (ReadCellCacheReplyMessage*)data; RegionDataRemoteCacheLine* cacheLine = (RegionDataRemoteCacheLine*)reply; cacheLine->start = r->start; cacheLine->end = r->end; memcpy(cacheLine->base, r->values, sizeof(ElementT) * (r->end + 1)); free(r); } void RegionDataRemote::writeCell(const IndexT* coord, ElementT value) { #ifdef DISTRIBUTED_CACHE cache()->writeCell(coord, value); #else writeNoCache(coord, value); #endif } void RegionDataRemote::writeNoCache(const IndexT* coord, ElementT value) { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(WriteCellMessage) + coord_sz; char buf[msg_len]; WriteCellMessage* msg = (WriteCellMessage*)buf; msg->value = value; memcpy(msg->coord, coord, coord_sz); JTRACE("write")(_D)(sizeof(IndexT))(coord_sz)(msg_len); void* data; size_t len; this->fetchData(buf, MessageTypes::WRITECELL, msg_len, &data, &len); WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data; free(reply); } void RegionDataRemote::writeByCache(const IndexT* coord, ElementT value) const { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(WriteCellMessage) + coord_sz; char buf[msg_len]; WriteCellMessage* msg = (WriteCellMessage*)buf; msg->value = value; memcpy(msg->coord, coord, coord_sz); void* data; size_t len; this->fetchData(msg, MessageTypes::WRITECELL, msg_len, &data, &len); WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data; free(reply); } DataHostPidList RegionDataRemote::hosts(IndexT* begin, IndexT* end) { GetHostListMessage msg; memcpy(msg.begin, begin, _D * sizeof(IndexT)); memcpy(msg.end, end, _D * sizeof(IndexT)); void* data; size_t len; this->fetchData(&msg, MessageTypes::GETHOSTLIST, sizeof(GetHostListMessage), &data, &len); GetHostListReplyMessage* reply = (GetHostListReplyMessage*)data; DataHostPidList list; for (int i = 0; i < reply->numHosts; i++) { list.push_back(reply->hosts[i]); } free(reply); return list; } RemoteHostPtr RegionDataRemote::host() { return _remoteObject->host(); } UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain(UpdateHandlerChainMessage& msg) { msg.numHops += 1; void* data; size_t len; this->fetchData(&msg, MessageTypes::UPDATEHANDLERCHAIN, sizeof(UpdateHandlerChainMessage), &data, &len); UpdateHandlerChainReplyMessage* _reply = (UpdateHandlerChainReplyMessage*)data; UpdateHandlerChainReplyMessage reply = *_reply; free(_reply); return reply; } UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain() { UpdateHandlerChainMessage msg; msg.requester = HostPid::self(); msg.numHops = 0; return this->updateHandlerChain(msg); } void RegionDataRemote::fetchData(const void* msg, MessageType type, size_t len, void** responseData, size_t* responseLen) const { *responseData = 0; *responseLen = 0; size_t dataLen = sizeof(GeneralMessageHeader) + len; GeneralMessageHeader* header = (GeneralMessageHeader*)malloc(dataLen); header->isForwardMessage = false; header->type = type; header->contentOffset = sizeof(GeneralMessageHeader); header->responseData = reinterpret_cast<EncodedPtr>(responseData); header->responseLen = reinterpret_cast<EncodedPtr>(responseLen); memcpy(header->content(), msg, len); _remoteObject->send(header, dataLen); free(header); // wait for the data while (*responseData == 0 || *responseLen == 0) { jalib::memFence(); sched_yield(); } } void RegionDataRemote::onRecv(const void* data, size_t len) { const BaseMessageHeader* base = (const BaseMessageHeader*)data; if (base->isForwardMessage) { const ForwardMessageHeader* header = (const ForwardMessageHeader*)data; IRegionReplyProxy* proxy = reinterpret_cast<IRegionReplyProxy*>(header->callback); proxy->processReplyMsg(base, len); } else { const GeneralMessageHeader* header = (const GeneralMessageHeader*)data; const void** responseData = reinterpret_cast<const void**>(header->responseData); size_t* responseLen = reinterpret_cast<size_t*>(header->responseLen); size_t sz = len - base->contentOffset; void* msg = malloc(sz); memcpy(msg, base->content(), sz); *responseData = msg; *responseLen = sz; } } // Process remote messages void RegionDataRemote::forwardMessage(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { size_t len = sizeof(ForwardMessageHeader) + baseLen; ForwardMessageHeader* data = (ForwardMessageHeader*)malloc(len); data->isForwardMessage = true; data->type = base->type; data->contentOffset = sizeof(ForwardMessageHeader) + base->contentOffset; data->callback = reinterpret_cast<EncodedPtr>(caller); memcpy(data->next(), base, baseLen); _remoteObject->send(data, len); free(data); } void RegionDataRemote::processReadCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processWriteCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processAllocDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processRandomizeDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processUpdateHandlerChainMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller, RegionDataIPtr) { UpdateHandlerChainMessage* msg = (UpdateHandlerChainMessage*)base->content(); msg->numHops++; this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processGetHostListMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } RemoteObjectPtr RegionDataRemote::genRemote() { return new RegionDataRemoteObject(); } <commit_msg>remove unused code<commit_after>#include "regiondataremote.h" #include "regionmatrixproxy.h" #include "workerthread.h" using namespace petabricks; using namespace petabricks::RegionDataRemoteMessage; RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) { init(dimensions, size, remoteObject); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHostPtr host) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg size_t size_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(CreateRegionDataInitialMessage) + size_sz; char buf[msg_len]; CreateRegionDataInitialMessage* msg = (CreateRegionDataInitialMessage*)buf; msg->type = MessageTypes::CREATEREGIONDATA; msg->dimensions = _D; memcpy(msg->size, size, size_sz); host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, buf, msg_len); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const IndexT* partOffset, RemoteHostPtr host) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg CreateRegionDataPartInitialMessage msg; msg.type = MessageTypes::CREATEREGIONDATAPART; msg.dimensions = _D; memcpy(msg.size, size, sizeof(msg.size)); if (partOffset) { memcpy(msg.partOffset, partOffset, sizeof(msg.partOffset)); } int len = sizeof(CreateRegionDataPartInitialMessage); host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len); } RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHost& host, const MessageType initialMessageType, const EncodedPtr encodePtr) { init(dimensions, size, new RegionDataRemoteObject()); // InitialMsg EncodedPtrInitialMessage msg; msg.type = initialMessageType; msg.encodedPtr = encodePtr; int len = sizeof(EncodedPtrInitialMessage); host.createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len); } void RegionDataRemote::init(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) { _D = dimensions; _type = RegionDataTypes::REGIONDATAREMOTE; _remoteObject = remoteObject; memcpy(_size, size, sizeof(IndexT) * _D); } int RegionDataRemote::allocData() { void* data; size_t len; this->fetchData(0, MessageTypes::ALLOCDATA, 0, &data, &len); AllocDataReplyMessage* reply = (AllocDataReplyMessage*)data; ElementT result = reply->result; free(reply); return result; } void RegionDataRemote::randomize() { void* data; size_t len; this->fetchData(0, MessageTypes::RANDOMIZEDATA, 0, &data, &len); free(data); } IRegionCachePtr RegionDataRemote::cacheGenerator() const { IndexT multipliers[_D]; multipliers[0] = 1; for (int i = 1; i < _D; i++) { multipliers[i] = multipliers[i - 1] * _size[i - 1]; } return new RegionDataRemoteCache(this, _D, multipliers); } IRegionCachePtr RegionDataRemote::cache() const { #ifdef DISTRIBUTED_CACHE return WorkerThread::self()->cache()->get(this); #else return NULL; #endif } void RegionDataRemote::invalidateCache() { #ifdef DISTRIBUTED_CACHE cache()->invalidate(); #endif } ElementT RegionDataRemote::readCell(const IndexT* coord) const { #ifdef DISTRIBUTED_CACHE return cache()->readCell(coord); #else return readNoCache(coord); #endif } ElementT RegionDataRemote::readNoCache(const IndexT* coord) const { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(ReadCellMessage) + coord_sz; char buf[msg_len]; ReadCellMessage* msg = (ReadCellMessage*)buf; memcpy(msg->coord, coord, coord_sz); void* data; size_t len; this->fetchData(buf, MessageTypes::READCELL, msg_len, &data, &len); ReadCellReplyMessage* reply = (ReadCellReplyMessage*)data; ElementT value = reply->value; free(reply); return value; } void RegionDataRemote::readByCache(void* request, size_t request_len, void* reply, size_t &/*reply_len*/) const { void* data; size_t len; this->fetchData(request, MessageTypes::READCELLCACHE, request_len, &data, &len); ReadCellCacheReplyMessage* r = (ReadCellCacheReplyMessage*)data; RegionDataRemoteCacheLine* cacheLine = (RegionDataRemoteCacheLine*)reply; cacheLine->start = r->start; cacheLine->end = r->end; memcpy(cacheLine->base, r->values, sizeof(ElementT) * (r->end + 1)); free(r); } void RegionDataRemote::writeCell(const IndexT* coord, ElementT value) { #ifdef DISTRIBUTED_CACHE cache()->writeCell(coord, value); #else writeNoCache(coord, value); #endif } void RegionDataRemote::writeNoCache(const IndexT* coord, ElementT value) { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(WriteCellMessage) + coord_sz; char buf[msg_len]; WriteCellMessage* msg = (WriteCellMessage*)buf; msg->value = value; memcpy(msg->coord, coord, coord_sz); JTRACE("write")(_D)(sizeof(IndexT))(coord_sz)(msg_len); void* data; size_t len; this->fetchData(buf, MessageTypes::WRITECELL, msg_len, &data, &len); WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data; free(reply); } void RegionDataRemote::writeByCache(const IndexT* coord, ElementT value) const { size_t coord_sz = _D * sizeof(IndexT); size_t msg_len = sizeof(WriteCellMessage) + coord_sz; char buf[msg_len]; WriteCellMessage* msg = (WriteCellMessage*)buf; msg->value = value; memcpy(msg->coord, coord, coord_sz); void* data; size_t len; this->fetchData(msg, MessageTypes::WRITECELL, msg_len, &data, &len); WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data; free(reply); } DataHostPidList RegionDataRemote::hosts(IndexT* begin, IndexT* end) { GetHostListMessage msg; memcpy(msg.begin, begin, _D * sizeof(IndexT)); memcpy(msg.end, end, _D * sizeof(IndexT)); void* data; size_t len; this->fetchData(&msg, MessageTypes::GETHOSTLIST, sizeof(GetHostListMessage), &data, &len); GetHostListReplyMessage* reply = (GetHostListReplyMessage*)data; DataHostPidList list; for (int i = 0; i < reply->numHosts; i++) { list.push_back(reply->hosts[i]); } free(reply); return list; } RemoteHostPtr RegionDataRemote::host() { return _remoteObject->host(); } UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain(UpdateHandlerChainMessage& msg) { msg.numHops += 1; void* data; size_t len; this->fetchData(&msg, MessageTypes::UPDATEHANDLERCHAIN, sizeof(UpdateHandlerChainMessage), &data, &len); UpdateHandlerChainReplyMessage* _reply = (UpdateHandlerChainReplyMessage*)data; UpdateHandlerChainReplyMessage reply = *_reply; free(_reply); return reply; } UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain() { UpdateHandlerChainMessage msg; msg.requester = HostPid::self(); msg.numHops = 0; return this->updateHandlerChain(msg); } void RegionDataRemote::fetchData(const void* msg, MessageType type, size_t len, void** responseData, size_t* responseLen) const { *responseData = 0; *responseLen = 0; size_t dataLen = sizeof(GeneralMessageHeader) + len; GeneralMessageHeader* header = (GeneralMessageHeader*)malloc(dataLen); header->isForwardMessage = false; header->type = type; header->contentOffset = sizeof(GeneralMessageHeader); header->responseData = reinterpret_cast<EncodedPtr>(responseData); header->responseLen = reinterpret_cast<EncodedPtr>(responseLen); memcpy(header->content(), msg, len); _remoteObject->send(header, dataLen); free(header); // wait for the data while (*responseData == 0 || *responseLen == 0) { jalib::memFence(); sched_yield(); } } void RegionDataRemote::onRecv(const void* data, size_t len) { const BaseMessageHeader* base = (const BaseMessageHeader*)data; if (base->isForwardMessage) { const ForwardMessageHeader* header = (const ForwardMessageHeader*)data; IRegionReplyProxy* proxy = reinterpret_cast<IRegionReplyProxy*>(header->callback); proxy->processReplyMsg(base, len); } else { const GeneralMessageHeader* header = (const GeneralMessageHeader*)data; const void** responseData = reinterpret_cast<const void**>(header->responseData); size_t* responseLen = reinterpret_cast<size_t*>(header->responseLen); size_t sz = len - base->contentOffset; void* msg = malloc(sz); memcpy(msg, base->content(), sz); *responseData = msg; *responseLen = sz; } } // Process remote messages void RegionDataRemote::forwardMessage(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { size_t len = sizeof(ForwardMessageHeader) + baseLen; ForwardMessageHeader* data = (ForwardMessageHeader*)malloc(len); data->isForwardMessage = true; data->type = base->type; data->contentOffset = sizeof(ForwardMessageHeader) + base->contentOffset; data->callback = reinterpret_cast<EncodedPtr>(caller); memcpy(data->next(), base, baseLen); _remoteObject->send(data, len); free(data); } void RegionDataRemote::processReadCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processWriteCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processAllocDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processRandomizeDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processUpdateHandlerChainMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller, RegionDataIPtr) { UpdateHandlerChainMessage* msg = (UpdateHandlerChainMessage*)base->content(); msg->numHops++; this->forwardMessage(base, baseLen, caller); } void RegionDataRemote::processGetHostListMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) { this->forwardMessage(base, baseLen, caller); } RemoteObjectPtr RegionDataRemote::genRemote() { return new RegionDataRemoteObject(); } <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/fusion_bitcast_lift.h" #include <vector> #include "absl/types/span.h" #include "tensorflow/compiler/xla/service/hlo_dce.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/tests/filecheck.h" namespace xla { namespace gpu { namespace { class FusionBitcastLiftTest : public HloTestBase {}; // Tests that we lift bitcast outside the fusion. // // This test MultiOutputFusion, multiple consecutive lift, bitcast // with multiple users and bitcast that are used many time by the same // user. This is a real kernel from Efficient Net, but with smaller // shape to speed up tests. // // Input graph: // Fusion 4d input, 2 1d output // // After optimization, the graph is: // Bitcast 4d -> 2d // | // Fusion 2d input, 2x1d outputs. TEST_F(FusionBitcastLiftTest, NoBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.21_4d (param_0.59: f16[2,14,14,672]) -> (f32[672], f32[672]) { %param_0.59 = f16[2,14,14,672] parameter(0) %convert.21 = f32[2,14,14,672] convert(%param_0.59) %bitcast.25 = f32[392,672] bitcast(%convert.21) %constant_84 = f32[] constant(0) %reduce.12 = f32[672]{0} reduce(%bitcast.25, %constant_84), dimensions={0}, to_apply=%scalar_add_computation %multiply.43.clone.1 = f32[2,14,14,672] multiply(%convert.21, %convert.21) %bitcast.24.clone.1 = f32[392,672] bitcast(%multiply.43.clone.1) %reduce.11.clone.1 = f32[672]{0} reduce(%bitcast.24.clone.1, %constant_84), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple.13 = (f32[672]{0}, f32[672]{0}) tuple(%reduce.12, %reduce.11.clone.1) } ENTRY main { %param_0.59 = f16[2,14,14,672] parameter(0) ROOT %fusion.21_4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0.59), kind=kInput, calls=%fused_computation.21_4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: %param_0.0 = f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: ROOT %fusion.21_4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } // Tests that we lift bitcast outside the fusion when scalar broadcasting are // present. // // Input graph: // Fusion 1x4d and 1x0d inputs, 2 1d output // // After optimization, the graph is: // Bitcast 4d -> 2d // | // Fusion 1x2d and 1x0d inputs, 2 1d output // Inside the fusion, there is a bitcast left after the broadcast. TEST_F(FusionBitcastLiftTest, ScalarBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.21_4d (param_0.59: f16[2,14,14,672], param_1: f32[]) -> (f32[672], f32[672]) { %param_0.59 = f16[2,14,14,672] parameter(0) %convert.21 = f32[2,14,14,672] convert(%param_0.59) %bitcast.25 = f32[392,672] bitcast(%convert.21) %constant_84 = f32[] constant(0) %reduce.12 = f32[672]{0} reduce(%bitcast.25, %constant_84), dimensions={0}, to_apply=%scalar_add_computation %param_1 = f32[] parameter(1) %broadcast = f32[2,14,14,672] broadcast(%param_1), dimensions={} %multiply.43.clone.1 = f32[2,14,14,672] multiply(%convert.21, %broadcast) %bitcast.24.clone.1 = f32[392,672] bitcast(%multiply.43.clone.1) %reduce.11.clone.1 = f32[672]{0} reduce(%bitcast.24.clone.1, %constant_84), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple.13 = (f32[672]{0}, f32[672]{0}) tuple(%reduce.12, %reduce.11.clone.1) } ENTRY main { %param_0.59 = f16[2,14,14,672] parameter(0) %param_1 = f32[] parameter(1) ROOT %fusion.21_4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0.59, %param_1), kind=kInput, calls=%fused_computation.21_4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK: f32[] parameter(1) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK: %broadcast.1 = ; CHECK-NEXT: bitcast(f32[2,14,14,672]{3,2,1,0} %broadcast.1) ; CHECK-NOT: bitcast( ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: %param_0.0 = f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: %param_1.1 = f32[] parameter(1) ; CHECK-NEXT: ROOT %fusion.21_4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } TEST_F(FusionBitcastLiftTest, RowBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.21_4d (param_0.59: f16[2,14,14,672], param_1: f32[672]) -> (f32[672], f32[672]) { %param_0.59 = f16[2,14,14,672] parameter(0) %convert.21 = f32[2,14,14,672] convert(%param_0.59) %bitcast.25 = f32[392,672] bitcast(%convert.21) %constant_84 = f32[] constant(0) %reduce.12 = f32[672]{0} reduce(%bitcast.25, %constant_84), dimensions={0}, to_apply=%scalar_add_computation %param_1 = f32[672] parameter(1) %broadcast = f32[2,14,14,672] broadcast(%param_1), dimensions={3} %multiply.43.clone.1 = f32[2,14,14,672] multiply(%convert.21, %broadcast) %bitcast.24.clone.1 = f32[392,672] bitcast(%multiply.43.clone.1) %reduce.11.clone.1 = f32[672]{0} reduce(%bitcast.24.clone.1, %constant_84), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple.13 = (f32[672]{0}, f32[672]{0}) tuple(%reduce.12, %reduce.11.clone.1) } ENTRY main { %param_0.59 = f16[2,14,14,672] parameter(0) %param_1 = f32[672] parameter(1) ROOT %fusion.21_4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0.59, %param_1), kind=kInput, calls=%fused_computation.21_4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK: f32[672]{0} parameter(1) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK: %broadcast.1 ; CHECK: bitcast(f32[2,14,14,672]{3,2,1,0} %broadcast.1) ; CHECK-NOT: bitcast( ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: %param_0.0 = f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: %param_1.1 = f32[672]{0} parameter(1) ; CHECK-NEXT: ROOT %fusion.21_4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } } // namespace } // namespace gpu } // namespace xla <commit_msg>Clean up HLO in tests.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/fusion_bitcast_lift.h" #include <vector> #include "absl/types/span.h" #include "tensorflow/compiler/xla/service/hlo_dce.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/tests/filecheck.h" namespace xla { namespace gpu { namespace { class FusionBitcastLiftTest : public HloTestBase {}; // Tests that we lift bitcast outside the fusion. // // This test MultiOutputFusion, multiple consecutive lift, bitcast // with multiple users and bitcast that are used many time by the same // user. This is a real kernel from Efficient Net, but with smaller // shape to speed up tests. // // Input graph: // Fusion 4d input, 2 1d output // // After optimization, the graph is: // Bitcast 4d -> 2d // | // Fusion 2d input, 2x1d outputs. TEST_F(FusionBitcastLiftTest, NoBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.4d (param_0: f16[2,14,14,672]) -> (f32[672], f32[672]) { %param_0 = f16[2,14,14,672] parameter(0) %convert = f32[2,14,14,672] convert(%param_0) %bitcast.1 = f32[392,672] bitcast(%convert) %constant_0 = f32[] constant(0) %reduce.1 = f32[672]{0} reduce(%bitcast.1, %constant_0), dimensions={0}, to_apply=%scalar_add_computation %multiply = f32[2,14,14,672] multiply(%convert, %convert) %bitcast.2 = f32[392,672] bitcast(%multiply) %reduce.2 = f32[672]{0} reduce(%bitcast.2, %constant_0), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple = (f32[672]{0}, f32[672]{0}) tuple(%reduce.1, %reduce.2) } ENTRY %main { %param_0 = f16[2,14,14,672] parameter(0) ROOT %fusion.4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0), kind=kInput, calls=%fused_computation.4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: ROOT %fusion.4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } // Tests that we lift bitcast outside the fusion when scalar broadcasting are // present. // // Input graph: // Fusion 1x4d and 1x0d inputs, 2 1d output // // After optimization, the graph is: // Bitcast 4d -> 2d // | // Fusion 1x2d and 1x0d inputs, 2 1d output // Inside the fusion, there is a bitcast left after the broadcast. TEST_F(FusionBitcastLiftTest, ScalarBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.4d (param_0: f16[2,14,14,672], param_1: f32[]) -> (f32[672], f32[672]) { %param_0 = f16[2,14,14,672] parameter(0) %convert = f32[2,14,14,672] convert(%param_0) %bitcast.1 = f32[392,672] bitcast(%convert) %constant_0 = f32[] constant(0) %reduce.1 = f32[672]{0} reduce(%bitcast.1, %constant_0), dimensions={0}, to_apply=%scalar_add_computation %param_1 = f32[] parameter(1) %broadcast = f32[2,14,14,672] broadcast(%param_1), dimensions={} %multiply = f32[2,14,14,672] multiply(%convert, %broadcast) %bitcast.2 = f32[392,672] bitcast(%multiply) %reduce.2 = f32[672]{0} reduce(%bitcast.2, %constant_0), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple = (f32[672]{0}, f32[672]{0}) tuple(%reduce.1, %reduce.2) } ENTRY %main { %param_0 = f16[2,14,14,672] parameter(0) %param_1 = f32[] parameter(1) ROOT %fusion.4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0, %param_1), kind=kInput, calls=%fused_computation.4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK: f32[] parameter(1) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK: %broadcast.1 = ; CHECK-NEXT: bitcast(f32[2,14,14,672]{3,2,1,0} %broadcast.1) ; CHECK-NOT: bitcast( ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: %param_1.1 = f32[] parameter(1) ; CHECK-NEXT: ROOT %fusion.4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } TEST_F(FusionBitcastLiftTest, RowBroadcastTest) { const char* hlo_text = R"( HloModule mod %scalar_add_computation (scalar_lhs.1: f32[], scalar_rhs.1: f32[]) -> f32[] { %scalar_lhs.1 = f32[] parameter(0) %scalar_rhs.1 = f32[] parameter(1) ROOT %add.5 = f32[] add(f32[] %scalar_lhs.1, f32[] %scalar_rhs.1) } %fused_computation.4d (param_0: f16[2,14,14,672], param_1: f32[672]) -> (f32[672], f32[672]) { %param_0 = f16[2,14,14,672] parameter(0) %convert = f32[2,14,14,672] convert(%param_0) %bitcast.1 = f32[392,672] bitcast(%convert) %constant_0 = f32[] constant(0) %reduce.1 = f32[672]{0} reduce(%bitcast.1, %constant_0), dimensions={0}, to_apply=%scalar_add_computation %param_1 = f32[672] parameter(1) %broadcast = f32[2,14,14,672] broadcast(%param_1), dimensions={3} %multiply = f32[2,14,14,672] multiply(%convert, %broadcast) %bitcast.2 = f32[392,672] bitcast(%multiply) %reduce.2 = f32[672]{0} reduce(%bitcast.2, %constant_0), dimensions={0}, to_apply=%scalar_add_computation ROOT %tuple = (f32[672]{0}, f32[672]{0}) tuple(%reduce.1, %reduce.2) } ENTRY %main { %param_0 = f16[2,14,14,672] parameter(0) %param_1 = f32[672] parameter(1) ROOT %fusion.4d = (f32[672]{0}, f32[672]{0}) fusion(%param_0, %param_1), kind=kInput, calls=%fused_computation.4d } )"; auto module = ParseAndReturnVerifiedModule(hlo_text).ValueOrDie(); EXPECT_TRUE(FusionBitcastLift().Run(module.get()).ValueOrDie()); // Remove the old fusion not used anymore. EXPECT_TRUE(HloDCE().Run(module.get()).ValueOrDie()); EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); StatusOr<bool> filecheck_result = RunFileCheck(module->ToString(), R"( ; CHECK-LABEL: %fused_computation ; CHECK: f16[392,672]{1,0} parameter(0) ; CHECK: f32[672]{0} parameter(1) ; CHECK-NOT: parameter ; CHECK-NOT: bitcast ; CHECK: %broadcast.1 ; CHECK: bitcast(f32[2,14,14,672]{3,2,1,0} %broadcast.1) ; CHECK-NOT: bitcast( ; CHECK-LABEL: ENTRY %main ; CHECK-NEXT: f16[2,14,14,672]{3,2,1,0} parameter(0) ; CHECK-NEXT: bitcast( ; CHECK-NEXT: %param_1.1 = f32[672]{0} parameter(1) ; CHECK-NEXT: ROOT %fusion.4d.bitcast )"); EXPECT_TRUE(filecheck_result.status().ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } } // namespace } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "runconfigurationaspects.h" #include "project.h" #include "runconfiguration.h" #include "environmentaspect.h" #include <coreplugin/coreconstants.h> #include <utils/fancylineedit.h> #include <utils/pathchooser.h> #include <QCheckBox> #include <QLineEdit> #include <QDebug> #include <QFormLayout> #include <QLabel> #include <QToolButton> using namespace Utils; namespace ProjectExplorer { /*! \class ProjectExplorer::TerminalAspect */ TerminalAspect::TerminalAspect(RunConfiguration *runConfig, const QString &key, bool useTerminal, bool userSet) : IRunConfigurationAspect(runConfig), m_useTerminal(useTerminal), m_userSet(userSet), m_checkBox(0), m_key(key) { setDisplayName(tr("Terminal")); setId("TerminalAspect"); } TerminalAspect *TerminalAspect::create(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, false, false); } TerminalAspect *TerminalAspect::clone(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, m_useTerminal, m_userSet); } void TerminalAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_checkBox); m_checkBox = new QCheckBox(tr("Run in terminal"), parent); m_checkBox->setChecked(m_useTerminal); layout->addRow(QString(), m_checkBox); connect(m_checkBox.data(), &QAbstractButton::clicked, this, [this] { m_userSet = true; m_useTerminal = m_checkBox->isChecked(); emit useTerminalChanged(m_useTerminal); }); } void TerminalAspect::fromMap(const QVariantMap &map) { if (map.contains(m_key)) { m_useTerminal = map.value(m_key).toBool(); m_userSet = true; } else { m_userSet = false; } } void TerminalAspect::toMap(QVariantMap &data) const { if (m_userSet) data.insert(m_key, m_useTerminal); } bool TerminalAspect::useTerminal() const { return m_useTerminal; } void TerminalAspect::setUseTerminal(bool useTerminal) { if (m_useTerminal != useTerminal) { m_useTerminal = useTerminal; emit useTerminalChanged(useTerminal); } if (m_checkBox) m_checkBox->setChecked(m_useTerminal); } bool TerminalAspect::isUserSet() const { return m_userSet; } ApplicationLauncher::Mode TerminalAspect::runMode() const { return m_useTerminal ? ApplicationLauncher::Console : ApplicationLauncher::Gui; } void TerminalAspect::setRunMode(ApplicationLauncher::Mode runMode) { setUseTerminal(runMode == ApplicationLauncher::Console); } /*! \class ProjectExplorer::WorkingDirectoryAspect */ WorkingDirectoryAspect::WorkingDirectoryAspect(RunConfiguration *runConfig, const QString &key, const QString &dir) : IRunConfigurationAspect(runConfig), m_workingDirectory(dir), m_chooser(0), m_key(key) { setDisplayName(tr("Working Directory")); setId("WorkingDirectoryAspect"); } WorkingDirectoryAspect *WorkingDirectoryAspect::create(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key); } WorkingDirectoryAspect *WorkingDirectoryAspect::clone(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key, m_workingDirectory); } void WorkingDirectoryAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new PathChooser(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setExpectedKind(Utils::PathChooser::Directory); m_chooser->setPromptDialogTitle(tr("Select Working Directory")); connect(m_chooser.data(), &PathChooser::pathChanged, this, &WorkingDirectoryAspect::setWorkingDirectory); auto resetButton = new QToolButton(parent); resetButton->setToolTip(tr("Reset to default")); resetButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RESET))); connect(resetButton, &QAbstractButton::clicked, this, &WorkingDirectoryAspect::resetPath); if (auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>()) { connect(envAspect, &EnvironmentAspect::environmentChanged, this, &WorkingDirectoryAspect::updateEnvironment); updateEnvironment(); } auto hbox = new QHBoxLayout; hbox->addWidget(m_chooser); hbox->addWidget(resetButton); layout->addRow(tr("Working directory:"), hbox); } void WorkingDirectoryAspect::updateEnvironment() { auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>(); QTC_ASSERT(envAspect, return); QTC_ASSERT(m_chooser, return); m_chooser->setEnvironment(envAspect->environment()); } void WorkingDirectoryAspect::resetPath() { QTC_ASSERT(m_chooser, return); m_chooser->setPath(QString()); } void WorkingDirectoryAspect::fromMap(const QVariantMap &map) { m_workingDirectory = map.value(m_key).toBool(); } void WorkingDirectoryAspect::toMap(QVariantMap &data) const { data.insert(m_key, m_workingDirectory); } QString WorkingDirectoryAspect::workingDirectory() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_workingDirectory); } QString WorkingDirectoryAspect::unexpandedWorkingDirectory() const { return m_workingDirectory; } void WorkingDirectoryAspect::setWorkingDirectory(const QString &workingDirectory) { m_workingDirectory = workingDirectory; } PathChooser *WorkingDirectoryAspect::pathChooser() const { return m_chooser; } /*! \class ProjectExplorer::ArgumentsAspect */ ArgumentsAspect::ArgumentsAspect(RunConfiguration *runConfig, const QString &key, const QString &arguments) : IRunConfigurationAspect(runConfig), m_arguments(arguments), m_chooser(0), m_key(key) { setDisplayName(tr("Arguments")); setId("ArgumentsAspect"); } QString ArgumentsAspect::arguments() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_arguments); } QString ArgumentsAspect::unexpandedArguments() const { return m_arguments; } void ArgumentsAspect::setArguments(const QString &arguments) { if (arguments != m_arguments) { m_arguments = arguments; emit argumentsChanged(arguments); } if (m_chooser->text() != arguments) m_chooser->setText(arguments); } void ArgumentsAspect::fromMap(const QVariantMap &map) { m_arguments = map.value(m_key).toString(); } void ArgumentsAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_arguments); } ArgumentsAspect *ArgumentsAspect::create(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key); } ArgumentsAspect *ArgumentsAspect::clone(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key, m_arguments); } void ArgumentsAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setText(m_arguments); connect(m_chooser.data(), &QLineEdit::textChanged, this, &ArgumentsAspect::setArguments); layout->addRow(tr("Command line arguments:"), m_chooser); } } // namespace ProjectExplorer <commit_msg>WorkingDirectoryAspect: Fix restoring.<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "runconfigurationaspects.h" #include "project.h" #include "runconfiguration.h" #include "environmentaspect.h" #include <coreplugin/coreconstants.h> #include <utils/fancylineedit.h> #include <utils/pathchooser.h> #include <QCheckBox> #include <QLineEdit> #include <QDebug> #include <QFormLayout> #include <QLabel> #include <QToolButton> using namespace Utils; namespace ProjectExplorer { /*! \class ProjectExplorer::TerminalAspect */ TerminalAspect::TerminalAspect(RunConfiguration *runConfig, const QString &key, bool useTerminal, bool userSet) : IRunConfigurationAspect(runConfig), m_useTerminal(useTerminal), m_userSet(userSet), m_checkBox(0), m_key(key) { setDisplayName(tr("Terminal")); setId("TerminalAspect"); } TerminalAspect *TerminalAspect::create(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, false, false); } TerminalAspect *TerminalAspect::clone(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, m_useTerminal, m_userSet); } void TerminalAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_checkBox); m_checkBox = new QCheckBox(tr("Run in terminal"), parent); m_checkBox->setChecked(m_useTerminal); layout->addRow(QString(), m_checkBox); connect(m_checkBox.data(), &QAbstractButton::clicked, this, [this] { m_userSet = true; m_useTerminal = m_checkBox->isChecked(); emit useTerminalChanged(m_useTerminal); }); } void TerminalAspect::fromMap(const QVariantMap &map) { if (map.contains(m_key)) { m_useTerminal = map.value(m_key).toBool(); m_userSet = true; } else { m_userSet = false; } } void TerminalAspect::toMap(QVariantMap &data) const { if (m_userSet) data.insert(m_key, m_useTerminal); } bool TerminalAspect::useTerminal() const { return m_useTerminal; } void TerminalAspect::setUseTerminal(bool useTerminal) { if (m_useTerminal != useTerminal) { m_useTerminal = useTerminal; emit useTerminalChanged(useTerminal); } if (m_checkBox) m_checkBox->setChecked(m_useTerminal); } bool TerminalAspect::isUserSet() const { return m_userSet; } ApplicationLauncher::Mode TerminalAspect::runMode() const { return m_useTerminal ? ApplicationLauncher::Console : ApplicationLauncher::Gui; } void TerminalAspect::setRunMode(ApplicationLauncher::Mode runMode) { setUseTerminal(runMode == ApplicationLauncher::Console); } /*! \class ProjectExplorer::WorkingDirectoryAspect */ WorkingDirectoryAspect::WorkingDirectoryAspect(RunConfiguration *runConfig, const QString &key, const QString &dir) : IRunConfigurationAspect(runConfig), m_workingDirectory(dir), m_chooser(0), m_key(key) { setDisplayName(tr("Working Directory")); setId("WorkingDirectoryAspect"); } WorkingDirectoryAspect *WorkingDirectoryAspect::create(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key); } WorkingDirectoryAspect *WorkingDirectoryAspect::clone(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key, m_workingDirectory); } void WorkingDirectoryAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new PathChooser(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setExpectedKind(Utils::PathChooser::Directory); m_chooser->setPromptDialogTitle(tr("Select Working Directory")); connect(m_chooser.data(), &PathChooser::pathChanged, this, &WorkingDirectoryAspect::setWorkingDirectory); auto resetButton = new QToolButton(parent); resetButton->setToolTip(tr("Reset to default")); resetButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RESET))); connect(resetButton, &QAbstractButton::clicked, this, &WorkingDirectoryAspect::resetPath); if (auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>()) { connect(envAspect, &EnvironmentAspect::environmentChanged, this, &WorkingDirectoryAspect::updateEnvironment); updateEnvironment(); } auto hbox = new QHBoxLayout; hbox->addWidget(m_chooser); hbox->addWidget(resetButton); layout->addRow(tr("Working directory:"), hbox); } void WorkingDirectoryAspect::updateEnvironment() { auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>(); QTC_ASSERT(envAspect, return); QTC_ASSERT(m_chooser, return); m_chooser->setEnvironment(envAspect->environment()); } void WorkingDirectoryAspect::resetPath() { QTC_ASSERT(m_chooser, return); m_chooser->setPath(QString()); } void WorkingDirectoryAspect::fromMap(const QVariantMap &map) { m_workingDirectory = map.value(m_key).toString(); } void WorkingDirectoryAspect::toMap(QVariantMap &data) const { data.insert(m_key, m_workingDirectory); } QString WorkingDirectoryAspect::workingDirectory() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_workingDirectory); } QString WorkingDirectoryAspect::unexpandedWorkingDirectory() const { return m_workingDirectory; } void WorkingDirectoryAspect::setWorkingDirectory(const QString &workingDirectory) { m_workingDirectory = workingDirectory; } PathChooser *WorkingDirectoryAspect::pathChooser() const { return m_chooser; } /*! \class ProjectExplorer::ArgumentsAspect */ ArgumentsAspect::ArgumentsAspect(RunConfiguration *runConfig, const QString &key, const QString &arguments) : IRunConfigurationAspect(runConfig), m_arguments(arguments), m_chooser(0), m_key(key) { setDisplayName(tr("Arguments")); setId("ArgumentsAspect"); } QString ArgumentsAspect::arguments() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_arguments); } QString ArgumentsAspect::unexpandedArguments() const { return m_arguments; } void ArgumentsAspect::setArguments(const QString &arguments) { if (arguments != m_arguments) { m_arguments = arguments; emit argumentsChanged(arguments); } if (m_chooser->text() != arguments) m_chooser->setText(arguments); } void ArgumentsAspect::fromMap(const QVariantMap &map) { m_arguments = map.value(m_key).toString(); } void ArgumentsAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_arguments); } ArgumentsAspect *ArgumentsAspect::create(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key); } ArgumentsAspect *ArgumentsAspect::clone(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key, m_arguments); } void ArgumentsAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setText(m_arguments); connect(m_chooser.data(), &QLineEdit::textChanged, this, &ArgumentsAspect::setArguments); layout->addRow(tr("Command line arguments:"), m_chooser); } } // namespace ProjectExplorer <|endoftext|>
<commit_before>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Wu Lin * 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 Shogun Development Team. * */ #ifdef HAVE_EIGEN3 #include <shogun/machine/gp/LogitPiecewiseBoundLikelihood.h> using namespace shogun; using namespace Eigen; CLogitPiecewiseBoundLikelihood::CLogitPiecewiseBoundLikelihood() : CLogitLikelihood() { init(); } CLogitPiecewiseBoundLikelihood::~CLogitPiecewiseBoundLikelihood() { } void CLogitPiecewiseBoundLikelihood::set_bound(SGMatrix<float64_t> bound) { m_bound = bound; } void CLogitPiecewiseBoundLikelihood::set_distribution(SGVector<float64_t> mu, SGVector<float64_t> s2, const CLabels* lab) { REQUIRE(lab, "Labels are required (lab should not be NULL)\n"); REQUIRE((mu.vlen==s2.vlen) && (mu.vlen==lab->get_num_labels()), "Length of the vector of means (%d), length of the vector of " "variances (%d) and number of labels (%d) should be the same\n", mu.vlen, s2.vlen, lab->get_num_labels()); REQUIRE(lab->get_label_type()==LT_BINARY, "Labels must be type of CBinaryLabels\n"); for(index_t i = 0; i < s2.vlen; ++i) ASSERT(s2[i] > 0.0); m_lab = ((CBinaryLabels*)lab)->get_labels(); /** convert the input label to standard label used in the class * * Note that Shogun uses -1 and 1 as labels and this class uses * 0 and 1 repectively. * */ for(index_t i = 0; i < m_lab.size(); ++i) m_lab[i] = CMath::max(m_lab[i], 0.0); m_mu = mu; m_s2 = s2; precompute(); } void CLogitPiecewiseBoundLikelihood::init() { SG_ADD(&m_bound, "bound", "Variational piecewise bound for logit likelihood", MS_NOT_AVAILABLE); SG_ADD(&m_mu, "mu", "The mean of variational normal distribution", MS_AVAILABLE, GRADIENT_AVAILABLE); SG_ADD(&m_s2, "sigma2", "The variance of variational normal distribution", MS_AVAILABLE,GRADIENT_AVAILABLE); SG_ADD(&m_lab, "y", "The data/labels (must be 0 or 1) drawn from the distribution", MS_NOT_AVAILABLE); SG_ADD(&m_pl, "pdf_l", "The pdf given the lower range and parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_ph, "pdf_h", "The pdf given the higher range and parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_cdf_diff, "cdf_h_minus_cdf_l", "The CDF difference between the lower and higher range given the parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_l2_plus_s2, "l2_plus_sigma2", "The result of l^2 + sigma^2", MS_NOT_AVAILABLE); SG_ADD(&m_h2_plus_s2, "h2_plus_sigma2", "The result of h^2 + sigma^2", MS_NOT_AVAILABLE); SG_ADD(&m_weighted_pdf_diff, "weighted_pdf_diff", "The result of l*pdf(l_norm)-h*pdf(h_norm)", MS_NOT_AVAILABLE); } void CLogitPiecewiseBoundLikelihood::precompute() { const Map<VectorXd> eigen_c(m_bound.get_column_vector(0), m_bound.num_rows); const Map<VectorXd> eigen_b(m_bound.get_column_vector(1), m_bound.num_rows); const Map<VectorXd> eigen_a(m_bound.get_column_vector(2), m_bound.num_rows); const Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen); const Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen); Map<VectorXd> eigen_l(m_bound.get_column_vector(3), m_bound.num_rows); Map<VectorXd> eigen_h(m_bound.get_column_vector(4), m_bound.num_rows); index_t num_rows = m_bound.num_rows; index_t num_cols = m_mu.vlen; m_pl = SGMatrix<float64_t>(num_rows,num_cols); m_ph = SGMatrix<float64_t>(num_rows,num_cols); m_cdf_diff = SGMatrix<float64_t>(num_rows,num_cols); m_l2_plus_s2 = SGMatrix<float64_t>(num_rows,num_cols); m_h2_plus_s2 = SGMatrix<float64_t>(num_rows,num_cols); m_weighted_pdf_diff = SGMatrix<float64_t>(num_rows,num_cols); Map<MatrixXd> eigen_pl(m_pl.matrix, num_rows, num_cols); Map<MatrixXd> eigen_ph(m_ph.matrix, num_rows, num_cols); Map<MatrixXd> eigen_cdf_diff(m_cdf_diff.matrix, num_rows, num_cols); Map<MatrixXd> eigen_l2_plus_s2(m_l2_plus_s2.matrix, num_rows, num_cols); Map<MatrixXd> eigen_h2_plus_s2(m_h2_plus_s2.matrix, num_rows, num_cols); Map<MatrixXd> eigen_weighted_pdf_diff(m_weighted_pdf_diff.matrix, num_rows, num_cols); SGMatrix<float64_t> zl(num_rows, num_cols); Map<MatrixXd> eigen_zl(zl.matrix, num_rows, num_cols); SGMatrix<float64_t> zh(num_rows, num_cols); Map<MatrixXd> eigen_zh(zh.matrix, num_rows, num_cols); //bsxfun(@minus,l,m) eigen_zl = ((-eigen_mu).replicate(1,eigen_l.rows()).array().transpose().colwise() + eigen_l.array()).matrix(); //bsxfun(@minus,h,m) eigen_zh = ((-eigen_mu).replicate(1,eigen_h.rows()).array().transpose().colwise() + eigen_h.array()).matrix(); VectorXd eigen_s_inv = eigen_s2.array().sqrt().inverse().matrix(); //zl = bsxfun(@times, bsxfun(@minus,l,m), 1./sqrt(v)) eigen_zl = (eigen_zl.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); //zh = bsxfun(@times, bsxfun(@minus,h,m), 1./sqrt(v)) eigen_zh = (eigen_zh.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); for (index_t r = 0; r < zl.num_rows; r++) for (index_t c = 0; c < zl.num_cols; c++) { if (zl(r, c) == CMath::INFTY || zl(r, c) == -CMath::INFTY) m_pl(r, c) = 0; else m_pl(r, c) = CMath::exp(CGaussianDistribution::univariate_log_pdf(zl(r, c))); if (zh(r, c) == CMath::INFTY || zh(r, c) == -CMath::INFTY) m_ph(r, c) = 0; else m_ph(r, c) = CMath::exp(CGaussianDistribution::univariate_log_pdf(zh(r, c))); } //pl = bsxfun(@times, normpdf(zl), 1./sqrt(v)); eigen_pl = (eigen_pl.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); //ph = bsxfun(@times, normpdf(zh), 1./sqrt(v)); eigen_ph = (eigen_ph.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); SGMatrix<float64_t> & cl = zl; SGMatrix<float64_t> & ch = zh; for (index_t r = 0; r < zl.num_rows; r++) for (index_t c = 0; c < zl.num_cols; c++) { //cl = 0.5*erf(zl/sqrt(2)); %normal cdf -const cl(r, c) = CStatistics::normal_cdf(zl(r, c)) - 0.5; //ch = 0.5*erf(zl/sqrt(2)); %normal cdf -const ch(r, c) = CStatistics::normal_cdf(zh(r, c)) - 0.5; } Map<MatrixXd> eigen_cl(cl.matrix, num_rows, num_cols); Map<MatrixXd> eigen_ch(ch.matrix, num_rows, num_cols); eigen_cdf_diff = eigen_ch - eigen_cl; float64_t l_bak = eigen_l(0); eigen_l(0) = 0; float64_t h_bak = eigen_h(eigen_h.size()-1); eigen_h(eigen_h.size()-1) = 0; //bsxfun(@plus, l.^2, v) eigen_l2_plus_s2 = (eigen_s2.replicate(1,eigen_l.rows()).array().transpose().colwise() + eigen_l.array().pow(2)).matrix(); //bsxfun(@plus, h.^2, v) eigen_h2_plus_s2 = (eigen_s2.replicate(1,eigen_h.rows()).array().transpose().colwise() + eigen_h.array().pow(2)).matrix(); //pl.*l - ph.*h eigen_weighted_pdf_diff = (eigen_pl.array().colwise()*eigen_l.array() - eigen_ph.array().colwise()*eigen_h.array()).matrix(); eigen_l(0) = l_bak; eigen_h(eigen_h.size()-1) = h_bak; } #endif /* HAVE_EIGEN3 */ <commit_msg>add the get_variational_expection method<commit_after>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Wu Lin * 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 Shogun Development Team. * */ #ifdef HAVE_EIGEN3 #include <shogun/machine/gp/LogitPiecewiseBoundLikelihood.h> using namespace shogun; using namespace Eigen; CLogitPiecewiseBoundLikelihood::CLogitPiecewiseBoundLikelihood() : CLogitLikelihood() { init(); } CLogitPiecewiseBoundLikelihood::~CLogitPiecewiseBoundLikelihood() { } void CLogitPiecewiseBoundLikelihood::set_bound(SGMatrix<float64_t> bound) { m_bound = bound; } SGVector<float64_t> CLogitPiecewiseBoundLikelihood::get_variational_expection() { const Map<VectorXd> eigen_c(m_bound.get_column_vector(0), m_bound.num_rows); const Map<VectorXd> eigen_b(m_bound.get_column_vector(1), m_bound.num_rows); const Map<VectorXd> eigen_a(m_bound.get_column_vector(2), m_bound.num_rows); const Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen); const Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen); Map<VectorXd> eigen_l(m_bound.get_column_vector(3), m_bound.num_rows); Map<VectorXd> eigen_h(m_bound.get_column_vector(4), m_bound.num_rows); index_t num_rows = m_bound.num_rows; index_t num_cols = m_mu.vlen; const Map<MatrixXd> eigen_cdf_diff(m_cdf_diff.matrix, num_rows, num_cols); const Map<MatrixXd> eigen_pl(m_pl.matrix, num_rows, num_cols); const Map<MatrixXd> eigen_ph(m_ph.matrix, num_rows, num_cols); float64_t l_bak = eigen_l(0); //l(1) = 0; eigen_l(0) = 0; float64_t h_bak = eigen_h(eigen_h.size()-1); //h(end) = 0; eigen_h(eigen_h.size()-1) = 0; //ex0 = ch-cl; const Map<MatrixXd> & eigen_ex0 = eigen_cdf_diff; //%ex1= v.*(pl-ph) + m.*(ch-cl); MatrixXd eigen_ex1 = ((eigen_pl - eigen_ph).array().rowwise()*eigen_s2.array().transpose() + eigen_cdf_diff.array().rowwise()*eigen_mu.array().transpose()).matrix(); //ex2 = bsxfun(@times, v, (bsxfun(@plus, l, m)).*pl - (bsxfun(@plus, h, m)).*ph) + bsxfun(@times, (v+m.^2), ex0); //bsxfun(@plus, l, m)).*pl - (bsxfun(@plus, h, m)).*ph MatrixXd eigen_ex2 = ((eigen_mu.replicate(1,eigen_l.rows()).array().transpose().colwise() + eigen_l.array())*eigen_pl.array() - (eigen_mu.replicate(1,eigen_h.rows()).array().transpose().colwise() + eigen_h.array())*eigen_ph.array()).matrix(); //bsxfun(@times, v, (bsxfun(@plus, l, m).*pl - bsxfun(@plus, h, m).*ph eigen_ex2 = (eigen_ex2.array().rowwise()*eigen_s2.array().transpose()).matrix(); //ex2 = bsxfun(@times, v, (bsxfun(@plus, l, m)).*pl - (bsxfun(@plus, h, m)).*ph) + bsxfun(@times, (v+m.^2), ex0); eigen_ex2 += (eigen_cdf_diff.array().rowwise()*(eigen_mu.array().pow(2) + eigen_s2.array()).transpose()).matrix(); SGVector<float64_t> f(m_mu.vlen); Map<VectorXd> eigen_f(f.vector, f.vlen); //%f = sum((a.*ex2 + b.*ex1 + c.*ex0),1); eigen_f = (eigen_ex2.array().colwise()*eigen_a.array() + eigen_ex1.array().colwise()*eigen_b.array() + eigen_ex0.array().colwise()*eigen_c.array()).colwise().sum().matrix(); eigen_l(0) = l_bak; eigen_h(eigen_h.size()-1) = h_bak; Map<VectorXd>eigen_lab(m_lab.vector, m_lab.vlen); eigen_f = eigen_lab.cwiseProduct(eigen_mu) - eigen_f; return f; } void CLogitPiecewiseBoundLikelihood::set_distribution(SGVector<float64_t> mu, SGVector<float64_t> s2, const CLabels* lab) { REQUIRE(lab, "Labels are required (lab should not be NULL)\n"); REQUIRE((mu.vlen==s2.vlen) && (mu.vlen==lab->get_num_labels()), "Length of the vector of means (%d), length of the vector of " "variances (%d) and number of labels (%d) should be the same\n", mu.vlen, s2.vlen, lab->get_num_labels()); REQUIRE(lab->get_label_type()==LT_BINARY, "Labels must be type of CBinaryLabels\n"); for(index_t i = 0; i < s2.vlen; ++i) ASSERT(s2[i] > 0.0); m_lab = ((CBinaryLabels*)lab)->get_labels(); /** convert the input label to standard label used in the class * * Note that Shogun uses -1 and 1 as labels and this class uses * 0 and 1 repectively. * */ for(index_t i = 0; i < m_lab.size(); ++i) m_lab[i] = CMath::max(m_lab[i], 0.0); m_mu = mu; m_s2 = s2; precompute(); } void CLogitPiecewiseBoundLikelihood::init() { SG_ADD(&m_bound, "bound", "Variational piecewise bound for logit likelihood", MS_NOT_AVAILABLE); SG_ADD(&m_mu, "mu", "The mean of variational normal distribution", MS_AVAILABLE, GRADIENT_AVAILABLE); SG_ADD(&m_s2, "sigma2", "The variance of variational normal distribution", MS_AVAILABLE,GRADIENT_AVAILABLE); SG_ADD(&m_lab, "y", "The data/labels (must be 0 or 1) drawn from the distribution", MS_NOT_AVAILABLE); SG_ADD(&m_pl, "pdf_l", "The pdf given the lower range and parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_ph, "pdf_h", "The pdf given the higher range and parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_cdf_diff, "cdf_h_minus_cdf_l", "The CDF difference between the lower and higher range given the parameters(mu and variance)", MS_NOT_AVAILABLE); SG_ADD(&m_l2_plus_s2, "l2_plus_sigma2", "The result of l^2 + sigma^2", MS_NOT_AVAILABLE); SG_ADD(&m_h2_plus_s2, "h2_plus_sigma2", "The result of h^2 + sigma^2", MS_NOT_AVAILABLE); SG_ADD(&m_weighted_pdf_diff, "weighted_pdf_diff", "The result of l*pdf(l_norm)-h*pdf(h_norm)", MS_NOT_AVAILABLE); } void CLogitPiecewiseBoundLikelihood::precompute() { const Map<VectorXd> eigen_c(m_bound.get_column_vector(0), m_bound.num_rows); const Map<VectorXd> eigen_b(m_bound.get_column_vector(1), m_bound.num_rows); const Map<VectorXd> eigen_a(m_bound.get_column_vector(2), m_bound.num_rows); const Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen); const Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen); Map<VectorXd> eigen_l(m_bound.get_column_vector(3), m_bound.num_rows); Map<VectorXd> eigen_h(m_bound.get_column_vector(4), m_bound.num_rows); index_t num_rows = m_bound.num_rows; index_t num_cols = m_mu.vlen; m_pl = SGMatrix<float64_t>(num_rows,num_cols); m_ph = SGMatrix<float64_t>(num_rows,num_cols); m_cdf_diff = SGMatrix<float64_t>(num_rows,num_cols); m_l2_plus_s2 = SGMatrix<float64_t>(num_rows,num_cols); m_h2_plus_s2 = SGMatrix<float64_t>(num_rows,num_cols); m_weighted_pdf_diff = SGMatrix<float64_t>(num_rows,num_cols); Map<MatrixXd> eigen_pl(m_pl.matrix, num_rows, num_cols); Map<MatrixXd> eigen_ph(m_ph.matrix, num_rows, num_cols); Map<MatrixXd> eigen_cdf_diff(m_cdf_diff.matrix, num_rows, num_cols); Map<MatrixXd> eigen_l2_plus_s2(m_l2_plus_s2.matrix, num_rows, num_cols); Map<MatrixXd> eigen_h2_plus_s2(m_h2_plus_s2.matrix, num_rows, num_cols); Map<MatrixXd> eigen_weighted_pdf_diff(m_weighted_pdf_diff.matrix, num_rows, num_cols); SGMatrix<float64_t> zl(num_rows, num_cols); Map<MatrixXd> eigen_zl(zl.matrix, num_rows, num_cols); SGMatrix<float64_t> zh(num_rows, num_cols); Map<MatrixXd> eigen_zh(zh.matrix, num_rows, num_cols); //bsxfun(@minus,l,m) eigen_zl = ((-eigen_mu).replicate(1,eigen_l.rows()).array().transpose().colwise() + eigen_l.array()).matrix(); //bsxfun(@minus,h,m) eigen_zh = ((-eigen_mu).replicate(1,eigen_h.rows()).array().transpose().colwise() + eigen_h.array()).matrix(); VectorXd eigen_s_inv = eigen_s2.array().sqrt().inverse().matrix(); //zl = bsxfun(@times, bsxfun(@minus,l,m), 1./sqrt(v)) eigen_zl = (eigen_zl.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); //zh = bsxfun(@times, bsxfun(@minus,h,m), 1./sqrt(v)) eigen_zh = (eigen_zh.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); for (index_t r = 0; r < zl.num_rows; r++) for (index_t c = 0; c < zl.num_cols; c++) { if (zl(r, c) == CMath::INFTY || zl(r, c) == -CMath::INFTY) m_pl(r, c) = 0; else m_pl(r, c) = CMath::exp(CGaussianDistribution::univariate_log_pdf(zl(r, c))); if (zh(r, c) == CMath::INFTY || zh(r, c) == -CMath::INFTY) m_ph(r, c) = 0; else m_ph(r, c) = CMath::exp(CGaussianDistribution::univariate_log_pdf(zh(r, c))); } //pl = bsxfun(@times, normpdf(zl), 1./sqrt(v)); eigen_pl = (eigen_pl.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); //ph = bsxfun(@times, normpdf(zh), 1./sqrt(v)); eigen_ph = (eigen_ph.array().rowwise()*eigen_s_inv.array().transpose()).matrix(); SGMatrix<float64_t> & cl = zl; SGMatrix<float64_t> & ch = zh; for (index_t r = 0; r < zl.num_rows; r++) for (index_t c = 0; c < zl.num_cols; c++) { //cl = 0.5*erf(zl/sqrt(2)); %normal cdf -const cl(r, c) = CStatistics::normal_cdf(zl(r, c)) - 0.5; //ch = 0.5*erf(zl/sqrt(2)); %normal cdf -const ch(r, c) = CStatistics::normal_cdf(zh(r, c)) - 0.5; } Map<MatrixXd> eigen_cl(cl.matrix, num_rows, num_cols); Map<MatrixXd> eigen_ch(ch.matrix, num_rows, num_cols); eigen_cdf_diff = eigen_ch - eigen_cl; float64_t l_bak = eigen_l(0); eigen_l(0) = 0; float64_t h_bak = eigen_h(eigen_h.size()-1); eigen_h(eigen_h.size()-1) = 0; //bsxfun(@plus, l.^2, v) eigen_l2_plus_s2 = (eigen_s2.replicate(1,eigen_l.rows()).array().transpose().colwise() + eigen_l.array().pow(2)).matrix(); //bsxfun(@plus, h.^2, v) eigen_h2_plus_s2 = (eigen_s2.replicate(1,eigen_h.rows()).array().transpose().colwise() + eigen_h.array().pow(2)).matrix(); //pl.*l - ph.*h eigen_weighted_pdf_diff = (eigen_pl.array().colwise()*eigen_l.array() - eigen_ph.array().colwise()*eigen_h.array()).matrix(); eigen_l(0) = l_bak; eigen_h(eigen_h.size()-1) = h_bak; } #endif /* HAVE_EIGEN3 */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "abstractmsvctoolchain.h" #include "msvcparser.h" #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorersettings.h> #include <projectexplorer/gcctoolchain.h> #include <utils/fileutils.h> #include <utils/qtcprocess.h> #include <utils/synchronousprocess.h> #include <QFileInfo> #include <QDir> #include <QTemporaryFile> enum { debug = 0 }; namespace ProjectExplorer { namespace Internal { AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, bool autodetect, const Abi &abi, const QString& vcvarsBat) : ToolChain(id, autodetect), m_lastEnvironment(Utils::Environment::systemEnvironment()), m_abi(abi), m_vcvarsBat(vcvarsBat) { Q_ASSERT(abi.os() == Abi::WindowsOS); Q_ASSERT(abi.binaryFormat() == Abi::PEFormat); Q_ASSERT(abi.osFlavor() != Abi::WindowsMSysFlavor); Q_ASSERT(!m_vcvarsBat.isEmpty()); } AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, bool autodetect) : ToolChain(id, autodetect), m_lastEnvironment(Utils::Environment::systemEnvironment()) { } Abi AbstractMsvcToolChain::targetAbi() const { return m_abi; } bool AbstractMsvcToolChain::isValid() const { return !m_vcvarsBat.isEmpty(); } QByteArray AbstractMsvcToolChain::predefinedMacros(const QStringList &cxxflags) const { if (m_predefinedMacros.isEmpty()) { Utils::Environment env(m_lastEnvironment); addToEnvironment(env); m_predefinedMacros = msvcPredefinedMacros(cxxflags, env); } return m_predefinedMacros; } ToolChain::CompilerFlags AbstractMsvcToolChain::compilerFlags(const QStringList &cxxflags) const { Q_UNUSED(cxxflags); switch (m_abi.osFlavor()) { case ProjectExplorer::Abi::WindowsMsvc2010Flavor: case ProjectExplorer::Abi::WindowsMsvc2012Flavor: return STD_CXX11; default: return NO_FLAGS; } } QList<HeaderPath> AbstractMsvcToolChain::systemHeaderPaths(const Utils::FileName &sysRoot) const { Q_UNUSED(sysRoot); if (m_headerPaths.isEmpty()) { Utils::Environment env(m_lastEnvironment); addToEnvironment(env); foreach (const QString &path, env.value(QLatin1String("INCLUDE")).split(QLatin1Char(';'))) m_headerPaths.append(HeaderPath(path, HeaderPath::GlobalHeaderPath)); } return m_headerPaths; } void AbstractMsvcToolChain::addToEnvironment(Utils::Environment &env) const { // We cache the full environment (incoming + modifications by setup script). if (!m_resultEnvironment.size() || env != m_lastEnvironment) { if (debug) qDebug() << "addToEnvironment: " << displayName(); m_lastEnvironment = env; m_resultEnvironment = readEnvironmentSetting(env); } env = m_resultEnvironment; } QString AbstractMsvcToolChain::makeCommand(const Utils::Environment &environment) const { bool useJom = ProjectExplorerPlugin::instance()->projectExplorerSettings().useJom; const QString jom = QLatin1String("jom.exe"); const QString nmake = QLatin1String("nmake.exe"); QString tmp; if (useJom) { tmp = environment.searchInPath(jom, QStringList() << QCoreApplication::applicationDirPath()); if (!tmp.isEmpty()) return tmp; } tmp = environment.searchInPath(nmake); if (!tmp.isEmpty()) return tmp; // Nothing found :( return useJom ? jom : nmake; } Utils::FileName AbstractMsvcToolChain::compilerCommand() const { Utils::Environment env; addToEnvironment(env); return Utils::FileName::fromString(env.searchInPath("cl.exe")); } IOutputParser *AbstractMsvcToolChain::outputParser() const { return new MsvcParser; } bool AbstractMsvcToolChain::canClone() const { return true; } QByteArray AbstractMsvcToolChain::msvcPredefinedMacros(const QStringList cxxflags, const Utils::Environment& env) const { Q_UNUSED(cxxflags); Q_UNUSED(env); QByteArray predefinedMacros = "#define __MSVCRT__\n" "#define __w64\n" "#define __int64 long long\n" "#define __int32 long\n" "#define __int16 short\n" "#define __int8 char\n" "#define __ptr32\n" "#define __ptr64\n"; return predefinedMacros; } bool AbstractMsvcToolChain::generateEnvironmentSettings(Utils::Environment &env, const QString& batchFile, const QString& batchArgs, QMap<QString, QString>& envPairs) const { // Create a temporary file name for the output. Use a temporary file here // as I don't know another way to do this in Qt... // Note, can't just use a QTemporaryFile all the way through as it remains open // internally so it can't be streamed to later. QString tempOutFile; QTemporaryFile* pVarsTempFile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/XXXXXX.txt")); pVarsTempFile->setAutoRemove(false); pVarsTempFile->open(); pVarsTempFile->close(); tempOutFile = pVarsTempFile->fileName(); delete pVarsTempFile; // Create a batch file to create and save the env settings Utils::TempFileSaver saver(QDir::tempPath() + QLatin1String("/XXXXXX.bat")); QByteArray call = "call "; call += Utils::QtcProcess::quoteArg(batchFile).toLocal8Bit(); if (!batchArgs.isEmpty()) { call += ' '; call += batchArgs.toLocal8Bit(); } call += "\r\n"; saver.write(call); const QByteArray redirect = "set > " + Utils::QtcProcess::quoteArg( QDir::toNativeSeparators(tempOutFile)).toLocal8Bit() + "\r\n"; saver.write(redirect); if (!saver.finalize()) { qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString())); return false; } Utils::QtcProcess run; // As of WinSDK 7.1, there is logic preventing the path from being set // correctly if "ORIGINALPATH" is already set. That can cause problems // if Creator is launched within a session set up by setenv.cmd. env.unset(QLatin1String("ORIGINALPATH")); run.setEnvironment(env); const QString cmdPath = QString::fromLocal8Bit(qgetenv("COMSPEC")); // Windows SDK setup scripts require command line switches for environment expansion. QString cmdArguments = QLatin1String(" /E:ON /V:ON /c \""); cmdArguments += QDir::toNativeSeparators(saver.fileName()); cmdArguments += QLatin1Char('"'); run.setCommand(cmdPath, cmdArguments); if (debug) qDebug() << "readEnvironmentSetting: " << call << cmdPath << cmdArguments << " Env: " << env.size(); run.start(); if (!run.waitForStarted()) { qWarning("%s: Unable to run '%s': %s", Q_FUNC_INFO, qPrintable(m_vcvarsBat), qPrintable(run.errorString())); return false; } if (!run.waitForFinished()) { qWarning("%s: Timeout running '%s'", Q_FUNC_INFO, qPrintable(m_vcvarsBat)); Utils::SynchronousProcess::stopProcess(run); return false; } // // Now parse the file to get the environment settings QFile varsFile(tempOutFile); if (!varsFile.open(QIODevice::ReadOnly)) return false; QRegExp regexp(QLatin1String("(\\w*)=(.*)")); while (!varsFile.atEnd()) { const QString line = QString::fromLocal8Bit(varsFile.readLine()).trimmed(); if (regexp.exactMatch(line)) { const QString varName = regexp.cap(1); const QString varValue = regexp.cap(2); if (!varValue.isEmpty()) envPairs.insert(varName, varValue); } } // Tidy up and remove the file varsFile.close(); varsFile.remove(); return true; } bool AbstractMsvcToolChain::operator ==(const ToolChain &other) const { if (!ToolChain::operator ==(other)) return false; const AbstractMsvcToolChain *msvcTc = static_cast<const AbstractMsvcToolChain *>(&other); return targetAbi() == msvcTc->targetAbi() && m_vcvarsBat == msvcTc->m_vcvarsBat; } } // namespace Internal } // namespace ProjectExplorer <commit_msg>Fix warning about running processes with empty environment.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "abstractmsvctoolchain.h" #include "msvcparser.h" #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorersettings.h> #include <projectexplorer/gcctoolchain.h> #include <utils/fileutils.h> #include <utils/qtcprocess.h> #include <utils/synchronousprocess.h> #include <QFileInfo> #include <QDir> #include <QTemporaryFile> enum { debug = 0 }; namespace ProjectExplorer { namespace Internal { AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, bool autodetect, const Abi &abi, const QString& vcvarsBat) : ToolChain(id, autodetect), m_lastEnvironment(Utils::Environment::systemEnvironment()), m_abi(abi), m_vcvarsBat(vcvarsBat) { Q_ASSERT(abi.os() == Abi::WindowsOS); Q_ASSERT(abi.binaryFormat() == Abi::PEFormat); Q_ASSERT(abi.osFlavor() != Abi::WindowsMSysFlavor); Q_ASSERT(!m_vcvarsBat.isEmpty()); } AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, bool autodetect) : ToolChain(id, autodetect), m_lastEnvironment(Utils::Environment::systemEnvironment()) { } Abi AbstractMsvcToolChain::targetAbi() const { return m_abi; } bool AbstractMsvcToolChain::isValid() const { return !m_vcvarsBat.isEmpty(); } QByteArray AbstractMsvcToolChain::predefinedMacros(const QStringList &cxxflags) const { if (m_predefinedMacros.isEmpty()) { Utils::Environment env(m_lastEnvironment); addToEnvironment(env); m_predefinedMacros = msvcPredefinedMacros(cxxflags, env); } return m_predefinedMacros; } ToolChain::CompilerFlags AbstractMsvcToolChain::compilerFlags(const QStringList &cxxflags) const { Q_UNUSED(cxxflags); switch (m_abi.osFlavor()) { case ProjectExplorer::Abi::WindowsMsvc2010Flavor: case ProjectExplorer::Abi::WindowsMsvc2012Flavor: return STD_CXX11; default: return NO_FLAGS; } } QList<HeaderPath> AbstractMsvcToolChain::systemHeaderPaths(const Utils::FileName &sysRoot) const { Q_UNUSED(sysRoot); if (m_headerPaths.isEmpty()) { Utils::Environment env(m_lastEnvironment); addToEnvironment(env); foreach (const QString &path, env.value(QLatin1String("INCLUDE")).split(QLatin1Char(';'))) m_headerPaths.append(HeaderPath(path, HeaderPath::GlobalHeaderPath)); } return m_headerPaths; } void AbstractMsvcToolChain::addToEnvironment(Utils::Environment &env) const { // We cache the full environment (incoming + modifications by setup script). if (!m_resultEnvironment.size() || env != m_lastEnvironment) { if (debug) qDebug() << "addToEnvironment: " << displayName(); m_lastEnvironment = env; m_resultEnvironment = readEnvironmentSetting(env); } env = m_resultEnvironment; } QString AbstractMsvcToolChain::makeCommand(const Utils::Environment &environment) const { bool useJom = ProjectExplorerPlugin::instance()->projectExplorerSettings().useJom; const QString jom = QLatin1String("jom.exe"); const QString nmake = QLatin1String("nmake.exe"); QString tmp; if (useJom) { tmp = environment.searchInPath(jom, QStringList() << QCoreApplication::applicationDirPath()); if (!tmp.isEmpty()) return tmp; } tmp = environment.searchInPath(nmake); if (!tmp.isEmpty()) return tmp; // Nothing found :( return useJom ? jom : nmake; } Utils::FileName AbstractMsvcToolChain::compilerCommand() const { Utils::Environment env = Utils::Environment::systemEnvironment(); addToEnvironment(env); return Utils::FileName::fromString(env.searchInPath("cl.exe")); } IOutputParser *AbstractMsvcToolChain::outputParser() const { return new MsvcParser; } bool AbstractMsvcToolChain::canClone() const { return true; } QByteArray AbstractMsvcToolChain::msvcPredefinedMacros(const QStringList cxxflags, const Utils::Environment& env) const { Q_UNUSED(cxxflags); Q_UNUSED(env); QByteArray predefinedMacros = "#define __MSVCRT__\n" "#define __w64\n" "#define __int64 long long\n" "#define __int32 long\n" "#define __int16 short\n" "#define __int8 char\n" "#define __ptr32\n" "#define __ptr64\n"; return predefinedMacros; } bool AbstractMsvcToolChain::generateEnvironmentSettings(Utils::Environment &env, const QString& batchFile, const QString& batchArgs, QMap<QString, QString>& envPairs) const { // Create a temporary file name for the output. Use a temporary file here // as I don't know another way to do this in Qt... // Note, can't just use a QTemporaryFile all the way through as it remains open // internally so it can't be streamed to later. QString tempOutFile; QTemporaryFile* pVarsTempFile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/XXXXXX.txt")); pVarsTempFile->setAutoRemove(false); pVarsTempFile->open(); pVarsTempFile->close(); tempOutFile = pVarsTempFile->fileName(); delete pVarsTempFile; // Create a batch file to create and save the env settings Utils::TempFileSaver saver(QDir::tempPath() + QLatin1String("/XXXXXX.bat")); QByteArray call = "call "; call += Utils::QtcProcess::quoteArg(batchFile).toLocal8Bit(); if (!batchArgs.isEmpty()) { call += ' '; call += batchArgs.toLocal8Bit(); } call += "\r\n"; saver.write(call); const QByteArray redirect = "set > " + Utils::QtcProcess::quoteArg( QDir::toNativeSeparators(tempOutFile)).toLocal8Bit() + "\r\n"; saver.write(redirect); if (!saver.finalize()) { qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString())); return false; } Utils::QtcProcess run; // As of WinSDK 7.1, there is logic preventing the path from being set // correctly if "ORIGINALPATH" is already set. That can cause problems // if Creator is launched within a session set up by setenv.cmd. env.unset(QLatin1String("ORIGINALPATH")); run.setEnvironment(env); const QString cmdPath = QString::fromLocal8Bit(qgetenv("COMSPEC")); // Windows SDK setup scripts require command line switches for environment expansion. QString cmdArguments = QLatin1String(" /E:ON /V:ON /c \""); cmdArguments += QDir::toNativeSeparators(saver.fileName()); cmdArguments += QLatin1Char('"'); run.setCommand(cmdPath, cmdArguments); if (debug) qDebug() << "readEnvironmentSetting: " << call << cmdPath << cmdArguments << " Env: " << env.size(); run.start(); if (!run.waitForStarted()) { qWarning("%s: Unable to run '%s': %s", Q_FUNC_INFO, qPrintable(m_vcvarsBat), qPrintable(run.errorString())); return false; } if (!run.waitForFinished()) { qWarning("%s: Timeout running '%s'", Q_FUNC_INFO, qPrintable(m_vcvarsBat)); Utils::SynchronousProcess::stopProcess(run); return false; } // // Now parse the file to get the environment settings QFile varsFile(tempOutFile); if (!varsFile.open(QIODevice::ReadOnly)) return false; QRegExp regexp(QLatin1String("(\\w*)=(.*)")); while (!varsFile.atEnd()) { const QString line = QString::fromLocal8Bit(varsFile.readLine()).trimmed(); if (regexp.exactMatch(line)) { const QString varName = regexp.cap(1); const QString varValue = regexp.cap(2); if (!varValue.isEmpty()) envPairs.insert(varName, varValue); } } // Tidy up and remove the file varsFile.close(); varsFile.remove(); return true; } bool AbstractMsvcToolChain::operator ==(const ToolChain &other) const { if (!ToolChain::operator ==(other)) return false; const AbstractMsvcToolChain *msvcTc = static_cast<const AbstractMsvcToolChain *>(&other); return targetAbi() == msvcTc->targetAbi() && m_vcvarsBat == msvcTc->m_vcvarsBat; } } // namespace Internal } // namespace ProjectExplorer <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/artificial_table/artificial_table.hpp" #include "rdb_protocol/artificial_table/backend.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/table_common.hpp" /* Determines how many coroutines we spawn for a batched replace or insert. */ static const int max_parallel_ops = 10; /* This is a wrapper around `backend->read_row()` that also performs sanity checking, to help catch bugs in the backend. */ bool checked_read_row_from_backend( artificial_table_backend_t *backend, const ql::datum_t &pval, signal_t *interruptor, ql::datum_t *row_out, std::string *error_out) { if (!backend->read_row(pval, interruptor, row_out, error_out)) { return false; } #ifndef NDEBUG if (row_out->has()) { ql::datum_t pval2 = row_out->get_field( datum_string_t(backend->get_primary_key_name()), ql::NOTHROW); rassert(pval2.has()); rassert(pval2 == pval); } #endif return true; } artificial_table_t::artificial_table_t(artificial_table_backend_t *_backend) : backend(_backend), primary_key(backend->get_primary_key_name()) { } const std::string &artificial_table_t::get_pkey() { return primary_key; } ql::datum_t artificial_table_t::read_row(ql::env_t *env, ql::datum_t pval, UNUSED bool use_outdated) { ql::datum_t row; std::string error; if (!checked_read_row_from_backend(backend, pval, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { row = ql::datum_t::null(); } return row; } counted_t<ql::datum_stream_t> artificial_table_t::read_all( ql::env_t *env, const std::string &get_all_sindex_id, const ql::protob_t<const Backtrace> &bt, const std::string &table_name, const ql::datum_range_t &range, sorting_t sorting, UNUSED bool use_outdated) { if (get_all_sindex_id != primary_key) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(get_all_sindex_id, table_name).c_str()); } counted_t<ql::datum_stream_t> stream; std::string error; if (!backend->read_all_rows_as_stream( bt, range, sorting, env->interruptor, &stream, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } return stream; } counted_t<ql::datum_stream_t> artificial_table_t::read_row_changes( UNUSED ql::env_t *env, UNUSED ql::datum_t pval, UNUSED const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { /* RSI(reql_admin): Artificial tables will eventually support change feeds. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support changefeeds."); } counted_t<ql::datum_stream_t> artificial_table_t::read_changes( ql::env_t *env, ql::changefeed::keyspec_t::spec_t &&spec, const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { counted_t<ql::datum_stream_t> stream; std::string error; if (!backend->read_changes(bt, spec, env->interruptor, &stream, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } return stream; } counted_t<ql::datum_stream_t> artificial_table_t::read_intersecting( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED const ql::datum_t &query_geometry) { guarantee(sindex != primary_key, "read_intersecting() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } ql::datum_t artificial_table_t::read_nearest( UNUSED ql::env_t *env, const std::string &sindex, const std::string &table_name, UNUSED bool use_outdated, UNUSED lon_lat_point_t center, UNUSED double max_dist, UNUSED uint64_t max_results, UNUSED const ellipsoid_spec_t &geo_system, UNUSED dist_unit_t dist_unit, UNUSED const ql::configured_limits_t &limits) { guarantee(sindex != primary_key, "read_nearest() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } ql::datum_t artificial_table_t::write_batched_replace( ql::env_t *env, const std::vector<ql::datum_t> &keys, const counted_t<const ql::func_t> &func, return_changes_t return_changes, UNUSED durability_requirement_t durability) { /* RSI(reql_admin): Should we require that durability is soft? */ ql::datum_t stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(keys.size(), [&] (int i) { try { do_single_update(env, keys[i], false, [&] (ql::datum_t old_row) { return func->call(env, old_row, ql::LITERAL_OK)->as_datum(); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats); obj_builder.add_warnings(conditions, env->limits()); return std::move(obj_builder).to_datum(); } ql::datum_t artificial_table_t::write_batched_insert( ql::env_t *env, std::vector<ql::datum_t> &&inserts, std::vector<bool> &&pkey_was_autogenerated, conflict_behavior_t conflict_behavior, return_changes_t return_changes, UNUSED durability_requirement_t durability) { ql::datum_t stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(inserts.size(), [&] (int i) { try { ql::datum_t insert_row = inserts[i]; ql::datum_t key = insert_row.get_field( datum_string_t(primary_key), ql::NOTHROW); guarantee(key.has(), "write_batched_insert() shouldn't ever be called with " "documents that lack a primary key."); do_single_update(env, key, pkey_was_autogenerated[i], [&](ql::datum_t old_row) { return resolve_insert_conflict( primary_key, old_row, insert_row, conflict_behavior); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats); obj_builder.add_warnings(conditions, env->limits()); return std::move(obj_builder).to_datum(); } bool artificial_table_t::write_sync_depending_on_durability( UNUSED ql::env_t *env, UNUSED durability_requirement_t durability) { /* Calling `sync()` on an artificial table is a meaningful operation; it would mean to flush the metadata to disk. But it would be a lot of trouble to implement in practice, so we don't. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support `sync()`."); } bool artificial_table_t::sindex_create( UNUSED ql::env_t *env, UNUSED const std::string &id, UNUSED counted_t<const ql::func_t> index_func, UNUSED sindex_multi_bool_t multi, UNUSED sindex_geo_bool_t geo) { rfail_datum(ql::base_exc_t::GENERIC, "Can't create a secondary index on an artificial table."); } bool artificial_table_t::sindex_drop(UNUSED ql::env_t *env, UNUSED const std::string &id) { rfail_datum(ql::base_exc_t::GENERIC, "Can't drop a secondary index on an artificial table."); } sindex_rename_result_t artificial_table_t::sindex_rename( UNUSED ql::env_t *env, UNUSED const std::string &old_name, UNUSED const std::string &new_name, UNUSED bool overwrite) { rfail_datum(ql::base_exc_t::GENERIC, "Can't rename a secondary index on an artificial table."); } std::vector<std::string> artificial_table_t::sindex_list(UNUSED ql::env_t *env) { return std::vector<std::string>(); } std::map<std::string, ql::datum_t> artificial_table_t::sindex_status( UNUSED ql::env_t *env, UNUSED const std::set<std::string> &sindexes) { return std::map<std::string, ql::datum_t>(); } void artificial_table_t::do_single_update( ql::env_t *env, ql::datum_t pval, bool pkey_was_autogenerated, const std::function<ql::datum_t(ql::datum_t)> &function, return_changes_t return_changes, signal_t *interruptor, ql::datum_t *stats_inout, std::set<std::string> *conditions_inout) { std::string error; ql::datum_t old_row; if (!checked_read_row_from_backend(backend, pval, interruptor, &old_row, &error)) { ql::datum_object_builder_t builder; builder.add_error(error.c_str()); *stats_inout = (*stats_inout).merge( std::move(builder).to_datum(), ql::stats_merge, env->limits(), conditions_inout); return; } if (!old_row.has()) { old_row = ql::datum_t::null(); } ql::datum_t resp; try { ql::datum_t new_row = function(old_row); if (new_row.get_type() == ql::datum_t::R_NULL) { new_row.reset(); } if (!backend->write_row(pval, pkey_was_autogenerated, &new_row, interruptor, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } if (!new_row.has()) { new_row = ql::datum_t::null(); } bool dummy_was_changed; resp = make_row_replacement_stats( datum_string_t(primary_key), store_key_t(pval.print_primary()), old_row, new_row, return_changes, &dummy_was_changed); } catch (const ql::base_exc_t &e) { resp = make_row_replacement_error_stats( old_row, return_changes, e.what()); } *stats_inout = (*stats_inout).merge( resp, ql::stats_merge, env->limits(), conditions_inout); } <commit_msg>Implement read_row_changes() on artificial_table_t.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/artificial_table/artificial_table.hpp" #include "rdb_protocol/artificial_table/backend.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/table_common.hpp" /* Determines how many coroutines we spawn for a batched replace or insert. */ static const int max_parallel_ops = 10; /* This is a wrapper around `backend->read_row()` that also performs sanity checking, to help catch bugs in the backend. */ bool checked_read_row_from_backend( artificial_table_backend_t *backend, const ql::datum_t &pval, signal_t *interruptor, ql::datum_t *row_out, std::string *error_out) { if (!backend->read_row(pval, interruptor, row_out, error_out)) { return false; } #ifndef NDEBUG if (row_out->has()) { ql::datum_t pval2 = row_out->get_field( datum_string_t(backend->get_primary_key_name()), ql::NOTHROW); rassert(pval2.has()); rassert(pval2 == pval); } #endif return true; } artificial_table_t::artificial_table_t(artificial_table_backend_t *_backend) : backend(_backend), primary_key(backend->get_primary_key_name()) { } const std::string &artificial_table_t::get_pkey() { return primary_key; } ql::datum_t artificial_table_t::read_row(ql::env_t *env, ql::datum_t pval, UNUSED bool use_outdated) { ql::datum_t row; std::string error; if (!checked_read_row_from_backend(backend, pval, env->interruptor, &row, &error)) { throw ql::datum_exc_t(ql::base_exc_t::GENERIC, error); } if (!row.has()) { row = ql::datum_t::null(); } return row; } counted_t<ql::datum_stream_t> artificial_table_t::read_all( ql::env_t *env, const std::string &get_all_sindex_id, const ql::protob_t<const Backtrace> &bt, const std::string &table_name, const ql::datum_range_t &range, sorting_t sorting, UNUSED bool use_outdated) { if (get_all_sindex_id != primary_key) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(get_all_sindex_id, table_name).c_str()); } counted_t<ql::datum_stream_t> stream; std::string error; if (!backend->read_all_rows_as_stream( bt, range, sorting, env->interruptor, &stream, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } return stream; } counted_t<ql::datum_stream_t> artificial_table_t::read_row_changes( ql::env_t *env, ql::datum_t pval, const ql::protob_t<const Backtrace> &bt, const std::string &table_name) { return read_changes( env, ql::changefeed::keyspec_t::spec_t( ql::changefeed::keyspec_t::point_t{ store_key_t(pval.print_primary())}), bt, table_name); } counted_t<ql::datum_stream_t> artificial_table_t::read_changes( ql::env_t *env, ql::changefeed::keyspec_t::spec_t &&spec, const ql::protob_t<const Backtrace> &bt, UNUSED const std::string &table_name) { counted_t<ql::datum_stream_t> stream; std::string error; if (!backend->read_changes(bt, spec, env->interruptor, &stream, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } return stream; } counted_t<ql::datum_stream_t> artificial_table_t::read_intersecting( UNUSED ql::env_t *env, const std::string &sindex, UNUSED const ql::protob_t<const Backtrace> &bt, const std::string &table_name, UNUSED bool use_outdated, UNUSED const ql::datum_t &query_geometry) { guarantee(sindex != primary_key, "read_intersecting() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } ql::datum_t artificial_table_t::read_nearest( UNUSED ql::env_t *env, const std::string &sindex, const std::string &table_name, UNUSED bool use_outdated, UNUSED lon_lat_point_t center, UNUSED double max_dist, UNUSED uint64_t max_results, UNUSED const ellipsoid_spec_t &geo_system, UNUSED dist_unit_t dist_unit, UNUSED const ql::configured_limits_t &limits) { guarantee(sindex != primary_key, "read_nearest() should never be called with " "the primary index"); rfail_datum(ql::base_exc_t::GENERIC, "%s", error_message_index_not_found(sindex, table_name).c_str()); } ql::datum_t artificial_table_t::write_batched_replace( ql::env_t *env, const std::vector<ql::datum_t> &keys, const counted_t<const ql::func_t> &func, return_changes_t return_changes, UNUSED durability_requirement_t durability) { /* RSI(reql_admin): Should we require that durability is soft? */ ql::datum_t stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(keys.size(), [&] (int i) { try { do_single_update(env, keys[i], false, [&] (ql::datum_t old_row) { return func->call(env, old_row, ql::LITERAL_OK)->as_datum(); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats); obj_builder.add_warnings(conditions, env->limits()); return std::move(obj_builder).to_datum(); } ql::datum_t artificial_table_t::write_batched_insert( ql::env_t *env, std::vector<ql::datum_t> &&inserts, std::vector<bool> &&pkey_was_autogenerated, conflict_behavior_t conflict_behavior, return_changes_t return_changes, UNUSED durability_requirement_t durability) { ql::datum_t stats = ql::datum_t::empty_object(); std::set<std::string> conditions; throttled_pmap(inserts.size(), [&] (int i) { try { ql::datum_t insert_row = inserts[i]; ql::datum_t key = insert_row.get_field( datum_string_t(primary_key), ql::NOTHROW); guarantee(key.has(), "write_batched_insert() shouldn't ever be called with " "documents that lack a primary key."); do_single_update(env, key, pkey_was_autogenerated[i], [&](ql::datum_t old_row) { return resolve_insert_conflict( primary_key, old_row, insert_row, conflict_behavior); }, return_changes, env->interruptor, &stats, &conditions); } catch (interrupted_exc_t) { /* don't throw since we're in throttled_pmap() */ } }, max_parallel_ops); if (env->interruptor->is_pulsed()) { throw interrupted_exc_t(); } ql::datum_object_builder_t obj_builder(stats); obj_builder.add_warnings(conditions, env->limits()); return std::move(obj_builder).to_datum(); } bool artificial_table_t::write_sync_depending_on_durability( UNUSED ql::env_t *env, UNUSED durability_requirement_t durability) { /* Calling `sync()` on an artificial table is a meaningful operation; it would mean to flush the metadata to disk. But it would be a lot of trouble to implement in practice, so we don't. */ rfail_datum(ql::base_exc_t::GENERIC, "Artificial tables don't support `sync()`."); } bool artificial_table_t::sindex_create( UNUSED ql::env_t *env, UNUSED const std::string &id, UNUSED counted_t<const ql::func_t> index_func, UNUSED sindex_multi_bool_t multi, UNUSED sindex_geo_bool_t geo) { rfail_datum(ql::base_exc_t::GENERIC, "Can't create a secondary index on an artificial table."); } bool artificial_table_t::sindex_drop(UNUSED ql::env_t *env, UNUSED const std::string &id) { rfail_datum(ql::base_exc_t::GENERIC, "Can't drop a secondary index on an artificial table."); } sindex_rename_result_t artificial_table_t::sindex_rename( UNUSED ql::env_t *env, UNUSED const std::string &old_name, UNUSED const std::string &new_name, UNUSED bool overwrite) { rfail_datum(ql::base_exc_t::GENERIC, "Can't rename a secondary index on an artificial table."); } std::vector<std::string> artificial_table_t::sindex_list(UNUSED ql::env_t *env) { return std::vector<std::string>(); } std::map<std::string, ql::datum_t> artificial_table_t::sindex_status( UNUSED ql::env_t *env, UNUSED const std::set<std::string> &sindexes) { return std::map<std::string, ql::datum_t>(); } void artificial_table_t::do_single_update( ql::env_t *env, ql::datum_t pval, bool pkey_was_autogenerated, const std::function<ql::datum_t(ql::datum_t)> &function, return_changes_t return_changes, signal_t *interruptor, ql::datum_t *stats_inout, std::set<std::string> *conditions_inout) { std::string error; ql::datum_t old_row; if (!checked_read_row_from_backend(backend, pval, interruptor, &old_row, &error)) { ql::datum_object_builder_t builder; builder.add_error(error.c_str()); *stats_inout = (*stats_inout).merge( std::move(builder).to_datum(), ql::stats_merge, env->limits(), conditions_inout); return; } if (!old_row.has()) { old_row = ql::datum_t::null(); } ql::datum_t resp; try { ql::datum_t new_row = function(old_row); if (new_row.get_type() == ql::datum_t::R_NULL) { new_row.reset(); } if (!backend->write_row(pval, pkey_was_autogenerated, &new_row, interruptor, &error)) { rfail_datum(ql::base_exc_t::GENERIC, "%s", error.c_str()); } if (!new_row.has()) { new_row = ql::datum_t::null(); } bool dummy_was_changed; resp = make_row_replacement_stats( datum_string_t(primary_key), store_key_t(pval.print_primary()), old_row, new_row, return_changes, &dummy_was_changed); } catch (const ql::base_exc_t &e) { resp = make_row_replacement_error_stats( old_row, return_changes, e.what()); } *stats_inout = (*stats_inout).merge( resp, ql::stats_merge, env->limits(), conditions_inout); } <|endoftext|>
<commit_before>/* * Author: Kurt Leucht * Maintainer: Kurt Leucht * Email: kurt.leucht@nasa.gov * NASA Center: Kennedy Space Center * Mail Stop: NE-C1 * * Project Name: Swarmie Robotics NASA Center Innovation Fund * Principal Investigator: Cheryle Mako * Email: cheryle.l.mako@nasa.gov * * Date Created: October 2, 2014 * Safety Critical: NO * NASA Software Classification: D * * This software is copyright the National Aeronautics and Space Administration (NASA) * and is distributed under the GNU LGPL license. All rights reserved. * Permission to use, copy, modify and distribute this software is granted under * the LGPL and there is no implied warranty for this software. This software is provided * "as is" and NASA or the authors are not responsible for indirect or direct damage * to any user of the software. The authors and NASA are under no obligation to provide * maintenence, updates, support or modifications to the software. * * Revision Log: * -cpu utilization COMPLETE, TBD-date (KWL) */ // ROS headers #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Int32.h> // C and Linux headers #include <cstdlib> using namespace std; #define MODULE_VERSION "1.0" #define STRING_LENGTH 255 // optional parameter server stored variables int HEALTH_PUB_BUF_SIZE = 1; int HEALTH_PUB_RATE = 1; // TODO: move these globals to a shared header file or go OO with getters #define SUCCESS 0 #define ERROR -1 /* * This subroutine loads all parameters from the ROS Parameter Server */ int initParams() { // if the parameters exist in the parameter server they will get overwritten, // otherwise hard coded values from above will remain in place ros::param::get("/HEALTH_PUB_BUF_SIZE", HEALTH_PUB_BUF_SIZE); ros::param::get("/HEALTH_PUB_RATE", HEALTH_PUB_RATE); return(SUCCESS); } /* * Main just initializes publishers and handlers and then spins forever. */ int main(int argc, char** argv) { ROS_INFO("health_status: module is initializing (v%s)", MODULE_VERSION); char host[STRING_LENGTH]; gethostname(host, sizeof (host)); string hostname(host); string publishedName; if (argc >= 2) { publishedName = argv[1]; cout << "Welcome to the world of tomorrow " << publishedName << "! Health & Status module started." << endl; } else { publishedName = hostname; cout << "No Name Selected. Default is: " << publishedName << endl; } ros::init(argc, argv, (publishedName + "_HEALTH_STATUS")); ros::NodeHandle n; // initialize variables from parameter server initParams(); // set up publication of busy CPU per second ros::Publisher busy_cpu_sec_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/busy_cpu_sec"), HEALTH_PUB_BUF_SIZE); ros::Rate health_loop_rate(HEALTH_PUB_RATE); // set up publication of busy CPU past minute average ros::Publisher busy_cpu_min_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/busy_cpu_min"), HEALTH_PUB_BUF_SIZE); // set up publication of used memory per second ros::Publisher used_memory_sec_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/used_memory_sec"), HEALTH_PUB_BUF_SIZE); // set up publication of used memory past minute average ros::Publisher used_memory_min_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/used_memory_min"), HEALTH_PUB_BUF_SIZE); // set up publication of uptime (in seconds) ros::Publisher uptime_pub = n.advertise<std_msgs::Int32>((publishedName + "/health/uptime_sec"), HEALTH_PUB_BUF_SIZE); // set up publication of total threads ros::Publisher threads_pub = n.advertise<std_msgs::Int32>((publishedName + "/health/threads"), HEALTH_PUB_BUF_SIZE); // variables used to calculate CPU utilization unsigned int prev_idle = 0; unsigned int prev_non_idle = 0; unsigned int prev_io_wait = 0; unsigned int prev_user = 0; unsigned int prev_nice = 0; unsigned int prev_system = 0; unsigned int prev_irq = 0; unsigned int prev_soft_irq = 0; unsigned int prev_steal = 0; unsigned int prev_total = 0; unsigned int curr_idle = 0; unsigned int curr_non_idle = 0; unsigned int curr_io_wait = 0; unsigned int curr_user = 0; unsigned int curr_nice = 0; unsigned int curr_system = 0; unsigned int curr_irq = 0; unsigned int curr_soft_irq = 0; unsigned int curr_steal = 0; unsigned int curr_total = 0; float cpu_min_calc = 0; float cpu_sec_calc[60]; // preset array of floats to zero for (int i = 0; i < 60; i++) { cpu_sec_calc[i] = 0; } // variables used to calculate memory utilization unsigned int total_memory = 0; unsigned int free_memory = 0; float memory_min_calc = 0; float memory_sec_calc[60]; // preset array of floats to zero for (int i = 0; i < 60; i++) { memory_sec_calc[i] = 0; } ROS_INFO("health_status: module is running"); while (ros::ok()) { std_msgs::Float32 busy_cpu_sec_msg; std_msgs::Float32 busy_cpu_min_msg; std_msgs::Float32 used_memory_sec_msg; std_msgs::Float32 used_memory_min_msg; std_msgs::Int32 uptime_msg; std_msgs::Int32 threads_msg; // open the stat file that holds CPU utilization data and read one line FILE *f = fopen("/proc/stat", "r"); size_t sz = 0; char * lin = 0; ssize_t lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into variables char seps[] = " \t\n/"; char *token; char *prevToken; int token_ctr = 0; token = strtok(lin, seps); token_ctr++; while (token != NULL) { prevToken = token; token = strtok(NULL, seps); if (token_ctr == 1) { curr_user = atoi(token); } else if (token_ctr == 2) { curr_nice = atoi(token); } else if (token_ctr == 3) { curr_system = atoi(token); } else if (token_ctr == 4) { curr_idle = atoi(token); } else if (token_ctr == 5) { curr_io_wait = atoi(token); } else if (token_ctr == 6) { curr_irq = atoi(token); } else if (token_ctr == 7) { curr_soft_irq = atoi(token); } else if (token_ctr == 8) { curr_steal = atoi(token); } token_ctr++; } // push all values down the array one index for (int i = 60 - 2; i >= 0; i--) { cpu_sec_calc[i + 1] = cpu_sec_calc[i]; } // perform the cpu calculation for the current second in time curr_idle = curr_idle + curr_io_wait; curr_non_idle = curr_user + curr_nice + curr_system + curr_irq + curr_soft_irq + curr_steal; curr_total = curr_idle + curr_non_idle; cpu_sec_calc[0] = 100 * (float)((curr_total-prev_total)-(curr_idle-prev_idle))/(curr_total-prev_total); ROS_DEBUG("health_status: calculated: %0.1f", cpu_sec_calc[0]); // populate all previous variables for next cycle prev_idle = curr_idle; prev_non_idle = curr_non_idle; prev_io_wait = curr_io_wait; prev_user = curr_user; prev_nice = curr_nice; prev_system = curr_system; prev_irq = curr_irq; prev_soft_irq = curr_soft_irq; prev_steal = curr_steal; prev_total = curr_total; // write value to ROS message busy_cpu_sec_msg.data = cpu_sec_calc[0]; busy_cpu_sec_pub.publish(busy_cpu_sec_msg); // calculate the past minute's average float grand_total = 0; for (int i = 0; i < 60; i++) { grand_total = grand_total + cpu_sec_calc[i]; } cpu_min_calc = grand_total / 60; // write value to ROS message busy_cpu_min_msg.data = cpu_min_calc; busy_cpu_min_pub.publish(busy_cpu_min_msg); // open the stat file that holds memory utilization data and read one line f = fopen("/proc/meminfo", "r"); lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); total_memory = atoi(token); // read the second line lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); free_memory = atoi(token); // push all values down the array one index for (int j = 60 - 2; j >= 0; j--) { memory_sec_calc[j + 1] = memory_sec_calc[j]; } // perform the memory calculation for the current second in time memory_sec_calc[0] = 100 * (float)(total_memory - free_memory) / total_memory; ROS_DEBUG("health_status: calculated: %0.1f", memory_sec_calc[0]); // write value to ROS message used_memory_sec_msg.data = memory_sec_calc[0]; used_memory_sec_pub.publish(used_memory_sec_msg); // calculate the past minute's average float memory_grand_total = 0; for (int j = 0; j < 60; j++) { memory_grand_total = memory_grand_total + memory_sec_calc[j]; } memory_min_calc = memory_grand_total / 60; // write value to ROS message used_memory_min_msg.data = memory_min_calc; used_memory_min_pub.publish(used_memory_min_msg); // open the stat file that holds uptime data and read one line f = fopen("/proc/uptime", "r"); sz = 0; lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); float uptime_float = atof(token); // write value to ROS message uptime_msg.data = (int)uptime_float; uptime_pub.publish(uptime_msg); // open the stat file that holds threads data and read one line f = fopen("/proc/loadavg", "r"); sz = 0; lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); int threads = atoi(token); // write value to ROS message threads_msg.data = threads; threads_pub.publish(threads_msg); // spin and sleep for next cycle ros::spinOnce(); health_loop_rate.sleep(); } return(SUCCESS); } <commit_msg>Stripping out NASA preamble<commit_after>// ROS headers #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Int32.h> // C and Linux headers #include <cstdlib> using namespace std; #define MODULE_VERSION "1.0" #define STRING_LENGTH 255 // optional parameter server stored variables int HEALTH_PUB_BUF_SIZE = 1; int HEALTH_PUB_RATE = 1; // TODO: move these globals to a shared header file or go OO with getters #define SUCCESS 0 #define ERROR -1 /* * This subroutine loads all parameters from the ROS Parameter Server */ int initParams() { // if the parameters exist in the parameter server they will get overwritten, // otherwise hard coded values from above will remain in place ros::param::get("/HEALTH_PUB_BUF_SIZE", HEALTH_PUB_BUF_SIZE); ros::param::get("/HEALTH_PUB_RATE", HEALTH_PUB_RATE); return(SUCCESS); } /* * Main just initializes publishers and handlers and then spins forever. */ int main(int argc, char** argv) { ROS_INFO("health_status: module is initializing (v%s)", MODULE_VERSION); char host[STRING_LENGTH]; gethostname(host, sizeof (host)); string hostname(host); string publishedName; if (argc >= 2) { publishedName = argv[1]; cout << "Welcome to the world of tomorrow " << publishedName << "! Health & Status module started." << endl; } else { publishedName = hostname; cout << "No Name Selected. Default is: " << publishedName << endl; } ros::init(argc, argv, (publishedName + "_HEALTH_STATUS")); ros::NodeHandle n; // initialize variables from parameter server initParams(); // set up publication of busy CPU per second ros::Publisher busy_cpu_sec_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/busy_cpu_sec"), HEALTH_PUB_BUF_SIZE); ros::Rate health_loop_rate(HEALTH_PUB_RATE); // set up publication of busy CPU past minute average ros::Publisher busy_cpu_min_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/busy_cpu_min"), HEALTH_PUB_BUF_SIZE); // set up publication of used memory per second ros::Publisher used_memory_sec_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/used_memory_sec"), HEALTH_PUB_BUF_SIZE); // set up publication of used memory past minute average ros::Publisher used_memory_min_pub = n.advertise<std_msgs::Float32>((publishedName + "/health/used_memory_min"), HEALTH_PUB_BUF_SIZE); // set up publication of uptime (in seconds) ros::Publisher uptime_pub = n.advertise<std_msgs::Int32>((publishedName + "/health/uptime_sec"), HEALTH_PUB_BUF_SIZE); // set up publication of total threads ros::Publisher threads_pub = n.advertise<std_msgs::Int32>((publishedName + "/health/threads"), HEALTH_PUB_BUF_SIZE); // variables used to calculate CPU utilization unsigned int prev_idle = 0; unsigned int prev_non_idle = 0; unsigned int prev_io_wait = 0; unsigned int prev_user = 0; unsigned int prev_nice = 0; unsigned int prev_system = 0; unsigned int prev_irq = 0; unsigned int prev_soft_irq = 0; unsigned int prev_steal = 0; unsigned int prev_total = 0; unsigned int curr_idle = 0; unsigned int curr_non_idle = 0; unsigned int curr_io_wait = 0; unsigned int curr_user = 0; unsigned int curr_nice = 0; unsigned int curr_system = 0; unsigned int curr_irq = 0; unsigned int curr_soft_irq = 0; unsigned int curr_steal = 0; unsigned int curr_total = 0; float cpu_min_calc = 0; float cpu_sec_calc[60]; // preset array of floats to zero for (int i = 0; i < 60; i++) { cpu_sec_calc[i] = 0; } // variables used to calculate memory utilization unsigned int total_memory = 0; unsigned int free_memory = 0; float memory_min_calc = 0; float memory_sec_calc[60]; // preset array of floats to zero for (int i = 0; i < 60; i++) { memory_sec_calc[i] = 0; } ROS_INFO("health_status: module is running"); while (ros::ok()) { std_msgs::Float32 busy_cpu_sec_msg; std_msgs::Float32 busy_cpu_min_msg; std_msgs::Float32 used_memory_sec_msg; std_msgs::Float32 used_memory_min_msg; std_msgs::Int32 uptime_msg; std_msgs::Int32 threads_msg; // open the stat file that holds CPU utilization data and read one line FILE *f = fopen("/proc/stat", "r"); size_t sz = 0; char * lin = 0; ssize_t lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into variables char seps[] = " \t\n/"; char *token; char *prevToken; int token_ctr = 0; token = strtok(lin, seps); token_ctr++; while (token != NULL) { prevToken = token; token = strtok(NULL, seps); if (token_ctr == 1) { curr_user = atoi(token); } else if (token_ctr == 2) { curr_nice = atoi(token); } else if (token_ctr == 3) { curr_system = atoi(token); } else if (token_ctr == 4) { curr_idle = atoi(token); } else if (token_ctr == 5) { curr_io_wait = atoi(token); } else if (token_ctr == 6) { curr_irq = atoi(token); } else if (token_ctr == 7) { curr_soft_irq = atoi(token); } else if (token_ctr == 8) { curr_steal = atoi(token); } token_ctr++; } // push all values down the array one index for (int i = 60 - 2; i >= 0; i--) { cpu_sec_calc[i + 1] = cpu_sec_calc[i]; } // perform the cpu calculation for the current second in time curr_idle = curr_idle + curr_io_wait; curr_non_idle = curr_user + curr_nice + curr_system + curr_irq + curr_soft_irq + curr_steal; curr_total = curr_idle + curr_non_idle; cpu_sec_calc[0] = 100 * (float)((curr_total-prev_total)-(curr_idle-prev_idle))/(curr_total-prev_total); ROS_DEBUG("health_status: calculated: %0.1f", cpu_sec_calc[0]); // populate all previous variables for next cycle prev_idle = curr_idle; prev_non_idle = curr_non_idle; prev_io_wait = curr_io_wait; prev_user = curr_user; prev_nice = curr_nice; prev_system = curr_system; prev_irq = curr_irq; prev_soft_irq = curr_soft_irq; prev_steal = curr_steal; prev_total = curr_total; // write value to ROS message busy_cpu_sec_msg.data = cpu_sec_calc[0]; busy_cpu_sec_pub.publish(busy_cpu_sec_msg); // calculate the past minute's average float grand_total = 0; for (int i = 0; i < 60; i++) { grand_total = grand_total + cpu_sec_calc[i]; } cpu_min_calc = grand_total / 60; // write value to ROS message busy_cpu_min_msg.data = cpu_min_calc; busy_cpu_min_pub.publish(busy_cpu_min_msg); // open the stat file that holds memory utilization data and read one line f = fopen("/proc/meminfo", "r"); lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); total_memory = atoi(token); // read the second line lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); free_memory = atoi(token); // push all values down the array one index for (int j = 60 - 2; j >= 0; j--) { memory_sec_calc[j + 1] = memory_sec_calc[j]; } // perform the memory calculation for the current second in time memory_sec_calc[0] = 100 * (float)(total_memory - free_memory) / total_memory; ROS_DEBUG("health_status: calculated: %0.1f", memory_sec_calc[0]); // write value to ROS message used_memory_sec_msg.data = memory_sec_calc[0]; used_memory_sec_pub.publish(used_memory_sec_msg); // calculate the past minute's average float memory_grand_total = 0; for (int j = 0; j < 60; j++) { memory_grand_total = memory_grand_total + memory_sec_calc[j]; } memory_min_calc = memory_grand_total / 60; // write value to ROS message used_memory_min_msg.data = memory_min_calc; used_memory_min_pub.publish(used_memory_min_msg); // open the stat file that holds uptime data and read one line f = fopen("/proc/uptime", "r"); sz = 0; lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); float uptime_float = atof(token); // write value to ROS message uptime_msg.data = (int)uptime_float; uptime_pub.publish(uptime_msg); // open the stat file that holds threads data and read one line f = fopen("/proc/loadavg", "r"); sz = 0; lsz = getline (&lin, &sz, f); ROS_DEBUG("health_status: read line: %s", lin); fclose (f); // parse tokens to get data into a variable token = strtok(lin, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); token = strtok(NULL, seps); int threads = atoi(token); // write value to ROS message threads_msg.data = threads; threads_pub.publish(threads_msg); // spin and sleep for next cycle ros::spinOnce(); health_loop_rate.sleep(); } return(SUCCESS); } <|endoftext|>
<commit_before>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_SUBTRACTION_HPP #define STAN__AGRAD__REV__OPERATORS__OPERATOR_SUBTRACTION_HPP #include <stan/agrad/rev/var.hpp> #include <stan/agrad/rev/internal/vv_vari.hpp> #include <stan/agrad/rev/internal/vd_vari.hpp> #include <stan/agrad/rev/internal/dv_vari.hpp> namespace stan { namespace agrad { namespace { class subtract_vv_vari : public op_vv_vari { public: subtract_vv_vari(vari* avi, vari* bvi) : op_vv_vari(avi->val_ - bvi->val_, avi, bvi) { } void chain() { avi_->adj_ += adj_; bvi_->adj_ -= adj_; } }; class subtract_vd_vari : public op_vd_vari { public: subtract_vd_vari(vari* avi, double b) : op_vd_vari(avi->val_ - b, avi, b) { } void chain() { avi_->adj_ += adj_; } }; class subtract_dv_vari : public op_dv_vari { public: subtract_dv_vari(double a, vari* bvi) : op_dv_vari(a - bvi->val_, a, bvi) { } void chain() { bvi_->adj_ -= adj_; } }; } /** * Subtraction operator for variables (C++). * * The partial derivatives are defined by * * \f$\frac{\partial}{\partial x} (x-y) = 1\f$, and * * \f$\frac{\partial}{\partial y} (x-y) = -1\f$. * * @param a First variable operand. * @param b Second variable operand. * @return Variable result of subtracting the second variable from * the first. */ inline var operator-(const var& a, const var& b) { return var(new subtract_vv_vari(a.vi_,b.vi_)); } /** * Subtraction operator for variable and scalar (C++). * * The derivative for the variable is * * \f$\frac{\partial}{\partial x} (x-c) = 1\f$, and * * @param a First variable operand. * @param b Second scalar operand. * @return Result of subtracting the scalar from the variable. */ inline var operator-(const var& a, const double b) { if (b == 0.0) return a; return var(new subtract_vd_vari(a.vi_,b)); } /** * Subtraction operator for scalar and variable (C++). * * The derivative for the variable is * * \f$\frac{\partial}{\partial y} (c-y) = -1\f$, and * * @param a First scalar operand. * @param b Second variable operand. * @return Result of sutracting a variable from a scalar. */ inline var operator-(const double a, const var& b) { return var(new subtract_dv_vari(a,b.vi_)); } } } #endif <commit_msg>fixed operator_subtraction so gradient returns NaN for NaN input<commit_after>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_SUBTRACTION_HPP #define STAN__AGRAD__REV__OPERATORS__OPERATOR_SUBTRACTION_HPP #include <stan/agrad/rev/var.hpp> #include <stan/agrad/rev/internal/vv_vari.hpp> #include <stan/agrad/rev/internal/vd_vari.hpp> #include <stan/agrad/rev/internal/dv_vari.hpp> #include <boost/math/special_functions/fpclassify.hpp> namespace stan { namespace agrad { namespace { class subtract_vv_vari : public op_vv_vari { public: subtract_vv_vari(vari* avi, vari* bvi) : op_vv_vari(avi->val_ - bvi->val_, avi, bvi) { } void chain() { if (unlikely(boost::math::isnan(avi_->val_) || boost::math::isnan(bvi_->val_))) { avi_->adj_ = std::numeric_limits<double>::quiet_NaN(); bvi_->adj_ = std::numeric_limits<double>::quiet_NaN(); } else { avi_->adj_ += adj_; bvi_->adj_ -= adj_; } } }; class subtract_vd_vari : public op_vd_vari { public: subtract_vd_vari(vari* avi, double b) : op_vd_vari(avi->val_ - b, avi, b) { } void chain() { if (unlikely(boost::math::isnan(avi_->val_) || boost::math::isnan(bd_))) avi_->adj_ = std::numeric_limits<double>::quiet_NaN(); else avi_->adj_ += adj_; } }; class subtract_dv_vari : public op_dv_vari { public: subtract_dv_vari(double a, vari* bvi) : op_dv_vari(a - bvi->val_, a, bvi) { } void chain() { if (unlikely(boost::math::isnan(ad_) || boost::math::isnan(bvi_->val_))) bvi_->adj_ = std::numeric_limits<double>::quiet_NaN(); else bvi_->adj_ -= adj_; } }; } /** * Subtraction operator for variables (C++). * * The partial derivatives are defined by * * \f$\frac{\partial}{\partial x} (x-y) = 1\f$, and * * \f$\frac{\partial}{\partial y} (x-y) = -1\f$. * * @param a First variable operand. * @param b Second variable operand. * @return Variable result of subtracting the second variable from * the first. */ inline var operator-(const var& a, const var& b) { return var(new subtract_vv_vari(a.vi_,b.vi_)); } /** * Subtraction operator for variable and scalar (C++). * * The derivative for the variable is * * \f$\frac{\partial}{\partial x} (x-c) = 1\f$, and * * @param a First variable operand. * @param b Second scalar operand. * @return Result of subtracting the scalar from the variable. */ inline var operator-(const var& a, const double b) { if (b == 0.0) return a; return var(new subtract_vd_vari(a.vi_,b)); } /** * Subtraction operator for scalar and variable (C++). * * The derivative for the variable is * * \f$\frac{\partial}{\partial y} (c-y) = -1\f$, and * * @param a First scalar operand. * @param b Second variable operand. * @return Result of sutracting a variable from a scalar. */ inline var operator-(const double a, const var& b) { return var(new subtract_dv_vari(a,b.vi_)); } } } #endif <|endoftext|>
<commit_before>#include "translate_gizmo.h" #include <components/sprite_component.h> #include "halley/entity/components/transform_2d_component.h" #include "halley/core/game/scene_editor_interface.h" #include "halley/core/graphics/painter.h" using namespace Halley; TranslateGizmo::TranslateGizmo(SnapRules snapRules, UIFactory& factory, ISceneEditorWindow& sceneEditorWindow) : SceneEditorGizmo(snapRules) , factory(factory) , sceneEditorWindow(sceneEditorWindow) { loadHandles(); } void TranslateGizmo::loadHandles() { const auto n = getEntities().size(); handles.resize(n); handleOffsets.resize(n); for (size_t i = 0; i < n; ++i) { handles[i].setBoundsCheck([=] (Vector2f myPos, Vector2f mousePos) -> bool { return getHandleBounds(handles[i]).contains(mousePos); }); handles[i].setGridSnap(getSnapRules().grid); } } void TranslateGizmo::update(Time time, const ISceneEditor& sceneEditor, const SceneEditorInputState& inputState) { const auto curMode = fromString<TranslateGizmoMode>(sceneEditorWindow.getSetting(EditorSettingType::Editor, "tools.translate.mode").asString("pivot")); if (curMode != mode) { setMode(curMode); } const auto n = getEntities().size(); // Drag for (size_t i = 0; i < n; ++i) { auto& handle = handles[i]; handle.update(inputState); if (handle.isHeld()) { const auto transform = getComponent<Transform2DComponent>(i); const auto oldPos = transform->getGlobalPosition(); transform->setGlobalPosition(handle.getPosition() - handleOffsets[i]); pendingMoveBy += transform->getGlobalPosition() - oldPos; } } doMoveBy(); for (size_t i = 0; i < n; ++i) { auto& handle = handles[i]; if (!handle.isHeld()) { const auto transform = getComponent<Transform2DComponent>(i); handle.setEnabled(!!transform); if (transform && !handle.isHeld()) { // Read from object handleOffsets[i] = getObjectOffset(i); handle.setPosition(transform->getGlobalPosition() + handleOffsets[i], false); } } } } void TranslateGizmo::draw(Painter& painter) const { for (const auto& handle: handles) { if (handle.isEnabled()) { const float zoom = getZoom(); const auto overCol = Colour4f(0.6f, 0.6f, 1); const auto outCol = Colour4f(0.4f, 0.4f, 1.0f); const auto col = handle.isOver() ? overCol : outCol; const auto circle = getHandleBounds(handle); const auto centre = circle.getCentre(); const auto radius = circle.getRadius(); const float lineWidth = 2.0f / zoom; const float fineLineWidth = 1.0f / zoom; painter.drawCircle(centre, radius, lineWidth + 2 / zoom, Colour4f(0, 0, 0, 0.5f)); painter.drawCircle(centre, radius, lineWidth, col); painter.drawLine({{ centre - Vector2f(radius * 0.6f, 0), centre + Vector2f(radius * 0.6f, 0) }}, fineLineWidth, col); painter.drawLine({{ centre - Vector2f(0, radius * 0.6f), centre + Vector2f(0, radius * 0.6f) }}, fineLineWidth, col); } } } bool TranslateGizmo::isHighlighted() const { return std::any_of(handles.begin(), handles.end(), [=] (const auto& e) { return e.isOver(); }); } std::shared_ptr<UIWidget> TranslateGizmo::makeUI() { auto ui = factory.makeUI("ui/halley/translate_gizmo_toolbar"); ui->setInteractWithMouse(true); uiMode = ui->getWidgetAs<UIList>("mode"); const auto initialMode = sceneEditorWindow.getSetting(EditorSettingType::Editor, "tools.translate.mode").asString("pivot"); setMode(fromString<TranslateGizmoMode>(initialMode)); ui->bindData("mode", initialMode, [=] (const String& value) { setMode(fromString<TranslateGizmoMode>(value)); }); return ui; } std::vector<String> TranslateGizmo::getHighlightedComponents() const { return { "Transform2D" }; } bool TranslateGizmo::onKeyPress(KeyboardKeyPress key) { const bool fast = (int(key.mod) & int(KeyMods::Shift)) != 0; const bool iso = (int(key.mod) & int(KeyMods::Ctrl)) != 0; const int speed = fast ? 5 : 1; const Vector2i xAxis = (iso ? Vector2i(2, 1) : Vector2i(1, 0)) * speed; const Vector2i yAxis = (iso ? Vector2i(2, -1) : Vector2i(0, -1)) * speed; if (key.key == KeyCode::Left) { moveBy(-xAxis); return true; } if (key.key == KeyCode::Right) { moveBy(xAxis); return true; } if (key.key == KeyCode::Up) { moveBy(yAxis); return true; } if (key.key == KeyCode::Down) { moveBy(-yAxis); return true; } return false; } void TranslateGizmo::onEntityChanged() { loadHandles(); } Circle TranslateGizmo::getHandleBounds(const SceneEditorGizmoHandle& handle) const { const auto pos = handle.getPosition(); return Circle(pos, 10.0f / getZoom()); } void TranslateGizmo::updateEntityData(Vector2f pos, size_t idx) { auto* data = getComponentData("Transform2D", idx); if (data) { (*data)["position"] = pos; } markModified("Transform2D", "position", idx); } Vector2f TranslateGizmo::getObjectOffset(size_t idx) const { if (mode == TranslateGizmoMode::Centre) { auto sprite = getComponent<SpriteComponent>(idx); if (sprite) { auto offset = sprite->sprite.getAABB().getCenter() - sprite->sprite.getPosition(); if (getSnapRules().grid == GridSnapMode::Pixel) { offset = offset.round(); } return offset; } } return Vector2f(); } void TranslateGizmo::setMode(TranslateGizmoMode mode) { this->mode = mode; uiMode->setSelectedOptionId(toString(mode)); sceneEditorWindow.setSetting(EditorSettingType::Editor, "tools.translate.mode", ConfigNode(toString(mode))); } void TranslateGizmo::moveBy(Vector2i delta) { pendingMoveBy += Vector2f(delta); } void TranslateGizmo::doMoveBy() { if (pendingMoveBy.manhattanLength() < 0.0001f) { return; } doMoveBy(pendingMoveBy); pendingMoveBy = Vector2f(); } void TranslateGizmo::doMoveBy(Vector2f delta) { const size_t n = getEntities().size(); Expects(handles.size() == n); std::vector<Vector2f> targetPos; targetPos.resize(n); for (size_t i = 0; i < n; ++i) { if (const auto transform = getComponent<Transform2DComponent>(i)) { targetPos[i] = transform->getGlobalPosition() + Vector2f(delta); } } for (size_t i = 0; i < n; ++i) { const auto transform = getComponent<Transform2DComponent>(i); if (!handles[i].isHeld() && transform) { const auto newPos = targetPos[i]; transform->setGlobalPosition(newPos); const auto newLocalPos = transform->getLocalPosition(); updateEntityData(newLocalPos, i); } } } <commit_msg>Fix undoing entity move<commit_after>#include "translate_gizmo.h" #include <components/sprite_component.h> #include "halley/entity/components/transform_2d_component.h" #include "halley/core/game/scene_editor_interface.h" #include "halley/core/graphics/painter.h" using namespace Halley; TranslateGizmo::TranslateGizmo(SnapRules snapRules, UIFactory& factory, ISceneEditorWindow& sceneEditorWindow) : SceneEditorGizmo(snapRules) , factory(factory) , sceneEditorWindow(sceneEditorWindow) { loadHandles(); } void TranslateGizmo::loadHandles() { const auto n = getEntities().size(); handles.resize(n); handleOffsets.resize(n); for (size_t i = 0; i < n; ++i) { handles[i].setBoundsCheck([=] (Vector2f myPos, Vector2f mousePos) -> bool { return getHandleBounds(handles[i]).contains(mousePos); }); handles[i].setGridSnap(getSnapRules().grid); } } void TranslateGizmo::update(Time time, const ISceneEditor& sceneEditor, const SceneEditorInputState& inputState) { const auto curMode = fromString<TranslateGizmoMode>(sceneEditorWindow.getSetting(EditorSettingType::Editor, "tools.translate.mode").asString("pivot")); if (curMode != mode) { setMode(curMode); } const auto n = getEntities().size(); // Drag for (size_t i = 0; i < n; ++i) { auto& handle = handles[i]; handle.update(inputState); if (handle.isHeld()) { const auto transform = getComponent<Transform2DComponent>(i); const auto oldPos = transform->getGlobalPosition(); transform->setGlobalPosition(handle.getPosition() - handleOffsets[i]); pendingMoveBy += transform->getGlobalPosition() - oldPos; } } doMoveBy(); for (size_t i = 0; i < n; ++i) { auto& handle = handles[i]; if (!handle.isHeld()) { const auto transform = getComponent<Transform2DComponent>(i); handle.setEnabled(!!transform); if (transform && !handle.isHeld()) { // Read from object handleOffsets[i] = getObjectOffset(i); handle.setPosition(transform->getGlobalPosition() + handleOffsets[i], false); } } } } void TranslateGizmo::draw(Painter& painter) const { for (const auto& handle: handles) { if (handle.isEnabled()) { const float zoom = getZoom(); const auto overCol = Colour4f(0.6f, 0.6f, 1); const auto outCol = Colour4f(0.4f, 0.4f, 1.0f); const auto col = handle.isOver() ? overCol : outCol; const auto circle = getHandleBounds(handle); const auto centre = circle.getCentre(); const auto radius = circle.getRadius(); const float lineWidth = 2.0f / zoom; const float fineLineWidth = 1.0f / zoom; painter.drawCircle(centre, radius, lineWidth + 2 / zoom, Colour4f(0, 0, 0, 0.5f)); painter.drawCircle(centre, radius, lineWidth, col); painter.drawLine({{ centre - Vector2f(radius * 0.6f, 0), centre + Vector2f(radius * 0.6f, 0) }}, fineLineWidth, col); painter.drawLine({{ centre - Vector2f(0, radius * 0.6f), centre + Vector2f(0, radius * 0.6f) }}, fineLineWidth, col); } } } bool TranslateGizmo::isHighlighted() const { return std::any_of(handles.begin(), handles.end(), [=] (const auto& e) { return e.isOver(); }); } std::shared_ptr<UIWidget> TranslateGizmo::makeUI() { auto ui = factory.makeUI("ui/halley/translate_gizmo_toolbar"); ui->setInteractWithMouse(true); uiMode = ui->getWidgetAs<UIList>("mode"); const auto initialMode = sceneEditorWindow.getSetting(EditorSettingType::Editor, "tools.translate.mode").asString("pivot"); setMode(fromString<TranslateGizmoMode>(initialMode)); ui->bindData("mode", initialMode, [=] (const String& value) { setMode(fromString<TranslateGizmoMode>(value)); }); return ui; } std::vector<String> TranslateGizmo::getHighlightedComponents() const { return { "Transform2D" }; } bool TranslateGizmo::onKeyPress(KeyboardKeyPress key) { const bool fast = (int(key.mod) & int(KeyMods::Shift)) != 0; const bool iso = (int(key.mod) & int(KeyMods::Ctrl)) != 0; const int speed = fast ? 5 : 1; const Vector2i xAxis = (iso ? Vector2i(2, 1) : Vector2i(1, 0)) * speed; const Vector2i yAxis = (iso ? Vector2i(2, -1) : Vector2i(0, -1)) * speed; if (key.key == KeyCode::Left) { moveBy(-xAxis); return true; } if (key.key == KeyCode::Right) { moveBy(xAxis); return true; } if (key.key == KeyCode::Up) { moveBy(yAxis); return true; } if (key.key == KeyCode::Down) { moveBy(-yAxis); return true; } return false; } void TranslateGizmo::onEntityChanged() { loadHandles(); } Circle TranslateGizmo::getHandleBounds(const SceneEditorGizmoHandle& handle) const { const auto pos = handle.getPosition(); return Circle(pos, 10.0f / getZoom()); } void TranslateGizmo::updateEntityData(Vector2f pos, size_t idx) { auto* data = getComponentData("Transform2D", idx); if (data) { (*data)["position"] = pos; } markModified("Transform2D", "position", idx); } Vector2f TranslateGizmo::getObjectOffset(size_t idx) const { if (mode == TranslateGizmoMode::Centre) { auto sprite = getComponent<SpriteComponent>(idx); if (sprite) { auto offset = sprite->sprite.getAABB().getCenter() - sprite->sprite.getPosition(); if (getSnapRules().grid == GridSnapMode::Pixel) { offset = offset.round(); } return offset; } } return Vector2f(); } void TranslateGizmo::setMode(TranslateGizmoMode mode) { this->mode = mode; uiMode->setSelectedOptionId(toString(mode)); sceneEditorWindow.setSetting(EditorSettingType::Editor, "tools.translate.mode", ConfigNode(toString(mode))); } void TranslateGizmo::moveBy(Vector2i delta) { pendingMoveBy += Vector2f(delta); } void TranslateGizmo::doMoveBy() { if (pendingMoveBy.manhattanLength() < 0.0001f) { return; } doMoveBy(pendingMoveBy); pendingMoveBy = Vector2f(); } void TranslateGizmo::doMoveBy(Vector2f delta) { const size_t n = getEntities().size(); Expects(handles.size() == n); std::vector<Vector2f> targetPos; targetPos.resize(n); for (size_t i = 0; i < n; ++i) { if (const auto transform = getComponent<Transform2DComponent>(i)) { targetPos[i] = transform->getGlobalPosition() + (handles[i].isHeld() ? Vector2f() : Vector2f(delta)); } } for (size_t i = 0; i < n; ++i) { if (const auto transform = getComponent<Transform2DComponent>(i)) { transform->setGlobalPosition(targetPos[i]); const auto newLocalPos = transform->getLocalPosition(); updateEntityData(newLocalPos, i); } } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.8 2003/12/29 16:15:42 knoaman * More PSVI updates * * Revision 1.7 2003/11/21 22:34:45 neilg * More schema component model implementation, thanks to David Cargill. * In particular, this cleans up and completes the XSModel, XSNamespaceItem, * XSAttributeDeclaration and XSAttributeGroup implementations. * * Revision 1.6 2003/11/21 17:19:30 knoaman * PSVI update. * * Revision 1.5 2003/11/14 22:47:53 neilg * fix bogus log message from previous commit... * * Revision 1.4 2003/11/14 22:33:30 neilg * Second phase of schema component model implementation. * Implement XSModel, XSNamespaceItem, and the plumbing necessary * to connect them to the other components. * Thanks to David Cargill. * * Revision 1.3 2003/11/06 15:30:04 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.2 2003/09/17 17:45:37 neilg * remove spurious inlines; hopefully this will make Solaris/AIX compilers happy. * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #include <xercesc/framework/psvi/XSAttributeDeclaration.hpp> #include <xercesc/framework/psvi/XSModel.hpp> #include <xercesc/framework/psvi/XSNamespaceItem.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/schema/SchemaGrammar.hpp> #include <xercesc/validators/schema/SchemaAttDef.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSAttributeDeclaration: Constructors and Destructor // --------------------------------------------------------------------------- XSAttributeDeclaration::XSAttributeDeclaration(SchemaAttDef* const attDef, XSSimpleTypeDefinition* const typeDef, XSAnnotation* const annot, XSModel* const xsModel, XSConstants::SCOPE scope, XSComplexTypeDefinition* enclosingCTDefinition, MemoryManager * const manager) : XSObject(XSConstants::ATTRIBUTE_DECLARATION, xsModel, manager) , fAttDef(attDef) , fTypeDefinition(typeDef) , fAnnotation(annot) , fScope(scope) , fEnclosingCTDefinition(enclosingCTDefinition) { } XSAttributeDeclaration::~XSAttributeDeclaration() { // don't delete fTypeDefinition - deleted by XSModel } // --------------------------------------------------------------------------- // XSAttributeDeclaration: XSObject virtual methods // --------------------------------------------------------------------------- const XMLCh *XSAttributeDeclaration::getName() { return fAttDef->getAttName()->getLocalPart(); } const XMLCh *XSAttributeDeclaration::getNamespace() { return fXSModel->getURIStringPool()->getValueForId(fAttDef->getAttName()->getURI()); } XSNamespaceItem *XSAttributeDeclaration::getNamespaceItem() { return fXSModel->getNamespaceItem(getNamespace()); } unsigned int XSAttributeDeclaration::getId() const { return fId; } // --------------------------------------------------------------------------- // XSAttributeDeclaration: access methods // --------------------------------------------------------------------------- XSConstants::VALUE_CONSTRAINT XSAttributeDeclaration::getConstraintType() const { if (fAttDef->getDefaultType() & XMLAttDef::Default) return XSConstants::VC_DEFAULT; if ((fAttDef->getDefaultType() == XMLAttDef::Fixed) || (fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed)) return XSConstants::VC_FIXED; return XSConstants::VC_NONE; } const XMLCh *XSAttributeDeclaration::getConstraintValue() { return fAttDef->getValue(); } bool XSAttributeDeclaration::getRequired() const { if (fAttDef->getDefaultType() == XMLAttDef::Required || fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed) return true; return false; } XERCES_CPP_NAMESPACE_END <commit_msg>PSVI: return value constraint only if global declaration<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.9 2003/12/29 17:06:31 knoaman * PSVI: return value constraint only if global declaration * * Revision 1.8 2003/12/29 16:15:42 knoaman * More PSVI updates * * Revision 1.7 2003/11/21 22:34:45 neilg * More schema component model implementation, thanks to David Cargill. * In particular, this cleans up and completes the XSModel, XSNamespaceItem, * XSAttributeDeclaration and XSAttributeGroup implementations. * * Revision 1.6 2003/11/21 17:19:30 knoaman * PSVI update. * * Revision 1.5 2003/11/14 22:47:53 neilg * fix bogus log message from previous commit... * * Revision 1.4 2003/11/14 22:33:30 neilg * Second phase of schema component model implementation. * Implement XSModel, XSNamespaceItem, and the plumbing necessary * to connect them to the other components. * Thanks to David Cargill. * * Revision 1.3 2003/11/06 15:30:04 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.2 2003/09/17 17:45:37 neilg * remove spurious inlines; hopefully this will make Solaris/AIX compilers happy. * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #include <xercesc/framework/psvi/XSAttributeDeclaration.hpp> #include <xercesc/framework/psvi/XSModel.hpp> #include <xercesc/framework/psvi/XSNamespaceItem.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/schema/SchemaGrammar.hpp> #include <xercesc/validators/schema/SchemaAttDef.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSAttributeDeclaration: Constructors and Destructor // --------------------------------------------------------------------------- XSAttributeDeclaration::XSAttributeDeclaration(SchemaAttDef* const attDef, XSSimpleTypeDefinition* const typeDef, XSAnnotation* const annot, XSModel* const xsModel, XSConstants::SCOPE scope, XSComplexTypeDefinition* enclosingCTDefinition, MemoryManager * const manager) : XSObject(XSConstants::ATTRIBUTE_DECLARATION, xsModel, manager) , fAttDef(attDef) , fTypeDefinition(typeDef) , fAnnotation(annot) , fScope(scope) , fEnclosingCTDefinition(enclosingCTDefinition) { } XSAttributeDeclaration::~XSAttributeDeclaration() { // don't delete fTypeDefinition - deleted by XSModel } // --------------------------------------------------------------------------- // XSAttributeDeclaration: XSObject virtual methods // --------------------------------------------------------------------------- const XMLCh *XSAttributeDeclaration::getName() { return fAttDef->getAttName()->getLocalPart(); } const XMLCh *XSAttributeDeclaration::getNamespace() { return fXSModel->getURIStringPool()->getValueForId(fAttDef->getAttName()->getURI()); } XSNamespaceItem *XSAttributeDeclaration::getNamespaceItem() { return fXSModel->getNamespaceItem(getNamespace()); } unsigned int XSAttributeDeclaration::getId() const { return fId; } // --------------------------------------------------------------------------- // XSAttributeDeclaration: access methods // --------------------------------------------------------------------------- XSConstants::VALUE_CONSTRAINT XSAttributeDeclaration::getConstraintType() const { if (fAttDef->getDefaultType() & XMLAttDef::Default) return XSConstants::VC_DEFAULT; if ((fAttDef->getDefaultType() == XMLAttDef::Fixed) || (fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed)) return XSConstants::VC_FIXED; return XSConstants::VC_NONE; } const XMLCh *XSAttributeDeclaration::getConstraintValue() { if (fScope == XSConstants::SCOPE_GLOBAL) return fAttDef->getValue(); return 0; } bool XSAttributeDeclaration::getRequired() const { if (fAttDef->getDefaultType() == XMLAttDef::Required || fAttDef->getDefaultType() == XMLAttDef::Required_And_Fixed) return true; return false; } XERCES_CPP_NAMESPACE_END <|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. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/XMLScanner.hpp> #include <xercesc/framework/XMLValidator.hpp> #include <xercesc/validators/datatype/DatatypeValidator.hpp> #include <xercesc/validators/schema/identity/FieldActivator.hpp> #include <xercesc/validators/schema/identity/ValueStore.hpp> #include <xercesc/validators/schema/identity/IC_Field.hpp> #include <xercesc/validators/schema/identity/IC_KeyRef.hpp> #include <xercesc/validators/schema/identity/ValueStoreCache.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ValueStore: Constructors and Destructor // --------------------------------------------------------------------------- ValueStore::ValueStore(IdentityConstraint* const ic, XMLScanner* const scanner, MemoryManager* const manager) : fDoReportError(false) , fValuesCount(0) , fIdentityConstraint(ic) , fValues(manager) , fValueTuples(0) , fKeyValueStore(0) , fScanner(scanner) , fMemoryManager(manager) { fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always)); } ValueStore::~ValueStore() { delete fValueTuples; } // --------------------------------------------------------------------------- // ValueStore: Helper methods // --------------------------------------------------------------------------- void ValueStore::addValue(FieldActivator* const fieldActivator, IC_Field* const field, DatatypeValidator* const dv, const XMLCh* const value) { if (!fieldActivator->getMayMatch(field) && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { if (fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_UnknownField); } return; } // store value if (!fValues.getDatatypeValidatorAt(index) && !fValues.getValueAt(index)) { fValuesCount++; } fValues.put(field, dv, value); if (fValuesCount == (int) fValues.size()) { // is this value as a group duplicated? if (contains(&fValues)) { duplicateValue(); } // store values if (!fValueTuples) { fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager); } fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues)); } } void ValueStore::append(const ValueStore* const other) { if (!other->fValueTuples) { return; } unsigned int tupleSize = other->fValueTuples->size(); for (unsigned int i=0; i<tupleSize; i++) { FieldValueMap* valueMap = other->fValueTuples->elementAt(i); if (!contains(valueMap)) { if (!fValueTuples) { fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager); } fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap)); } } } void ValueStore::startValueScope() { fValuesCount = 0; int count = fIdentityConstraint->getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0); } } void ValueStore::endValueScope() { if (fValuesCount == 0) { if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue, fIdentityConstraint->getElementName()); } return; } // do we have enough values? if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) { if(fIdentityConstraint->getType()==IdentityConstraint::ICType_KEY) { fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues, fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName()); } } } bool ValueStore::contains(const FieldValueMap* const other) { if (fValueTuples) { unsigned int otherSize = other->size(); unsigned int tupleSize = fValueTuples->size(); for (unsigned int i=0; i<tupleSize; i++) { FieldValueMap* valueMap = fValueTuples->elementAt(i); if (otherSize == valueMap->size()) { bool matchFound = true; for (unsigned int j=0; j<otherSize; j++) { if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j), other->getDatatypeValidatorAt(j), other->getValueAt(j))) { matchFound = false; break; } } if (matchFound) { // found it return true; } } } } return false; } bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1, DatatypeValidator* const dv2, const XMLCh* const val2) { // if either validator's null, fall back on string comparison if(!dv1 || !dv2) { return (XMLString::equals(val1, val2)); } bool val1IsEmpty = (val1==0 || *val1==0); bool val2IsEmpty = (val2==0 || *val2==0); if (val1IsEmpty && val2IsEmpty) { if (dv1 == dv2) { return true; } return false; } if (val1IsEmpty || val2IsEmpty) { return false; } // are the validators equal? // As always we are obliged to compare by reference... if (dv1 == dv2 || ((dv1->getType()==DatatypeValidator::ID || dv1->getType()==DatatypeValidator::IDREF) && (dv2->getType()==DatatypeValidator::ID || dv2->getType()==DatatypeValidator::IDREF))) { return ((dv1->compare(val1, val2, fMemoryManager)) == 0); } // see if this.fValidator is derived from value.fValidator: DatatypeValidator* tempVal = dv1; for(; tempVal != NULL && tempVal != dv2; tempVal = tempVal->getBaseValidator()) ; if (tempVal) { // was derived! return ((dv2->compare(val1, val2, fMemoryManager)) == 0); } // see if value.fValidator is derived from this.fValidator: for(tempVal = dv2; tempVal != NULL && tempVal != dv1; tempVal = tempVal->getBaseValidator()) ; if(tempVal) { // was derived! return ((dv1->compare(val1, val2, fMemoryManager)) == 0); } // if we're here it means the types weren't related. They are different: return false; } // --------------------------------------------------------------------------- // ValueStore: Document handling methods // --------------------------------------------------------------------------- void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) { if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) { // verify references // get the key store corresponding (if it exists): fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey()); if (!fKeyValueStore) { if (fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope, fIdentityConstraint->getIdentityConstraintName()); } return; } unsigned int count = (fValueTuples) ? fValueTuples->size() : 0; for (unsigned int i = 0; i < count; i++) { FieldValueMap* valueMap = fValueTuples->elementAt(i); if (!fKeyValueStore->contains(valueMap) && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound, fIdentityConstraint->getElementName()); } } } } // --------------------------------------------------------------------------- // ValueStore: Error reporting methods // --------------------------------------------------------------------------- void ValueStore::reportNilError(IdentityConstraint* const ic) { if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) { fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable, ic->getElementName()); } } void ValueStore::duplicateValue() { if (fDoReportError) { switch (fIdentityConstraint->getType()) { case IdentityConstraint::ICType_UNIQUE: { fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique, fIdentityConstraint->getElementName()); break; } case IdentityConstraint::ICType_KEY: { fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey, fIdentityConstraint->getElementName()); break; } } } } XERCES_CPP_NAMESPACE_END /** * End of file ValueStore.cpp */ <commit_msg>Even if the XSTS suite thinks differently, the XMLSchema 1.1 clarifies that two values derived from the same value space should be treated as equals; so find out the common ancestor and use it to perform the comparison<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. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/XMLScanner.hpp> #include <xercesc/framework/XMLValidator.hpp> #include <xercesc/validators/datatype/DatatypeValidator.hpp> #include <xercesc/validators/schema/identity/FieldActivator.hpp> #include <xercesc/validators/schema/identity/ValueStore.hpp> #include <xercesc/validators/schema/identity/IC_Field.hpp> #include <xercesc/validators/schema/identity/IC_KeyRef.hpp> #include <xercesc/validators/schema/identity/ValueStoreCache.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ValueStore: Constructors and Destructor // --------------------------------------------------------------------------- ValueStore::ValueStore(IdentityConstraint* const ic, XMLScanner* const scanner, MemoryManager* const manager) : fDoReportError(false) , fValuesCount(0) , fIdentityConstraint(ic) , fValues(manager) , fValueTuples(0) , fKeyValueStore(0) , fScanner(scanner) , fMemoryManager(manager) { fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always)); } ValueStore::~ValueStore() { delete fValueTuples; } // --------------------------------------------------------------------------- // ValueStore: Helper methods // --------------------------------------------------------------------------- void ValueStore::addValue(FieldActivator* const fieldActivator, IC_Field* const field, DatatypeValidator* const dv, const XMLCh* const value) { if (!fieldActivator->getMayMatch(field) && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { if (fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_UnknownField); } return; } // store value if (!fValues.getDatatypeValidatorAt(index) && !fValues.getValueAt(index)) { fValuesCount++; } fValues.put(field, dv, value); if (fValuesCount == (int) fValues.size()) { // is this value as a group duplicated? if (contains(&fValues)) { duplicateValue(); } // store values if (!fValueTuples) { fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager); } fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues)); } } void ValueStore::append(const ValueStore* const other) { if (!other->fValueTuples) { return; } unsigned int tupleSize = other->fValueTuples->size(); for (unsigned int i=0; i<tupleSize; i++) { FieldValueMap* valueMap = other->fValueTuples->elementAt(i); if (!contains(valueMap)) { if (!fValueTuples) { fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager); } fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap)); } } } void ValueStore::startValueScope() { fValuesCount = 0; int count = fIdentityConstraint->getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0); } } void ValueStore::endValueScope() { if (fValuesCount == 0) { if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue, fIdentityConstraint->getElementName()); } return; } // do we have enough values? if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) { if(fIdentityConstraint->getType()==IdentityConstraint::ICType_KEY) { fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues, fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName()); } } } bool ValueStore::contains(const FieldValueMap* const other) { if (fValueTuples) { unsigned int otherSize = other->size(); unsigned int tupleSize = fValueTuples->size(); for (unsigned int i=0; i<tupleSize; i++) { FieldValueMap* valueMap = fValueTuples->elementAt(i); if (otherSize == valueMap->size()) { bool matchFound = true; for (unsigned int j=0; j<otherSize; j++) { if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j), other->getDatatypeValidatorAt(j), other->getValueAt(j))) { matchFound = false; break; } } if (matchFound) { // found it return true; } } } } return false; } bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1, DatatypeValidator* const dv2, const XMLCh* const val2) { // if either validator's null, fall back on string comparison if(!dv1 || !dv2) { return (XMLString::equals(val1, val2)); } bool val1IsEmpty = (val1==0 || *val1==0); bool val2IsEmpty = (val2==0 || *val2==0); if (val1IsEmpty && val2IsEmpty) { if (dv1 == dv2) { return true; } return false; } if (val1IsEmpty || val2IsEmpty) { return false; } // find the common ancestor, if there is one DatatypeValidator* tempVal1 = dv1; while(tempVal1) { DatatypeValidator* tempVal2 = dv2; for(; tempVal2 != NULL && tempVal2 != tempVal1; tempVal2 = tempVal2->getBaseValidator()) ; if (tempVal2) return ((tempVal2->compare(val1, val2, fMemoryManager)) == 0); tempVal1=tempVal1->getBaseValidator(); } // if we're here it means the types weren't related. They are different: return false; } // --------------------------------------------------------------------------- // ValueStore: Document handling methods // --------------------------------------------------------------------------- void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) { if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) { // verify references // get the key store corresponding (if it exists): fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey()); if (!fKeyValueStore) { if (fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope, fIdentityConstraint->getIdentityConstraintName()); } return; } unsigned int count = (fValueTuples) ? fValueTuples->size() : 0; for (unsigned int i = 0; i < count; i++) { FieldValueMap* valueMap = fValueTuples->elementAt(i); if (!fKeyValueStore->contains(valueMap) && fDoReportError) { fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound, fIdentityConstraint->getElementName()); } } } } // --------------------------------------------------------------------------- // ValueStore: Error reporting methods // --------------------------------------------------------------------------- void ValueStore::reportNilError(IdentityConstraint* const ic) { if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) { fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable, ic->getElementName()); } } void ValueStore::duplicateValue() { if (fDoReportError) { switch (fIdentityConstraint->getType()) { case IdentityConstraint::ICType_UNIQUE: { fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique, fIdentityConstraint->getElementName()); break; } case IdentityConstraint::ICType_KEY: { fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey, fIdentityConstraint->getElementName()); break; } } } } XERCES_CPP_NAMESPACE_END /** * End of file ValueStore.cpp */ <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/common/tasks/padding.h" #include <string> #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/task/work_group_picking.h" namespace tflite { namespace gpu { namespace { std::string GetPaddingCode(const OperationDef& op_def, const PadAttributes& attr, GPUOperation* op) { op->AddSrcTensor("src_tensor", op_def.src_tensors[0]); op->AddDstTensor("dst_tensor", op_def.dst_tensors[0]); op->args_.AddInt("prepended_x", attr.prepended.w); op->args_.AddInt("prepended_y", attr.prepended.h); op->args_.AddInt("prepended_z", attr.prepended.c); op->args_.AddInt("prepended_w", attr.prepended.b); const std::string dst_batch = op_def.dst_tensors[0].HasAxis(Axis::BATCH) ? "B" : "0"; std::string c; const std::string channels[] = {".x", ".y", ".z", ".w"}; if (attr.type == PaddingContentType::REFLECT) { c += "int reflect(int x, int size) {\n"; c += " int t = abs(x) - size + 1;\n"; c += " return size - 1 - abs(t);\n"; c += "}\n\n"; } c += "MAIN_FUNCTION($0) {\n"; if (op_def.dst_tensors[0].HasAxis(Axis::BATCH)) { c += " int linear_id = GLOBAL_ID_0;\n"; c += " int X = linear_id / args.dst_tensor.Batch();\n"; c += " int B = linear_id % args.dst_tensor.Batch();\n"; c += " args.dst_tensor.SetBatchRef(B);\n"; } else { c += " int X = GLOBAL_ID_0;\n"; } c += " int Y = GLOBAL_ID_1;\n"; c += " int Z = GLOBAL_ID_2;\n"; c += " if (X >= args.dst_tensor.Width() || Y >= args.dst_tensor.Height() || " "Z >= args.dst_tensor.Slices()) { \n"; c += " return; \n"; c += " } \n"; c += " FLT4 result = INIT_FLT4(0.0);\n"; c += " int s_x = X - args.prepended_x;\n"; c += " int s_y = Y - args.prepended_y;\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " int s_b = " + dst_batch + " - args.prepended_w;\n"; c += " args.src_tensor.SetBatchRef(s_b);\n"; } if (attr.type == PaddingContentType::REFLECT) { c += " s_x = reflect(s_x, args.src_tensor.Width());\n"; c += " s_y = reflect(s_y, args.src_tensor.Height());\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " int s_b = reflect(s_b, args.src_tensor.Batch());\n"; } if (attr.prepended.c == 0 && attr.appended.c == 0) { // optimized case c += " result = args.src_tensor.Read(s_x, s_y, Z);\n"; } else { c += " int start_channel = Z * 4;\n"; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; c += " {\n"; c += " int channel = start_channel + " + std::to_string(i) + ";\n"; c += " int s_z = channel - args.prepended_z;\n"; // We need additional clamp for z, so that we use alignment for channels // and can proceed extra channels that can lead to reading out of // resource. c += " s_z = clamp(reflect(s_z, args.src_tensor.Channels()), 0, " "args.src_tensor.Channels() - " "1);\n"; c += " FLT4 t = args.src_tensor.Read(s_x, s_y, s_z / 4);\n"; c += " result" + s + " = SELECT_BY_INDEX_FROM_FLT4(t, s_z % 4);\n"; c += " }\n"; } } } else { c += " bool inside_x = s_x >= 0 && s_x < args.src_tensor.Width();\n"; c += " bool inside_y = s_y >= 0 && s_y < args.src_tensor.Height();\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " inside_y &= (s_b >= 0 && s_b < args.src_tensor.Batch());\n"; } c += " if (inside_x && inside_y) {\n"; if (attr.prepended.c == 0 && attr.appended.c == 0) { // optimized case c += " result = args.src_tensor.Read(s_x, s_y, Z);\n"; } else if (attr.prepended.c % 4 == 0) { c += " int s_z = Z - args.prepended_z / 4;\n"; c += " if (s_z >= 0 && s_z < args.src_tensor.Slices()) {\n"; c += " result = args.src_tensor.Read(s_x, s_y, s_z);\n"; c += " }\n"; } else { c += " int start_channel = Z * 4;\n"; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; c += " {\n"; c += " int channel = start_channel + " + std::to_string(i) + ";\n"; c += " int s_z = channel - args.prepended_z;\n"; c += " if (s_z >= 0 && s_z < args.src_tensor.Channels()) {\n"; c += " FLT4 t = args.src_tensor.Read(s_x, s_y, s_z / 4);\n"; c += " result" + s + " = SELECT_BY_INDEX_FROM_FLT4(t, s_z % 4);\n"; c += " }\n"; c += " }\n"; } } c += " }\n"; } c += " args.dst_tensor.Write(result, X, Y, Z);\n"; c += "}\n"; return c; } } // namespace GPUOperation CreatePadding(const OperationDef& definition, const PadAttributes& attr) { GPUOperation op(definition); op.code_ = GetPaddingCode(definition, attr, &op); op.tensor_to_grid_ = TensorToGrid::kWBToX_HDToY_SToZ; return op; } } // namespace gpu } // namespace tflite <commit_msg>Kernel function name changed from reflect to reflect_coord to exclude conflict with builtin function.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/common/tasks/padding.h" #include <string> #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/task/work_group_picking.h" namespace tflite { namespace gpu { namespace { std::string GetPaddingCode(const OperationDef& op_def, const PadAttributes& attr, GPUOperation* op) { op->AddSrcTensor("src_tensor", op_def.src_tensors[0]); op->AddDstTensor("dst_tensor", op_def.dst_tensors[0]); op->args_.AddInt("prepended_x", attr.prepended.w); op->args_.AddInt("prepended_y", attr.prepended.h); op->args_.AddInt("prepended_z", attr.prepended.c); op->args_.AddInt("prepended_w", attr.prepended.b); const std::string dst_batch = op_def.dst_tensors[0].HasAxis(Axis::BATCH) ? "B" : "0"; std::string c; const std::string channels[] = {".x", ".y", ".z", ".w"}; if (attr.type == PaddingContentType::REFLECT) { c += "int reflect_coord(int x, int size) {\n"; c += " int t = abs(x) - size + 1;\n"; c += " return size - 1 - abs(t);\n"; c += "}\n\n"; } c += "MAIN_FUNCTION($0) {\n"; if (op_def.dst_tensors[0].HasAxis(Axis::BATCH)) { c += " int linear_id = GLOBAL_ID_0;\n"; c += " int X = linear_id / args.dst_tensor.Batch();\n"; c += " int B = linear_id % args.dst_tensor.Batch();\n"; c += " args.dst_tensor.SetBatchRef(B);\n"; } else { c += " int X = GLOBAL_ID_0;\n"; } c += " int Y = GLOBAL_ID_1;\n"; c += " int Z = GLOBAL_ID_2;\n"; c += " if (X >= args.dst_tensor.Width() || Y >= args.dst_tensor.Height() || " "Z >= args.dst_tensor.Slices()) { \n"; c += " return; \n"; c += " } \n"; c += " FLT4 result = INIT_FLT4(0.0);\n"; c += " int s_x = X - args.prepended_x;\n"; c += " int s_y = Y - args.prepended_y;\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " int s_b = " + dst_batch + " - args.prepended_w;\n"; c += " args.src_tensor.SetBatchRef(s_b);\n"; } if (attr.type == PaddingContentType::REFLECT) { c += " s_x = reflect_coord(s_x, args.src_tensor.Width());\n"; c += " s_y = reflect_coord(s_y, args.src_tensor.Height());\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " int s_b = reflect_coord(s_b, args.src_tensor.Batch());\n"; } if (attr.prepended.c == 0 && attr.appended.c == 0) { // optimized case c += " result = args.src_tensor.Read(s_x, s_y, Z);\n"; } else { c += " int start_channel = Z * 4;\n"; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; c += " {\n"; c += " int channel = start_channel + " + std::to_string(i) + ";\n"; c += " int s_z = channel - args.prepended_z;\n"; // We need additional clamp for z, so that we use alignment for channels // and can proceed extra channels that can lead to reading out of // resource. c += " s_z = clamp(reflect_coord(s_z, args.src_tensor.Channels()), " "0, " "args.src_tensor.Channels() - " "1);\n"; c += " FLT4 t = args.src_tensor.Read(s_x, s_y, s_z / 4);\n"; c += " result" + s + " = SELECT_BY_INDEX_FROM_FLT4(t, s_z % 4);\n"; c += " }\n"; } } } else { c += " bool inside_x = s_x >= 0 && s_x < args.src_tensor.Width();\n"; c += " bool inside_y = s_y >= 0 && s_y < args.src_tensor.Height();\n"; if (op_def.src_tensors[0].HasAxis(Axis::BATCH)) { c += " inside_y &= (s_b >= 0 && s_b < args.src_tensor.Batch());\n"; } c += " if (inside_x && inside_y) {\n"; if (attr.prepended.c == 0 && attr.appended.c == 0) { // optimized case c += " result = args.src_tensor.Read(s_x, s_y, Z);\n"; } else if (attr.prepended.c % 4 == 0) { c += " int s_z = Z - args.prepended_z / 4;\n"; c += " if (s_z >= 0 && s_z < args.src_tensor.Slices()) {\n"; c += " result = args.src_tensor.Read(s_x, s_y, s_z);\n"; c += " }\n"; } else { c += " int start_channel = Z * 4;\n"; for (int i = 0; i < 4; ++i) { const auto& s = channels[i]; c += " {\n"; c += " int channel = start_channel + " + std::to_string(i) + ";\n"; c += " int s_z = channel - args.prepended_z;\n"; c += " if (s_z >= 0 && s_z < args.src_tensor.Channels()) {\n"; c += " FLT4 t = args.src_tensor.Read(s_x, s_y, s_z / 4);\n"; c += " result" + s + " = SELECT_BY_INDEX_FROM_FLT4(t, s_z % 4);\n"; c += " }\n"; c += " }\n"; } } c += " }\n"; } c += " args.dst_tensor.Write(result, X, Y, Z);\n"; c += "}\n"; return c; } } // namespace GPUOperation CreatePadding(const OperationDef& definition, const PadAttributes& attr) { GPUOperation op(definition); op.code_ = GetPaddingCode(definition, attr, &op); op.tensor_to_grid_ = TensorToGrid::kWBToX_HDToY_SToZ; return op; } } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>#include "ofApp.h" #include "ofxXmlSettings.h" #include "ofxJSONElement.h" void ofApp::setup(){ ofBackground(54, 54, 54, 255); #ifdef TARGET_OSX ofSetDataPathRoot("../Resources/data/"); #endif // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { std::cerr << "Error opening events.txt - !!!DATA WILL BE LOST!!!" << std::endl; } if (!configuration.Read()) { std::cerr << "Error reading configuration" << std::endl; } gameStats.Read(); ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); //ofSetWindowShape(1000, 200); ofSetWindowPosition(0, 0); // Distance reader serialReader.ActiveSerialPort = configuration.ActiveSerialPort; serialReader.startThread(); // HUD if (!hudFont.loadFont("verdana.ttf", 12, true, true)) { std::cerr << "Error loading HUD font" << std::endl; } hudFont.setLineHeight(18.0f); hudFont.setLetterSpacing(1.037); // Overlay if (!overlayFont.loadFont("verdana.ttf", 300, true, true)) { std::cerr << "Error loading overlay font" << std::endl; } if (!stateFont.loadFont("verdana.ttf", 100, true, true)) { std::cerr << "Error loading status font" << std::endl; } // Audio if (!heartbeatSound.loadSound("2.mp3")) { std::cerr << "Error loading heartbeat sound" << std::endl; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { std::cerr << "Error loading video" << std::endl; } // Intro and outro pics if (!intro.loadImage(ofToDataPath(configuration.IntroFileName))) { std::cerr << "Error loading intro" << std::endl; } serialReader.SetMaxReading(configuration.MaxDistance); serialReader.Enable(); } const int kForward = 1; const int kBack = -1; void ofApp::exit() { serialReader.stopThread(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); totalNumOfFrames = videoPlayer.getTotalNumFrames(); return true; } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); const int distance = serialReader.Reading(); if (kStateWaiting == state.name) { // If user finds itself *in* the save zone, we start the game. if (distance < configuration.MaxDistance && distance >= configuration.MaxDistance - configuration.SaveZone) { startGame(); } } else if (kStateStarted == state.name) { if (distance < configuration.MinDistance + configuration.DeathZone) { // Determine if user is now in the death zone killGame(); } else if (state.saveZoneActive && distance > configuration.MaxDistance - configuration.SaveZone) { // If save zone is active and user finds itself in it, // then declare the game saved and finish it. saveGame("user walked into save zone"); } else if (!state.saveZoneActive && distance < configuration.MaxDistance - configuration.SaveZone) { // If user has moved out of save zone, and game is not finished // yet, activate save zone state.saveZoneActive = true; } else if (serialReader.LastUserInputAt() < now - (configuration.AutoSaveSeconds*1000)) { // If we have no new input for N seconds, consider the game // as saved, as it seems that the user has left the building saveGame("user has left the game"); } } else if (kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000)) { restartGame(); } } else if (kStateKilled == state.name || kStateSaved == state.name) { int destinationFrame = frameForDistance(distance); if (destinationFrame == videoPlayer.getCurrentFrame()) { showStats(); } } else { throw("invalid state"); } updateVideo(distance); updateAudio(distance); } void ofApp::showStats() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Showing stats " << now << std::endl; if (kStateKilled == state.name) { state.name = kStateStatsKilled; } else if (kStateSaved == state.name) { state.name = kStateStatsSaved; } else { throw("invalid state"); } state.finishedAt = now; } void ofApp::updateVideo(const int distance) { if (kStateWaiting == state.name || kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (videoPlayer.isPlaying()) { videoPlayer.stop(); } return; } int currentFrame = videoPlayer.getCurrentFrame(); int destinationFrame = frameForDistance(distance); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (currentFrame >= destinationFrame) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (currentFrame <= destinationFrame) { videoPlayer.setPaused(true); } } } else { if (currentFrame > destinationFrame) { videoPlayer.setSpeed(kBack); videoPlayer.setPaused(false); } else if (currentFrame < destinationFrame) { videoPlayer.setSpeed(kForward); videoPlayer.setPaused(false); } } videoPlayer.update(); } void ofApp::killGame() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Game finished with kill at " << now << std::endl; eventLog << "killed=" << now << std::endl; state.name = kStateKilled; gameStats.AddKill(); } void ofApp::saveGame(const std::string reason) { long now = ofGetElapsedTimeMillis(); std::cout << "Game finished with save at " << now << " because of " << reason << std::endl; eventLog << "saved=" << now << std::endl; state.name = kStateSaved; gameStats.AddSave(); } void ofApp::keyPressed(int key) { ofLogNotice() << "keyPressed key=" << key; const int kMinStep = 50; if (OF_KEY_UP == key) { serialReader.AddReading(ofClamp(serialReader.Reading() - kMinStep, configuration.MinDistance, configuration.MaxDistance)); } else if (OF_KEY_DOWN == key) { serialReader.AddReading(ofClamp(serialReader.Reading() + kMinStep, configuration.MinDistance, configuration.MaxDistance)); } } void ofApp::updateAudio(const int distance) { // Game over, dudes if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } else { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(videoPlayer.getCurrentFrame(), 0, totalNumOfFrames, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } ofSoundUpdate(); } void ofApp::restartGame() { std::cout << "Game restarted" << std::endl; state = GameState(); serialReader.Disable(); serialReader.Clear(); serialReader.Enable(); if (!loadVideo()) { std::cerr << "Error loading video after kill" << std::endl; } std::cout << "frame after resettting video player: " << videoPlayer.getCurrentFrame() << std::endl; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } void ofApp::startGame() { long now = ofGetElapsedTimeMillis(); serialReader.Enable(); std::cout << "Game started at " << now << std::endl; state.name = kStateStarted; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance(const int distance) const { int d(0); // Override dest. frame on certain conditions, like kill, save, waiting etc if (kStateKilled == state.name || kStateStatsKilled == state.name) { d = configuration.MinDistance; } else if (kStateSaved == state.name || kStateStatsSaved == state.name) { d = configuration.MaxDistance; } else if (kStateWaiting == state.name || kStateStarted == state.name) { d = distance; } else { throw("invalid state!"); } return ofMap(d, configuration.MaxDistance, configuration.MinDistance, 0, totalNumOfFrames); } const int kColorWhite = 0xFFFFFF; const int kColorBlack = 0x000000; void ofApp::draw(){ long now = ofGetElapsedTimeMillis(); int restartCountdownSeconds = 0; if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } int autosaveCountdownSeconds = 0; if (kStateStarted == state.name) { int inactiveSeconds = (now - serialReader.LastUserInputAt()) / 1000; autosaveCountdownSeconds = configuration.AutoSaveSeconds - inactiveSeconds; } // Update HUD const int distance = serialReader.Reading(); ofSetColor(255); if (configuration.DebugOverlay) { int y = 20; hudFont.drawString("distance=" + ofToString(distance), 10, y); hudFont.drawString("frame=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(totalNumOfFrames), 200, y); hudFont.drawString("dest.f=" + ofToString(frameForDistance(distance)), 400, y); hudFont.drawString("max distance=" + ofToString(configuration.MaxDistance), 600, y); hudFont.drawString("video=" + ofToString(isPlaying() ? "yes" : "no"), 800, y); y = 40; hudFont.drawString("restart=" + ofToString(restartCountdownSeconds), 10, y); hudFont.drawString("save zone=" + ofToString(configuration.SaveZone), 200, y); hudFont.drawString("death zone=" + ofToString(configuration.DeathZone), 400, y); hudFont.drawString("save active=" + ofToString(state.saveZoneActive ? "yes" : "no"), 600, y); hudFont.drawString("autosave=" + ofToString(autosaveCountdownSeconds), 800, y); } int margin(0); if (configuration.DebugOverlay) { margin = 50; } if (kStateStatsSaved == state.name) { ofSetHexColor(kColorWhite); ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); ofSetHexColor(kColorBlack); hudFont.drawString("LIFES SAVED: " + ofToString(gameStats.TotalSaves()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateStatsKilled == state.name) { ofSetHexColor(kColorBlack); ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); ofSetHexColor(kColorWhite); hudFont.drawString("TOTAL KILLS: " + ofToString(gameStats.TotalKills()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateWaiting == state.name) { ofSetHexColor(kColorWhite); ofFill(); intro.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); } else if (kStateStarted == state.name || kStateKilled == state.name || kStateSaved == state.name) { ofSetHexColor(kColorWhite); ofFill(); videoPlayer.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); // Draw overlay, for debugging if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); overlayFont.drawString(ofToString(distance), 100, ofGetWindowHeight() / 2); } } else { throw("invalid state"); } if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); stateFont.drawString(state.name, 100, ofGetWindowHeight() / 2 + 200); } }<commit_msg>change data root, so that data persists<commit_after>#include "ofApp.h" #include "ofxXmlSettings.h" #include "ofxJSONElement.h" void ofApp::setup(){ ofBackground(54, 54, 54, 255); #ifdef TARGET_OSX ofSetDataPathRoot("~/curiosity_data/"); #endif // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { std::cerr << "Error opening events.txt - !!!DATA WILL BE LOST!!!" << std::endl; } if (!configuration.Read()) { std::cerr << "Error reading configuration" << std::endl; } gameStats.Read(); ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); //ofSetWindowShape(1000, 200); ofSetWindowPosition(0, 0); // Distance reader serialReader.ActiveSerialPort = configuration.ActiveSerialPort; serialReader.startThread(); // HUD if (!hudFont.loadFont("verdana.ttf", 12, true, true)) { std::cerr << "Error loading HUD font" << std::endl; } hudFont.setLineHeight(18.0f); hudFont.setLetterSpacing(1.037); // Overlay if (!overlayFont.loadFont("verdana.ttf", 300, true, true)) { std::cerr << "Error loading overlay font" << std::endl; } if (!stateFont.loadFont("verdana.ttf", 100, true, true)) { std::cerr << "Error loading status font" << std::endl; } // Audio if (!heartbeatSound.loadSound("2.mp3")) { std::cerr << "Error loading heartbeat sound" << std::endl; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { std::cerr << "Error loading video" << std::endl; } // Intro and outro pics if (!intro.loadImage(ofToDataPath(configuration.IntroFileName))) { std::cerr << "Error loading intro" << std::endl; } serialReader.SetMaxReading(configuration.MaxDistance); serialReader.Enable(); } const int kForward = 1; const int kBack = -1; void ofApp::exit() { serialReader.stopThread(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); totalNumOfFrames = videoPlayer.getTotalNumFrames(); return true; } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); const int distance = serialReader.Reading(); if (kStateWaiting == state.name) { // If user finds itself *in* the save zone, we start the game. if (distance < configuration.MaxDistance && distance >= configuration.MaxDistance - configuration.SaveZone) { startGame(); } } else if (kStateStarted == state.name) { if (distance < configuration.MinDistance + configuration.DeathZone) { // Determine if user is now in the death zone killGame(); } else if (state.saveZoneActive && distance > configuration.MaxDistance - configuration.SaveZone) { // If save zone is active and user finds itself in it, // then declare the game saved and finish it. saveGame("user walked into save zone"); } else if (!state.saveZoneActive && distance < configuration.MaxDistance - configuration.SaveZone) { // If user has moved out of save zone, and game is not finished // yet, activate save zone state.saveZoneActive = true; } else if (serialReader.LastUserInputAt() < now - (configuration.AutoSaveSeconds*1000)) { // If we have no new input for N seconds, consider the game // as saved, as it seems that the user has left the building saveGame("user has left the game"); } } else if (kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000)) { restartGame(); } } else if (kStateKilled == state.name || kStateSaved == state.name) { int destinationFrame = frameForDistance(distance); if (destinationFrame == videoPlayer.getCurrentFrame()) { showStats(); } } else { throw("invalid state"); } updateVideo(distance); updateAudio(distance); } void ofApp::showStats() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Showing stats " << now << std::endl; if (kStateKilled == state.name) { state.name = kStateStatsKilled; } else if (kStateSaved == state.name) { state.name = kStateStatsSaved; } else { throw("invalid state"); } state.finishedAt = now; } void ofApp::updateVideo(const int distance) { if (kStateWaiting == state.name || kStateStatsKilled == state.name || kStateStatsSaved == state.name) { if (videoPlayer.isPlaying()) { videoPlayer.stop(); } return; } int currentFrame = videoPlayer.getCurrentFrame(); int destinationFrame = frameForDistance(distance); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (currentFrame >= destinationFrame) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (currentFrame <= destinationFrame) { videoPlayer.setPaused(true); } } } else { if (currentFrame > destinationFrame) { videoPlayer.setSpeed(kBack); videoPlayer.setPaused(false); } else if (currentFrame < destinationFrame) { videoPlayer.setSpeed(kForward); videoPlayer.setPaused(false); } } videoPlayer.update(); } void ofApp::killGame() { long now = ofGetElapsedTimeMillis(); serialReader.Disable(); std::cout << "Game finished with kill at " << now << std::endl; eventLog << "killed=" << now << std::endl; state.name = kStateKilled; gameStats.AddKill(); } void ofApp::saveGame(const std::string reason) { long now = ofGetElapsedTimeMillis(); std::cout << "Game finished with save at " << now << " because of " << reason << std::endl; eventLog << "saved=" << now << std::endl; state.name = kStateSaved; gameStats.AddSave(); } void ofApp::keyPressed(int key) { ofLogNotice() << "keyPressed key=" << key; const int kMinStep = 50; if (OF_KEY_UP == key) { serialReader.AddReading(ofClamp(serialReader.Reading() - kMinStep, configuration.MinDistance, configuration.MaxDistance)); } else if (OF_KEY_DOWN == key) { serialReader.AddReading(ofClamp(serialReader.Reading() + kMinStep, configuration.MinDistance, configuration.MaxDistance)); } } void ofApp::updateAudio(const int distance) { // Game over, dudes if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } else { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(videoPlayer.getCurrentFrame(), 0, totalNumOfFrames, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } ofSoundUpdate(); } void ofApp::restartGame() { std::cout << "Game restarted" << std::endl; state = GameState(); serialReader.Disable(); serialReader.Clear(); serialReader.Enable(); if (!loadVideo()) { std::cerr << "Error loading video after kill" << std::endl; } std::cout << "frame after resettting video player: " << videoPlayer.getCurrentFrame() << std::endl; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } void ofApp::startGame() { long now = ofGetElapsedTimeMillis(); serialReader.Enable(); std::cout << "Game started at " << now << std::endl; state.name = kStateStarted; eventLog << "started=" << ofGetElapsedTimeMillis() << std::endl; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance(const int distance) const { int d(0); // Override dest. frame on certain conditions, like kill, save, waiting etc if (kStateKilled == state.name || kStateStatsKilled == state.name) { d = configuration.MinDistance; } else if (kStateSaved == state.name || kStateStatsSaved == state.name) { d = configuration.MaxDistance; } else if (kStateWaiting == state.name || kStateStarted == state.name) { d = distance; } else { throw("invalid state!"); } return ofMap(d, configuration.MaxDistance, configuration.MinDistance, 0, totalNumOfFrames); } const int kColorWhite = 0xFFFFFF; const int kColorBlack = 0x000000; void ofApp::draw(){ long now = ofGetElapsedTimeMillis(); int restartCountdownSeconds = 0; if (kStateStatsSaved == state.name || kStateStatsKilled == state.name) { int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } int autosaveCountdownSeconds = 0; if (kStateStarted == state.name) { int inactiveSeconds = (now - serialReader.LastUserInputAt()) / 1000; autosaveCountdownSeconds = configuration.AutoSaveSeconds - inactiveSeconds; } // Update HUD const int distance = serialReader.Reading(); ofSetColor(255); if (configuration.DebugOverlay) { int y = 20; hudFont.drawString("distance=" + ofToString(distance), 10, y); hudFont.drawString("frame=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(totalNumOfFrames), 200, y); hudFont.drawString("dest.f=" + ofToString(frameForDistance(distance)), 400, y); hudFont.drawString("max distance=" + ofToString(configuration.MaxDistance), 600, y); hudFont.drawString("video=" + ofToString(isPlaying() ? "yes" : "no"), 800, y); y = 40; hudFont.drawString("restart=" + ofToString(restartCountdownSeconds), 10, y); hudFont.drawString("save zone=" + ofToString(configuration.SaveZone), 200, y); hudFont.drawString("death zone=" + ofToString(configuration.DeathZone), 400, y); hudFont.drawString("save active=" + ofToString(state.saveZoneActive ? "yes" : "no"), 600, y); hudFont.drawString("autosave=" + ofToString(autosaveCountdownSeconds), 800, y); } int margin(0); if (configuration.DebugOverlay) { margin = 50; } if (kStateStatsSaved == state.name) { ofSetHexColor(kColorWhite); ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); ofSetHexColor(kColorBlack); hudFont.drawString("LIFES SAVED: " + ofToString(gameStats.TotalSaves()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateStatsKilled == state.name) { ofSetHexColor(kColorBlack); ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); ofSetHexColor(kColorWhite); hudFont.drawString("TOTAL KILLS: " + ofToString(gameStats.TotalKills()), ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); } else if (kStateWaiting == state.name) { ofSetHexColor(kColorWhite); ofFill(); intro.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); } else if (kStateStarted == state.name || kStateKilled == state.name || kStateSaved == state.name) { ofSetHexColor(kColorWhite); ofFill(); videoPlayer.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); // Draw overlay, for debugging if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); overlayFont.drawString(ofToString(distance), 100, ofGetWindowHeight() / 2); } } else { throw("invalid state"); } if (configuration.DebugOverlay) { ofSetHexColor(kColorBlack); stateFont.drawString(state.name, 100, ofGetWindowHeight() / 2 + 200); } }<|endoftext|>
<commit_before>#pragma once #include "filter.h" #include <xmmintrin.h> #define COEFY 1.0037736040867458f, 1.0031713814217937f, 1.0038646965904563f #define COEFU 0.0009812686948862392f, -0.34182057237626395f, 1.7738420513779833f #define COEFV 1.4028706125758748f, -0.7126004638855613f, 0.0018494308641594699f #define COEFR 0.297607421875f, -0.1689453125f, 0.5f #define COEFG 0.586181640625f, -0.331298828125f, -0.419189453125f #define COEFB 0.11279296875f, 0.5f, -0.0810546875f namespace color_cvt { inline void yc2rgb(float(&buf)[4], const PIXEL_YC* px) noexcept { // Load YUV2RGB matrix static const __m128 cy = _mm_set_ps(COEFY, 0.f); static const __m128 cu = _mm_set_ps(COEFU, 0.f); static const __m128 cv = _mm_set_ps(COEFV, 0.f); __m128 my = _mm_set1_ps(static_cast<float>(px->y)); __m128 mu = _mm_set1_ps(static_cast<float>(px->cb)); __m128 mv = _mm_set1_ps(static_cast<float>(px->cr)); my = _mm_mul_ps(my, cy); mu = _mm_mul_ps(mu, cu); mv = _mm_mul_ps(mv, cv); my = _mm_add_ps(my, mu); my = _mm_add_ps(my, mv); //result in my _mm_storeu_ps(buf, my); // buf: 0, b, g, r } inline void rgb2yc(PIXEL_YC* px, const float(&buf)[4]) noexcept { // Load RGB2YUV matrix static const __m128 cr = _mm_set_ps(COEFR, 0.f); static const __m128 cg = _mm_set_ps(COEFG, 0.f); static const __m128 cb = _mm_set_ps(COEFB, 0.f); __m128 my = _mm_set1_ps(buf[1]); __m128 mu = _mm_set1_ps(buf[2]); __m128 mv = _mm_set1_ps(buf[3]); my = _mm_mul_ps(my, cb); mu = _mm_mul_ps(mu, cg); mv = _mm_mul_ps(mv, cr); my = _mm_add_ps(my, mu); my = _mm_add_ps(my, mv); //result in my float tmp[4]; _mm_storeu_ps(tmp, my); // tmp: 0, v, u, y px->y = static_cast<short>(tmp[3]); px->cb = static_cast<short>(tmp[2]); px->cr = static_cast<short>(tmp[1]); } } <commit_msg>stop to specify static<commit_after>#pragma once #include "filter.h" #include <xmmintrin.h> namespace color_cvt { inline void yc2rgb(float(&buf)[4], const PIXEL_YC* px) noexcept { // Load YUV2RGB matrix const __m128 cy = _mm_set_ps(1.0037736040867458f, 1.0031713814217937f, 1.0038646965904563f, 0.f); const __m128 cu = _mm_set_ps(0.0009812686948862392f, -0.34182057237626395f, 1.7738420513779833f, 0.f); const __m128 cv = _mm_set_ps(1.4028706125758748f, -0.7126004638855613f, 0.0018494308641594699f, 0.f); __m128 my = _mm_set1_ps(static_cast<float>(px->y)); __m128 mu = _mm_set1_ps(static_cast<float>(px->cb)); __m128 mv = _mm_set1_ps(static_cast<float>(px->cr)); my = _mm_mul_ps(my, cy); mu = _mm_mul_ps(mu, cu); mv = _mm_mul_ps(mv, cv); my = _mm_add_ps(my, mu); my = _mm_add_ps(my, mv); //result in my _mm_storeu_ps(buf, my); // buf: 0, b, g, r } inline void rgb2yc(PIXEL_YC* px, const float(&buf)[4]) noexcept { // Load RGB2YUV matrix const __m128 cr = _mm_set_ps(0.297607421875f, -0.1689453125f, 0.5f, 0.f); const __m128 cg = _mm_set_ps(0.586181640625f, -0.331298828125f, -0.419189453125f, 0.f); const __m128 cb = _mm_set_ps(0.11279296875f, 0.5f, -0.0810546875f, 0.f); __m128 my = _mm_set1_ps(buf[1]); __m128 mu = _mm_set1_ps(buf[2]); __m128 mv = _mm_set1_ps(buf[3]); my = _mm_mul_ps(my, cb); mu = _mm_mul_ps(mu, cg); mv = _mm_mul_ps(mv, cr); my = _mm_add_ps(my, mu); my = _mm_add_ps(my, mv); //result in my float tmp[4]; _mm_storeu_ps(tmp, my); // tmp: 0, v, u, y px->y = static_cast<short>(tmp[3]); px->cb = static_cast<short>(tmp[2]); px->cr = static_cast<short>(tmp[1]); } } <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENUMS_GRAPHICS_HPP #define NAZARA_ENUMS_GRAPHICS_HPP namespace Nz { enum BackgroundType { BackgroundType_Color, // ColorBackground BackgroundType_Skybox, // SkyboxBackground BackgroundType_Texture, // TextureBackground BackgroundType_User, BackgroundType_Max = BackgroundType_User }; enum class CullTest { NoTest, Sphere, Volume }; enum ProjectionType { ProjectionType_Orthogonal, ProjectionType_Perspective, ProjectionType_Max = ProjectionType_Perspective }; enum LightType { LightType_Directional, LightType_Point, LightType_Spot, LightType_Max = LightType_Spot }; enum MaterialUniform { MaterialUniform_AlphaMap, MaterialUniform_AlphaThreshold, MaterialUniform_Ambient, MaterialUniform_Diffuse, MaterialUniform_DiffuseMap, MaterialUniform_EmissiveMap, MaterialUniform_HeightMap, MaterialUniform_NormalMap, MaterialUniform_Shininess, MaterialUniform_Specular, MaterialUniform_SpecularMap, MaterialUniform_Max = MaterialUniform_SpecularMap }; enum ParticleComponent { ParticleComponent_Unused = -1, ParticleComponent_Color, ParticleComponent_Life, ParticleComponent_Mass, ParticleComponent_Normal, ParticleComponent_Position, ParticleComponent_Radius, ParticleComponent_Rotation, ParticleComponent_Size, ParticleComponent_Velocity, ParticleComponent_Userdata0, ParticleComponent_Userdata1, ParticleComponent_Userdata2, ParticleComponent_Userdata3, ParticleComponent_Userdata4, ParticleComponent_Userdata5, ParticleComponent_Userdata6, ParticleComponent_Userdata7, ParticleComponent_Userdata8, ParticleComponent_Max = ParticleComponent_Userdata8 }; enum ParticleLayout { ParticleLayout_Billboard, ParticleLayout_Model, ParticleLayout_Sprite, ParticleLayout_Max = ParticleLayout_Sprite }; enum RenderPassType { RenderPassType_AA, RenderPassType_Bloom, RenderPassType_DOF, RenderPassType_Final, RenderPassType_Fog, RenderPassType_Forward, RenderPassType_Lighting, RenderPassType_LightScattering, RenderPassType_Geometry, RenderPassType_SSAO, RenderPassType_Max = RenderPassType_SSAO }; enum RenderTechniqueType { RenderTechniqueType_AdvancedForward, // AdvancedForwardRenderTechnique RenderTechniqueType_BasicForward, // BasicForwardRenderTechnique RenderTechniqueType_DeferredShading, // DeferredRenderTechnique RenderTechniqueType_Depth, // DepthRenderTechnique RenderTechniqueType_LightPrePass, // LightPrePassRenderTechnique RenderTechniqueType_User, RenderTechniqueType_Max = RenderTechniqueType_User }; enum ReflectionMode { ReflectionMode_RealTime, ReflectionMode_Probe, ReflectionMode_Skybox, ReflectionMode_Max = ReflectionMode_Skybox }; enum SceneNodeType { SceneNodeType_Light, // Light SceneNodeType_Model, // Model SceneNodeType_ParticleEmitter, // ParticleEmitter SceneNodeType_Root, // SceneRoot SceneNodeType_Sprite, // Sprite SceneNodeType_TextSprite, // TextSprite SceneNodeType_User, SceneNodeType_Max = SceneNodeType_User }; // These parameters are independant of the material: they can not be asked for the moment enum ShaderFlags { ShaderFlags_None = 0, ShaderFlags_Billboard = 0x01, ShaderFlags_Deferred = 0x02, ShaderFlags_Instancing = 0x04, ShaderFlags_TextureOverlay = 0x08, ShaderFlags_VertexColor = 0x10, ShaderFlags_Max = ShaderFlags_VertexColor * 2 - 1 }; enum TextureMap { TextureMap_Alpha, TextureMap_Diffuse, TextureMap_Emissive, TextureMap_Height, TextureMap_ReflectionCube, TextureMap_Normal, TextureMap_Overlay, TextureMap_Shadow2D_1, TextureMap_Shadow2D_2, TextureMap_Shadow2D_3, TextureMap_ShadowCube_1, TextureMap_ShadowCube_2, TextureMap_ShadowCube_3, TextureMap_Specular, TextureMap_Max = TextureMap_Specular }; } #endif // NAZARA_ENUMS_GRAPHICS_HPP <commit_msg>Revert "Oops again"<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENUMS_GRAPHICS_HPP #define NAZARA_ENUMS_GRAPHICS_HPP namespace Nz { enum BackgroundType { BackgroundType_Color, // ColorBackground BackgroundType_Skybox, // SkyboxBackground BackgroundType_Texture, // TextureBackground BackgroundType_User, BackgroundType_Max = BackgroundType_User }; enum class CullTest { NoTest, Sphere, Volume }; enum ProjectionType { ProjectionType_Orthogonal, ProjectionType_Perspective, ProjectionType_Max = ProjectionType_Perspective }; enum LightType { LightType_Directional, LightType_Point, LightType_Spot, LightType_Max = LightType_Spot }; enum MaterialUniform { MaterialUniform_AlphaMap, MaterialUniform_AlphaThreshold, MaterialUniform_Ambient, MaterialUniform_Diffuse, MaterialUniform_DiffuseMap, MaterialUniform_EmissiveMap, MaterialUniform_HeightMap, MaterialUniform_NormalMap, MaterialUniform_Shininess, MaterialUniform_Specular, MaterialUniform_SpecularMap, MaterialUniform_Max = MaterialUniform_SpecularMap }; enum ParticleComponent { ParticleComponent_Unused = -1, ParticleComponent_Color, ParticleComponent_Life, ParticleComponent_Mass, ParticleComponent_Normal, ParticleComponent_Position, ParticleComponent_Radius, ParticleComponent_Rotation, ParticleComponent_Size, ParticleComponent_Velocity, ParticleComponent_Userdata0, ParticleComponent_Userdata1, ParticleComponent_Userdata2, ParticleComponent_Userdata3, ParticleComponent_Userdata4, ParticleComponent_Userdata5, ParticleComponent_Userdata6, ParticleComponent_Userdata7, ParticleComponent_Userdata8, ParticleComponent_Max = ParticleComponent_Userdata8 }; enum ParticleLayout { ParticleLayout_Billboard, ParticleLayout_Model, ParticleLayout_Sprite, ParticleLayout_Max = ParticleLayout_Sprite }; enum RenderPassType { RenderPassType_AA, RenderPassType_Bloom, RenderPassType_DOF, RenderPassType_Final, RenderPassType_Fog, RenderPassType_Forward, RenderPassType_Lighting, RenderPassType_Geometry, RenderPassType_SSAO, RenderPassType_Max = RenderPassType_SSAO }; enum RenderTechniqueType { RenderTechniqueType_AdvancedForward, // AdvancedForwardRenderTechnique RenderTechniqueType_BasicForward, // BasicForwardRenderTechnique RenderTechniqueType_DeferredShading, // DeferredRenderTechnique RenderTechniqueType_Depth, // DepthRenderTechnique RenderTechniqueType_LightPrePass, // LightPrePassRenderTechnique RenderTechniqueType_User, RenderTechniqueType_Max = RenderTechniqueType_User }; enum ReflectionMode { ReflectionMode_RealTime, ReflectionMode_Probe, ReflectionMode_Skybox, ReflectionMode_Max = ReflectionMode_Skybox }; enum SceneNodeType { SceneNodeType_Light, // Light SceneNodeType_Model, // Model SceneNodeType_ParticleEmitter, // ParticleEmitter SceneNodeType_Root, // SceneRoot SceneNodeType_Sprite, // Sprite SceneNodeType_TextSprite, // TextSprite SceneNodeType_User, SceneNodeType_Max = SceneNodeType_User }; // These parameters are independant of the material: they can not be asked for the moment enum ShaderFlags { ShaderFlags_None = 0, ShaderFlags_Billboard = 0x01, ShaderFlags_Deferred = 0x02, ShaderFlags_Instancing = 0x04, ShaderFlags_TextureOverlay = 0x08, ShaderFlags_VertexColor = 0x10, ShaderFlags_Max = ShaderFlags_VertexColor * 2 - 1 }; enum TextureMap { TextureMap_Alpha, TextureMap_Diffuse, TextureMap_Emissive, TextureMap_Height, TextureMap_ReflectionCube, TextureMap_Normal, TextureMap_Overlay, TextureMap_Shadow2D_1, TextureMap_Shadow2D_2, TextureMap_Shadow2D_3, TextureMap_ShadowCube_1, TextureMap_ShadowCube_2, TextureMap_ShadowCube_3, TextureMap_Specular, TextureMap_Max = TextureMap_Specular }; } #endif // NAZARA_ENUMS_GRAPHICS_HPP <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Error.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Math/Config.hpp> #include <algorithm> #include <cstring> #include <Nazara/Core/Debug.hpp> #define F(a) static_cast<T>(a) #define F2(a) static_cast<T2>(a) template<typename T> T NzApproach(T value, T objective, T increment) { ///TODO: Marquer comme constexpr en C++14 if (value < objective) return std::min(value + increment, objective); else if (value > objective) return std::max(value - increment, objective); else return value; } template<typename T> constexpr T NzClamp(T value, T min, T max) { return std::max(std::min(value, max), min); } template<typename T> constexpr T NzDegreeToRadian(T degrees) { return degrees * F(M_PI/180.0); } template<typename T> constexpr T NzFromDegrees(T degrees) { #if NAZARA_MATH_ANGLE_RADIAN return NzDegreeToRadian(degrees); #else return degrees; #endif } template<typename T> constexpr T NzFromRadians(T radians) { #if NAZARA_MATH_ANGLE_RADIAN return radians; #else return NzRadianToDegree(radians); #endif } inline unsigned int NzGetNearestPowerOfTwo(unsigned int number) { ///TODO: Marquer comme constexpr en C++14 unsigned int x = 1; // Tant que x est plus petit que n, on décale ses bits vers la gauche, ce qui revient à multiplier par deux while (x <= number) x <<= 1; return x; } inline unsigned int NzGetNumberLength(signed char number) { ///TODO: Marquer comme constexpr en C++14 // Le standard définit le char comme étant codé sur un octet static_assert(sizeof(number) == 1, "Signed char must be one byte-sized"); if (number >= 100) return 3; else if (number >= 10) return 2; else if (number >= 0) return 1; else if (number > -10) return 2; else if (number > -100) return 3; else return 4; } inline unsigned int NzGetNumberLength(unsigned char number) { ///TODO: Marquer comme constexpr en C++14 // Le standard définit le char comme étant codé sur un octet static_assert(sizeof(number) == 1, "Unsigned char must be one byte-sized"); if (number >= 100) return 3; else if (number >= 10) return 2; else return 1; } inline unsigned int NzGetNumberLength(int number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(std::abs(number)))+(number < 0 ? 2 : 1); } inline unsigned int NzGetNumberLength(unsigned int number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(number))+1; } inline unsigned int NzGetNumberLength(long long number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(std::abs(number)))+(number < 0 ? 2 : 1); } inline unsigned int NzGetNumberLength(unsigned long long number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(number))+1; } inline unsigned int NzGetNumberLength(float number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzGetNumberLength(double number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzGetNumberLength(long double number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzIntegralPow(unsigned int base, unsigned int exponent) { ///TODO: Marquer comme constexpr en C++14 unsigned int r = 1; for (unsigned int i = 0; i < exponent; ++i) r *= base; return r; } template<typename T, typename T2> T NzLerp(T from, T to, T2 interpolation) { #ifdef NAZARA_DEBUG if (interpolation < F2(0.0) || interpolation > F2(1.0)) NazaraWarning("Interpolation should be in range [0..1] (Got " + NzString::Number(interpolation) + ')'); #endif return from + interpolation*(to - from); } template<typename T> T NzMultiplyAdd(T x, T y, T z) { return x*y + z; } #ifdef FP_FAST_FMAF template<> inline float NzMultiplyAdd(float x, float y, float z) { return std::fmaf(x, y, z); } #endif #ifdef FP_FAST_FMA template<> inline double NzMultiplyAdd(double x, double y, double z) { return std::fma(x, y, z); } #endif #ifdef FP_FAST_FMAL template<> inline long double NzMultiplyAdd(long double x, long double y, long double z) { return std::fmal(x, y, z); } #endif template<typename T> T NzNormalizeAngle(T angle) { #if NAZARA_MATH_ANGLE_RADIAN const T limit = F(M_PI); #else const T limit = F(180.0); #endif const T twoLimit = limit*F(2.0); angle = std::fmod(angle + limit, twoLimit); if (angle < F(0.0)) angle += twoLimit; return angle - limit; } template<typename T> bool NzNumberEquals(T a, T b, T maxDifference) { T diff = a - b; if (diff < F(0.0)) diff = -diff; return diff <= maxDifference; } inline NzString NzNumberToString(long long number, nzUInt8 radix) { #if NAZARA_MATH_SAFE if (radix < 2 || radix > 36) { NazaraError("Base must be between 2 and 36"); return NzString(); } #endif if (number == 0) return NzString('0'); static const char* symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; bool negative; if (number < 0) { negative = true; number = -number; } else negative = false; NzString str; str.Reserve(NzGetNumberLength(number)); // Prends en compte le signe négatif do { str += symbols[number % radix]; number /= radix; } while (number > 0); if (negative) str += '-'; return str.Reversed(); } template<typename T> T NzRadianToDegree(T radians) { return radians * F(180.0/M_PI); } inline long long NzStringToNumber(NzString str, nzUInt8 radix, bool* ok) { #if NAZARA_MATH_SAFE if (radix < 2 || radix > 36) { NazaraError("Radix must be between 2 and 36"); if (ok) *ok = false; return 0; } #endif static const char* symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; str.Simplify(); if (radix > 10) str = str.ToUpper(); bool negative = str.StartsWith('-'); char* digit = &str[(negative) ? 1 : 0]; unsigned long long total = 0; do { if (*digit == ' ') continue; total *= radix; const char* c = std::strchr(symbols, *digit); if (c && c-symbols < radix) total += c-symbols; else { if (ok) *ok = false; return 0; } } while (*++digit); if (ok) *ok = true; return (negative) ? -static_cast<long long>(total) : total; } template<typename T> constexpr T NzToDegrees(T angle) { #if NAZARA_MATH_ANGLE_RADIAN return NzRadianToDegree(angle); #else return angle; #endif } template<typename T> constexpr T NzToRadians(T angle) { #if NAZARA_MATH_ANGLE_RADIAN return angle; #else return NzDegreeToRadian(angle); #endif } #undef F2 #undef F #include <Nazara/Core/DebugOff.hpp> <commit_msg>Fixed GetNearestPowerOfTwo function<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Error.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Math/Config.hpp> #include <algorithm> #include <cstring> #include <Nazara/Core/Debug.hpp> #define F(a) static_cast<T>(a) #define F2(a) static_cast<T2>(a) template<typename T> T NzApproach(T value, T objective, T increment) { ///TODO: Marquer comme constexpr en C++14 if (value < objective) return std::min(value + increment, objective); else if (value > objective) return std::max(value - increment, objective); else return value; } template<typename T> constexpr T NzClamp(T value, T min, T max) { return std::max(std::min(value, max), min); } template<typename T> constexpr T NzDegreeToRadian(T degrees) { return degrees * F(M_PI/180.0); } template<typename T> constexpr T NzFromDegrees(T degrees) { #if NAZARA_MATH_ANGLE_RADIAN return NzDegreeToRadian(degrees); #else return degrees; #endif } template<typename T> constexpr T NzFromRadians(T radians) { #if NAZARA_MATH_ANGLE_RADIAN return radians; #else return NzRadianToDegree(radians); #endif } inline unsigned int NzGetNearestPowerOfTwo(unsigned int number) { ///TODO: Marquer comme constexpr en C++14 unsigned int x = 1; // Tant que x est plus petit que n, on décale ses bits vers la gauche, ce qui revient à multiplier par deux while (x < number) x <<= 1; return x; } inline unsigned int NzGetNumberLength(signed char number) { ///TODO: Marquer comme constexpr en C++14 // Le standard définit le char comme étant codé sur un octet static_assert(sizeof(number) == 1, "Signed char must be one byte-sized"); if (number >= 100) return 3; else if (number >= 10) return 2; else if (number >= 0) return 1; else if (number > -10) return 2; else if (number > -100) return 3; else return 4; } inline unsigned int NzGetNumberLength(unsigned char number) { ///TODO: Marquer comme constexpr en C++14 // Le standard définit le char comme étant codé sur un octet static_assert(sizeof(number) == 1, "Unsigned char must be one byte-sized"); if (number >= 100) return 3; else if (number >= 10) return 2; else return 1; } inline unsigned int NzGetNumberLength(int number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(std::abs(number)))+(number < 0 ? 2 : 1); } inline unsigned int NzGetNumberLength(unsigned int number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(number))+1; } inline unsigned int NzGetNumberLength(long long number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(std::abs(number)))+(number < 0 ? 2 : 1); } inline unsigned int NzGetNumberLength(unsigned long long number) { if (number == 0) return 1; return static_cast<unsigned int>(std::log10(number))+1; } inline unsigned int NzGetNumberLength(float number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzGetNumberLength(double number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzGetNumberLength(long double number, nzUInt8 precision) { // L'imprécision des flottants nécessite un cast (log10(9.99999) = 0.99999) return NzGetNumberLength(static_cast<long long>(number)) + precision + 1; // Plus un pour le point } inline unsigned int NzIntegralPow(unsigned int base, unsigned int exponent) { ///TODO: Marquer comme constexpr en C++14 unsigned int r = 1; for (unsigned int i = 0; i < exponent; ++i) r *= base; return r; } template<typename T, typename T2> T NzLerp(T from, T to, T2 interpolation) { #ifdef NAZARA_DEBUG if (interpolation < F2(0.0) || interpolation > F2(1.0)) NazaraWarning("Interpolation should be in range [0..1] (Got " + NzString::Number(interpolation) + ')'); #endif return from + interpolation*(to - from); } template<typename T> T NzMultiplyAdd(T x, T y, T z) { return x*y + z; } #ifdef FP_FAST_FMAF template<> inline float NzMultiplyAdd(float x, float y, float z) { return std::fmaf(x, y, z); } #endif #ifdef FP_FAST_FMA template<> inline double NzMultiplyAdd(double x, double y, double z) { return std::fma(x, y, z); } #endif #ifdef FP_FAST_FMAL template<> inline long double NzMultiplyAdd(long double x, long double y, long double z) { return std::fmal(x, y, z); } #endif template<typename T> T NzNormalizeAngle(T angle) { #if NAZARA_MATH_ANGLE_RADIAN const T limit = F(M_PI); #else const T limit = F(180.0); #endif const T twoLimit = limit*F(2.0); angle = std::fmod(angle + limit, twoLimit); if (angle < F(0.0)) angle += twoLimit; return angle - limit; } template<typename T> bool NzNumberEquals(T a, T b, T maxDifference) { T diff = a - b; if (diff < F(0.0)) diff = -diff; return diff <= maxDifference; } inline NzString NzNumberToString(long long number, nzUInt8 radix) { #if NAZARA_MATH_SAFE if (radix < 2 || radix > 36) { NazaraError("Base must be between 2 and 36"); return NzString(); } #endif if (number == 0) return NzString('0'); static const char* symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; bool negative; if (number < 0) { negative = true; number = -number; } else negative = false; NzString str; str.Reserve(NzGetNumberLength(number)); // Prends en compte le signe négatif do { str += symbols[number % radix]; number /= radix; } while (number > 0); if (negative) str += '-'; return str.Reversed(); } template<typename T> T NzRadianToDegree(T radians) { return radians * F(180.0/M_PI); } inline long long NzStringToNumber(NzString str, nzUInt8 radix, bool* ok) { #if NAZARA_MATH_SAFE if (radix < 2 || radix > 36) { NazaraError("Radix must be between 2 and 36"); if (ok) *ok = false; return 0; } #endif static const char* symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; str.Simplify(); if (radix > 10) str = str.ToUpper(); bool negative = str.StartsWith('-'); char* digit = &str[(negative) ? 1 : 0]; unsigned long long total = 0; do { if (*digit == ' ') continue; total *= radix; const char* c = std::strchr(symbols, *digit); if (c && c-symbols < radix) total += c-symbols; else { if (ok) *ok = false; return 0; } } while (*++digit); if (ok) *ok = true; return (negative) ? -static_cast<long long>(total) : total; } template<typename T> constexpr T NzToDegrees(T angle) { #if NAZARA_MATH_ANGLE_RADIAN return NzRadianToDegree(angle); #else return angle; #endif } template<typename T> constexpr T NzToRadians(T angle) { #if NAZARA_MATH_ANGLE_RADIAN return angle; #else return NzDegreeToRadian(angle); #endif } #undef F2 #undef F #include <Nazara/Core/DebugOff.hpp> <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error Please #include <abaclade.hxx> instead of this file #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::detail::thread_local_storage namespace abc { namespace detail { // Forward declaration. class thread_local_var_impl; //! Abaclade’s TLS slot data manager. /* TODO: this will need changes to support dynamic loading and unloading of libraries that depend on Abaclade. The m_pb byte array should be replaced with a map from library address/name to library-specific TLS, and each library would have its own byte array (keyed in the same way). Loading a new library would add a new element in the maps (and in the TLS block for each existing thread), and unloading it would remove the library from all maps (and in the TLS block for each thread). */ class ABACLADE_SYM thread_local_storage : public noncopyable { public: /*! Adds the specified size to the storage and assigns the corresponding offset within to the specified thread_local_var_impl instance; it also initializes the m_ptlviNext and m_ibTlsOffset members of the latter. This function will be called during initialization of a new dynamic library as it’s being loaded, not during normal run-time. ptlvi Pointer to the new variable to assign storage to. cb Requested storage size. */ static void add_var(thread_local_var_impl * ptlvi, std::size_t cb); #if ABC_HOST_API_WIN32 /*! Hook invoked by DllMain() in abaclade.dll. iReason Reason why DllMain() was invoked; one of DLL_{PROCESS,THREAD}_{ATTACH,DETACH}. */ static bool dllmain_hook(unsigned iReason); #endif /*! Returns a pointer to the specified offset in the storage. On the first call from a new thread, this also lazily creates the thread_local_storage, unless bCreateNewIfNull is false. bCreateNewIfNull If the TLS slot is nullptr and bCreateNewIfNull is true, a new new TLS instance will be created; if bCreateNewIfNull is false, nullptr will be returned instead if the TLS slot is uninitialized. return Pointer to the data store. */ static thread_local_storage * get(bool bCreateNewIfNull = true); /*! Returns a pointer to the specified offset in the thread-local data store. ibOffset Desired offset. return Corresponding pointer. */ void * get_storage(std::size_t ibOffset) const { return &m_pb[ibOffset]; } private: //! Constructor. thread_local_storage(); //! Destructor. ~thread_local_storage(); //! Allocates the TLS slot for the process. static void alloc_slot(); #if ABC_HOST_API_POSIX /*! Destructs the storage instance for the current thread. Invoked by pthread_key_create() when a thread terminates. pThis Pointer to the TLS for the current thread. */ static void destruct(void * pThis = get()); #endif //! Deallocates the TLS slot for the process. // TODO: call free_slot() in the POSIX Threads case using reference counting in destruct(). static void free_slot(); private: //! Raw byte storage. std::unique_ptr<std::int8_t[]> m_pb; //! OS-defined TLS key. #if ABC_HOST_API_POSIX static pthread_key_t sm_pthkey; #elif ABC_HOST_API_WIN32 static DWORD sm_iTls; #endif #if ABC_HOST_API_POSIX //! One-time initializer for sm_pthkey. static pthread_once_t sm_pthonce; #endif //! Pointer to the first thread_local_var_impl instance. static thread_local_var_impl const * sm_ptlviHead; //! Cumulative storage size registered with calls to add_var(). static std::size_t sm_cb; }; } //namespace detail } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::detail::thread_local_var_impl namespace abc { namespace detail { //! Non-template implementation of abc::thread_local_value and abc::thread_local_ptr. class ABACLADE_SYM thread_local_var_impl : public noncopyable { private: friend class thread_local_storage; protected: /*! Constructor. cbObject Size of the object pointed to by the thread_local_value/thread_local_ptr subclass. */ thread_local_var_impl(std::size_t cbObject); /*! Constructs the thread-local value for a new thread. Invoked at most once for each thread. p Pointer to the memory block where the new value should be constructed. */ virtual void construct(void * p) const = 0; /*! Destructs the thread-local value for a terminating thread. Invoked at most once for each thread. p Pointer to the value to be destructed. */ virtual void destruct(void * p) const = 0; /*! Returns a pointer to the current thread’s copy of the variable. return Pointer to the thread-local value for this object. */ template <typename T> T * get_ptr() const { return static_cast<T *>(thread_local_storage::get()->get_storage(m_ibTlsOffset)); } private: //! Pointer to the next thread_local_var_impl instance. thread_local_var_impl const * m_ptlviNext; //! Offset of this variable in the TLS block. std::size_t m_ibTlsOffset; }; } //namespace detail } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::thread_local_value namespace abc { /*! Variable with separate per-thread values. Variables of this type cannot be non-static class members. */ template <typename T> class thread_local_value : private detail::thread_local_var_impl { public: /*! Constructor. tDefault Value that will be copied to initialize the TLS for each thread. */ thread_local_value(T tDefault = T()) : detail::thread_local_var_impl(sizeof(T)), mc_tDefault(std::move(tDefault)) { } /*! Assignment operator. t Source object. return *this. */ thread_local_value & operator=(T t) { get() = std::move(t); return *this; } /*! Implicit cast to T &. return Reference to the object’s value. */ operator T &() { return get(); } operator T const &() const { return get(); } private: //! See detail::thread_local_var_impl::construct(). virtual void construct(void * p) const override { new(p) T(mc_tDefault); } //! See detail::thread_local_var_impl::destruct(). virtual void destruct(void * p) const override { static_cast<T *>(p)->~T(); } /*! Returns a reference to the thread-local copy of the value. return Reference to the value. */ T & get() const { return *get_ptr<T>(); } private: //! Default value for each per-thread copy of the value. T const mc_tDefault; }; } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::thread_local_ptr namespace abc { /*! Thread-local pointer to an object. The memory this points to is permanently allocated for each thread, and an instance of this class lets each thread access its own private copy of the value pointed to by it. Variables of this type cannot be non-static class members. */ template <typename T> class thread_local_ptr : private detail::thread_local_var_impl, public support_explicit_operator_bool<thread_local_ptr<T>> { private: //! Contains a T and a bool to track whether the T has been constructed. struct value_t { std::int8_t t[sizeof(T)]; bool bConstructed; }; public: //! Constructor. thread_local_ptr() : detail::thread_local_var_impl(sizeof(value_t)) { } /*! Dereference operator. return Reference to the owned object. */ T & operator*() const { return *get(); } /*! Dereferencing member access operator. return Pointer to the owned object. */ T * operator->() const { return get(); } /*! Boolean evaluation operator. return true if get() != nullptr, or false otherwise. */ explicit_operator_bool() const { return get_ptr<value_t>()->bConstructed; } /*! Returns the address of the thread-local value this object points to. return Internal pointer. */ T * get() const { value_t * pValue = get_ptr<value_t>(); return pValue->bConstructed ? reinterpret_cast<T *>(&pValue->t) : nullptr; } /*! Deletes the object currently pointed to, if any, resetting the pointer to nullptr. pt Pointer to a new object to take ownership of. */ void reset() { destruct(get_ptr<value_t>()); } /*! Destructs the object currently pointed to, if any, and constructs a new object. tSrc Source object to be move-construct the new object from. */ void reset_new() { T tNew; reset(); value_t * pValue = get_ptr<value_t>(); new(&pValue->t) T(std::move(tNew)); pValue->bConstructed = true; } void reset_new(T tSrc) { reset(); value_t * pValue = get_ptr<value_t>(); new(&pValue->t) T(std::move(tSrc)); pValue->bConstructed = true; } private: //! See detail::thread_local_var_impl::construct(). virtual void construct(void * p) const override { value_t * pValue = new(p) value_t; pValue->bConstructed = false; } //! See detail::thread_local_var_impl::destruct(). virtual void destruct(void * p) const override { value_t * pValue = static_cast<value_t *>(p); if (pValue->bConstructed) { reinterpret_cast<T *>(&pValue->t)->~T(); pValue->bConstructed = false; } } }; } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Make abc::thread_local_ptr::destruct() symmetrical with construct()<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error Please #include <abaclade.hxx> instead of this file #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::detail::thread_local_storage namespace abc { namespace detail { // Forward declaration. class thread_local_var_impl; //! Abaclade’s TLS slot data manager. /* TODO: this will need changes to support dynamic loading and unloading of libraries that depend on Abaclade. The m_pb byte array should be replaced with a map from library address/name to library-specific TLS, and each library would have its own byte array (keyed in the same way). Loading a new library would add a new element in the maps (and in the TLS block for each existing thread), and unloading it would remove the library from all maps (and in the TLS block for each thread). */ class ABACLADE_SYM thread_local_storage : public noncopyable { public: /*! Adds the specified size to the storage and assigns the corresponding offset within to the specified thread_local_var_impl instance; it also initializes the m_ptlviNext and m_ibTlsOffset members of the latter. This function will be called during initialization of a new dynamic library as it’s being loaded, not during normal run-time. ptlvi Pointer to the new variable to assign storage to. cb Requested storage size. */ static void add_var(thread_local_var_impl * ptlvi, std::size_t cb); #if ABC_HOST_API_WIN32 /*! Hook invoked by DllMain() in abaclade.dll. iReason Reason why DllMain() was invoked; one of DLL_{PROCESS,THREAD}_{ATTACH,DETACH}. */ static bool dllmain_hook(unsigned iReason); #endif /*! Returns a pointer to the specified offset in the storage. On the first call from a new thread, this also lazily creates the thread_local_storage, unless bCreateNewIfNull is false. bCreateNewIfNull If the TLS slot is nullptr and bCreateNewIfNull is true, a new new TLS instance will be created; if bCreateNewIfNull is false, nullptr will be returned instead if the TLS slot is uninitialized. return Pointer to the data store. */ static thread_local_storage * get(bool bCreateNewIfNull = true); /*! Returns a pointer to the specified offset in the thread-local data store. ibOffset Desired offset. return Corresponding pointer. */ void * get_storage(std::size_t ibOffset) const { return &m_pb[ibOffset]; } private: //! Constructor. thread_local_storage(); //! Destructor. ~thread_local_storage(); //! Allocates the TLS slot for the process. static void alloc_slot(); #if ABC_HOST_API_POSIX /*! Destructs the storage instance for the current thread. Invoked by pthread_key_create() when a thread terminates. pThis Pointer to the TLS for the current thread. */ static void destruct(void * pThis = get()); #endif //! Deallocates the TLS slot for the process. // TODO: call free_slot() in the POSIX Threads case using reference counting in destruct(). static void free_slot(); private: //! Raw byte storage. std::unique_ptr<std::int8_t[]> m_pb; //! OS-defined TLS key. #if ABC_HOST_API_POSIX static pthread_key_t sm_pthkey; #elif ABC_HOST_API_WIN32 static DWORD sm_iTls; #endif #if ABC_HOST_API_POSIX //! One-time initializer for sm_pthkey. static pthread_once_t sm_pthonce; #endif //! Pointer to the first thread_local_var_impl instance. static thread_local_var_impl const * sm_ptlviHead; //! Cumulative storage size registered with calls to add_var(). static std::size_t sm_cb; }; } //namespace detail } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::detail::thread_local_var_impl namespace abc { namespace detail { //! Non-template implementation of abc::thread_local_value and abc::thread_local_ptr. class ABACLADE_SYM thread_local_var_impl : public noncopyable { private: friend class thread_local_storage; protected: /*! Constructor. cbObject Size of the object pointed to by the thread_local_value/thread_local_ptr subclass. */ thread_local_var_impl(std::size_t cbObject); /*! Constructs the thread-local value for a new thread. Invoked at most once for each thread. p Pointer to the memory block where the new value should be constructed. */ virtual void construct(void * p) const = 0; /*! Destructs the thread-local value for a terminating thread. Invoked at most once for each thread. p Pointer to the value to be destructed. */ virtual void destruct(void * p) const = 0; /*! Returns a pointer to the current thread’s copy of the variable. return Pointer to the thread-local value for this object. */ template <typename T> T * get_ptr() const { return static_cast<T *>(thread_local_storage::get()->get_storage(m_ibTlsOffset)); } private: //! Pointer to the next thread_local_var_impl instance. thread_local_var_impl const * m_ptlviNext; //! Offset of this variable in the TLS block. std::size_t m_ibTlsOffset; }; } //namespace detail } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::thread_local_value namespace abc { /*! Variable with separate per-thread values. Variables of this type cannot be non-static class members. */ template <typename T> class thread_local_value : private detail::thread_local_var_impl { public: /*! Constructor. tDefault Value that will be copied to initialize the TLS for each thread. */ thread_local_value(T tDefault = T()) : detail::thread_local_var_impl(sizeof(T)), mc_tDefault(std::move(tDefault)) { } /*! Assignment operator. t Source object. return *this. */ thread_local_value & operator=(T t) { get() = std::move(t); return *this; } /*! Implicit cast to T &. return Reference to the object’s value. */ operator T &() { return get(); } operator T const &() const { return get(); } private: //! See detail::thread_local_var_impl::construct(). virtual void construct(void * p) const override { new(p) T(mc_tDefault); } //! See detail::thread_local_var_impl::destruct(). virtual void destruct(void * p) const override { static_cast<T *>(p)->~T(); } /*! Returns a reference to the thread-local copy of the value. return Reference to the value. */ T & get() const { return *get_ptr<T>(); } private: //! Default value for each per-thread copy of the value. T const mc_tDefault; }; } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::thread_local_ptr namespace abc { /*! Thread-local pointer to an object. The memory this points to is permanently allocated for each thread, and an instance of this class lets each thread access its own private copy of the value pointed to by it. Variables of this type cannot be non-static class members. */ template <typename T> class thread_local_ptr : private detail::thread_local_var_impl, public support_explicit_operator_bool<thread_local_ptr<T>> { private: //! Contains a T and a bool to track whether the T has been constructed. struct value_t { std::int8_t t[sizeof(T)]; bool bConstructed; }; public: //! Constructor. thread_local_ptr() : detail::thread_local_var_impl(sizeof(value_t)) { } /*! Dereference operator. return Reference to the owned object. */ T & operator*() const { return *get(); } /*! Dereferencing member access operator. return Pointer to the owned object. */ T * operator->() const { return get(); } /*! Boolean evaluation operator. return true if get() != nullptr, or false otherwise. */ explicit_operator_bool() const { return get_ptr<value_t>()->bConstructed; } /*! Returns the address of the thread-local value this object points to. return Internal pointer. */ T * get() const { value_t * pValue = get_ptr<value_t>(); return pValue->bConstructed ? reinterpret_cast<T *>(&pValue->t) : nullptr; } /*! Deletes the object currently pointed to, if any, resetting the pointer to nullptr. pt Pointer to a new object to take ownership of. */ void reset() { value_t * pValue = get_ptr<value_t>(); if (pValue->bConstructed) { reinterpret_cast<T *>(&pValue->t)->~T(); pValue->bConstructed = false; } } /*! Destructs the object currently pointed to, if any, and constructs a new object. tSrc Source object to be move-construct the new object from. */ void reset_new() { T tNew; reset(); value_t * pValue = get_ptr<value_t>(); new(&pValue->t) T(std::move(tNew)); pValue->bConstructed = true; } void reset_new(T tSrc) { reset(); value_t * pValue = get_ptr<value_t>(); new(&pValue->t) T(std::move(tSrc)); pValue->bConstructed = true; } private: //! See detail::thread_local_var_impl::construct(). virtual void construct(void * p) const override { value_t * pValue = new(p) value_t; pValue->bConstructed = false; } //! See detail::thread_local_var_impl::destruct(). virtual void destruct(void * p) const override { value_t * pValue = static_cast<value_t *>(p); if (pValue->bConstructed) { reinterpret_cast<T *>(&pValue->t)->~T(); } // This is technically a no-op, but keeps destruct() symmetric with construct(). pValue->~value_t(); } }; } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#pragma once #include <baka/io/io_error.hpp> #include <cstddef> #include <stdexcept> #include <vector> namespace baka { namespace io { class memory_stream { public: memory_stream() : offset(0) { } char const* write(char const* begin, char const* end) { while (begin != end) { if (data.size() == offset) { data.push_back(*begin); } else { data[offset] = *begin; } ++offset; ++begin; } return end; } char* read(char* begin, char* end) { if (offset == data.size()) { throw eof_error("eof"); } while (begin != end) { if (data.size() == offset) { return begin; } *begin = data[offset]; ++offset; ++begin; } return end; } void seek_begin(std::size_t offset_) { if (offset_ > data.size()) { throw std::runtime_error("bad seek"); } offset = offset_; } private: std::vector<char> data; std::size_t offset; }; } } <commit_msg>Implement tell<commit_after>#pragma once #include <baka/io/io_error.hpp> #include <cstddef> #include <stdexcept> #include <vector> namespace baka { namespace io { class memory_stream { public: memory_stream() : offset(0) { } char const* write(char const* begin, char const* end) { while (begin != end) { if (data.size() == offset) { data.push_back(*begin); } else { data[offset] = *begin; } ++offset; ++begin; } return end; } char* read(char* begin, char* end) { if (offset == data.size()) { throw eof_error("eof"); } while (begin != end) { if (data.size() == offset) { return begin; } *begin = data[offset]; ++offset; ++begin; } return end; } void seek_begin(std::size_t offset_) { if (offset_ > data.size()) { throw std::runtime_error("bad seek"); } offset = offset_; } std::size_t tell() const { return offset; } private: std::vector<char> data; std::size_t offset; }; } } <|endoftext|>
<commit_before>#pragma once // ------------------------------------------------------------------------------ // CONSTANTS GLOBALS STATICS // ------------------------------------------------------------------------------ // NOTE: You must provide this in derived class. const string semanticVersion(); typedef enum { // assert( HM_COUNT == 5 ); HM_FIRST = 0, HM_GET = HM_FIRST, HM_PUT , HM_POST , HM_DELETE , HM_PATCH , HM_COUNT } HTML_METHOD; typedef enum { // assert( HW_COUNT == 5 ); HW_FIRST = 0, HW_LINE_BEGIN = HW_FIRST, HW_LINE_END , HW_METHOD , HW_PATH , HW_PARAM , HW_COUNT } HTML_WRAPPERS_INDEX; // This default set of API wrappers works well with bootstrap. // Provide your own as needed, to present your API in any desired style. // You can use the following variables and a substitution will be done: __API_url__, __API_method__, __API_token__ // assert( HW_COUNT == 5 ); const vector<string> c_default_wrappers = { "<form class=\"api-form\" method=\"__API_method__\" action=\"__API_url__\"><div class=\"form-inline\">", // HW_LINE_BEGIN "</div></form>", // HW_LINE_END "<button type=\"submit\" class=\"btn btn-__API_method__\">__API_method__</button><div class=\"form-group\">", // HW_METHOD "<label>__API_token__</label>", // HW_PATH " <input type=\"text\" name=\"__API_token__\" class=\"form-control\" placeholder=\"__API_token__\"/> " // HW_PARAM }; // ------------------------------------------------------------------------------ // API_call // This class wraps everything that defines a RESTful API call. It has tons of helpers to manage the call, too. class API_call { public: API_call( HTML_METHOD method, vector<string> path_tokens, vector<string> types, map<const string,string> url_params = map<const string,string>(), bool b_url_params_are_mandatory = true, bool b_has_static_html = true ) : method_(method), path_tokens_(path_tokens), types_(types), url_params_(url_params), b_url_params_are_mandatory_(b_url_params_are_mandatory), b_has_static_html_(b_has_static_html) {} // This is used to create keys etc, but never for full API call objects. API_call() {} // Call handlers should follow this pattern: // // 1) on startup, read a static html skeleton into memory. // 2) on call, gather dynamic data and inject into the pre-loaded static html // // This base class can do (1) for you in this function. // It creates a set of static html that mirrors the API structure and the base will read from them. // This also allows us to browse the static html directly, essential when working on the html/css/js skeleton. inline bool load_static_html(); string url() const { string url; for (auto& token : path_tokens_) { url += "/"; url += token; } return url; } string regex() const { // result regex eg: // source /v1/car/:id/:brand/pic.png // regex "^/#semver#/car/[0-9].*/[s]/pic.png" string regex("^"); for (auto& token: path_tokens_) { regex += string("/"); if (token[0] == ':') { // Special meanings: // /:int/ only numerals // /:double/ only numerals and [.] // default any alphanumeric BUT NOTHING ELSE (eg SLASH :-) ). // Reommended to use /:string/ for consistency string id = token.substr(1,token.length()-1); if (strings_are_equal(id,"int")) regex += "[[:digit:]]*"; else if (strings_are_equal(id,"double")) regex += "[[:digit:].]*"; else regex += "[[:alnum:].]*"; } else if (token == "v1") { // This is our placeholder for the semver, replace it. regex += semanticVersion(); } else { regex += token; } } regex += string("[.]("); bool bFirst = true; for (auto& type: types_) { if (bFirst) { bFirst = false; } else { regex += "|"; } regex += type; } regex += ")"; return regex; } string method() const { switch (method_) { case HM_GET : return "GET" ; case HM_PUT : return "PUT" ; case HM_POST : return "POST" ; case HM_DELETE : return "DELETE" ; case HM_PATCH : return "PATCH" ; default : return "Unsupported method"; } } void set_method(string m) { if (m == "GET" ) method_ = HM_GET ; else if (m == "PUT" ) method_ = HM_PUT ; else if (m == "POST" ) method_ = HM_POST ; else if (m == "DELETE" ) method_ = HM_DELETE ; else if (m == "PATCH" ) method_ = HM_PATCH ; else method_ = HM_COUNT ; } bool b_has_type(string search_type) const { for (auto& t : types_) if (strings_are_equal(t,search_type)) return true; return false; } // These test the *first* type, which should be set for valid API calls. bool b_no_type() const { return types_.empty(); } bool b_type(const string& test_type) const { return !b_no_type() && strings_are_equal(types_[0],test_type); } // Param helpers inline bool getUrlParam_int64( const string& key, // in int64_t& n_value // out ) { string value; if (!getUrlParam(key,value)) return false; try { n_value = boost::lexical_cast<int64_t>(value); } catch (...) { return false; } return true; } inline bool getUrlParam( const string& key, // in string& value // out ) { auto it = url_params_.find(key); if (it == url_params_.end()) return false; value = it->second; return true; } HTML_METHOD method_; vector<string> path_tokens_; vector<string> types_; map<const string,string> url_params_; bool b_url_params_are_mandatory_; bool b_has_static_html_; string static_html_; }; bool API_call::load_static_html() { if (types_.empty() || types_[0] != "html") return false; string filename = "htdocs"; // NOTE that we do NOT want the actual token here: [auto& token]. // We want to work with a copy. So here, we use [auto token]. // THIS IS AN EXCEPTION TO THE GENERAL RULE. Be C++11 smart, my friend. :-) for (auto token : path_tokens_) { assert(token.length() > 0); // REST api is documented with a leading colon for caller-provided id-type fields. // Remove these from the pathname. if (token[0] == ':') token = token.substr(1,token.length()-1); filename += string("/") + token; } filename += string(".") + types_[0]; try { static_html_ = read_file(filename); } catch (...) { log(LV_ERROR,string("Unable to load static html:") + filename); return false; } return true; } <commit_msg>Allow API calls that do not need supporting static html<commit_after>#pragma once // ------------------------------------------------------------------------------ // CONSTANTS GLOBALS STATICS // ------------------------------------------------------------------------------ // NOTE: You must provide this in derived class. const string semanticVersion(); typedef enum { // assert( HM_COUNT == 5 ); HM_FIRST = 0, HM_GET = HM_FIRST, HM_PUT , HM_POST , HM_DELETE , HM_PATCH , HM_COUNT } HTML_METHOD; typedef enum { // assert( HW_COUNT == 5 ); HW_FIRST = 0, HW_LINE_BEGIN = HW_FIRST, HW_LINE_END , HW_METHOD , HW_PATH , HW_PARAM , HW_COUNT } HTML_WRAPPERS_INDEX; // This default set of API wrappers works well with bootstrap. // Provide your own as needed, to present your API in any desired style. // You can use the following variables and a substitution will be done: __API_url__, __API_method__, __API_token__ // assert( HW_COUNT == 5 ); const vector<string> c_default_wrappers = { "<form class=\"api-form\" method=\"__API_method__\" action=\"__API_url__\"><div class=\"form-inline\">", // HW_LINE_BEGIN "</div></form>", // HW_LINE_END "<button type=\"submit\" class=\"btn btn-__API_method__\">__API_method__</button><div class=\"form-group\">", // HW_METHOD "<label>__API_token__</label>", // HW_PATH " <input type=\"text\" name=\"__API_token__\" class=\"form-control\" placeholder=\"__API_token__\"/> " // HW_PARAM }; // ------------------------------------------------------------------------------ // API_call // This class wraps everything that defines a RESTful API call. It has tons of helpers to manage the call, too. class API_call { public: API_call( HTML_METHOD method, vector<string> path_tokens, vector<string> types, map<const string,string> url_params = map<const string,string>(), bool b_url_params_are_mandatory = true, bool b_has_static_html = true ) : method_(method), path_tokens_(path_tokens), types_(types), url_params_(url_params), b_url_params_are_mandatory_(b_url_params_are_mandatory), b_has_static_html_(b_has_static_html) {} // This is used to create keys etc, but never for full API call objects. API_call() {} // Call handlers should follow this pattern: // // 1) on startup, read a static html skeleton into memory. // 2) on call, gather dynamic data and inject into the pre-loaded static html // // This base class can do (1) for you in this function. // It creates a set of static html that mirrors the API structure and the base will read from them. // This also allows us to browse the static html directly, essential when working on the html/css/js skeleton. inline bool load_static_html(); string url() const { string url; for (auto& token : path_tokens_) { url += "/"; url += token; } return url; } string regex() const { // result regex eg: // source /v1/car/:id/:brand/pic.png // regex "^/#semver#/car/[0-9].*/[s]/pic.png" string regex("^"); for (auto& token: path_tokens_) { regex += string("/"); if (token[0] == ':') { // Special meanings: // /:int/ only numerals // /:double/ only numerals and [.] // default any alphanumeric BUT NOTHING ELSE (eg SLASH :-) ). // Reommended to use /:string/ for consistency string id = token.substr(1,token.length()-1); if (strings_are_equal(id,"int")) regex += "[[:digit:]]*"; else if (strings_are_equal(id,"double")) regex += "[[:digit:].]*"; else regex += "[[:alnum:].]*"; } else if (token == "v1") { // This is our placeholder for the semver, replace it. regex += semanticVersion(); } else { regex += token; } } regex += string("[.]("); bool bFirst = true; for (auto& type: types_) { if (bFirst) { bFirst = false; } else { regex += "|"; } regex += type; } regex += ")"; return regex; } string method() const { switch (method_) { case HM_GET : return "GET" ; case HM_PUT : return "PUT" ; case HM_POST : return "POST" ; case HM_DELETE : return "DELETE" ; case HM_PATCH : return "PATCH" ; default : return "Unsupported method"; } } void set_method(string m) { if (m == "GET" ) method_ = HM_GET ; else if (m == "PUT" ) method_ = HM_PUT ; else if (m == "POST" ) method_ = HM_POST ; else if (m == "DELETE" ) method_ = HM_DELETE ; else if (m == "PATCH" ) method_ = HM_PATCH ; else method_ = HM_COUNT ; } bool b_has_type(string search_type) const { for (auto& t : types_) if (strings_are_equal(t,search_type)) return true; return false; } // These test the *first* type, which should be set for valid API calls. bool b_no_type() const { return types_.empty(); } bool b_type(const string& test_type) const { return !b_no_type() && strings_are_equal(types_[0],test_type); } // Param helpers inline bool getUrlParam_int64( const string& key, // in int64_t& n_value // out ) { string value; if (!getUrlParam(key,value)) return false; try { n_value = boost::lexical_cast<int64_t>(value); } catch (...) { return false; } return true; } inline bool getUrlParam( const string& key, // in string& value // out ) { auto it = url_params_.find(key); if (it == url_params_.end()) return false; value = it->second; return true; } HTML_METHOD method_; vector<string> path_tokens_; vector<string> types_; map<const string,string> url_params_; bool b_url_params_are_mandatory_; bool b_has_static_html_; string static_html_; }; bool API_call::load_static_html() { if (!b_has_static_html_) return false; if (types_.empty() || types_[0] != "html") return false; string filename = "htdocs"; // NOTE that we do NOT want the actual token here: [auto& token]. // We want to work with a copy. So here, we use [auto token]. // THIS IS AN EXCEPTION TO THE GENERAL RULE. Be C++11 smart, my friend. :-) for (auto token : path_tokens_) { assert(token.length() > 0); // REST api is documented with a leading colon for caller-provided id-type fields. // Remove these from the pathname. if (token[0] == ':') token = token.substr(1,token.length()-1); filename += string("/") + token; } filename += string(".") + types_[0]; try { static_html_ = read_file(filename); } catch (...) { log(LV_ERROR,string("Unable to load static html:") + filename); return false; } return true; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #include "../include/librealsense2/hpp/rs_sensor.hpp" #include "../include/librealsense2/hpp/rs_processing.hpp" #include "proc/synthetic-stream.h" #include "context.h" #include "environment.h" #include "option.h" #include "colorizer.h" #include "disparity-transform.h" namespace librealsense { static color_map hue{ { { 255, 0, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 255, 255 }, { 0, 0, 255 }, { 255, 0, 255 }, { 255, 0, 0 }, } }; static color_map jet{ { { 0, 0, 255 }, { 0, 255, 255 }, { 255, 255, 0 }, { 255, 0, 0 }, { 50, 0, 0 }, } }; static color_map classic{ { { 30, 77, 203 }, { 25, 60, 192 }, { 45, 117, 220 }, { 204, 108, 191 }, { 196, 57, 178 }, { 198, 33, 24 }, } }; static color_map grayscale{ { { 255, 255, 255 }, { 0, 0, 0 }, } }; static color_map inv_grayscale{ { { 0, 0, 0 }, { 255, 255, 255 }, } }; static color_map biomes{ { { 0, 0, 204 }, { 204, 230, 255 }, { 255, 255, 153 }, { 170, 255, 128 }, { 0, 153, 0 }, { 230, 242, 255 }, } }; static color_map cold{ { { 230, 247, 255 }, { 0, 92, 230 }, { 0, 179, 179 }, { 0, 51, 153 }, { 0, 5, 15 } } }; static color_map warm{ { { 255, 255, 230 }, { 255, 204, 0 }, { 255, 136, 77 }, { 255, 51, 0 }, { 128, 0, 0 }, { 10, 0, 0 } } }; static color_map quantized{ { { 255, 255, 255 }, { 0, 0, 0 }, }, 6 }; static color_map pattern{ { { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, } }; colorizer::colorizer() : colorizer("Depth Visualization") {} colorizer::colorizer(const char* name) : stream_filter_processing_block(name), _min(0.f), _max(6.f), _equalize(true), _target_stream_profile(), _histogram() { _histogram = std::vector<int>(MAX_DEPTH, 0); _hist_data = _histogram.data(); _stream_filter.stream = RS2_STREAM_DEPTH; _stream_filter.format = RS2_FORMAT_Z16; _maps = { &jet, &classic, &grayscale, &inv_grayscale, &biomes, &cold, &warm, &quantized, &pattern, &hue }; auto min_opt = std::make_shared<ptr_option<float>>(0.f, 16.f, 0.1f, 0.f, &_min, "Min range in meters"); auto max_opt = std::make_shared<ptr_option<float>>(0.f, 16.f, 0.1f, 6.f, &_max, "Max range in meters"); register_option(RS2_OPTION_MAX_DISTANCE, std::make_shared<max_distance_option>( max_opt, min_opt)); register_option(RS2_OPTION_MIN_DISTANCE, std::make_shared<min_distance_option>( min_opt, max_opt)); auto color_map = std::make_shared<ptr_option<int>>(0, (int)_maps.size() - 1, 1, 0, &_map_index, "Color map"); color_map->set_description(0.f, "Jet"); color_map->set_description(1.f, "Classic"); color_map->set_description(2.f, "White to Black"); color_map->set_description(3.f, "Black to White"); color_map->set_description(4.f, "Bio"); color_map->set_description(5.f, "Cold"); color_map->set_description(6.f, "Warm"); color_map->set_description(7.f, "Quantized"); color_map->set_description(8.f, "Pattern"); color_map->set_description(9.f, "Hue"); register_option(RS2_OPTION_COLOR_SCHEME, color_map); auto preset_opt = std::make_shared<ptr_option<int>>(0, 3, 1, 0, &_preset, "Preset depth colorization"); preset_opt->set_description(0.f, "Dynamic"); preset_opt->set_description(1.f, "Fixed"); preset_opt->set_description(2.f, "Near"); preset_opt->set_description(3.f, "Far"); preset_opt->on_set([this](float val) { if (fabs(val - 0.f) < 1e-6) { // Dynamic _equalize = true; _map_index = 0; } if (fabs(val - 1.f) < 1e-6) { // Fixed _equalize = false; _map_index = 0; _min = 0.f; _max = 6.f; } if (fabs(val - 2.f) < 1e-6) { // Near _equalize = false; _map_index = 1; _min = 0.3f; _max = 1.5f; } if (fabs(val - 3.f) < 1e-6) { // Far _equalize = false; _map_index = 0; _min = 1.f; _max = 16.f; } }); register_option(RS2_OPTION_VISUAL_PRESET, preset_opt); auto hist_opt = std::make_shared<ptr_option<bool>>(false, true, true, true, &_equalize, "Perform histogram equalization"); register_option(RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED, hist_opt); } bool colorizer::should_process(const rs2::frame& frame) { if (!frame || frame.is<rs2::frameset>()) return false; if (frame.get_profile().stream_type() != RS2_STREAM_DEPTH) return false; return true; } rs2::frame colorizer::process_frame(const rs2::frame_source& source, const rs2::frame& f) { if (f.get_profile().get() != _source_stream_profile.get()) { _source_stream_profile = f.get_profile(); _target_stream_profile = f.get_profile().clone(RS2_STREAM_DEPTH, f.get_profile().stream_index(), RS2_FORMAT_RGB8); auto info = disparity_info::update_info_from_frame(f); _depth_units = info.depth_units; _d2d_convert_factor = info.d2d_convert_factor; } auto make_equalized_histogram = [this](const rs2::video_frame& depth, rs2::video_frame rgb) { auto depth_format = depth.get_profile().format(); const auto w = depth.get_width(), h = depth.get_height(); auto rgb_data = reinterpret_cast<uint8_t*>(const_cast<void *>(rgb.get_data())); auto coloring_function = [&, this](float data) { auto hist_data = _hist_data[(int)data]; auto pixels = (float)_hist_data[MAX_DEPTH - 1]; return (hist_data / pixels); }; if (depth_format == RS2_FORMAT_DISPARITY32) { auto depth_data = reinterpret_cast<const float*>(depth.get_data()); update_histogram(_hist_data, depth_data, w, h); make_rgb_data<float>(depth_data, rgb_data, w, h, coloring_function); } else if (depth_format == RS2_FORMAT_Z16) { auto depth_data = reinterpret_cast<const uint16_t*>(depth.get_data()); update_histogram(_hist_data, depth_data, w, h); make_rgb_data<uint16_t>(depth_data, rgb_data, w, h, coloring_function); } }; auto make_value_cropped_frame = [this](const rs2::video_frame& depth, rs2::video_frame rgb) { auto depth_format = depth.get_profile().format(); const auto w = depth.get_width(), h = depth.get_height(); auto rgb_data = reinterpret_cast<uint8_t*>(const_cast<void *>(rgb.get_data())); if (depth_format == RS2_FORMAT_DISPARITY32) { auto depth_data = reinterpret_cast<const float*>(depth.get_data()); // convert from depth min max to disparity min max // note: max min value is inverted in disparity domain auto __min = _min; if (__min < 1e-6f) { __min = 1e-6f; } // Min value set to prevent zero division. only when _min is zero. auto max = (_d2d_convert_factor / (__min)) * _depth_units + .5f; auto min = (_d2d_convert_factor / (_max)) * _depth_units + .5f; auto coloring_function = [&, this](float data) { return (data - min) / (max - min); }; make_rgb_data<float>(depth_data, rgb_data, w, h, coloring_function); } else if (depth_format == RS2_FORMAT_Z16) { auto depth_data = reinterpret_cast<const uint16_t*>(depth.get_data()); auto min = _min; auto max = _max; auto coloring_function = [&, this](float data) { if (max == min) return data * _depth_units; return (data * _depth_units - min) / (max - min); }; make_rgb_data<uint16_t>(depth_data, rgb_data, w, h, coloring_function); } }; rs2::frame ret; auto vf = f.as<rs2::video_frame>(); ret = source.allocate_video_frame(_target_stream_profile, f, 3, vf.get_width(), vf.get_height(), vf.get_width() * 3, RS2_EXTENSION_VIDEO_FRAME); if (_equalize) make_equalized_histogram(f, ret); else make_value_cropped_frame(f, ret); return ret; } } <commit_msg>Colorizer - fix division by zero<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #include "../include/librealsense2/hpp/rs_sensor.hpp" #include "../include/librealsense2/hpp/rs_processing.hpp" #include "proc/synthetic-stream.h" #include "context.h" #include "environment.h" #include "option.h" #include "colorizer.h" #include "disparity-transform.h" namespace librealsense { static color_map hue{ { { 255, 0, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 255, 255 }, { 0, 0, 255 }, { 255, 0, 255 }, { 255, 0, 0 }, } }; static color_map jet{ { { 0, 0, 255 }, { 0, 255, 255 }, { 255, 255, 0 }, { 255, 0, 0 }, { 50, 0, 0 }, } }; static color_map classic{ { { 30, 77, 203 }, { 25, 60, 192 }, { 45, 117, 220 }, { 204, 108, 191 }, { 196, 57, 178 }, { 198, 33, 24 }, } }; static color_map grayscale{ { { 255, 255, 255 }, { 0, 0, 0 }, } }; static color_map inv_grayscale{ { { 0, 0, 0 }, { 255, 255, 255 }, } }; static color_map biomes{ { { 0, 0, 204 }, { 204, 230, 255 }, { 255, 255, 153 }, { 170, 255, 128 }, { 0, 153, 0 }, { 230, 242, 255 }, } }; static color_map cold{ { { 230, 247, 255 }, { 0, 92, 230 }, { 0, 179, 179 }, { 0, 51, 153 }, { 0, 5, 15 } } }; static color_map warm{ { { 255, 255, 230 }, { 255, 204, 0 }, { 255, 136, 77 }, { 255, 51, 0 }, { 128, 0, 0 }, { 10, 0, 0 } } }; static color_map quantized{ { { 255, 255, 255 }, { 0, 0, 0 }, }, 6 }; static color_map pattern{ { { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, { 255, 255, 255 }, { 0, 0, 0 }, } }; colorizer::colorizer() : colorizer("Depth Visualization") {} colorizer::colorizer(const char* name) : stream_filter_processing_block(name), _min(0.f), _max(6.f), _equalize(true), _target_stream_profile(), _histogram() { _histogram = std::vector<int>(MAX_DEPTH, 0); _hist_data = _histogram.data(); _stream_filter.stream = RS2_STREAM_DEPTH; _stream_filter.format = RS2_FORMAT_Z16; _maps = { &jet, &classic, &grayscale, &inv_grayscale, &biomes, &cold, &warm, &quantized, &pattern, &hue }; auto min_opt = std::make_shared<ptr_option<float>>(0.f, 16.f, 0.1f, 0.f, &_min, "Min range in meters"); auto max_opt = std::make_shared<ptr_option<float>>(0.f, 16.f, 0.1f, 6.f, &_max, "Max range in meters"); register_option(RS2_OPTION_MAX_DISTANCE, std::make_shared<max_distance_option>( max_opt, min_opt)); register_option(RS2_OPTION_MIN_DISTANCE, std::make_shared<min_distance_option>( min_opt, max_opt)); auto color_map = std::make_shared<ptr_option<int>>(0, (int)_maps.size() - 1, 1, 0, &_map_index, "Color map"); color_map->set_description(0.f, "Jet"); color_map->set_description(1.f, "Classic"); color_map->set_description(2.f, "White to Black"); color_map->set_description(3.f, "Black to White"); color_map->set_description(4.f, "Bio"); color_map->set_description(5.f, "Cold"); color_map->set_description(6.f, "Warm"); color_map->set_description(7.f, "Quantized"); color_map->set_description(8.f, "Pattern"); color_map->set_description(9.f, "Hue"); register_option(RS2_OPTION_COLOR_SCHEME, color_map); auto preset_opt = std::make_shared<ptr_option<int>>(0, 3, 1, 0, &_preset, "Preset depth colorization"); preset_opt->set_description(0.f, "Dynamic"); preset_opt->set_description(1.f, "Fixed"); preset_opt->set_description(2.f, "Near"); preset_opt->set_description(3.f, "Far"); preset_opt->on_set([this](float val) { if (fabs(val - 0.f) < 1e-6) { // Dynamic _equalize = true; _map_index = 0; } if (fabs(val - 1.f) < 1e-6) { // Fixed _equalize = false; _map_index = 0; _min = 0.f; _max = 6.f; } if (fabs(val - 2.f) < 1e-6) { // Near _equalize = false; _map_index = 1; _min = 0.3f; _max = 1.5f; } if (fabs(val - 3.f) < 1e-6) { // Far _equalize = false; _map_index = 0; _min = 1.f; _max = 16.f; } }); register_option(RS2_OPTION_VISUAL_PRESET, preset_opt); auto hist_opt = std::make_shared<ptr_option<bool>>(false, true, true, true, &_equalize, "Perform histogram equalization"); register_option(RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED, hist_opt); } bool colorizer::should_process(const rs2::frame& frame) { if (!frame || frame.is<rs2::frameset>()) return false; if (frame.get_profile().stream_type() != RS2_STREAM_DEPTH) return false; return true; } rs2::frame colorizer::process_frame(const rs2::frame_source& source, const rs2::frame& f) { if (f.get_profile().get() != _source_stream_profile.get()) { _source_stream_profile = f.get_profile(); _target_stream_profile = f.get_profile().clone(RS2_STREAM_DEPTH, f.get_profile().stream_index(), RS2_FORMAT_RGB8); auto info = disparity_info::update_info_from_frame(f); _depth_units = info.depth_units; _d2d_convert_factor = info.d2d_convert_factor; } auto make_equalized_histogram = [this](const rs2::video_frame& depth, rs2::video_frame rgb) { auto depth_format = depth.get_profile().format(); const auto w = depth.get_width(), h = depth.get_height(); auto rgb_data = reinterpret_cast<uint8_t*>(const_cast<void *>(rgb.get_data())); auto coloring_function = [&, this](float data) { auto hist_data = _hist_data[(int)data]; auto pixels = (float)_hist_data[MAX_DEPTH - 1]; return (hist_data / pixels); }; if (depth_format == RS2_FORMAT_DISPARITY32) { auto depth_data = reinterpret_cast<const float*>(depth.get_data()); update_histogram(_hist_data, depth_data, w, h); make_rgb_data<float>(depth_data, rgb_data, w, h, coloring_function); } else if (depth_format == RS2_FORMAT_Z16) { auto depth_data = reinterpret_cast<const uint16_t*>(depth.get_data()); update_histogram(_hist_data, depth_data, w, h); make_rgb_data<uint16_t>(depth_data, rgb_data, w, h, coloring_function); } }; auto make_value_cropped_frame = [this](const rs2::video_frame& depth, rs2::video_frame rgb) { auto depth_format = depth.get_profile().format(); const auto w = depth.get_width(), h = depth.get_height(); auto rgb_data = reinterpret_cast<uint8_t*>(const_cast<void *>(rgb.get_data())); if (depth_format == RS2_FORMAT_DISPARITY32) { auto depth_data = reinterpret_cast<const float*>(depth.get_data()); // convert from depth min max to disparity min max // note: max min value is inverted in disparity domain auto __min = _min; if (__min < 1e-6f) { __min = 1e-6f; } // Min value set to prevent zero division. only when _min is zero. auto max = (_d2d_convert_factor / (__min)) * _depth_units + .5f; auto min = (_d2d_convert_factor / (_max)) * _depth_units + .5f; auto coloring_function = [&, this](float data) { if (max == min) return data; return (data - min) / (max - min); }; make_rgb_data<float>(depth_data, rgb_data, w, h, coloring_function); } else if (depth_format == RS2_FORMAT_Z16) { auto depth_data = reinterpret_cast<const uint16_t*>(depth.get_data()); auto min = _min; auto max = _max; auto coloring_function = [&, this](float data) { if (max == min) return data * _depth_units; return (data * _depth_units - min) / (max - min); }; make_rgb_data<uint16_t>(depth_data, rgb_data, w, h, coloring_function); } }; rs2::frame ret; auto vf = f.as<rs2::video_frame>(); ret = source.allocate_video_frame(_target_stream_profile, f, 3, vf.get_width(), vf.get_height(), vf.get_width() * 3, RS2_EXTENSION_VIDEO_FRAME); if (_equalize) make_equalized_histogram(f, ret); else make_value_cropped_frame(f, ret); return ret; } } <|endoftext|>
<commit_before>/** * @file hud_girl.cpp * @brief Purpose: Contains methods to game class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/hud_girl.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Class Contructor. * * Sets Hud Girl's firsts informations (attributes' values). * (Hud Girl: Girl's health bar). * * @param name Hud Girl's name(name of the object). * @param position Hud Girl's coordinates in the game's map. * @param priority Hud Girl's priority in game's execution. * @return void. */ HudGirl::HudGirl( std::string name, std::pair<int, int> position, int priority) :engine::GameObject( name, position, priority, { //No engine Keyboard Event needed. } ) { initialize_animations(); }; /** * @brief Notifies Hud Girl of Girl's state. * * Verifies Girl's state and sets hp' animation depending of the quantity of * life of the Girl. * * @param game_object Object for observe game's situation, * in this case, the Girl. * @return void. */ void HudGirl::notify(engine::Observable* game_object) { DEBUG("Started: HudGirl notify()"); LittleGirl* little_girl = nullptr; /**< LittleGirl. initialize a new girl */ little_girl = dynamic_cast<LittleGirl *>(game_object); if (little_girl) { float reducer_percentage = 0; /**< float. Reducer percentage of the life */ int bar_size = 0; /**< int. Size of the total life */ engine::Image* bar = nullptr; /**< Image of the girl life */ const int max_life = 180; /**< const int. Max life of the girl */ const int first_image = 0; /**< const int. select first image of the animation */ const float reducer_denominator = 90.0; /**< const float. Denominator that devide the hp to reduce */ reducer_percentage = little_girl->get_hp()/reducer_denominator; bar_size = reducer_percentage * max_life; bar = dynamic_cast<engine::Image *>(images[first_image]); const int max_height = 10; /**< const int. Max height that hp contains */ const int min_life = 10; /**< const int. Min life of the girl */ bar->set_values( std::make_pair(bar_size, max_height), std::make_pair(max_life, min_life), std::make_pair(first_image, first_image) ); } DEBUG("Ended: HudGirl notify()"); } /** * @brief Initiates Hud Girl's animation. * * Initiates Hud Girl's sprites(health bar with right hp). * * @return void. */ void HudGirl::initialize_animations() { DEBUG("Started: HudGirl initialize_animations()"); engine::Image* hp = nullptr; /**< Image. Health points image */ hp = create_image(); add_component(hp); engine::Animation* girl_hp = nullptr; /**< Animation. Initialize pointer of girl_hp animation */ girl_hp = create_animation( "../assets/images/sprites/hud/hud_girl.png", 1,1,0.9, "RIGHT" ); add_animation("girl_hp", girl_hp); girl_hp->activate(); set_actual_animation(girl_hp); DEBUG("Ended: HudGirl initialize_animations()"); } /** * @brief Creates Health bar's animation. * * Creates Health bar's animation. * * @return void. */ engine::Image* HudGirl::create_image() { DEBUG("Started: HudGirl create_image() - health_bar"); engine::Game& game = engine::Game::get_instance(); /**< Instance. Game instance */ engine::Image* health_bar = nullptr; /**< Image. Image pointer of health_bar */ health_bar = new engine::Image(game.get_renderer(), "../assets/images/sprites/sprites_test/health_bar.jpg", true, std::make_pair(74, 64), 70); const int max_hp = 180; /**< const int. Max life of the girl */ const int min_hp = 10; /**< const int. Min life of the girl */ health_bar->set_values( std::make_pair(max_hp, min_hp), std::make_pair(max_hp, min_hp), std::make_pair(0, 0) ); return health_bar; DEBUG("Ended: HudGirl create_image() - health_bar"); } /** * @brief Creates Hud Girl's animation. * * Creates all Hud Girl's animation based on Hud Girl's sprites. * * @param image_path Path of the Hud Girl's sprite. * @param sprite_lines Line of the Hud Girl's sprite. * @warning Limitations of sprite_lines and sprite_columns are * 1 to the quantity of lines/columns in the image. * @param sprite_columns Column of the Girl's sprite needed. * @param duration Duration of the Hud Girl's image to show up. * @param direction Direction of the Hud Girl's image. * @return engine::Animation* The animation constructed. */ engine::Animation* HudGirl::create_animation( std::string path, int sprite_lines, int sprite_columns, double duration, std::string direction) { DEBUG("Started: HudGirl create_animation()"); engine::Game& game = engine::Game::get_instance(); /**< Instance. Initialize instace of the game */ engine::Animation* animation = nullptr; /**< Animation. Animation of the girl */ animation = new engine::Animation( game.get_renderer(), /* Hud Girl image path */ path, /* is_active */ false, std::make_pair(0, 0), /* priority */ 1, sprite_lines, sprite_columns, duration, /* in_loop */ true, direction ); animation->set_values( std::make_pair(266, 90), std::make_pair(266, 90), std::make_pair(0, 0) ); return animation; DEBUG("Ended: HudGirl create_animation()"); } <commit_msg>[RELEVANTS METHODS] Applies technique in hud_girl<commit_after>/** * @file hud_girl.cpp * @brief Purpose: Contains methods to game class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/hud_girl.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Class Contructor. * * Sets Hud Girl's firsts informations (attributes' values). * (Hud Girl: Girl's health bar). * * @param name Hud Girl's name(name of the object). * @param position Hud Girl's coordinates in the game's map. * @param priority Hud Girl's priority in game's execution. * @return void. */ HudGirl::HudGirl( std::string name, std::pair<int, int> position, int priority) :engine::GameObject( name, position, priority, { //No engine Keyboard Event needed. } ) { initialize_animations(); }; /** * @brief Creates Hud Girl's animation. * * Creates all Hud Girl's animation based on Hud Girl's sprites. * * @param image_path Path of the Hud Girl's sprite. * @param sprite_lines Line of the Hud Girl's sprite. * @warning Limitations of sprite_lines and sprite_columns are * 1 to the quantity of lines/columns in the image. * @param sprite_columns Column of the Girl's sprite needed. * @param duration Duration of the Hud Girl's image to show up. * @param direction Direction of the Hud Girl's image. * @return engine::Animation* The animation constructed. */ engine::Animation* HudGirl::create_animation( std::string path, int sprite_lines, int sprite_columns, double duration, std::string direction) { DEBUG("Started: HudGirl create_animation()"); engine::Game& game = engine::Game::get_instance(); /**< Instance. Initialize instace of the game */ engine::Animation* animation = nullptr; /**< Animation. Animation of the girl */ animation = new engine::Animation( game.get_renderer(), /* Hud Girl image path */ path, /* is_active */ false, std::make_pair(0, 0), /* priority */ 1, sprite_lines, sprite_columns, duration, /* in_loop */ true, direction ); animation->set_values( std::make_pair(266, 90), std::make_pair(266, 90), std::make_pair(0, 0) ); return animation; DEBUG("Ended: HudGirl create_animation()"); } /** * @brief Notifies Hud Girl of Girl's state. * * Verifies Girl's state and sets hp' animation depending of the quantity of * life of the Girl. * * @param game_object Object for observe game's situation, * in this case, the Girl. * @return void. */ void HudGirl::notify(engine::Observable* game_object) { DEBUG("Started: HudGirl notify()"); LittleGirl* little_girl = nullptr; /**< LittleGirl. initialize a new girl */ little_girl = dynamic_cast<LittleGirl *>(game_object); if (little_girl) { float reducer_percentage = 0; /**< float. Reducer percentage of the life */ int bar_size = 0; /**< int. Size of the total life */ engine::Image* bar = nullptr; /**< Image of the girl life */ const int max_life = 180; /**< const int. Max life of the girl */ const int first_image = 0; /**< const int. select first image of the animation */ const float reducer_denominator = 90.0; /**< const float. Denominator that devide the hp to reduce */ reducer_percentage = little_girl->get_hp()/reducer_denominator; bar_size = reducer_percentage * max_life; bar = dynamic_cast<engine::Image *>(images[first_image]); const int max_height = 10; /**< const int. Max height that hp contains */ const int min_life = 10; /**< const int. Min life of the girl */ bar->set_values( std::make_pair(bar_size, max_height), std::make_pair(max_life, min_life), std::make_pair(first_image, first_image) ); } DEBUG("Ended: HudGirl notify()"); } /** * @brief Initiates Hud Girl's animation. * * Initiates Hud Girl's sprites(health bar with right hp). * * @return void. */ void HudGirl::initialize_animations() { DEBUG("Started: HudGirl initialize_animations()"); engine::Image* hp = nullptr; /**< Image. Health points image */ hp = create_image(); add_component(hp); engine::Animation* girl_hp = nullptr; /**< Animation. Initialize pointer of girl_hp animation */ girl_hp = create_animation( "../assets/images/sprites/hud/hud_girl.png", 1,1,0.9, "RIGHT" ); add_animation("girl_hp", girl_hp); girl_hp->activate(); set_actual_animation(girl_hp); DEBUG("Ended: HudGirl initialize_animations()"); } /** * @brief Creates Health bar's animation. * * Creates Health bar's images. * * @return void. */ engine::Image* HudGirl::create_image() { DEBUG("Started: HudGirl create_image() - health_bar"); engine::Game& game = engine::Game::get_instance(); /**< Instance. Game instance */ engine::Image* health_bar = nullptr; /**< Image. Image pointer of health_bar */ health_bar = new engine::Image(game.get_renderer(), "../assets/images/sprites/sprites_test/health_bar.jpg", true, std::make_pair(74, 64), 70); const int max_hp = 180; /**< const int. Max life of the girl */ const int min_hp = 10; /**< const int. Min life of the girl */ health_bar->set_values( std::make_pair(max_hp, min_hp), std::make_pair(max_hp, min_hp), std::make_pair(0, 0) ); return health_bar; DEBUG("Ended: HudGirl create_image() - health_bar"); } <|endoftext|>
<commit_before>#include "prog_translator.h" #include "CoinPackedVector.hpp" #include "OsiSolverInterface.hpp" #include "cyc_limits.h" #include "exchange_graph.h" namespace cyclus { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface, bool exclusive) : g_(g), iface_(iface), excl_(exclusive) { arc_offset_ = g_->arcs().size(); int reserve = arc_offset_ + g_->request_groups().size(); ctx_.obj_coeffs.reserve(reserve); ctx_.col_ubs.reserve(reserve); ctx_.col_lbs.reserve(reserve); ctx_.m = CoinPackedMatrix(false, 0, 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::Translate() { // number of variables = number of arcs + 1 faux arc per request group int n_cols = g_->arcs().size() + g_->request_groups().size(); ctx_.m.setDimensions(0, n_cols); bool req; std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups(); for (int i = 0; i != sgs.size(); i++) { req = false; XlateGrp_(sgs[i].get(), req); } // std::vector<RequestGroup::Ptr>& rgs = g_->request_groups(); // for (int i = 0; i != rgs.size(); i++) { // req = true; // XlateGrp_(rgs[i].get(), req); // } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::Populate() { iface_->setObjSense(-1.0); // maximize // load er up! iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0], &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]); if (excl_) { std::vector<Arc>& arcs = g_->arcs(); for (int i = 0; i != arcs.size(); i++) { Arc& a = arcs[i]; if (a.exclusive) { iface_->setInteger(g_->arc_ids()[a]); } } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::ToProg() { Translate(); Populate(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool req) { double inf = iface_->getInfinity(); std::vector<double>& caps = grp->capacities(); std::vector<CoinPackedVector> cap_rows; std::vector<CoinPackedVector> excl_rows; for (int i = 0; i != caps.size(); i++) { cap_rows.push_back(CoinPackedVector()); } std::vector<ExchangeNode::Ptr>& nodes = grp->nodes(); for (int i = 0; i != nodes.size(); i++) { std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities; std::map<Arc, std::vector<double> >::iterator cap_it; CoinPackedVector excl_row; // add each arc for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) { const Arc& a = cap_it->first; std::vector<double>& ucaps = cap_it->second; int arc_id = g_->arc_ids()[a]; // add each unit capacity coefficient for (int j = 0; j != ucaps.size(); j++) { double coeff = ucaps[j]; if (excl_ && a.exclusive) { coeff *= a.excl_val; } cap_rows[j].insert(arc_id, coeff); } // add exclusive arc if (excl_ && a.exclusive) { excl_row.insert(arc_id, 1.0); } // add obj coeff for arc double pref = nodes[i]->prefs[a]; ctx_.obj_coeffs[arc_id] = a.exclusive ? pref * a.excl_val : pref; ctx_.col_lbs[arc_id] = 0; ctx_.col_ubs[arc_id] = a.exclusive ? 1 : inf; } if (excl_row.getNumElements() > 0) { excl_rows.push_back(excl_row); } } double faux_id; if (req) { faux_id = ++arc_offset_; ctx_.obj_coeffs[faux_id] = 0; ctx_.col_lbs[faux_id] = 0; ctx_.col_ubs[faux_id] = inf; } // add all capacity rows for (int i = 0; i != cap_rows.size(); i++) { if (req) { cap_rows[i].insert(faux_id, 1.0); // faux arc } double lb = req ? caps[i] : 0; double ub = req ? inf : caps[i]; ctx_.row_lbs.push_back(lb); ctx_.row_ubs.push_back(ub); ctx_.m.appendRow(cap_rows[i]); } // add all exclusive rows for (int i = 0; i != excl_rows.size(); i++) { ctx_.row_lbs.push_back(0.0); ctx_.row_ubs.push_back(1.0); ctx_.m.appendRow(excl_rows[i]); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::FromProg() { const double* sol = iface_->getColSolution(); std::vector<Arc>& arcs = g_->arcs(); for (int i = 0; i < arcs.size(); i++) { double flow = sol[i]; Arc& a = g_->arc_by_id().at(i); flow = (a.exclusive) ? flow * a.excl_val : flow; if (flow > cyclus::eps()) { g_->AddMatch(a, flow); } } } } // namespace cyclus <commit_msg>found the bug, pre-incrementing vs. post-incrementing<commit_after>#include "prog_translator.h" #include "CoinPackedVector.hpp" #include "OsiSolverInterface.hpp" #include "cyc_limits.h" #include "exchange_graph.h" namespace cyclus { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface, bool exclusive) : g_(g), iface_(iface), excl_(exclusive) { arc_offset_ = g_->arcs().size(); int reserve = arc_offset_ + g_->request_groups().size(); ctx_.obj_coeffs.reserve(reserve); ctx_.col_ubs.reserve(reserve); ctx_.col_lbs.reserve(reserve); ctx_.m = CoinPackedMatrix(false, 0, 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::Translate() { // number of variables = number of arcs + 1 faux arc per request group int n_cols = g_->arcs().size() + g_->request_groups().size(); ctx_.m.setDimensions(0, n_cols); bool req; std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups(); for (int i = 0; i != sgs.size(); i++) { req = false; XlateGrp_(sgs[i].get(), req); } std::vector<RequestGroup::Ptr>& rgs = g_->request_groups(); for (int i = 0; i != rgs.size(); i++) { req = true; XlateGrp_(rgs[i].get(), req); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::Populate() { iface_->setObjSense(-1.0); // maximize // load er up! iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0], &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]); if (excl_) { std::vector<Arc>& arcs = g_->arcs(); for (int i = 0; i != arcs.size(); i++) { Arc& a = arcs[i]; if (a.exclusive) { iface_->setInteger(g_->arc_ids()[a]); } } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::ToProg() { Translate(); Populate(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool req) { double inf = iface_->getInfinity(); std::vector<double>& caps = grp->capacities(); std::vector<CoinPackedVector> cap_rows; std::vector<CoinPackedVector> excl_rows; for (int i = 0; i != caps.size(); i++) { cap_rows.push_back(CoinPackedVector()); } std::vector<ExchangeNode::Ptr>& nodes = grp->nodes(); for (int i = 0; i != nodes.size(); i++) { std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities; std::map<Arc, std::vector<double> >::iterator cap_it; CoinPackedVector excl_row; // add each arc for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) { const Arc& a = cap_it->first; std::vector<double>& ucaps = cap_it->second; int arc_id = g_->arc_ids()[a]; // add each unit capacity coefficient for (int j = 0; j != ucaps.size(); j++) { double coeff = ucaps[j]; if (excl_ && a.exclusive) { coeff *= a.excl_val; } cap_rows[j].insert(arc_id, coeff); } // add exclusive arc if (excl_ && a.exclusive) { excl_row.insert(arc_id, 1.0); } // add obj coeff for arc double pref = nodes[i]->prefs[a]; ctx_.obj_coeffs[arc_id] = a.exclusive ? pref * a.excl_val : pref; ctx_.col_lbs[arc_id] = 0; ctx_.col_ubs[arc_id] = a.exclusive ? 1 : inf; } if (excl_row.getNumElements() > 0) { excl_rows.push_back(excl_row); } } int faux_id; if (req) { faux_id = arc_offset_++; ctx_.obj_coeffs[faux_id] = 0; ctx_.col_lbs[faux_id] = 0; ctx_.col_ubs[faux_id] = inf; } // add all capacity rows for (int i = 0; i != cap_rows.size(); i++) { if (req) { cap_rows[i].insert(faux_id, 1.0); // faux arc } double lb = req ? caps[i] : 0; double ub = req ? inf : caps[i]; ctx_.row_lbs.push_back(lb); ctx_.row_ubs.push_back(ub); ctx_.m.appendRow(cap_rows[i]); } // add all exclusive rows for (int i = 0; i != excl_rows.size(); i++) { ctx_.row_lbs.push_back(0.0); ctx_.row_ubs.push_back(1.0); ctx_.m.appendRow(excl_rows[i]); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ProgTranslator::FromProg() { const double* sol = iface_->getColSolution(); std::vector<Arc>& arcs = g_->arcs(); for (int i = 0; i < arcs.size(); i++) { double flow = sol[i]; Arc& a = g_->arc_by_id().at(i); flow = (a.exclusive) ? flow * a.excl_val : flow; if (flow > cyclus::eps()) { g_->AddMatch(a, flow); } } } } // namespace cyclus <|endoftext|>
<commit_before>//============================================================================== // CellML file element //============================================================================== #include "cellmlfileelement.h" #include "cellmlfilemanager.h" //============================================================================== #include <QStringList> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Model *pModel) : mCellmlFile(pCellmlFile), mCellmlElement(pModel), mCmetaId(QString::fromStdWString(pModel->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLImport *pCellmlImport) : mCellmlFile(pCellmlFile), mCellmlElement(pCellmlImport), mCmetaId(QString::fromStdWString(pCellmlImport->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ImportUnits *pImportUnits) : mCellmlFile(pCellmlFile), mCellmlElement(pImportUnits), mCmetaId(QString::fromStdWString(pImportUnits->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ImportComponent *pImportComponent) : mCellmlFile(pCellmlFile), mCellmlElement(pImportComponent), mCmetaId(QString::fromStdWString(pImportComponent->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Units *pUnits) : mCellmlFile(pCellmlFile), mCellmlElement(pUnits), mCmetaId(QString::fromStdWString(pUnits->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Unit *pUnit) : mCellmlFile(pCellmlFile), mCellmlElement(pUnit), mCmetaId(QString::fromStdWString(pUnit->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLComponent *pComponent) : mCellmlFile(pCellmlFile), mCellmlElement(pComponent), mCmetaId(QString::fromStdWString(pComponent->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLVariable *pVariable) : mCellmlFile(pCellmlFile), mCellmlElement(pVariable), mCmetaId(QString::fromStdWString(pVariable->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Group *pGroup) : mCellmlFile(pCellmlFile), mCellmlElement(pGroup), mCmetaId(QString::fromStdWString(pGroup->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::RelationshipRef *pRelationshipRef) : mCellmlFile(pCellmlFile), mCellmlElement(pRelationshipRef), mCmetaId(QString::fromStdWString(pRelationshipRef->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ComponentRef *pComponentRef) : mCellmlFile(pCellmlFile), mCellmlElement(pComponentRef), mCmetaId(QString::fromStdWString(pComponentRef->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Connection *pConnection) : mCellmlFile(pCellmlFile), mCellmlElement(pConnection), mCmetaId(QString::fromStdWString(pConnection->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::MapComponents *pMapComponents) : mCellmlFile(pCellmlFile), mCellmlElement(pMapComponents), mCmetaId(QString::fromStdWString(pMapComponents->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::MapVariables *pMapVariables) : mCellmlFile(pCellmlFile), mCellmlElement(pMapVariables), mCmetaId(QString::fromStdWString(pMapVariables->cmetaId())) { } //============================================================================== CellmlFileElement::~CellmlFileElement() { // We took ownership of the CellML API element (i.e. mCellmlElement), so we // must call its release_ref() method mCellmlElement->release_ref(); } //============================================================================== CellmlFileRdfTriples CellmlFileElement::rdfTriples() const { // Return all the RDF triples associated with the element if (mCmetaId.isEmpty()) // The element doesn't have a 'proper' cmeta:id, so... return CellmlFileRdfTriples(mCellmlFile); else // The element has a 'proper' cmeta:id, so we can retrieve and return // the RDF triples associated with it return mCellmlFile->rdfTriples(mCmetaId); } //============================================================================== QString CellmlFileElement::rdfTripleSubject() { // Make sure that we have a 'proper' cmeta:id or generate one, if needed if (mCmetaId.isEmpty()) { // We don't have a 'proper' cmeta:id, so we need to generate one and in // order to do so, we need to know what cmeta:ids are currently in use // in the CellML file, meaning we first need to retrieve all the RDF // triples in the CellML file CellmlFileRdfTriples *rdfTriples = mCellmlFile->rdfTriples(); // Next, we need to retrieve all the cmeta:ids from our different RDF // triples QStringList cmetaIds = QStringList(); foreach (CellmlFileRdfTriple *rdfTriple, *rdfTriples) { QString cmetaId = rdfTriple->metadataId(); if (!cmetaIds.contains(cmetaId)) cmetaIds << cmetaId; } // Now, we try different cmeta:id values until we find one which is not // present in our list int counter = 0; forever { mCmetaId = QString("id_%1").arg(++counter, 5, 10, QChar('0')); if (!cmetaIds.contains(mCmetaId)) { // We have found a unique cmeta:id, so update our CellML element // and leave mCellmlElement->cmetaId(mCmetaId.toStdWString()); mCellmlFile->setModified(true); break; } } } // Return the subject which should be used for an RDF triple return mCellmlFile->uriBase()+"#"+mCmetaId; } //============================================================================== bool CellmlFileElement::hasMetadata(const QString &pQualifier, const QString &pResource, const QString &pId) { // Return whether the given metadata is associated with the CellML element if (mCmetaId.isEmpty()) // The CellML element doesn't have a 'proper' cmeta:id, so... return false; // Go through the RDF triples associated with the CellML element and check // whether one of them corresponds to the given metadata CellmlFileRdfTriples rdfTriples = mCellmlFile->rdfTriples(mCmetaId); foreach (CellmlFileRdfTriple *rdfTriple, rdfTriples) if ( !pQualifier.compare(rdfTriple->qualifierAsString()) && !pResource.compare(rdfTriple->resource()) && !pId.compare(rdfTriple->id())) // This is the metadata we are after, so... return true; // We couldn't find the metadata, so... return false; } //============================================================================== bool CellmlFileElement::hasMetadata(const CellMLSupport::CellmlFileRdfTriple::ModelQualifier &pModelQualifier, const QString &pResource, const QString &pId) { // Call our generic hasMetadata() function return hasMetadata(CellMLSupport::CellmlFileRdfTriple::modelQualifierAsString(pModelQualifier), pResource, pId); } //============================================================================== bool CellmlFileElement::hasMetadata(const CellMLSupport::CellmlFileRdfTriple::BioQualifier &pBioQualifier, const QString &pResource, const QString &pId) { // Call our generic hasMetadata() function return hasMetadata(CellMLSupport::CellmlFileRdfTriple::bioQualifierAsString(pBioQualifier), pResource, pId); } //============================================================================== CellMLSupport::CellmlFileRdfTriple * CellmlFileElement::addMetadata(const CellMLSupport::CellmlFileRdfTriple::ModelQualifier &pModelQualifier, const QString &pResource, const QString &pId) { // Add our metadata to our CellML file, this as an RDF triple return mCellmlFile->rdfTriples()->add(new CellMLSupport::CellmlFileRdfTriple(mCellmlFile, rdfTripleSubject(), pModelQualifier, pResource, pId)); } //============================================================================== CellMLSupport::CellmlFileRdfTriple * CellmlFileElement::addMetadata(const CellMLSupport::CellmlFileRdfTriple::BioQualifier &pBioQualifier, const QString &pResource, const QString &pId) { // Add our metadata to our CellML file, this as an RDF triple return mCellmlFile->rdfTriples()->add(new CellMLSupport::CellmlFileRdfTriple(mCellmlFile, rdfTripleSubject(), pBioQualifier, pResource, pId)); } //============================================================================== void CellmlFileElement::removeAllMetadata() { // Remove, from our CellML file, all the metadata associated with the CellML // element's cmeta:id, but only if the CellML element has a 'proper' // cmeta:id if (!mCmetaId.isEmpty()) mCellmlFile->rdfTriples()->remove(mCmetaId); } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up (#57).<commit_after>//============================================================================== // CellML file element //============================================================================== #include "cellmlfileelement.h" #include "cellmlfilemanager.h" //============================================================================== #include <QStringList> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Model *pModel) : mCellmlFile(pCellmlFile), mCellmlElement(pModel), mCmetaId(QString::fromStdWString(pModel->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLImport *pCellmlImport) : mCellmlFile(pCellmlFile), mCellmlElement(pCellmlImport), mCmetaId(QString::fromStdWString(pCellmlImport->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ImportUnits *pImportUnits) : mCellmlFile(pCellmlFile), mCellmlElement(pImportUnits), mCmetaId(QString::fromStdWString(pImportUnits->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ImportComponent *pImportComponent) : mCellmlFile(pCellmlFile), mCellmlElement(pImportComponent), mCmetaId(QString::fromStdWString(pImportComponent->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Units *pUnits) : mCellmlFile(pCellmlFile), mCellmlElement(pUnits), mCmetaId(QString::fromStdWString(pUnits->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Unit *pUnit) : mCellmlFile(pCellmlFile), mCellmlElement(pUnit), mCmetaId(QString::fromStdWString(pUnit->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLComponent *pComponent) : mCellmlFile(pCellmlFile), mCellmlElement(pComponent), mCmetaId(QString::fromStdWString(pComponent->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::CellMLVariable *pVariable) : mCellmlFile(pCellmlFile), mCellmlElement(pVariable), mCmetaId(QString::fromStdWString(pVariable->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Group *pGroup) : mCellmlFile(pCellmlFile), mCellmlElement(pGroup), mCmetaId(QString::fromStdWString(pGroup->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::RelationshipRef *pRelationshipRef) : mCellmlFile(pCellmlFile), mCellmlElement(pRelationshipRef), mCmetaId(QString::fromStdWString(pRelationshipRef->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::ComponentRef *pComponentRef) : mCellmlFile(pCellmlFile), mCellmlElement(pComponentRef), mCmetaId(QString::fromStdWString(pComponentRef->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::Connection *pConnection) : mCellmlFile(pCellmlFile), mCellmlElement(pConnection), mCmetaId(QString::fromStdWString(pConnection->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::MapComponents *pMapComponents) : mCellmlFile(pCellmlFile), mCellmlElement(pMapComponents), mCmetaId(QString::fromStdWString(pMapComponents->cmetaId())) { } //============================================================================== CellmlFileElement::CellmlFileElement(CellmlFile *pCellmlFile, iface::cellml_api::MapVariables *pMapVariables) : mCellmlFile(pCellmlFile), mCellmlElement(pMapVariables), mCmetaId(QString::fromStdWString(pMapVariables->cmetaId())) { } //============================================================================== CellmlFileElement::~CellmlFileElement() { // Release some internal objects mCellmlElement->release_ref(); } //============================================================================== CellmlFileRdfTriples CellmlFileElement::rdfTriples() const { // Return all the RDF triples associated with the element if (mCmetaId.isEmpty()) // The element doesn't have a 'proper' cmeta:id, so... return CellmlFileRdfTriples(mCellmlFile); else // The element has a 'proper' cmeta:id, so we can retrieve and return // the RDF triples associated with it return mCellmlFile->rdfTriples(mCmetaId); } //============================================================================== QString CellmlFileElement::rdfTripleSubject() { // Make sure that we have a 'proper' cmeta:id or generate one, if needed if (mCmetaId.isEmpty()) { // We don't have a 'proper' cmeta:id, so we need to generate one and in // order to do so, we need to know what cmeta:ids are currently in use // in the CellML file, meaning we first need to retrieve all the RDF // triples in the CellML file CellmlFileRdfTriples *rdfTriples = mCellmlFile->rdfTriples(); // Next, we need to retrieve all the cmeta:ids from our different RDF // triples QStringList cmetaIds = QStringList(); foreach (CellmlFileRdfTriple *rdfTriple, *rdfTriples) { QString cmetaId = rdfTriple->metadataId(); if (!cmetaIds.contains(cmetaId)) cmetaIds << cmetaId; } // Now, we try different cmeta:id values until we find one which is not // present in our list int counter = 0; forever { mCmetaId = QString("id_%1").arg(++counter, 5, 10, QChar('0')); if (!cmetaIds.contains(mCmetaId)) { // We have found a unique cmeta:id, so update our CellML element // and leave mCellmlElement->cmetaId(mCmetaId.toStdWString()); mCellmlFile->setModified(true); break; } } } // Return the subject which should be used for an RDF triple return mCellmlFile->uriBase()+"#"+mCmetaId; } //============================================================================== bool CellmlFileElement::hasMetadata(const QString &pQualifier, const QString &pResource, const QString &pId) { // Return whether the given metadata is associated with the CellML element if (mCmetaId.isEmpty()) // The CellML element doesn't have a 'proper' cmeta:id, so... return false; // Go through the RDF triples associated with the CellML element and check // whether one of them corresponds to the given metadata CellmlFileRdfTriples rdfTriples = mCellmlFile->rdfTriples(mCmetaId); foreach (CellmlFileRdfTriple *rdfTriple, rdfTriples) if ( !pQualifier.compare(rdfTriple->qualifierAsString()) && !pResource.compare(rdfTriple->resource()) && !pId.compare(rdfTriple->id())) // This is the metadata we are after, so... return true; // We couldn't find the metadata, so... return false; } //============================================================================== bool CellmlFileElement::hasMetadata(const CellMLSupport::CellmlFileRdfTriple::ModelQualifier &pModelQualifier, const QString &pResource, const QString &pId) { // Call our generic hasMetadata() function return hasMetadata(CellMLSupport::CellmlFileRdfTriple::modelQualifierAsString(pModelQualifier), pResource, pId); } //============================================================================== bool CellmlFileElement::hasMetadata(const CellMLSupport::CellmlFileRdfTriple::BioQualifier &pBioQualifier, const QString &pResource, const QString &pId) { // Call our generic hasMetadata() function return hasMetadata(CellMLSupport::CellmlFileRdfTriple::bioQualifierAsString(pBioQualifier), pResource, pId); } //============================================================================== CellMLSupport::CellmlFileRdfTriple * CellmlFileElement::addMetadata(const CellMLSupport::CellmlFileRdfTriple::ModelQualifier &pModelQualifier, const QString &pResource, const QString &pId) { // Add our metadata to our CellML file, this as an RDF triple return mCellmlFile->rdfTriples()->add(new CellMLSupport::CellmlFileRdfTriple(mCellmlFile, rdfTripleSubject(), pModelQualifier, pResource, pId)); } //============================================================================== CellMLSupport::CellmlFileRdfTriple * CellmlFileElement::addMetadata(const CellMLSupport::CellmlFileRdfTriple::BioQualifier &pBioQualifier, const QString &pResource, const QString &pId) { // Add our metadata to our CellML file, this as an RDF triple return mCellmlFile->rdfTriples()->add(new CellMLSupport::CellmlFileRdfTriple(mCellmlFile, rdfTripleSubject(), pBioQualifier, pResource, pId)); } //============================================================================== void CellmlFileElement::removeAllMetadata() { // Remove, from our CellML file, all the metadata associated with the CellML // element's cmeta:id, but only if the CellML element has a 'proper' // cmeta:id if (!mCmetaId.isEmpty()) mCellmlFile->rdfTriples()->remove(mCmetaId); } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#ifndef ENGINE_API_MATRIX_HPP #define ENGINE_API_MATRIX_HPP #include "engine/api/base_api.hpp" #include "engine/api/json_factory.hpp" #include "engine/api/matrix_parameters.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "engine/guidance/assemble_geometry.hpp" #include "engine/guidance/assemble_leg.hpp" #include "engine/guidance/assemble_overview.hpp" #include "engine/guidance/assemble_route.hpp" #include "engine/guidance/assemble_steps.hpp" #include "engine/internal_route_result.hpp" #include "util/integer_range.hpp" #include <boost/range/algorithm/transform.hpp> #include <iterator> namespace osrm { namespace engine { namespace api { class MatrixAPI final : public BaseAPI { public: MatrixAPI(const datafacade::BaseDataFacade &facade_, const MatrixParameters &parameters_) : BaseAPI(facade_, parameters_), parameters(parameters_) { } virtual void MakeResponse(const std::vector<std::pair<EdgeWeight, double>> &durations, const std::vector<PhantomNode> &phantoms, util::json::Object &response) const { auto number_of_coordinates = phantoms.size(); response.values["sources"] = MakeWaypoints(phantoms); response.values["destinations"] = MakeWaypoints(phantoms); response.values["durations"] = MakeMatrix(durations, number_of_coordinates); response.values["code"] = "Ok"; } protected: virtual util::json::Array MakeWaypoints(const std::vector<PhantomNode> &phantoms) const { util::json::Array json_waypoints; json_waypoints.values.reserve(phantoms.size()); BOOST_ASSERT(phantoms.size() == parameters.coordinates.size()); boost::range::transform( phantoms, std::back_inserter(json_waypoints.values), [this](const PhantomNode &phantom) { util::json::Array array; array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lon))); array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lat))); return array; }); return json_waypoints; } virtual util::json::Array MakeMatrix(const std::vector<std::pair<EdgeWeight, double>> &values, std::size_t matrix_size) const { util::json::Array json_table; for (const auto row : util::irange<std::size_t>(0UL, matrix_size)) { util::json::Array json_row; auto row_begin_iterator = values.begin() + (row * matrix_size); auto row_end_iterator = values.begin() + ((row + 1) * matrix_size); json_row.values.resize(matrix_size); std::transform(row_begin_iterator, row_end_iterator, json_row.values.begin(), [](const std::pair<EdgeWeight, double> duration) { util::json::Object result = util::json::Object(); if (duration.first == MAXIMAL_EDGE_DURATION) { result.values["distance"] = util::json::Null(); result.values["time"] = util::json::Null(); } else { result.values["distance"] = duration.first; result.values["time"] = duration.second; } return result; }); json_table.values.push_back(std::move(json_row)); } return json_table; } const MatrixParameters &parameters; }; } // ns api } // ns engine } // ns osrm #endif <commit_msg>Rename matrix durations to distances<commit_after>#ifndef ENGINE_API_MATRIX_HPP #define ENGINE_API_MATRIX_HPP #include "engine/api/base_api.hpp" #include "engine/api/json_factory.hpp" #include "engine/api/matrix_parameters.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "engine/guidance/assemble_geometry.hpp" #include "engine/guidance/assemble_leg.hpp" #include "engine/guidance/assemble_overview.hpp" #include "engine/guidance/assemble_route.hpp" #include "engine/guidance/assemble_steps.hpp" #include "engine/internal_route_result.hpp" #include "util/integer_range.hpp" #include <boost/range/algorithm/transform.hpp> #include <iterator> namespace osrm { namespace engine { namespace api { class MatrixAPI final : public BaseAPI { public: MatrixAPI(const datafacade::BaseDataFacade &facade_, const MatrixParameters &parameters_) : BaseAPI(facade_, parameters_), parameters(parameters_) { } virtual void MakeResponse(const std::vector<std::pair<EdgeWeight, double>> &durations, const std::vector<PhantomNode> &phantoms, util::json::Object &response) const { auto number_of_coordinates = phantoms.size(); response.values["sources"] = MakeWaypoints(phantoms); response.values["destinations"] = MakeWaypoints(phantoms); response.values["distances"] = MakeMatrix(durations, number_of_coordinates); response.values["code"] = "Ok"; } protected: virtual util::json::Array MakeWaypoints(const std::vector<PhantomNode> &phantoms) const { util::json::Array json_waypoints; json_waypoints.values.reserve(phantoms.size()); BOOST_ASSERT(phantoms.size() == parameters.coordinates.size()); boost::range::transform( phantoms, std::back_inserter(json_waypoints.values), [this](const PhantomNode &phantom) { util::json::Array array; array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lon))); array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lat))); return array; }); return json_waypoints; } virtual util::json::Array MakeMatrix(const std::vector<std::pair<EdgeWeight, double>> &values, std::size_t matrix_size) const { util::json::Array json_table; for (const auto row : util::irange<std::size_t>(0UL, matrix_size)) { util::json::Array json_row; auto row_begin_iterator = values.begin() + (row * matrix_size); auto row_end_iterator = values.begin() + ((row + 1) * matrix_size); json_row.values.resize(matrix_size); std::transform(row_begin_iterator, row_end_iterator, json_row.values.begin(), [](const std::pair<EdgeWeight, double> duration) { util::json::Object result = util::json::Object(); if (duration.first == MAXIMAL_EDGE_DURATION) { result.values["distance"] = util::json::Null(); result.values["time"] = util::json::Null(); } else { result.values["distance"] = duration.first; result.values["time"] = duration.second; } return result; }); json_table.values.push_back(std::move(json_row)); } return json_table; } const MatrixParameters &parameters; }; } // ns api } // ns engine } // ns osrm #endif <|endoftext|>
<commit_before>/// @example primesieve_iterator.cpp /// Iterate over primes using primesieve::iterator. #include <primesieve.hpp> #include <iostream> int main() { primesieve::iterator it; uint64_t prime = it.next_prime(); uint64_t sum = 0; // iterate over the primes below 10^9 for (; prime < 1000000000ull; prime = it.next_prime()) sum += prime; std::cout << "Sum of the primes below 10^9 = " << sum << std::endl; // generate primes > 1000 it.skipto(1000); prime = it.next_prime(); for (; prime < 1100; prime = it.next_prime()) std::cout << prime << std::endl; return 0; } <commit_msg>Convert to benchmark program<commit_after>/// @example primesieve_iterator.cpp /// Iterate over primes using primesieve::iterator. #include <primesieve.hpp> #include <cstdlib> #include <iostream> int main(int argc, char** argv) { primesieve::iterator it; uint64_t limit = 10000000000ull; uint64_t prime = it.next_prime(); uint64_t sum = 0; if (argc > 1) limit = std::atol(argv[1]); // iterate over the primes below 10^9 for (; prime < limit; prime = it.next_prime()) sum += prime; std::cout << "Sum of primes < " << limit << " = " << sum << std::endl; // Note that since sum is a 64-bit variable the result // will be incorrect (due to integer overflow) if // limit > 10^10. However we do allow limits > 10^10 // since this is useful for benchmarking. if (limit > 10000000000ull) std::cerr << "Warning: sum is likely incorrect due to 64-bit integer overflow!" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/json/json_trace_parser.h" #include <inttypes.h> #include <limits> #include <string> #include "perfetto/base/logging.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/ext/base/utils.h" #include "src/trace_processor/importers/json/json_tracker.h" #include "src/trace_processor/importers/json/json_utils.h" #include "src/trace_processor/process_tracker.h" #include "src/trace_processor/slice_tracker.h" #include "src/trace_processor/trace_processor_context.h" #include "src/trace_processor/track_tracker.h" namespace perfetto { namespace trace_processor { JsonTraceParser::JsonTraceParser(TraceProcessorContext* context) : context_(context), systrace_line_parser_(context) {} JsonTraceParser::~JsonTraceParser() = default; void JsonTraceParser::ParseFtracePacket(uint32_t, int64_t, TimestampedTracePiece) { PERFETTO_FATAL("Json Trace Parser cannot handle ftrace packets."); } void JsonTraceParser::ParseTracePacket(int64_t timestamp, TimestampedTracePiece ttp) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) PERFETTO_DCHECK(ttp.type == TimestampedTracePiece::Type::kJsonValue || ttp.type == TimestampedTracePiece::Type::kSystraceLine); if (ttp.type == TimestampedTracePiece::Type::kSystraceLine) { systrace_line_parser_.ParseLine(*ttp.systrace_line); return; } const Json::Value& value = *(ttp.json_value); ProcessTracker* procs = context_->process_tracker.get(); TraceStorage* storage = context_->storage.get(); SliceTracker* slice_tracker = context_->slice_tracker.get(); auto& ph = value["ph"]; if (!ph.isString()) return; char phase = *ph.asCString(); base::Optional<uint32_t> opt_pid; base::Optional<uint32_t> opt_tid; if (value.isMember("pid")) opt_pid = json::CoerceToUint32(value["pid"]); if (value.isMember("tid")) opt_tid = json::CoerceToUint32(value["tid"]); uint32_t pid = opt_pid.value_or(0); uint32_t tid = opt_tid.value_or(pid); base::StringView cat = value.isMember("cat") ? base::StringView(value["cat"].asCString()) : base::StringView(); base::StringView name = value.isMember("name") ? base::StringView(value["name"].asCString()) : base::StringView(); StringId cat_id = storage->InternString(cat); StringId name_id = storage->InternString(name); UniqueTid utid = procs->UpdateThread(tid, pid); switch (phase) { case 'B': { // TRACE_EVENT_BEGIN. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Begin(timestamp, track_id, cat_id, name_id); break; } case 'E': { // TRACE_EVENT_END. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->End(timestamp, track_id, cat_id, name_id); break; } case 'X': { // TRACE_EVENT (scoped event). base::Optional<int64_t> opt_dur = JsonTracker::GetOrCreate(context_)->CoerceToTs(value["dur"]); if (!opt_dur.has_value()) return; TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, opt_dur.value()); break; } case 'M': { // Metadata events (process and thread names). if (strcmp(value["name"].asCString(), "thread_name") == 0 && !value["args"]["name"].empty()) { const char* thread_name = value["args"]["name"].asCString(); auto thread_name_id = context_->storage->InternString(thread_name); procs->UpdateThreadName(tid, thread_name_id); break; } if (strcmp(value["name"].asCString(), "process_name") == 0 && !value["args"]["name"].empty()) { const char* proc_name = value["args"]["name"].asCString(); procs->SetProcessMetadata(pid, base::nullopt, proc_name); break; } } } #else perfetto::base::ignore_result(timestamp); perfetto::base::ignore_result(ttp); perfetto::base::ignore_result(context_); PERFETTO_ELOG("Cannot parse JSON trace due to missing JSON support"); #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } } // namespace trace_processor } // namespace perfetto <commit_msg>tp: ingest args from json events am: 8561f1e807 am: e2b286d534<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/json/json_trace_parser.h" #include <inttypes.h> #include <limits> #include <string> #include "perfetto/base/logging.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/ext/base/utils.h" #include "src/trace_processor/importers/json/json_tracker.h" #include "src/trace_processor/importers/json/json_utils.h" #include "src/trace_processor/process_tracker.h" #include "src/trace_processor/slice_tracker.h" #include "src/trace_processor/trace_processor_context.h" #include "src/trace_processor/track_tracker.h" namespace perfetto { namespace trace_processor { JsonTraceParser::JsonTraceParser(TraceProcessorContext* context) : context_(context), systrace_line_parser_(context) {} JsonTraceParser::~JsonTraceParser() = default; void JsonTraceParser::ParseFtracePacket(uint32_t, int64_t, TimestampedTracePiece) { PERFETTO_FATAL("Json Trace Parser cannot handle ftrace packets."); } void JsonTraceParser::ParseTracePacket(int64_t timestamp, TimestampedTracePiece ttp) { PERFETTO_DCHECK(json::IsJsonSupported()); #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) PERFETTO_DCHECK(ttp.type == TimestampedTracePiece::Type::kJsonValue || ttp.type == TimestampedTracePiece::Type::kSystraceLine); if (ttp.type == TimestampedTracePiece::Type::kSystraceLine) { systrace_line_parser_.ParseLine(*ttp.systrace_line); return; } const Json::Value& value = *(ttp.json_value); ProcessTracker* procs = context_->process_tracker.get(); TraceStorage* storage = context_->storage.get(); SliceTracker* slice_tracker = context_->slice_tracker.get(); auto& ph = value["ph"]; if (!ph.isString()) return; char phase = *ph.asCString(); base::Optional<uint32_t> opt_pid; base::Optional<uint32_t> opt_tid; if (value.isMember("pid")) opt_pid = json::CoerceToUint32(value["pid"]); if (value.isMember("tid")) opt_tid = json::CoerceToUint32(value["tid"]); uint32_t pid = opt_pid.value_or(0); uint32_t tid = opt_tid.value_or(pid); base::StringView cat = value.isMember("cat") ? base::StringView(value["cat"].asCString()) : base::StringView(); base::StringView name = value.isMember("name") ? base::StringView(value["name"].asCString()) : base::StringView(); StringId cat_id = storage->InternString(cat); StringId name_id = storage->InternString(name); UniqueTid utid = procs->UpdateThread(tid, pid); auto args_inserter = [this, &value](ArgsTracker::BoundInserter* inserter) { if (value.isMember("args")) { json::AddJsonValueToArgs(value["args"], /* flat_key = */ "args", /* key = */ "args", context_->storage.get(), inserter); } }; switch (phase) { case 'B': { // TRACE_EVENT_BEGIN. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Begin(timestamp, track_id, cat_id, name_id, args_inserter); break; } case 'E': { // TRACE_EVENT_END. TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->End(timestamp, track_id, cat_id, name_id, args_inserter); break; } case 'X': { // TRACE_EVENT (scoped event). base::Optional<int64_t> opt_dur = JsonTracker::GetOrCreate(context_)->CoerceToTs(value["dur"]); if (!opt_dur.has_value()) return; TrackId track_id = context_->track_tracker->InternThreadTrack(utid); slice_tracker->Scoped(timestamp, track_id, cat_id, name_id, opt_dur.value(), args_inserter); break; } case 'M': { // Metadata events (process and thread names). if (strcmp(value["name"].asCString(), "thread_name") == 0 && !value["args"]["name"].empty()) { const char* thread_name = value["args"]["name"].asCString(); auto thread_name_id = context_->storage->InternString(thread_name); procs->UpdateThreadName(tid, thread_name_id); break; } if (strcmp(value["name"].asCString(), "process_name") == 0 && !value["args"]["name"].empty()) { const char* proc_name = value["args"]["name"].asCString(); procs->SetProcessMetadata(pid, base::nullopt, proc_name); break; } } } #else perfetto::base::ignore_result(timestamp); perfetto::base::ignore_result(ttp); perfetto::base::ignore_result(context_); PERFETTO_ELOG("Cannot parse JSON trace due to missing JSON support"); #endif // PERFETTO_BUILDFLAG(PERFETTO_TP_JSON) } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP #include <type_traits> #include "meta_list.hpp" #include "utils.hpp" #include "traits.hpp" #include "injected.hpp" namespace kgr { struct Container; template<typename T, T t> using Method = std::integral_constant<T, t>; template<typename M, typename... Ps> struct Invoke : M { using Parameters = detail::meta_list<Ps...>; }; template<template<typename> class M, typename... Ts> struct AutoCall { using Autocall = detail::meta_list<Ts...>; template<typename T> using Map = M<T>; }; template<typename... Ts> struct AutoCallNoMap { using Autocall = detail::meta_list<Ts...>; }; namespace detail { template<typename, typename = void> struct has_map_entry : std::false_type {}; template<typename P> struct has_map_entry<P, void_t<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>> : std::true_type {}; template<typename P> struct has_map_entry<P, void_t<decltype(service_map(std::declval<P>()))>> : std::true_type {}; template<typename, typename = void> struct AdlMapHelper {}; template<typename Parameter> struct AdlMapHelper<Parameter, detail::enable_if_t<detail::has_map_entry<Parameter>::value>> { private: template<typename P> // The space is needed on the next line for visual studio. static auto map(int) -> decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >())); template<typename P> static auto map(...) -> decltype(service_map(std::declval<P>())); public: using Service = decltype(map<Parameter>(0)); }; } // namespace detail template<typename P> struct AdlMap : detail::AdlMapHelper<P> {}; } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP <commit_msg>added autocall traits<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP #include <type_traits> #include "meta_list.hpp" #include "utils.hpp" #include "traits.hpp" #include "injected.hpp" namespace kgr { struct Container; template<typename T, T t> using Method = std::integral_constant<T, t>; template<typename M, typename... Ps> struct Invoke : M { using Parameters = detail::meta_list<Ps...>; }; template<template<typename> class M, typename... Ts> struct AutoCall { using Autocall = detail::meta_list<Ts...>; template<typename T> using Map = M<T>; }; template<typename... Ts> struct AutoCallNoMap { using Autocall = detail::meta_list<Ts...>; }; namespace detail { template<typename T, typename F> struct autocall_function { private: template<typename U, typename C> struct get_member_autocall { using type = std::integral_constant< decltype(&U::template autocall<C, U::template Map>), &U::template autocall<C, U::template Map> >; }; template<typename U, typename C, std::size_t... S> struct get_invoke_autocall { using type = std::integral_constant< decltype(&U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...>), &U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...> >; }; template<typename U, typename C, std::size_t... S> static get_invoke_autocall<U, C, S...> test_helper(seq<S...>); template<typename U, typename C, enable_if_t<is_invoke_call<C>::value, int> = 0> static decltype(test_helper<U, C>(tuple_seq<typename C::Parameters>{})) test(); template<typename U, typename C, enable_if_t<is_member_autocall<U, C>::value, int> = 0> static get_member_autocall<U, C> test(); using inner_type = decltype(test<T, F>()); public: using type = typename inner_type::type; }; template<typename, typename, typename = void> struct autocall_arguments; template<typename T, typename F> struct autocall_arguments<T, F, enable_if_t<is_invoke_call<F>::value>> { using type = typename F::Parameters; }; template<typename T, typename F> struct autocall_arguments<T, F, enable_if_t<is_member_autocall<T, F>::value>> { private: template<template<typename> class Map> struct mapped_type { template<typename U> using map = service_map_t<Map, U>; }; public: using type = meta_list_transform_t<function_arguments_t<typename F::value_type>, mapped_type<T::template Map>::template map>; }; template<typename T, typename F> using autocall_function_t = typename autocall_function<T, F>::type; template<typename T, typename F> using autocall_arguments_t = typename autocall_arguments<T, F>::type; template<typename T, typename F> using is_valid_autocall_function = std::integral_constant<bool, is_invoke_call<F>::value || is_member_autocall<T, F>::value >; template<typename, typename = void> struct has_map_entry : std::false_type {}; template<typename P> struct has_map_entry<P, void_t<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>> : std::true_type {}; template<typename P> struct has_map_entry<P, void_t<decltype(service_map(std::declval<P>()))>> : std::true_type {}; template<typename, typename = void> struct AdlMapHelper {}; template<typename Parameter> struct AdlMapHelper<Parameter, detail::enable_if_t<detail::has_map_entry<Parameter>::value>> { private: template<typename P> // The space is needed on the next line for visual studio. static auto map(int) -> decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >())); template<typename P> static auto map(...) -> decltype(service_map(std::declval<P>())); public: using Service = decltype(map<Parameter>(0)); }; } // namespace detail template<typename P> struct AdlMap : detail::AdlMapHelper<P> {}; } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP <|endoftext|>
<commit_before>#include "videosourcefactory.h" #include "videotargetfactory.h" #include "except.h" #include "iobservable.h" #include "gil.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> #ifdef USE_NUMPY #include <boost/python/numpy.hpp> #endif using namespace boost::python; class VideoFrameNumPyWrapper : public gg::VideoFrame, public wrapper<gg::VideoFrame> { public: //! //! \brief //! \param rhs //! VideoFrameNumPyWrapper(const gg::VideoFrame & rhs) : gg::VideoFrame(rhs) { // nop } //! //! \brief //! \param colour //! \param cols //! \param rows //! VideoFrameNumPyWrapper(enum gg::ColourSpace colour, size_t cols, size_t rows) : gg::VideoFrame(colour, cols, rows) { // nop } //! //! \brief //! \param colour //! \param manage_data //! VideoFrameNumPyWrapper(enum gg::ColourSpace colour, bool manage_data) : gg::VideoFrame(colour, manage_data) { // nop } #ifdef USE_NUMPY //! //! \brief Create a NumPy array referencing gg::VideoFrame::data() //! \return //! boost::python::numpy::ndarray data_as_ndarray() { return boost::python::numpy::from_data( this->data(), boost::python::numpy::dtype::get_builtin<uint8_t>(), // shape boost::python::make_tuple(data_length()), // stride, i.e. 1 byte to go to next entry in this case boost::python::make_tuple(sizeof(uint8_t)), // owner (dangerous to pass None) boost::python::object() ); } #endif }; class IObservableWrapper : public gg::IObservable, public wrapper<gg::IObservable> { public: void attach(gg::IObserver & observer) { if (override f = this->get_override("attach")) f(boost::ref(observer)); else gg::IObservable::attach(boost::ref(observer)); } void default_attach(gg::IObserver & observer) { gg::IObservable::attach(boost::ref(observer)); } void detach(gg::IObserver & observer) { if (override f = this->get_override("detach")) f(boost::ref(observer)); else gg::IObservable::detach(boost::ref(observer)); } void default_detach(gg::IObserver & observer) { gg::IObservable::detach(boost::ref(observer)); } }; class IVideoSourceWrapper : public IVideoSource, public wrapper<IVideoSource> { public: bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(gg::VideoFrame & frame) { return this->get_override("get_frame")(frame); } double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; /* The inheritance should be public, in order to preserve * the public accessibility of the update() method. The * Boost.Python examples feature struct's rather than * classes, and in struct's everything is public by * definition. */ class IObserverWrapper : public gg::IObserver, public wrapper<gg::IObserver> { public: IObserverWrapper() { /* Default constructor that needs to be called within * child Python class, e.g. super(Child, self).__init__() * This is normally generated by the compiler * automatically, but we define it here explicitly so * that it can serve as an example for this complex case. */ } void update(gg::VideoFrame & frame) { gg::ScopedPythonGILLock gil_lock; this->get_override("update")(boost::ref(frame)); } }; class IVideoTargetWrapper : public gg::IVideoTarget, public wrapper<gg::IVideoTarget> { public: void append(const gg::VideoFrame & frame) { this->get_override("append")(frame); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceAlreadyConnected(gg::DeviceAlreadyConnected const & e) { std::string msg; msg.append("DeviceAlreadyConnected: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_ObserverError(gg::ObserverError const & e) { std::string msg; msg.append("ObserverError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { PyEval_InitThreads(); #ifdef USE_NUMPY boost::python::numpy::initialize(); #endif register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceAlreadyConnected>(&translate_DeviceAlreadyConnected); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); register_exception_translator<gg::ObserverError>(&translate_ObserverError); enum_<gg::ColourSpace>("ColourSpace") .value("BGRA", gg::ColourSpace::BGRA) .value("I420", gg::ColourSpace::I420) ; enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Codec>("Codec") .value("HEVC", gg::Codec::HEVC) .value("Xvid", gg::Codec::Xvid) .value("VP9", gg::Codec::VP9) ; class_<VideoFrameNumPyWrapper>("VideoFrame", init<enum gg::ColourSpace, bool>()) .def(init<enum gg::ColourSpace, const size_t, const size_t>()) .def("rows", &VideoFrameNumPyWrapper::rows) .def("cols", &VideoFrameNumPyWrapper::cols) .def("data_length", &VideoFrameNumPyWrapper::data_length) #ifdef USE_NUMPY .def("data", &VideoFrameNumPyWrapper::data_as_ndarray) #endif ; class_<IObservableWrapper, boost::noncopyable>("IObservable", no_init) .def("attach", &IObservableWrapper::attach) .def("detach", &IObservableWrapper::detach) ; class_<IVideoSource, bases<gg::IObservable>, boost::noncopyable>( "IVideoSource", no_init) ; #ifdef USE_OPENCV class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", &VideoSourceOpenCV::get_frame) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif // USE_OPENCV #ifdef USE_EPIPHANSDK class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", &gg::VideoSourceEpiphanSDK::get_frame) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif #ifdef USE_LIBVLC class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>( "VideoSourceVLC", init<const std::string>()) .def("get_frame", &gg::VideoSourceVLC::get_frame) .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame) .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif class_<IObserverWrapper, boost::noncopyable>("IObserver") .def("update", pure_virtual(&gg::IObserver::update)) ; class_<gg::IVideoTarget, bases<gg::IObserver>, boost::noncopyable>( "IVideoTarget", no_init) .def("update", &gg::IVideoTarget::update) ; #ifdef USE_FFMPEG class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string, std::string, float>()) .def("append", &gg::VideoTargetFFmpeg::append) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string, std::string, float>()) .def("append", &gg::VideoTargetOpenCV::append) ; #endif // USE_OPENCV class_<gg::VideoSourceFactory, boost::noncopyable>("VideoSourceFactory", no_init) .def("get_device", &gg::VideoSourceFactory::get_device /* Keep returned pointer (0) alive as long as factory (1) alive. * Boost.Python documentation says reference_existing_object is * dangerous, but apparently only when no additional lifetime * management with a call policy is provided (for details, see: * http://www.boost.org/doc/libs/1_39_0/libs/python/doc/v2/reference_existing_object.html * ). */ , return_value_policy<reference_existing_object, with_custodian_and_ward_postcall<1, 0> >() ) .def("free_device", &gg::VideoSourceFactory::free_device) .def("get_instance", &gg::VideoSourceFactory::get_instance , return_value_policy<reference_existing_object>() ) .staticmethod("get_instance") ; class_<gg::VideoTargetFactory, boost::noncopyable>("VideoTargetFactory", no_init) .def("create_file_writer", &gg::VideoTargetFactory::create_file_writer, /* We use manage_new_object here in order * to give ownership is to client. Also * this ensures that the newly created * object will be destroyed as part of the * Python object destruction procedure. See * https://wiki.python.org/moin/boost.python/CallPolicy#manage_new_object */ return_value_policy<manage_new_object>() ) .def("get_instance", &gg::VideoTargetFactory::get_instance , return_value_policy<reference_existing_object>() ) .staticmethod("get_instance") ; } <commit_msg>Issue #132: VideoFrameNumPyWrapper: added verbose documentation and revised for readability<commit_after>#include "videosourcefactory.h" #include "videotargetfactory.h" #include "except.h" #include "iobservable.h" #include "gil.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> #ifdef USE_NUMPY #include <boost/python/numpy.hpp> #endif using namespace boost::python; class VideoFrameNumPyWrapper : public gg::VideoFrame, public wrapper<gg::VideoFrame> { public: //! //! \brief Copy constructor needs to be defined //! here as well for compatibility with exposed //! interface //! \param rhs //! VideoFrameNumPyWrapper(const gg::VideoFrame & rhs) : gg::VideoFrame(rhs) { // nop } //! //! \brief This constructor needs to be defined //! here as well for compatibility with exposed //! interface //! \param colour //! \param cols //! \param rows //! VideoFrameNumPyWrapper(enum gg::ColourSpace colour, size_t cols, size_t rows) : gg::VideoFrame(colour, cols, rows) { // nop } //! //! \brief This constructor needs to be defined //! here as well for compatibility with exposed //! interface //! \param colour //! \param manage_data //! VideoFrameNumPyWrapper(enum gg::ColourSpace colour, bool manage_data) : gg::VideoFrame(colour, manage_data) { // nop } #ifdef USE_NUMPY //! //! \brief Create a NumPy array referencing gg::VideoFrame::data() //! \return //! boost::python::numpy::ndarray data_as_ndarray() { return boost::python::numpy::from_data( this->data(), boost::python::numpy::dtype::get_builtin<uint8_t>(), // shape boost::python::make_tuple(data_length()), // stride, i.e. 1 byte to go to next entry in this case boost::python::make_tuple(sizeof(uint8_t)), // owner (dangerous to pass None) boost::python::object() ); } #endif }; class IObservableWrapper : public gg::IObservable, public wrapper<gg::IObservable> { public: void attach(gg::IObserver & observer) { if (override f = this->get_override("attach")) f(boost::ref(observer)); else gg::IObservable::attach(boost::ref(observer)); } void default_attach(gg::IObserver & observer) { gg::IObservable::attach(boost::ref(observer)); } void detach(gg::IObserver & observer) { if (override f = this->get_override("detach")) f(boost::ref(observer)); else gg::IObservable::detach(boost::ref(observer)); } void default_detach(gg::IObserver & observer) { gg::IObservable::detach(boost::ref(observer)); } }; class IVideoSourceWrapper : public IVideoSource, public wrapper<IVideoSource> { public: bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(gg::VideoFrame & frame) { return this->get_override("get_frame")(frame); } double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; /* The inheritance should be public, in order to preserve * the public accessibility of the update() method. The * Boost.Python examples feature struct's rather than * classes, and in struct's everything is public by * definition. */ class IObserverWrapper : public gg::IObserver, public wrapper<gg::IObserver> { public: IObserverWrapper() { /* Default constructor that needs to be called within * child Python class, e.g. super(Child, self).__init__() * This is normally generated by the compiler * automatically, but we define it here explicitly so * that it can serve as an example for this complex case. */ } void update(gg::VideoFrame & frame) { gg::ScopedPythonGILLock gil_lock; this->get_override("update")(boost::ref(frame)); } }; class IVideoTargetWrapper : public gg::IVideoTarget, public wrapper<gg::IVideoTarget> { public: void append(const gg::VideoFrame & frame) { this->get_override("append")(frame); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceAlreadyConnected(gg::DeviceAlreadyConnected const & e) { std::string msg; msg.append("DeviceAlreadyConnected: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_ObserverError(gg::ObserverError const & e) { std::string msg; msg.append("ObserverError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { PyEval_InitThreads(); #ifdef USE_NUMPY boost::python::numpy::initialize(); #endif register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceAlreadyConnected>(&translate_DeviceAlreadyConnected); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); register_exception_translator<gg::ObserverError>(&translate_ObserverError); enum_<gg::ColourSpace>("ColourSpace") .value("BGRA", gg::ColourSpace::BGRA) .value("I420", gg::ColourSpace::I420) ; enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Codec>("Codec") .value("HEVC", gg::Codec::HEVC) .value("Xvid", gg::Codec::Xvid) .value("VP9", gg::Codec::VP9) ; class_<VideoFrameNumPyWrapper>("VideoFrame", init<enum gg::ColourSpace, bool>()) .def(init<enum gg::ColourSpace, const size_t, const size_t>()) .def("rows", &VideoFrameNumPyWrapper::rows) .def("cols", &VideoFrameNumPyWrapper::cols) .def("data_length", &VideoFrameNumPyWrapper::data_length) #ifdef USE_NUMPY .def("data", &VideoFrameNumPyWrapper::data_as_ndarray) #endif ; class_<IObservableWrapper, boost::noncopyable>("IObservable", no_init) .def("attach", &IObservableWrapper::attach) .def("detach", &IObservableWrapper::detach) ; class_<IVideoSource, bases<gg::IObservable>, boost::noncopyable>( "IVideoSource", no_init) ; #ifdef USE_OPENCV class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", &VideoSourceOpenCV::get_frame) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif // USE_OPENCV #ifdef USE_EPIPHANSDK class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", &gg::VideoSourceEpiphanSDK::get_frame) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif #ifdef USE_LIBVLC class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>( "VideoSourceVLC", init<const std::string>()) .def("get_frame", &gg::VideoSourceVLC::get_frame) .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame) .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame) .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach) .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach) ; #endif class_<IObserverWrapper, boost::noncopyable>("IObserver") .def("update", pure_virtual(&gg::IObserver::update)) ; class_<gg::IVideoTarget, bases<gg::IObserver>, boost::noncopyable>( "IVideoTarget", no_init) .def("update", &gg::IVideoTarget::update) ; #ifdef USE_FFMPEG class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string, std::string, float>()) .def("append", &gg::VideoTargetFFmpeg::append) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string, std::string, float>()) .def("append", &gg::VideoTargetOpenCV::append) ; #endif // USE_OPENCV class_<gg::VideoSourceFactory, boost::noncopyable>("VideoSourceFactory", no_init) .def("get_device", &gg::VideoSourceFactory::get_device /* Keep returned pointer (0) alive as long as factory (1) alive. * Boost.Python documentation says reference_existing_object is * dangerous, but apparently only when no additional lifetime * management with a call policy is provided (for details, see: * http://www.boost.org/doc/libs/1_39_0/libs/python/doc/v2/reference_existing_object.html * ). */ , return_value_policy<reference_existing_object, with_custodian_and_ward_postcall<1, 0> >() ) .def("free_device", &gg::VideoSourceFactory::free_device) .def("get_instance", &gg::VideoSourceFactory::get_instance , return_value_policy<reference_existing_object>() ) .staticmethod("get_instance") ; class_<gg::VideoTargetFactory, boost::noncopyable>("VideoTargetFactory", no_init) .def("create_file_writer", &gg::VideoTargetFactory::create_file_writer, /* We use manage_new_object here in order * to give ownership is to client. Also * this ensures that the newly created * object will be destroyed as part of the * Python object destruction procedure. See * https://wiki.python.org/moin/boost.python/CallPolicy#manage_new_object */ return_value_policy<manage_new_object>() ) .def("get_instance", &gg::VideoTargetFactory::get_instance , return_value_policy<reference_existing_object>() ) .staticmethod("get_instance") ; } <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP #include "traits.hpp" #include "meta_list.hpp" namespace kgr { struct single { single() = default; ~single() = default; single(const single&) = delete; single& operator=(const single&) = delete; single(single&&) = default; single& operator=(single&&) = default; }; struct polymorphic {}; struct final {}; struct supplied : single {}; struct abstract : polymorphic, single {}; template<typename T> struct defaults_to { using default_service = T; }; template<typename... Types> struct overrides { using parent_types = detail::meta_list<Types...>; }; namespace detail { template<typename, typename = void> struct parent_type_helper { using parent_types = meta_list<>; }; template<typename T> struct parent_type_helper<T, void_t<typename T::parent_types>> { using parent_types = typename T::parent_types; }; template<typename T> using parent_types = typename parent_type_helper<T>::parent_types; template<typename, typename = void> struct default_type_helper { using has_default = std::false_type; }; template<typename T> struct default_type_helper<T, void_t<typename T::default_service>> { using has_default = std::true_type; using service = typename T::default_service; }; template<typename T> using default_type = typename default_type_helper<T>::service; template<typename T> using has_default = typename default_type_helper<T>::has_default; template<typename T> using is_abstract_service = std::is_base_of<abstract, T>; template<typename T> using is_single = std::is_base_of<single, T>; template<typename T> using is_supplied_service = std::is_base_of<supplied, T>; template<typename T> using is_final_service = std::is_base_of<final, T>; template<typename T> using is_polymorphic = std::integral_constant<bool, std::is_base_of<polymorphic, T>::value || !meta_list_empty<parent_types<T>>::value>; template<typename Service, typename Overrider> using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP <commit_msg>Supplied no longer implicitly make a service single<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP #include "traits.hpp" #include "meta_list.hpp" namespace kgr { struct single { single() = default; ~single() = default; single(const single&) = delete; single& operator=(const single&) = delete; single(single&&) = default; single& operator=(single&&) = default; }; struct polymorphic {}; struct final {}; struct supplied {}; struct abstract : polymorphic, single {}; template<typename T> struct defaults_to { using default_service = T; }; template<typename... Types> struct overrides { using parent_types = detail::meta_list<Types...>; }; namespace detail { template<typename, typename = void> struct parent_type_helper { using parent_types = meta_list<>; }; template<typename T> struct parent_type_helper<T, void_t<typename T::parent_types>> { using parent_types = typename T::parent_types; }; template<typename T> using parent_types = typename parent_type_helper<T>::parent_types; template<typename, typename = void> struct default_type_helper { using has_default = std::false_type; }; template<typename T> struct default_type_helper<T, void_t<typename T::default_service>> { using has_default = std::true_type; using service = typename T::default_service; }; template<typename T> using default_type = typename default_type_helper<T>::service; template<typename T> using has_default = typename default_type_helper<T>::has_default; template<typename T> using is_abstract_service = std::is_base_of<abstract, T>; template<typename T> using is_single = std::is_base_of<single, T>; template<typename T> using is_supplied_service = std::is_base_of<supplied, T>; template<typename T> using is_final_service = std::is_base_of<final, T>; template<typename T> using is_polymorphic = std::integral_constant<bool, std::is_base_of<polymorphic, T>::value || !meta_list_empty<parent_types<T>>::value>; template<typename Service, typename Overrider> using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/object_life_monitor.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #include "v8/include/v8-profiler.h" namespace { v8::Local<v8::Object> CreateObjectWithName(v8::Isolate* isolate, v8::Local<v8::String> name) { v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate); t->SetClassName(name); return t->GetFunction()->NewInstance(); } v8::Local<v8::Value> GetHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key) { return object->GetHiddenValue(key); } void SetHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { object->SetHiddenValue(key, value); } void DeleteHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key) { object->DeleteHiddenValue(key); } int32_t GetObjectHash(v8::Local<v8::Object> object) { return object->GetIdentityHash(); } void SetDestructor(v8::Isolate* isolate, v8::Local<v8::Object> object, v8::Local<v8::Function> callback) { atom::ObjectLifeMonitor::BindTo(isolate, object, callback); } void TakeHeapSnapshot(v8::Isolate* isolate) { isolate->GetHeapProfiler()->TakeHeapSnapshot(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createObjectWithName", &CreateObjectWithName); dict.SetMethod("getHiddenValue", &GetHiddenValue); dict.SetMethod("setHiddenValue", &SetHiddenValue); dict.SetMethod("deleteHiddenValue", &DeleteHiddenValue); dict.SetMethod("getObjectHash", &GetObjectHash); dict.SetMethod("setDestructor", &SetDestructor); dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_v8_util, Initialize) <commit_msg>Optimize the case when creating plain object<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/object_life_monitor.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #include "v8/include/v8-profiler.h" namespace { v8::Local<v8::Object> CreateObjectWithName(v8::Isolate* isolate, const std::string& name) { if (name == "Object") return v8::Object::New(isolate); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate); t->SetClassName(mate::StringToV8(isolate, name)); return t->GetFunction()->NewInstance(); } v8::Local<v8::Value> GetHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key) { return object->GetHiddenValue(key); } void SetHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { object->SetHiddenValue(key, value); } void DeleteHiddenValue(v8::Local<v8::Object> object, v8::Local<v8::String> key) { object->DeleteHiddenValue(key); } int32_t GetObjectHash(v8::Local<v8::Object> object) { return object->GetIdentityHash(); } void SetDestructor(v8::Isolate* isolate, v8::Local<v8::Object> object, v8::Local<v8::Function> callback) { atom::ObjectLifeMonitor::BindTo(isolate, object, callback); } void TakeHeapSnapshot(v8::Isolate* isolate) { isolate->GetHeapProfiler()->TakeHeapSnapshot(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createObjectWithName", &CreateObjectWithName); dict.SetMethod("getHiddenValue", &GetHiddenValue); dict.SetMethod("setHiddenValue", &SetHiddenValue); dict.SetMethod("deleteHiddenValue", &DeleteHiddenValue); dict.SetMethod("getObjectHash", &GetObjectHash); dict.SetMethod("setDestructor", &SetDestructor); dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_v8_util, Initialize) <|endoftext|>
<commit_before>#include <gst/gst.h> #include "MediaPipeline.hpp" #include <WebRtcEndpointImplFactory.hpp> #include "WebRtcEndpointImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <boost/filesystem.hpp> #include <IceCandidate.hpp> #include <webrtcendpoint/kmsicecandidate.h> #include <IceComponentState.hpp> #include <SignalHandler.hpp> #define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl" #define FACTORY_NAME "webrtcendpoint" namespace kurento { static const uint DEFAULT_STUN_PORT = 3478; static const gchar *supported_codecs[] = { "VP8", "opus", "PCMU" }; static void remove_not_supported_codecs_from_array (GstElement *element, GArray *codecs) { guint i; if (codecs == NULL) { return; } for (i = 0; i < codecs->len; i++) { GValue *v = &g_array_index (codecs, GValue, i); const GstStructure *s; const gchar *codec_name; gboolean supported = FALSE; guint j; if (!GST_VALUE_HOLDS_STRUCTURE (v) ) { GST_WARNING_OBJECT (element, "Value into array is not a GstStructure"); continue; } s = gst_value_get_structure (v); codec_name = gst_structure_get_name (s); for (j = 0; j < G_N_ELEMENTS (supported_codecs); j++) { if (g_str_has_prefix (codec_name, supported_codecs[j]) ) { supported = TRUE; break; } } if (!supported) { GST_INFO_OBJECT (element, "Removing not supported codec '%s'", codec_name); g_array_remove_index (codecs, i); i--; } } } static void remove_not_supported_codecs (GstElement *element) { GArray *codecs; g_object_get (element, "audio-codecs", &codecs, NULL); remove_not_supported_codecs_from_array (element, codecs); g_object_get (element, "video-codecs", &codecs, NULL); remove_not_supported_codecs_from_array (element, codecs); } void WebRtcEndpointImpl::onIceCandidate (KmsIceCandidate *candidate) { try { std::string cand_str (kms_ice_candidate_get_candidate (candidate) ); std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) ); int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate); std::shared_ptr <IceCandidate> cand ( new IceCandidate (cand_str, mid_str, sdp_m_line_index) ); OnIceCandidate event (shared_from_this(), OnIceCandidate::getName(), cand); signalOnIceCandidate (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::onIceGatheringDone () { try { OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() ); signalOnIceGatheringDone (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::onIceComponentStateChanged (guint streamId, guint componentId, guint state) { try { IceComponentState::type type; switch (state) { case NICE_COMPONENT_STATE_DISCONNECTED: type = IceComponentState::DISCONNECTED; break; case NICE_COMPONENT_STATE_GATHERING: type = IceComponentState::GATHERING; break; case NICE_COMPONENT_STATE_CONNECTING: type = IceComponentState::CONNECTING; break; case NICE_COMPONENT_STATE_CONNECTED: type = IceComponentState::CONNECTED; break; case NICE_COMPONENT_STATE_READY: type = IceComponentState::READY; break; case NICE_COMPONENT_STATE_FAILED: type = IceComponentState::FAILED; break; default: type = IceComponentState::FAILED; break; } IceComponentState *componentState = new IceComponentState (type); OnIceComponentStateChanged event (shared_from_this(), OnIceComponentStateChanged::getName(), streamId, componentId, std::shared_ptr<IceComponentState> (componentState) ); signalOnIceComponentStateChanged (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::postConstructor () { BaseRtpEndpointImpl::postConstructor (); handlerOnIceCandidate = register_signal_handler (G_OBJECT (element), "on-ice-candidate", std::function <void (GstElement *, KmsIceCandidate *) > (std::bind (&WebRtcEndpointImpl::onIceCandidate, this, std::placeholders::_2) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); handlerOnIceGatheringDone = register_signal_handler (G_OBJECT (element), "on-ice-gathering-done", std::function <void (GstElement *) > (std::bind (&WebRtcEndpointImpl::onIceGatheringDone, this) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); handlerOnIceComponentStateChanged = register_signal_handler (G_OBJECT (element), "on-ice-component-state-changed", std::function <void (GstElement *, guint, guint, guint) > (std::bind (&WebRtcEndpointImpl::onIceComponentStateChanged, this, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); } WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) : BaseRtpEndpointImpl (conf, std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME) { uint stunPort; std::string stunAddress; std::string turnURL; remove_not_supported_codecs (element); //set properties try { stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Setting default port %d to stun server", DEFAULT_STUN_PORT); stunPort = DEFAULT_STUN_PORT; } if (stunPort != 0) { try { stunAddress = getConfigValue <std::string, WebRtcEndpoint> ("stunServerAddress"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Stun address not found in config, cannot operate behind a NAT" ); } if (!stunAddress.empty() ) { GST_INFO ("stun port %d\n", stunPort ); g_object_set ( G_OBJECT (element), "stun-server-port", stunPort, NULL); GST_INFO ("stun address %s\n", stunAddress.c_str() ); g_object_set ( G_OBJECT (element), "stun-server", stunAddress.c_str(), NULL); } } try { turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL"); GST_INFO ("turn info: %s\n", turnURL.c_str() ); g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(), NULL); } catch (boost::property_tree::ptree_error &e) { } } WebRtcEndpointImpl::~WebRtcEndpointImpl() { if (handlerOnIceCandidate > 0) { unregister_signal_handler (element, handlerOnIceCandidate); } if (handlerOnIceGatheringDone > 0) { unregister_signal_handler (element, handlerOnIceGatheringDone); } if (handlerOnIceComponentStateChanged > 0) { unregister_signal_handler (element, handlerOnIceComponentStateChanged); } } std::string WebRtcEndpointImpl::getStunServerAddress () { gchar *ret; g_object_get ( G_OBJECT (element), "stun-server", &ret, NULL); std::string stunServerAddress (ret); g_free (ret); return stunServerAddress; } void WebRtcEndpointImpl::setStunServerAddress (const std::string &stunServerAddress) { g_object_set ( G_OBJECT (element), "stun-server", stunServerAddress.c_str(), NULL); } int WebRtcEndpointImpl::getStunServerPort () { int ret; g_object_get ( G_OBJECT (element), "stun-server-port", &ret, NULL); return ret; } void WebRtcEndpointImpl::setStunServerPort (int stunServerPort) { g_object_set ( G_OBJECT (element), "stun-server-port", stunServerPort, NULL); } std::string WebRtcEndpointImpl::getTurnUrl () { gchar *ret; g_object_get ( G_OBJECT (element), "turn-url", &ret, NULL); std::string turnUrl (ret); g_free (ret); return turnUrl; } void WebRtcEndpointImpl::setTurnUrl (const std::string &turnUrl) { g_object_set ( G_OBJECT (element), "turn-url", turnUrl.c_str(), NULL); } void WebRtcEndpointImpl::gatherCandidates () { gboolean ret; g_signal_emit_by_name (element, "gather-candidates", &ret); if (!ret) { throw KurentoException (ICE_GATHER_CANDIDATES_ERROR, "Error gathering candidates"); } } void WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate) { gboolean ret; const char *cand_str = candidate->getCandidate().c_str (); const char *mid_str = candidate->getSdpMid().c_str (); guint8 sdp_m_line_index = candidate->getSdpMLineIndex (); KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str, sdp_m_line_index); g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret); g_object_unref (cand); if (!ret) { throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate"); } } MediaObjectImpl * WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) const { return new WebRtcEndpointImpl (conf, mediaPipeline); } WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor; WebRtcEndpointImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <commit_msg>WebRtcEndpointImpl: Fix memory leaks in codec garrays<commit_after>#include <gst/gst.h> #include "MediaPipeline.hpp" #include <WebRtcEndpointImplFactory.hpp> #include "WebRtcEndpointImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <boost/filesystem.hpp> #include <IceCandidate.hpp> #include <webrtcendpoint/kmsicecandidate.h> #include <IceComponentState.hpp> #include <SignalHandler.hpp> #define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl" #define FACTORY_NAME "webrtcendpoint" namespace kurento { static const uint DEFAULT_STUN_PORT = 3478; static const gchar *supported_codecs[] = { "VP8", "opus", "PCMU" }; static void remove_not_supported_codecs_from_array (GstElement *element, GArray *codecs) { guint i; if (codecs == NULL) { return; } for (i = 0; i < codecs->len; i++) { GValue *v = &g_array_index (codecs, GValue, i); const GstStructure *s; const gchar *codec_name; gboolean supported = FALSE; guint j; if (!GST_VALUE_HOLDS_STRUCTURE (v) ) { GST_WARNING_OBJECT (element, "Value into array is not a GstStructure"); continue; } s = gst_value_get_structure (v); codec_name = gst_structure_get_name (s); for (j = 0; j < G_N_ELEMENTS (supported_codecs); j++) { if (g_str_has_prefix (codec_name, supported_codecs[j]) ) { supported = TRUE; break; } } if (!supported) { GST_INFO_OBJECT (element, "Removing not supported codec '%s'", codec_name); g_array_remove_index (codecs, i); i--; } } } static void remove_not_supported_codecs (GstElement *element) { GArray *codecs; g_object_get (element, "audio-codecs", &codecs, NULL); remove_not_supported_codecs_from_array (element, codecs); g_array_unref (codecs); g_object_get (element, "video-codecs", &codecs, NULL); remove_not_supported_codecs_from_array (element, codecs); g_array_unref (codecs); } void WebRtcEndpointImpl::onIceCandidate (KmsIceCandidate *candidate) { try { std::string cand_str (kms_ice_candidate_get_candidate (candidate) ); std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) ); int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate); std::shared_ptr <IceCandidate> cand ( new IceCandidate (cand_str, mid_str, sdp_m_line_index) ); OnIceCandidate event (shared_from_this(), OnIceCandidate::getName(), cand); signalOnIceCandidate (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::onIceGatheringDone () { try { OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() ); signalOnIceGatheringDone (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::onIceComponentStateChanged (guint streamId, guint componentId, guint state) { try { IceComponentState::type type; switch (state) { case NICE_COMPONENT_STATE_DISCONNECTED: type = IceComponentState::DISCONNECTED; break; case NICE_COMPONENT_STATE_GATHERING: type = IceComponentState::GATHERING; break; case NICE_COMPONENT_STATE_CONNECTING: type = IceComponentState::CONNECTING; break; case NICE_COMPONENT_STATE_CONNECTED: type = IceComponentState::CONNECTED; break; case NICE_COMPONENT_STATE_READY: type = IceComponentState::READY; break; case NICE_COMPONENT_STATE_FAILED: type = IceComponentState::FAILED; break; default: type = IceComponentState::FAILED; break; } IceComponentState *componentState = new IceComponentState (type); OnIceComponentStateChanged event (shared_from_this(), OnIceComponentStateChanged::getName(), streamId, componentId, std::shared_ptr<IceComponentState> (componentState) ); signalOnIceComponentStateChanged (event); } catch (std::bad_weak_ptr &e) { } } void WebRtcEndpointImpl::postConstructor () { BaseRtpEndpointImpl::postConstructor (); handlerOnIceCandidate = register_signal_handler (G_OBJECT (element), "on-ice-candidate", std::function <void (GstElement *, KmsIceCandidate *) > (std::bind (&WebRtcEndpointImpl::onIceCandidate, this, std::placeholders::_2) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); handlerOnIceGatheringDone = register_signal_handler (G_OBJECT (element), "on-ice-gathering-done", std::function <void (GstElement *) > (std::bind (&WebRtcEndpointImpl::onIceGatheringDone, this) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); handlerOnIceComponentStateChanged = register_signal_handler (G_OBJECT (element), "on-ice-component-state-changed", std::function <void (GstElement *, guint, guint, guint) > (std::bind (&WebRtcEndpointImpl::onIceComponentStateChanged, this, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ), std::dynamic_pointer_cast<WebRtcEndpointImpl> (shared_from_this() ) ); } WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) : BaseRtpEndpointImpl (conf, std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME) { uint stunPort; std::string stunAddress; std::string turnURL; remove_not_supported_codecs (element); //set properties try { stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Setting default port %d to stun server", DEFAULT_STUN_PORT); stunPort = DEFAULT_STUN_PORT; } if (stunPort != 0) { try { stunAddress = getConfigValue <std::string, WebRtcEndpoint> ("stunServerAddress"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Stun address not found in config, cannot operate behind a NAT" ); } if (!stunAddress.empty() ) { GST_INFO ("stun port %d\n", stunPort ); g_object_set ( G_OBJECT (element), "stun-server-port", stunPort, NULL); GST_INFO ("stun address %s\n", stunAddress.c_str() ); g_object_set ( G_OBJECT (element), "stun-server", stunAddress.c_str(), NULL); } } try { turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL"); GST_INFO ("turn info: %s\n", turnURL.c_str() ); g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(), NULL); } catch (boost::property_tree::ptree_error &e) { } } WebRtcEndpointImpl::~WebRtcEndpointImpl() { if (handlerOnIceCandidate > 0) { unregister_signal_handler (element, handlerOnIceCandidate); } if (handlerOnIceGatheringDone > 0) { unregister_signal_handler (element, handlerOnIceGatheringDone); } if (handlerOnIceComponentStateChanged > 0) { unregister_signal_handler (element, handlerOnIceComponentStateChanged); } } std::string WebRtcEndpointImpl::getStunServerAddress () { gchar *ret; g_object_get ( G_OBJECT (element), "stun-server", &ret, NULL); std::string stunServerAddress (ret); g_free (ret); return stunServerAddress; } void WebRtcEndpointImpl::setStunServerAddress (const std::string &stunServerAddress) { g_object_set ( G_OBJECT (element), "stun-server", stunServerAddress.c_str(), NULL); } int WebRtcEndpointImpl::getStunServerPort () { int ret; g_object_get ( G_OBJECT (element), "stun-server-port", &ret, NULL); return ret; } void WebRtcEndpointImpl::setStunServerPort (int stunServerPort) { g_object_set ( G_OBJECT (element), "stun-server-port", stunServerPort, NULL); } std::string WebRtcEndpointImpl::getTurnUrl () { gchar *ret; g_object_get ( G_OBJECT (element), "turn-url", &ret, NULL); std::string turnUrl (ret); g_free (ret); return turnUrl; } void WebRtcEndpointImpl::setTurnUrl (const std::string &turnUrl) { g_object_set ( G_OBJECT (element), "turn-url", turnUrl.c_str(), NULL); } void WebRtcEndpointImpl::gatherCandidates () { gboolean ret; g_signal_emit_by_name (element, "gather-candidates", &ret); if (!ret) { throw KurentoException (ICE_GATHER_CANDIDATES_ERROR, "Error gathering candidates"); } } void WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate) { gboolean ret; const char *cand_str = candidate->getCandidate().c_str (); const char *mid_str = candidate->getSdpMid().c_str (); guint8 sdp_m_line_index = candidate->getSdpMLineIndex (); KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str, sdp_m_line_index); g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret); g_object_unref (cand); if (!ret) { throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate"); } } MediaObjectImpl * WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) const { return new WebRtcEndpointImpl (conf, mediaPipeline); } WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor; WebRtcEndpointImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkFirstOrderTextureFeaturesImageFilter.h" #include "itkFlatStructuringElement.h" #include "itkAdditiveGaussianNoiseImageFilter.h" #include "itkFilterWatcher.h" #include "gtest/gtest.h" namespace { template<typename T> void print_feature( const T &p, std::ostream &out = std::cout ) { out << "mean: " << p[0] << std::endl; out << "minimum: " << p[1] << std::endl; out << "maximum: " << p[2] << std::endl; out << "variance: " << p[3] << std::endl; out << "standard deviation: " << p[4] << std::endl; out << "skewness: " << p[5] << std::endl; out << "kurtosis: " << p[6] << std::endl; out << "entropy: " << p[7] << std::endl; } } TEST(TextureFeatures, FirstOrder_Test1) { constexpr unsigned int ImageDimension = 2; using ImageType = itk::Image<float, ImageDimension >; using OImageType = itk::Image<itk::FixedArray<float,8>, ImageDimension >; using KernelType = itk::FlatStructuringElement< ImageDimension >; unsigned int r = 50u; unsigned int d = r*2 + 1; ImageType::SizeType imageSize = {{ d, d }}; ImageType::SpacingValueType imageSpacing[] = { 1.0f, 1.0f }; ImageType::Pointer image = ImageType::New(); image->SetRegions( ImageType::RegionType(imageSize) ); image->SetSpacing( imageSpacing ); image->Allocate(); image->FillBuffer(0); using ImageNoiseType = itk::AdditiveGaussianNoiseImageFilter< ImageType >; ImageNoiseType::Pointer noiseFilter = ImageNoiseType::New(); noiseFilter->SetSeed(124); noiseFilter->SetMean(0.0); noiseFilter->SetStandardDeviation(.1); noiseFilter->SetInput(image); using TextureFilterType = itk::FirstOrderTextureFeaturesImageFilter< ImageType, OImageType, KernelType >; KernelType::SizeType radius; radius.Fill( r ); KernelType kernel = KernelType::Box( radius ); TextureFilterType::Pointer filter = TextureFilterType::New(); filter->SetKernel( kernel ); filter->SetInput( noiseFilter->GetOutput() ); FilterWatcher watcher(filter, "filter"); ImageType::SizeType requestSize = {{10,10}}; ImageType::IndexType requestIndex = {{45,45}}; ImageType::RegionType request(requestIndex, requestSize); filter->GetOutput()->SetRequestedRegion( request ); filter->Update(); OImageType::ConstPointer output = filter->GetOutput(); { ImageType::IndexType idx = {{r,r}}; const OImageType::PixelType &p = output->GetPixel(idx); print_feature( p ); // The following is for a Gaussian sample with std dev of .1 // The expected value was analytically computed, while the // tolerances were estimated based on 10,000 different sample set // distributions in numpy. EXPECT_NEAR( 0.0, p[0], 0.002) << "mean"; EXPECT_GT(-.3, p[1]) << "min"; EXPECT_LT(.3, p[2]) << "max"; EXPECT_NEAR(0.01, p[3], .001) << "variance"; EXPECT_NEAR(0.1, p[4], .01) << "standard deviation"; EXPECT_NEAR(0, p[5], .1) << "skewness"; EXPECT_NEAR(0, p[6], .2) << "kurtosis"; EXPECT_NEAR(13.3, p[7], .1) << "entropy"; } } TEST(TextureFeatures, FirstOrder_Test2) { constexpr unsigned int ImageDimension = 2; using ImageType = itk::Image<float, ImageDimension >; using OImageType = itk::Image<itk::FixedArray<float,8>, ImageDimension >; using KernelType = itk::FlatStructuringElement< ImageDimension >; unsigned int r = 50u; unsigned int d = r*2 + 1; ImageType::SizeType imageSize = {{ d, d }}; ImageType::SpacingValueType imageSpacing[] = { 1.0f, 1.0f }; ImageType::Pointer image = ImageType::New(); image->SetRegions( ImageType::RegionType(imageSize) ); image->SetSpacing( imageSpacing ); image->Allocate(); image->FillBuffer(0); using ImageNoiseType = itk::AdditiveGaussianNoiseImageFilter< ImageType >; ImageNoiseType::Pointer noiseFilter = ImageNoiseType::New(); noiseFilter->SetSeed(124); noiseFilter->SetMean(100.0); noiseFilter->SetStandardDeviation(1); noiseFilter->SetInput(image); using TextureFilterType = itk::FirstOrderTextureFeaturesImageFilter< ImageType, OImageType, KernelType >; KernelType::SizeType radius; radius.Fill( r ); KernelType kernel = KernelType::Box( radius ); TextureFilterType::Pointer filter = TextureFilterType::New(); filter->SetKernel( kernel ); filter->SetInput( noiseFilter->GetOutput() ); FilterWatcher watcher(filter, "filter"); ImageType::SizeType requestSize = {{10,10}}; ImageType::IndexType requestIndex = {{45,45}}; ImageType::RegionType request(requestIndex, requestSize); filter->GetOutput()->SetRequestedRegion( request ); filter->Update(); OImageType::ConstPointer output = filter->GetOutput(); { ImageType::IndexType idx = {{r,r}}; const OImageType::PixelType &p = output->GetPixel(idx); print_feature( p ); // The following is for a Gaussian sample with std dev of .1 // The expected value was analytically computed, while the // tolerances were estimated based on 10,000 different sample set // distributions in numpy. EXPECT_NEAR( 100, p[0], 0.02) << "mean"; EXPECT_GT(97, p[1]) << "min"; EXPECT_LT(103, p[2]) << "max"; EXPECT_NEAR(1, p[3], .1) << "variance"; EXPECT_NEAR(1, p[4], .1) << "standard deviation"; EXPECT_NEAR(0, p[5], .1) << "skewness"; EXPECT_NEAR(0, p[6], .2) << "kurtosis"; EXPECT_NEAR(13.3, p[7], .2) << "entropy"; } } <commit_msg>BUG: Use itk::SimpleFilterWatcher instead of itk::FilterWatcher.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkFirstOrderTextureFeaturesImageFilter.h" #include "itkFlatStructuringElement.h" #include "itkAdditiveGaussianNoiseImageFilter.h" #include "itkSimpleFilterWatcher.h" #include "gtest/gtest.h" namespace { template<typename T> void print_feature( const T &p, std::ostream &out = std::cout ) { out << "mean: " << p[0] << std::endl; out << "minimum: " << p[1] << std::endl; out << "maximum: " << p[2] << std::endl; out << "variance: " << p[3] << std::endl; out << "standard deviation: " << p[4] << std::endl; out << "skewness: " << p[5] << std::endl; out << "kurtosis: " << p[6] << std::endl; out << "entropy: " << p[7] << std::endl; } } TEST(TextureFeatures, FirstOrder_Test1) { constexpr unsigned int ImageDimension = 2; using ImageType = itk::Image<float, ImageDimension >; using OImageType = itk::Image<itk::FixedArray<float,8>, ImageDimension >; using KernelType = itk::FlatStructuringElement< ImageDimension >; unsigned int r = 50u; unsigned int d = r*2 + 1; ImageType::SizeType imageSize = {{ d, d }}; ImageType::SpacingValueType imageSpacing[] = { 1.0f, 1.0f }; ImageType::Pointer image = ImageType::New(); image->SetRegions( ImageType::RegionType(imageSize) ); image->SetSpacing( imageSpacing ); image->Allocate(); image->FillBuffer(0); using ImageNoiseType = itk::AdditiveGaussianNoiseImageFilter< ImageType >; ImageNoiseType::Pointer noiseFilter = ImageNoiseType::New(); noiseFilter->SetSeed(124); noiseFilter->SetMean(0.0); noiseFilter->SetStandardDeviation(.1); noiseFilter->SetInput(image); using TextureFilterType = itk::FirstOrderTextureFeaturesImageFilter< ImageType, OImageType, KernelType >; KernelType::SizeType radius; radius.Fill( r ); KernelType kernel = KernelType::Box( radius ); TextureFilterType::Pointer filter = TextureFilterType::New(); filter->SetKernel( kernel ); filter->SetInput( noiseFilter->GetOutput() ); itk::SimpleFilterWatcher watcher(filter, "filter"); ImageType::SizeType requestSize = {{10,10}}; ImageType::IndexType requestIndex = {{45,45}}; ImageType::RegionType request(requestIndex, requestSize); filter->GetOutput()->SetRequestedRegion( request ); filter->Update(); OImageType::ConstPointer output = filter->GetOutput(); { ImageType::IndexType idx = {{r,r}}; const OImageType::PixelType &p = output->GetPixel(idx); print_feature( p ); // The following is for a Gaussian sample with std dev of .1 // The expected value was analytically computed, while the // tolerances were estimated based on 10,000 different sample set // distributions in numpy. EXPECT_NEAR( 0.0, p[0], 0.002) << "mean"; EXPECT_GT(-.3, p[1]) << "min"; EXPECT_LT(.3, p[2]) << "max"; EXPECT_NEAR(0.01, p[3], .001) << "variance"; EXPECT_NEAR(0.1, p[4], .01) << "standard deviation"; EXPECT_NEAR(0, p[5], .1) << "skewness"; EXPECT_NEAR(0, p[6], .2) << "kurtosis"; EXPECT_NEAR(13.3, p[7], .1) << "entropy"; } } TEST(TextureFeatures, FirstOrder_Test2) { constexpr unsigned int ImageDimension = 2; using ImageType = itk::Image<float, ImageDimension >; using OImageType = itk::Image<itk::FixedArray<float,8>, ImageDimension >; using KernelType = itk::FlatStructuringElement< ImageDimension >; unsigned int r = 50u; unsigned int d = r*2 + 1; ImageType::SizeType imageSize = {{ d, d }}; ImageType::SpacingValueType imageSpacing[] = { 1.0f, 1.0f }; ImageType::Pointer image = ImageType::New(); image->SetRegions( ImageType::RegionType(imageSize) ); image->SetSpacing( imageSpacing ); image->Allocate(); image->FillBuffer(0); using ImageNoiseType = itk::AdditiveGaussianNoiseImageFilter< ImageType >; ImageNoiseType::Pointer noiseFilter = ImageNoiseType::New(); noiseFilter->SetSeed(124); noiseFilter->SetMean(100.0); noiseFilter->SetStandardDeviation(1); noiseFilter->SetInput(image); using TextureFilterType = itk::FirstOrderTextureFeaturesImageFilter< ImageType, OImageType, KernelType >; KernelType::SizeType radius; radius.Fill( r ); KernelType kernel = KernelType::Box( radius ); TextureFilterType::Pointer filter = TextureFilterType::New(); filter->SetKernel( kernel ); filter->SetInput( noiseFilter->GetOutput() ); itk::SimpleFilterWatcher watcher(filter, "filter"); ImageType::SizeType requestSize = {{10,10}}; ImageType::IndexType requestIndex = {{45,45}}; ImageType::RegionType request(requestIndex, requestSize); filter->GetOutput()->SetRequestedRegion( request ); filter->Update(); OImageType::ConstPointer output = filter->GetOutput(); { ImageType::IndexType idx = {{r,r}}; const OImageType::PixelType &p = output->GetPixel(idx); print_feature( p ); // The following is for a Gaussian sample with std dev of .1 // The expected value was analytically computed, while the // tolerances were estimated based on 10,000 different sample set // distributions in numpy. EXPECT_NEAR( 100, p[0], 0.02) << "mean"; EXPECT_GT(97, p[1]) << "min"; EXPECT_LT(103, p[2]) << "max"; EXPECT_NEAR(1, p[3], .1) << "variance"; EXPECT_NEAR(1, p[4], .1) << "standard deviation"; EXPECT_NEAR(0, p[5], .1) << "skewness"; EXPECT_NEAR(0, p[6], .2) << "kurtosis"; EXPECT_NEAR(13.3, p[7], .2) << "entropy"; } } <|endoftext|>
<commit_before>#include "Slog.h" __declspec(dllexport) void testLibs() { printf("test lib cmake %d\n", 1); }<commit_msg>PREF c++ vscode test slibs/slog 修正 Slog.cpp<commit_after>#include "Slog.h" void testLibs() { printf("test lib cmake %d\n", 1); }<|endoftext|>
<commit_before>/*********************************************************************** created: Sun Jun 19 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/falagard/TextComponent.h" #include "CEGUI/falagard/XMLEnumHelper.h" #include "CEGUI/falagard/XMLHandler.h" #include "CEGUI/FontManager.h" #include "CEGUI/Exceptions.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/Font.h" #include "CEGUI/LeftAlignedRenderedString.h" #include "CEGUI/RightAlignedRenderedString.h" #include "CEGUI/CentredRenderedString.h" #include "CEGUI/JustifiedRenderedString.h" #include "CEGUI/RenderedStringWordWrapper.h" #include <iostream> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { TextComponent::TextComponent() : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)), d_lastHorzFormatting(HTF_LEFT_ALIGNED), d_vertFormatting(VTF_TOP_ALIGNED), d_horzFormatting(HTF_LEFT_ALIGNED) {} TextComponent::~TextComponent() { delete d_bidiVisualMapping; } TextComponent::TextComponent(const TextComponent& obj) : FalagardComponentBase(obj), d_textLogical(obj.d_textLogical), #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #endif d_bidiDataValid(false), d_renderedString(obj.d_renderedString), d_formattedRenderedString(obj.d_formattedRenderedString), d_lastHorzFormatting(obj.d_lastHorzFormatting), d_font(obj.d_font), d_vertFormatting(obj.d_vertFormatting), d_horzFormatting(obj.d_horzFormatting), d_textPropertyName(obj.d_textPropertyName), d_fontPropertyName(obj.d_fontPropertyName) { } TextComponent& TextComponent::operator=(const TextComponent& other) { if (this == &other) return *this; FalagardComponentBase::operator=(other); d_textLogical = other.d_textLogical; // note we do not assign the BidiVisualMapping object, we just mark our // existing one as invalid so it's data gets regenerated next time it's // needed. d_bidiDataValid = false; d_renderedString = other.d_renderedString; d_formattedRenderedString = other.d_formattedRenderedString; d_lastHorzFormatting = other.d_lastHorzFormatting; d_font = other.d_font; d_vertFormatting = other.d_vertFormatting; d_horzFormatting = other.d_horzFormatting; d_textPropertyName = other.d_textPropertyName; d_fontPropertyName = other.d_fontPropertyName; return *this; } const String& TextComponent::getText() const { return d_textLogical; } void TextComponent::setText(const String& text) { d_textLogical = text; d_bidiDataValid = false; } const String& TextComponent::getFont() const { return d_font; } void TextComponent::setFont(const String& font) { d_font = font; } VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const { return d_vertFormatting.get(wnd); } VerticalTextFormatting TextComponent::getVerticalFormattingFromComponent() const { return d_vertFormatting.getValue(); } void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt) { d_vertFormatting.set(fmt); } HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const { return d_horzFormatting.get(wnd); } HorizontalTextFormatting TextComponent::getHorizontalFormattingFromComponent() const { return d_horzFormatting.getValue(); } void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt) { d_horzFormatting.set(fmt); } const String& TextComponent::getHorizontalFormattingPropertySource() const { return d_horzFormatting.getPropertySource(); } void TextComponent::setHorizontalFormattingPropertySource( const String& property_name) { d_horzFormatting.setPropertySource(property_name); } const String& TextComponent::getVerticalFormattingPropertySource() const { return d_vertFormatting.getPropertySource(); } void TextComponent::setVerticalFormattingPropertySource( const String& property_name) { d_vertFormatting.setPropertySource(property_name); } void TextComponent::setupStringFormatter(const Window& window, const RenderedString& rendered_string) const { const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window); // no formatting change if (horzFormatting == d_lastHorzFormatting) { d_formattedRenderedString->setRenderedString(rendered_string); return; } d_lastHorzFormatting = horzFormatting; switch(horzFormatting) { case HTF_LEFT_ALIGNED: d_formattedRenderedString = new LeftAlignedRenderedString(rendered_string); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = new CentredRenderedString(rendered_string); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = new RightAlignedRenderedString(rendered_string); break; case HTF_JUSTIFIED: d_formattedRenderedString = new JustifiedRenderedString(rendered_string); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <LeftAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <CentredRenderedString>(rendered_string); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <RightAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = new RenderedStringWordWrapper <JustifiedRenderedString>(rendered_string); break; } } void TextComponent::addImageRenderGeometryToWindow_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const { updateFormatting(srcWindow, destRect.getSize()); // Get total formatted height. const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow); // handle dest area adjustments for vertical formatting. const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow); switch(vertFormatting) { case VTF_CENTRE_ALIGNED: destRect.d_min.y += (destRect.getHeight() - textHeight) * 0.5f; break; case VTF_BOTTOM_ALIGNED: destRect.d_min.y = destRect.d_max.y - textHeight; break; default: // default is VTF_TOP_ALIGNED, for which we take no action. break; } // calculate final colours to be used ColourRect finalColours; initColoursRect(srcWindow, modColours, finalColours); // add geometry for text to the target window. d_formattedRenderedString->createRenderGeometry(&srcWindow, destRect.getPosition(), &finalColours, clipper); } const Font* TextComponent::getFontObject(const Window& window) const { try { return d_fontPropertyName.empty() ? (d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font)) : &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName)); } catch (UnknownObjectException&) { return 0; } } void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const { // opening tag xml_stream.openTag(Falagard_xmlHandler::TextComponentElement); // write out area d_area.writeXMLToStream(xml_stream); // write text element if (!d_font.empty() || !getText().empty()) { xml_stream.openTag(Falagard_xmlHandler::TextElement); if (!d_font.empty()) xml_stream.attribute(Falagard_xmlHandler::FontAttribute, d_font); if (!getText().empty()) xml_stream.attribute(Falagard_xmlHandler::StringAttribute, getText()); xml_stream.closeTag(); } // write text property element if (!d_textPropertyName.empty()) { xml_stream.openTag(Falagard_xmlHandler::TextPropertyElement) .attribute(Falagard_xmlHandler::NameAttribute, d_textPropertyName) .closeTag(); } // write font property element if (!d_fontPropertyName.empty()) { xml_stream.openTag(Falagard_xmlHandler::FontPropertyElement) .attribute(Falagard_xmlHandler::NameAttribute, d_fontPropertyName) .closeTag(); } // get base class to write colours writeColoursXML(xml_stream); d_vertFormatting.writeXMLToStream(xml_stream); d_horzFormatting.writeXMLToStream(xml_stream); // closing tag xml_stream.closeTag(); } bool TextComponent::isTextFetchedFromProperty() const { return !d_textPropertyName.empty(); } const String& TextComponent::getTextPropertySource() const { return d_textPropertyName; } void TextComponent::setTextPropertySource(const String& property) { d_textPropertyName = property; } bool TextComponent::isFontFetchedFromProperty() const { return !d_fontPropertyName.empty(); } const String& TextComponent::getFontPropertySource() const { return d_fontPropertyName; } void TextComponent::setFontPropertySource(const String& property) { d_fontPropertyName = property; } const String& TextComponent::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } float TextComponent::getHorizontalTextExtent(const Window& window) const { updateFormatting(window); return d_formattedRenderedString->getHorizontalExtent(&window); } float TextComponent::getVerticalTextExtent(const Window& window) const { updateFormatting(window); return d_formattedRenderedString->getVerticalExtent(&window); } bool TextComponent::handleFontRenderSizeChange(Window& window, const Font* font) const { const bool res = FalagardComponentBase::handleFontRenderSizeChange(window, font); if (font == getFontObject(window)) { window.invalidate(); return true; } return res; } //------------------------------------------------------------------------// void TextComponent::updateFormatting(const Window& srcWindow) const { updateFormatting(srcWindow, d_area.getPixelRect(srcWindow).getSize()); } //------------------------------------------------------------------------// void TextComponent::updateFormatting( const Window& srcWindow, const Sizef& size) const { const Font* font = getFontObject(srcWindow); // exit if we have no font to use. if (!font) throw InvalidRequestException("Window doesn't have a font."); const RenderedString* rs = &d_renderedString; // do we fetch text from a property if (!d_textPropertyName.empty()) { // fetch text & do bi-directional reordering as needed String vis; #ifdef CEGUI_BIDI_SUPPORT BidiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l); #else vis = srcWindow.getProperty(d_textPropertyName); #endif // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser().parse(vis, font, 0); } // do we use a static text string from the looknfeel else if (!getTextVisual().empty()) // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser(). parse(getTextVisual(), font, 0); // do we have to override the font? else if (font != srcWindow.getFont()) d_renderedString = srcWindow.getRenderedStringParser(). parse(srcWindow.getTextVisual(), font, 0); // use ready-made RenderedString from the Window itself else rs = &srcWindow.getRenderedString(); setupStringFormatter(srcWindow, *rs); d_formattedRenderedString->format(&srcWindow, size); } //----------------------------------------------------------------------------// String TextComponent::getEffectiveText(const Window& wnd) const { if (!d_textPropertyName.empty()) return wnd.getProperty(d_textPropertyName); else if (d_textLogical.empty()) return wnd.getText(); else return d_textLogical; } //----------------------------------------------------------------------------// String TextComponent::getEffectiveVisualText(const Window& wnd) const { #ifndef CEGUI_BIDI_SUPPORT return getEffectiveText(wnd); #else if (!d_textPropertyName.empty()) { String visual; BidiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( wnd.getProperty(d_textPropertyName), visual, l2v, v2l); return visual; } // do we use a static text string from the looknfeel else if (d_textLogical.empty()) return wnd.getTextVisual(); else getTextVisual(); #endif } //----------------------------------------------------------------------------// String TextComponent::getEffectiveFont(const Window& wnd) const { if (!d_fontPropertyName.empty()) return wnd.getProperty(d_fontPropertyName); else if (d_font.empty()) { if (const Font* font = wnd.getFont()) return font->getName(); else return String(); } else return d_font; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: Fixing another font rendering problem (TextComponents didn't render)<commit_after>/*********************************************************************** created: Sun Jun 19 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/falagard/TextComponent.h" #include "CEGUI/falagard/XMLEnumHelper.h" #include "CEGUI/falagard/XMLHandler.h" #include "CEGUI/FontManager.h" #include "CEGUI/Exceptions.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/Font.h" #include "CEGUI/LeftAlignedRenderedString.h" #include "CEGUI/RightAlignedRenderedString.h" #include "CEGUI/CentredRenderedString.h" #include "CEGUI/JustifiedRenderedString.h" #include "CEGUI/RenderedStringWordWrapper.h" #include <iostream> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { TextComponent::TextComponent() : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)), d_lastHorzFormatting(HTF_LEFT_ALIGNED), d_vertFormatting(VTF_TOP_ALIGNED), d_horzFormatting(HTF_LEFT_ALIGNED) {} TextComponent::~TextComponent() { delete d_bidiVisualMapping; } TextComponent::TextComponent(const TextComponent& obj) : FalagardComponentBase(obj), d_textLogical(obj.d_textLogical), #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #endif d_bidiDataValid(false), d_renderedString(obj.d_renderedString), d_formattedRenderedString(obj.d_formattedRenderedString), d_lastHorzFormatting(obj.d_lastHorzFormatting), d_font(obj.d_font), d_vertFormatting(obj.d_vertFormatting), d_horzFormatting(obj.d_horzFormatting), d_textPropertyName(obj.d_textPropertyName), d_fontPropertyName(obj.d_fontPropertyName) { } TextComponent& TextComponent::operator=(const TextComponent& other) { if (this == &other) return *this; FalagardComponentBase::operator=(other); d_textLogical = other.d_textLogical; // note we do not assign the BidiVisualMapping object, we just mark our // existing one as invalid so it's data gets regenerated next time it's // needed. d_bidiDataValid = false; d_renderedString = other.d_renderedString; d_formattedRenderedString = other.d_formattedRenderedString; d_lastHorzFormatting = other.d_lastHorzFormatting; d_font = other.d_font; d_vertFormatting = other.d_vertFormatting; d_horzFormatting = other.d_horzFormatting; d_textPropertyName = other.d_textPropertyName; d_fontPropertyName = other.d_fontPropertyName; return *this; } const String& TextComponent::getText() const { return d_textLogical; } void TextComponent::setText(const String& text) { d_textLogical = text; d_bidiDataValid = false; } const String& TextComponent::getFont() const { return d_font; } void TextComponent::setFont(const String& font) { d_font = font; } VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const { return d_vertFormatting.get(wnd); } VerticalTextFormatting TextComponent::getVerticalFormattingFromComponent() const { return d_vertFormatting.getValue(); } void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt) { d_vertFormatting.set(fmt); } HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const { return d_horzFormatting.get(wnd); } HorizontalTextFormatting TextComponent::getHorizontalFormattingFromComponent() const { return d_horzFormatting.getValue(); } void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt) { d_horzFormatting.set(fmt); } const String& TextComponent::getHorizontalFormattingPropertySource() const { return d_horzFormatting.getPropertySource(); } void TextComponent::setHorizontalFormattingPropertySource( const String& property_name) { d_horzFormatting.setPropertySource(property_name); } const String& TextComponent::getVerticalFormattingPropertySource() const { return d_vertFormatting.getPropertySource(); } void TextComponent::setVerticalFormattingPropertySource( const String& property_name) { d_vertFormatting.setPropertySource(property_name); } void TextComponent::setupStringFormatter(const Window& window, const RenderedString& rendered_string) const { const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window); // no formatting change if (horzFormatting == d_lastHorzFormatting) { d_formattedRenderedString->setRenderedString(rendered_string); return; } d_lastHorzFormatting = horzFormatting; switch(horzFormatting) { case HTF_LEFT_ALIGNED: d_formattedRenderedString = new LeftAlignedRenderedString(rendered_string); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = new CentredRenderedString(rendered_string); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = new RightAlignedRenderedString(rendered_string); break; case HTF_JUSTIFIED: d_formattedRenderedString = new JustifiedRenderedString(rendered_string); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <LeftAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <CentredRenderedString>(rendered_string); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <RightAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = new RenderedStringWordWrapper <JustifiedRenderedString>(rendered_string); break; } } void TextComponent::addImageRenderGeometryToWindow_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const { updateFormatting(srcWindow, destRect.getSize()); // Get total formatted height. const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow); // handle dest area adjustments for vertical formatting. const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow); switch(vertFormatting) { case VTF_CENTRE_ALIGNED: destRect.d_min.y += (destRect.getHeight() - textHeight) * 0.5f; break; case VTF_BOTTOM_ALIGNED: destRect.d_min.y = destRect.d_max.y - textHeight; break; default: // default is VTF_TOP_ALIGNED, for which we take no action. break; } // calculate final colours to be used ColourRect finalColours; initColoursRect(srcWindow, modColours, finalColours); // add geometry for text to the target window. auto geomBuffers = d_formattedRenderedString->createRenderGeometry( &srcWindow, destRect.getPosition(), &finalColours, clipper); srcWindow.appendGeometryBuffers(geomBuffers); } const Font* TextComponent::getFontObject(const Window& window) const { try { return d_fontPropertyName.empty() ? (d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font)) : &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName)); } catch (UnknownObjectException&) { return 0; } } void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const { // opening tag xml_stream.openTag(Falagard_xmlHandler::TextComponentElement); // write out area d_area.writeXMLToStream(xml_stream); // write text element if (!d_font.empty() || !getText().empty()) { xml_stream.openTag(Falagard_xmlHandler::TextElement); if (!d_font.empty()) xml_stream.attribute(Falagard_xmlHandler::FontAttribute, d_font); if (!getText().empty()) xml_stream.attribute(Falagard_xmlHandler::StringAttribute, getText()); xml_stream.closeTag(); } // write text property element if (!d_textPropertyName.empty()) { xml_stream.openTag(Falagard_xmlHandler::TextPropertyElement) .attribute(Falagard_xmlHandler::NameAttribute, d_textPropertyName) .closeTag(); } // write font property element if (!d_fontPropertyName.empty()) { xml_stream.openTag(Falagard_xmlHandler::FontPropertyElement) .attribute(Falagard_xmlHandler::NameAttribute, d_fontPropertyName) .closeTag(); } // get base class to write colours writeColoursXML(xml_stream); d_vertFormatting.writeXMLToStream(xml_stream); d_horzFormatting.writeXMLToStream(xml_stream); // closing tag xml_stream.closeTag(); } bool TextComponent::isTextFetchedFromProperty() const { return !d_textPropertyName.empty(); } const String& TextComponent::getTextPropertySource() const { return d_textPropertyName; } void TextComponent::setTextPropertySource(const String& property) { d_textPropertyName = property; } bool TextComponent::isFontFetchedFromProperty() const { return !d_fontPropertyName.empty(); } const String& TextComponent::getFontPropertySource() const { return d_fontPropertyName; } void TextComponent::setFontPropertySource(const String& property) { d_fontPropertyName = property; } const String& TextComponent::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } float TextComponent::getHorizontalTextExtent(const Window& window) const { updateFormatting(window); return d_formattedRenderedString->getHorizontalExtent(&window); } float TextComponent::getVerticalTextExtent(const Window& window) const { updateFormatting(window); return d_formattedRenderedString->getVerticalExtent(&window); } bool TextComponent::handleFontRenderSizeChange(Window& window, const Font* font) const { const bool res = FalagardComponentBase::handleFontRenderSizeChange(window, font); if (font == getFontObject(window)) { window.invalidate(); return true; } return res; } //------------------------------------------------------------------------// void TextComponent::updateFormatting(const Window& srcWindow) const { updateFormatting(srcWindow, d_area.getPixelRect(srcWindow).getSize()); } //------------------------------------------------------------------------// void TextComponent::updateFormatting( const Window& srcWindow, const Sizef& size) const { const Font* font = getFontObject(srcWindow); // exit if we have no font to use. if (!font) throw InvalidRequestException("Window doesn't have a font."); const RenderedString* rs = &d_renderedString; // do we fetch text from a property if (!d_textPropertyName.empty()) { // fetch text & do bi-directional reordering as needed String vis; #ifdef CEGUI_BIDI_SUPPORT BidiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l); #else vis = srcWindow.getProperty(d_textPropertyName); #endif // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser().parse(vis, font, 0); } // do we use a static text string from the looknfeel else if (!getTextVisual().empty()) // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser(). parse(getTextVisual(), font, 0); // do we have to override the font? else if (font != srcWindow.getFont()) d_renderedString = srcWindow.getRenderedStringParser(). parse(srcWindow.getTextVisual(), font, 0); // use ready-made RenderedString from the Window itself else rs = &srcWindow.getRenderedString(); setupStringFormatter(srcWindow, *rs); d_formattedRenderedString->format(&srcWindow, size); } //----------------------------------------------------------------------------// String TextComponent::getEffectiveText(const Window& wnd) const { if (!d_textPropertyName.empty()) return wnd.getProperty(d_textPropertyName); else if (d_textLogical.empty()) return wnd.getText(); else return d_textLogical; } //----------------------------------------------------------------------------// String TextComponent::getEffectiveVisualText(const Window& wnd) const { #ifndef CEGUI_BIDI_SUPPORT return getEffectiveText(wnd); #else if (!d_textPropertyName.empty()) { String visual; BidiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( wnd.getProperty(d_textPropertyName), visual, l2v, v2l); return visual; } // do we use a static text string from the looknfeel else if (d_textLogical.empty()) return wnd.getTextVisual(); else getTextVisual(); #endif } //----------------------------------------------------------------------------// String TextComponent::getEffectiveFont(const Window& wnd) const { if (!d_fontPropertyName.empty()) return wnd.getProperty(d_fontPropertyName); else if (d_font.empty()) { if (const Font* font = wnd.getFont()) return font->getName(); else return String(); } else return d_font; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before> #include "core/deep_flow.h" #include "core/session.h" #include <random> #include <gflags/gflags.h> DEFINE_string(mnist, "D:/Projects/deepflow/data/mnist", "Path to mnist folder dataset"); DEFINE_string(i, "", "Trained network model to load"); DEFINE_string(o, "", "Trained network model to save"); DEFINE_bool(text, false, "Save model as text"); DEFINE_bool(includeweights, false, "Also save weights in text mode"); DEFINE_bool(includeinits, false, "Also save initial values"); DEFINE_int32(batch, 100, "Batch size"); DEFINE_string(run,"", "Phase to execute graph"); DEFINE_bool(printiter, false, "Print iteration message"); DEFINE_bool(printepoch, true, "Print epoch message"); DEFINE_int32(debug, 0, "Level of debug"); DEFINE_int32(epoch, 1000000, "Maximum epochs"); DEFINE_int32(iter, -1, "Maximum iterations"); DEFINE_bool(cpp, false, "Print C++ code"); std::shared_ptr<Session> create_mnist_reader() { DeepFlow df; df.mnist_reader(FLAGS_mnist, 100, MNISTReader::MNISTReaderType::Train, MNISTReader::Data, "mnist_data"); return df.session(); } std::shared_ptr<Session> create_mnist_labels() { DeepFlow df; df.data_generator(df.random_uniform({ FLAGS_batch, 1, 1, 1 }, 0.8, 1.0), 10000, "", "mnist_labels"); return df.session(); } std::shared_ptr<Session> create_generator_labels() { DeepFlow df; df.data_generator(df.random_uniform({ FLAGS_batch, 1, 1, 1 }, 0, 0.2), 10000, "", "generator_labels"); return df.session(); } std::shared_ptr<Session> create_loss() { DeepFlow df; auto discriminator_input = df.place_holder({ FLAGS_batch, 1, 1, 1 }, Tensor::Float, "discriminator_input"); auto labels_input = df.place_holder({ FLAGS_batch, 1, 1, 1 }, Tensor::Float, "labels_input"); df.euclidean_loss(discriminator_input, labels_input); auto sub = df.subtract(discriminator_input, labels_input); auto reduce = df.reduce_norm1(sub, 0); df.print({ reduce }, " NORM {0}\n", DeepFlow::EVERY_PASS); return df.session(); } std::shared_ptr<Session> create_generator() { DeepFlow df; auto mean = 0; auto stddev = 0.02; auto negative_slope = 0.05; auto g_solver = df.adam_solver(0.00002f, 0.5f, 0.999f); auto gin = df.data_generator(df.three_state({ FLAGS_batch, 100, 1, 1 }, "random_input"), 10000, "", "input"); auto gfc_w = df.variable(df.random_normal({ 100, 256, 4, 4 }, mean, stddev), g_solver, "gfc_w"); auto gfc = df.matmul(gin, gfc_w, "gfc"); auto gfc_r = df.leaky_relu(gfc, negative_slope); auto gfc_drop = df.dropout(gfc_r); auto gconv1_f = df.variable(df.random_normal({ 256, 128, 2, 2 }, mean, stddev), g_solver, "gconv1_f"); auto gconv1_t = df.transposed_conv2d(gfc_drop, gconv1_f, 1, 1, 2, 2, 1, 1, "gconv1"); auto gconv1_n = df.batch_normalization(gconv1_t, DeepFlow::SPATIAL, 0.01f); auto gconv1_r = df.leaky_relu(gconv1_n, negative_slope); auto gconv2_f = df.variable(df.random_normal({ 128, 64, 3, 3 }, mean, stddev), g_solver, "gconv2_f"); auto gconv2_t = df.transposed_conv2d(gconv1_r, gconv2_f, 1, 1, 2, 2, 1, 1, "gconv2"); auto gconv2_n = df.batch_normalization(gconv2_t, DeepFlow::SPATIAL, 0.01f); auto gconv2_r = df.leaky_relu(gconv2_n, negative_slope); auto gconv3_f = df.variable(df.random_normal({ 64, 1, 3, 3 }, mean, stddev), g_solver, "gconv3_f"); auto gconv3_t = df.transposed_conv2d(gconv2_r, gconv3_f, 1, 1, 2, 2, 1, 1, "gconv3"); auto gconv3_n = df.batch_normalization(gconv3_t, DeepFlow::SPATIAL, 0.01f); auto gout = df.tanh(gconv3_t, "gout"); auto disp = df.display(gout, 1, DeepFlow::EVERY_PASS, DeepFlow::VALUES); //auto replay_memory = df.replay_memory(gout, 10000, "replay_memory"); return df.session(); } std::shared_ptr<Session> create_discriminator() { DeepFlow df; auto mean = 0; auto stddev = 0.02; auto d_solver = df.adam_solver(0.0002f, 0.5f, 0.999f); auto negative_slope = 0.1; auto input = df.place_holder({ FLAGS_batch , 1, 28, 28 }, Tensor::Float, "input"); auto conv1_w = df.variable(df.random_uniform({ 16, 1, 3, 3 }, -0.100000, 0.100000), d_solver, "conv1_w"); auto conv1 = df.conv2d(input, conv1_w, 1, 1, 2, 2, 1, 1, "conv1"); //auto conv1_n = df.batch_normalization(conv1, DeepFlow::PER_ACTIVATION); auto conv1_r = df.leaky_relu(conv1, negative_slope); auto conv2_w = df.variable(df.random_uniform({ 32, 16, 3, 3 }, -0.100000, 0.100000), d_solver, "conv2_w"); auto conv2 = df.conv2d(conv1_r, conv2_w, 1, 1, 2, 2, 1, 1, "conv2"); //auto conv2_n = df.batch_normalization(conv2, DeepFlow::PER_ACTIVATION); auto conv2_r = df.leaky_relu(conv2, negative_slope); auto conv3_w = df.variable(df.random_uniform({ 64, 32, 3, 3 }, -0.100000, 0.100000), d_solver, "conv3_w"); auto conv3 = df.conv2d(conv2_r, conv3_w, 1, 1, 2, 2, 1, 1, "conv3"); //auto conv3_n = df.batch_normalization(conv3, DeepFlow::PER_ACTIVATION); auto conv3_r = df.leaky_relu(conv3, negative_slope); auto drop1 = df.dropout(conv3_r); auto w1 = df.variable(df.random_uniform({ 1024, 500, 1, 1 }, -0.100000, 0.100000), d_solver, "w1"); auto m1 = df.matmul(drop1, w1, "m1"); auto b1 = df.variable(df.step({ 1, 500, 1, 1 }, -1.000000, 1.000000), d_solver, "b1"); auto bias1 = df.bias_add(m1, b1, "bias1"); auto relu1 = df.leaky_relu(bias1, negative_slope, "relu1"); auto drop2 = df.dropout(relu1); auto w2 = df.variable(df.random_uniform({ 500, 1, 1, 1 }, -0.100000, 0.100000), d_solver, "w2"); auto m2 = df.matmul(drop2, w2, "m2"); auto b2 = df.variable(df.step({ 1, 1, 1, 1 }, -1.000000, 1.000000), d_solver, "b2"); auto bias2 = df.bias_add(m2, b2, "bias2"); auto dout = df.sigmoid(bias2, "dout"); return df.session(); } void main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); CudaHelper::setOptimalThreadsPerBlock(); auto execution_context = std::make_shared<ExecutionContext>(); execution_context->debug_level = FLAGS_debug; auto generator = create_generator(); generator->initialize(); generator->set_execution_context(execution_context); auto discriminator = create_discriminator(); discriminator->initialize(); discriminator->set_execution_context(execution_context); auto mnist_reader = create_mnist_reader(); mnist_reader->initialize(); mnist_reader->set_execution_context(execution_context); auto mnist_labels = create_mnist_labels(); mnist_labels->initialize(); mnist_labels->set_execution_context(execution_context); auto generator_labels = create_generator_labels(); generator_labels->initialize(); generator_labels->set_execution_context(execution_context); auto loss = create_loss(); loss->initialize(); loss->set_execution_context(execution_context); auto mnist_reader_data = mnist_reader->get_node("mnist_data"); auto generator_output = generator->get_node("gout"); //auto replay_memory_output = generator->get_node("replay_memory"); auto discriminator_input = discriminator->get_placeholder("input"); auto discriminator_output = discriminator->get_node("dout"); auto generator_labels_output = generator_labels->get_node("generator_labels"); auto mnist_labels_output = mnist_labels->get_node("mnist_labels"); auto loss_discriminator_input = loss->get_placeholder("discriminator_input"); auto loss_labels_input = loss->get_placeholder("labels_input"); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> select_dist(0, 2); for (int i = 1; i <= FLAGS_epoch && execution_context->quit != true; ++i) { std::cout << "Epoch: " << i << std::endl; for (int k = 0; k <= 2; ++k) { discriminator->reset_gradients(); loss->reset_gradients(); if (k == 1) { // GENERATOR std::cout << " GENERATOR INPUT " << std::endl; generator->forward(); discriminator_input->feed_forward(generator_output, 0); discriminator->forward(); generator_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(generator_labels_output, 0); } else { // MNIST std::cout << " MNIST INPUT " << std::endl; mnist_reader_data->forward(); discriminator_input->feed_forward(mnist_reader_data, 0); discriminator->forward(); mnist_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(mnist_labels_output, 0); } loss->forward(); loss->backward(); discriminator_output->feed_backward(loss_discriminator_input, 0); discriminator->backward(); discriminator->apply_solvers(); } std::cout << " TRAINING GENERATOR " << std::endl; generator->reset_gradients(); discriminator->reset_gradients(); loss->reset_gradients(); generator->forward(); discriminator_input->feed_forward(generator_output, 0); discriminator->forward(); mnist_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(mnist_labels_output, 0); loss->forward(); loss->backward(); discriminator_output->feed_backward(loss_discriminator_input, 0); discriminator->backward(); generator_output->feed_backward(discriminator_input, 0); generator->backward(); generator->apply_solvers(); } } <commit_msg>Improvements<commit_after> #include "core/deep_flow.h" #include "core/session.h" #include <random> #include <gflags/gflags.h> DEFINE_string(mnist, "D:/Projects/deepflow/data/mnist", "Path to mnist folder dataset"); DEFINE_string(i, "", "Trained network model to load"); DEFINE_string(o, "", "Trained network model to save"); DEFINE_bool(text, false, "Save model as text"); DEFINE_bool(includeweights, false, "Also save weights in text mode"); DEFINE_bool(includeinits, false, "Also save initial values"); DEFINE_int32(batch, 100, "Batch size"); DEFINE_string(run,"", "Phase to execute graph"); DEFINE_bool(printiter, false, "Print iteration message"); DEFINE_bool(printepoch, true, "Print epoch message"); DEFINE_int32(debug, 0, "Level of debug"); DEFINE_int32(epoch, 1000000, "Maximum epochs"); DEFINE_int32(iter, -1, "Maximum iterations"); DEFINE_bool(cpp, false, "Print C++ code"); std::shared_ptr<Session> create_mnist_reader() { DeepFlow df; df.mnist_reader(FLAGS_mnist, 100, MNISTReader::MNISTReaderType::Train, MNISTReader::Data, "mnist_data"); return df.session(); } std::shared_ptr<Session> create_mnist_labels() { DeepFlow df; df.data_generator(df.random_uniform({ FLAGS_batch, 1, 1, 1 }, 0.8, 1.0), 10000, "", "mnist_labels"); return df.session(); } std::shared_ptr<Session> create_generator_labels() { DeepFlow df; df.data_generator(df.random_uniform({ FLAGS_batch, 1, 1, 1 }, 0, 0.2), 10000, "", "generator_labels"); return df.session(); } std::shared_ptr<Session> create_loss() { DeepFlow df; auto discriminator_input = df.place_holder({ FLAGS_batch, 1, 1, 1 }, Tensor::Float, "discriminator_input"); auto labels_input = df.place_holder({ FLAGS_batch, 1, 1, 1 }, Tensor::Float, "labels_input"); df.euclidean_loss(discriminator_input, labels_input); auto sub = df.subtract(discriminator_input, labels_input); auto reduce = df.reduce_norm1(sub, 0); df.print({ reduce }, " NORM {0}\n", DeepFlow::EVERY_PASS); return df.session(); } std::shared_ptr<Session> create_generator() { DeepFlow df; auto mean = 0; auto stddev = 0.02; auto negative_slope = 0.05; auto g_solver = df.adam_solver(0.00002f, 0.5f, 0.999f); auto gin = df.data_generator(df.three_state({ FLAGS_batch, 100, 1, 1 }, "random_input"), 10000, "", "input"); auto gfc_w = df.variable(df.random_normal({ 100, 256, 4, 4 }, mean, stddev), g_solver, "gfc_w"); auto gfc = df.matmul(gin, gfc_w, "gfc"); auto gfc_r = df.leaky_relu(gfc, negative_slope); auto gfc_drop = df.dropout(gfc_r); auto gconv1_f = df.variable(df.random_normal({ 256, 128, 2, 2 }, mean, stddev), g_solver, "gconv1_f"); auto gconv1_t = df.transposed_conv2d(gfc_drop, gconv1_f, 1, 1, 2, 2, 1, 1, "gconv1"); auto gconv1_n = df.batch_normalization(gconv1_t, DeepFlow::SPATIAL, 0.01f); auto gconv1_r = df.leaky_relu(gconv1_n, negative_slope); auto gconv2_f = df.variable(df.random_normal({ 128, 64, 3, 3 }, mean, stddev), g_solver, "gconv2_f"); auto gconv2_t = df.transposed_conv2d(gconv1_r, gconv2_f, 1, 1, 2, 2, 1, 1, "gconv2"); auto gconv2_n = df.batch_normalization(gconv2_t, DeepFlow::SPATIAL, 0.01f); auto gconv2_r = df.leaky_relu(gconv2_n, negative_slope); auto gconv3_f = df.variable(df.random_normal({ 64, 1, 3, 3 }, mean, stddev), g_solver, "gconv3_f"); auto gconv3_t = df.transposed_conv2d(gconv2_r, gconv3_f, 1, 1, 2, 2, 1, 1, "gconv3"); auto gconv3_n = df.batch_normalization(gconv3_t, DeepFlow::SPATIAL, 0.01f); auto gout = df.tanh(gconv3_t, "gout"); auto disp = df.display(gout, 1, DeepFlow::EVERY_PASS, DeepFlow::VALUES); //auto replay_memory = df.replay_memory(gout, 10000, "replay_memory"); return df.session(); } std::shared_ptr<Session> create_discriminator() { DeepFlow df; auto mean = 0; auto stddev = 0.02; auto d_solver = df.adam_solver(0.0002f, 0.9f, 0.999f); auto negative_slope = 0.1; auto input = df.place_holder({ FLAGS_batch , 1, 28, 28 }, Tensor::Float, "input"); auto conv1_w = df.variable(df.random_uniform({ 64, 1, 3, 3 }, -0.100000, 0.100000), d_solver, "conv1_w"); auto conv1 = df.conv2d(input, conv1_w, 1, 1, 2, 2, 1, 1, "conv1"); auto conv1_r = df.leaky_relu(conv1, negative_slope); //auto conv1_n = df.batch_normalization(conv1_r, DeepFlow::SPATIAL); auto conv2_w = df.variable(df.random_uniform({ 64, 64, 3, 3 }, -0.100000, 0.100000), d_solver, "conv2_w"); auto conv2 = df.conv2d(conv1_r, conv2_w, 1, 1, 2, 2, 1, 1, "conv2"); auto conv2_r = df.leaky_relu(conv2, negative_slope); //auto conv2_n = df.batch_normalization(conv2_r, DeepFlow::SPATIAL); auto conv3_w = df.variable(df.random_uniform({ 128, 64, 3, 3 }, -0.100000, 0.100000), d_solver, "conv3_w"); auto conv3 = df.conv2d(conv2_r, conv3_w, 1, 1, 2, 2, 1, 1, "conv3"); auto conv3_r = df.leaky_relu(conv3, negative_slope); //auto conv3_n = df.batch_normalization(conv3_r, DeepFlow::SPATIAL); auto drop1 = df.dropout(conv3_r); auto w1 = df.variable(df.random_uniform({ 2048, 500, 1, 1 }, -0.100000, 0.100000), d_solver, "w1"); auto m1 = df.matmul(drop1, w1, "m1"); auto b1 = df.variable(df.step({ 1, 500, 1, 1 }, -1.000000, 1.000000), d_solver, "b1"); auto bias1 = df.bias_add(m1, b1, "bias1"); auto relu1 = df.leaky_relu(bias1, negative_slope, "relu1"); auto drop2 = df.dropout(relu1); auto w2 = df.variable(df.random_uniform({ 500, 1, 1, 1 }, -0.100000, 0.100000), d_solver, "w2"); auto m2 = df.matmul(drop2, w2, "m2"); auto b2 = df.variable(df.step({ 1, 1, 1, 1 }, -1.000000, 1.000000), d_solver, "b2"); auto bias2 = df.bias_add(m2, b2, "bias2"); auto dout = df.sigmoid(bias2, "dout"); //df.logger({ conv1_r, conv1_n}, "./log.txt", "R -> {0}\nN -> {0}\n\n", DeepFlow::EVERY_PASS); return df.session(); } void main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); CudaHelper::setOptimalThreadsPerBlock(); auto execution_context = std::make_shared<ExecutionContext>(); execution_context->debug_level = FLAGS_debug; auto generator = create_generator(); generator->initialize(); generator->set_execution_context(execution_context); auto discriminator = create_discriminator(); discriminator->initialize(); discriminator->set_execution_context(execution_context); auto mnist_reader = create_mnist_reader(); mnist_reader->initialize(); mnist_reader->set_execution_context(execution_context); auto mnist_labels = create_mnist_labels(); mnist_labels->initialize(); mnist_labels->set_execution_context(execution_context); auto generator_labels = create_generator_labels(); generator_labels->initialize(); generator_labels->set_execution_context(execution_context); auto loss = create_loss(); loss->initialize(); loss->set_execution_context(execution_context); auto mnist_reader_data = mnist_reader->get_node("mnist_data"); auto generator_output = generator->get_node("gout"); //auto replay_memory_output = generator->get_node("replay_memory"); auto discriminator_input = discriminator->get_placeholder("input"); auto discriminator_output = discriminator->get_node("dout"); auto generator_labels_output = generator_labels->get_node("generator_labels"); auto mnist_labels_output = mnist_labels->get_node("mnist_labels"); auto loss_discriminator_input = loss->get_placeholder("discriminator_input"); auto loss_labels_input = loss->get_placeholder("labels_input"); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> select_dist(0, 2); for (int i = 1; i <= FLAGS_epoch && execution_context->quit != true; ++i) { std::cout << "Epoch: " << i << std::endl; for (int k = 0; k <= 2; ++k) { discriminator->reset_gradients(); loss->reset_gradients(); if (k == 1) { // GENERATOR std::cout << " GENERATOR INPUT " << std::endl; generator->forward(); discriminator_input->feed_forward(generator_output, 0); discriminator->forward(); generator_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(generator_labels_output, 0); } else { // MNIST std::cout << " MNIST INPUT " << std::endl; mnist_reader_data->forward(); discriminator_input->feed_forward(mnist_reader_data, 0); discriminator->forward(); mnist_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(mnist_labels_output, 0); } loss->forward(); loss->backward(); discriminator_output->feed_backward(loss_discriminator_input, 0); discriminator->backward(); discriminator->apply_solvers(); } std::cout << " TRAINING GENERATOR " << std::endl; generator->reset_gradients(); discriminator->reset_gradients(); loss->reset_gradients(); generator->forward(); discriminator_input->feed_forward(generator_output, 0); discriminator->forward(); mnist_labels->forward(); loss_discriminator_input->feed_forward(discriminator_output, 0); loss_labels_input->feed_forward(mnist_labels_output, 0); loss->forward(); loss->backward(); discriminator_output->feed_backward(loss_discriminator_input, 0); discriminator->backward(); generator_output->feed_backward(discriminator_input, 0); generator->backward(); generator->apply_solvers(); } } <|endoftext|>
<commit_before>#include "factory.h" #include "except.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> using namespace boost::python; class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource> { bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(gg::VideoFrame & frame) { return this->get_override("get_frame")(frame); } double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget> { void init(const std::string filepath, const float framerate) { this->get_override("init")(filepath, framerate); } void append(const gg::VideoFrame & frame) { this->get_override("append")(frame); } void finalise() { this->get_override("finalise")(); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); enum_<gg::ColourSpace>("ColourSpace") .value("BGRA", gg::ColourSpace::BGRA) .value("I420", gg::ColourSpace::I420) ; enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Storage>("Storage") .value("File_HEVC", gg::Storage::File_HEVC) .value("File_XviD", gg::Storage::File_XviD) .value("File_VP9", gg::Storage::File_VP9) ; class_<gg::VideoFrame>("VideoFrame", init<enum gg::ColourSpace, bool>()) .def(init<enum gg::ColourSpace, const size_t, const size_t>()) .def("rows", &gg::VideoFrame::rows) .def("cols", &gg::VideoFrame::cols) ; class_<gg::IObserver>("IObserver", no_init) ; class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init) ; #ifdef USE_OPENCV class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", &VideoSourceOpenCV::get_frame) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) ; #endif // USE_OPENCV #ifdef USE_EPIPHANSDK class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", &gg::VideoSourceEpiphanSDK::get_frame) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) ; #endif #ifdef USE_LIBVLC class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>( "VideoSourceVLC", init<const std::string>()) .def("get_frame", &gg::VideoSourceVLC::get_frame) .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame) .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame) ; #endif class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init) ; #ifdef USE_FFMPEG class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string>()) .def("init", &gg::VideoTargetFFmpeg::init) .def("append", &gg::VideoTargetFFmpeg::append) .def("finalise", &gg::VideoTargetFFmpeg::finalise) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string>()) .def("init", &gg::VideoTargetOpenCV::init) .def("append", &gg::VideoTargetOpenCV::append) .def("finalise", &gg::VideoTargetOpenCV::finalise) ; #endif // USE_OPENCV class_<gg::Factory>("Factory", no_init) .def("connect", &gg::Factory::connect, /* because client should never delete returned * object on its own, but should rather call * disconnect when done */ return_value_policy<reference_existing_object>()) .staticmethod("connect") .def("disconnect", &gg::Factory::disconnect) .staticmethod("disconnect") .def("writer", &gg::Factory::writer, // because ownership is passed to client return_value_policy<manage_new_object>()) .staticmethod("writer") ; } <commit_msg>Issue #86: exported ObserverError to Python<commit_after>#include "factory.h" #include "except.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> using namespace boost::python; class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource> { bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(gg::VideoFrame & frame) { return this->get_override("get_frame")(frame); } double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget> { void init(const std::string filepath, const float framerate) { this->get_override("init")(filepath, framerate); } void append(const gg::VideoFrame & frame) { this->get_override("append")(frame); } void finalise() { this->get_override("finalise")(); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_ObserverError(gg::ObserverError const & e) { std::string msg; msg.append("ObserverError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); register_exception_translator<gg::ObserverError>(&translate_ObserverError); enum_<gg::ColourSpace>("ColourSpace") .value("BGRA", gg::ColourSpace::BGRA) .value("I420", gg::ColourSpace::I420) ; enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Storage>("Storage") .value("File_HEVC", gg::Storage::File_HEVC) .value("File_XviD", gg::Storage::File_XviD) .value("File_VP9", gg::Storage::File_VP9) ; class_<gg::VideoFrame>("VideoFrame", init<enum gg::ColourSpace, bool>()) .def(init<enum gg::ColourSpace, const size_t, const size_t>()) .def("rows", &gg::VideoFrame::rows) .def("cols", &gg::VideoFrame::cols) ; class_<gg::IObserver>("IObserver", no_init) ; class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init) ; #ifdef USE_OPENCV class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", &VideoSourceOpenCV::get_frame) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) ; #endif // USE_OPENCV #ifdef USE_EPIPHANSDK class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", &gg::VideoSourceEpiphanSDK::get_frame) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) ; #endif #ifdef USE_LIBVLC class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>( "VideoSourceVLC", init<const std::string>()) .def("get_frame", &gg::VideoSourceVLC::get_frame) .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame) .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame) ; #endif class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init) ; #ifdef USE_FFMPEG class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string>()) .def("init", &gg::VideoTargetFFmpeg::init) .def("append", &gg::VideoTargetFFmpeg::append) .def("finalise", &gg::VideoTargetFFmpeg::finalise) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string>()) .def("init", &gg::VideoTargetOpenCV::init) .def("append", &gg::VideoTargetOpenCV::append) .def("finalise", &gg::VideoTargetOpenCV::finalise) ; #endif // USE_OPENCV class_<gg::Factory>("Factory", no_init) .def("connect", &gg::Factory::connect, /* because client should never delete returned * object on its own, but should rather call * disconnect when done */ return_value_policy<reference_existing_object>()) .staticmethod("connect") .def("disconnect", &gg::Factory::disconnect) .staticmethod("disconnect") .def("writer", &gg::Factory::writer, // because ownership is passed to client return_value_policy<manage_new_object>()) .staticmethod("writer") ; } <|endoftext|>
<commit_before>/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_http.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl <peter.knafl@gmail.com> * @license See attached LICENSE.txt ************************************************************************/ #include <boost/test/unit_test.hpp> #ifdef HTTP_TESTING #define BOOST_TEST_MODULE connector_http #include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/client/connectors/httpclient.h> #include <curl/curl.h> #include "mockclientconnectionhandler.h" #include "testhttpserver.h" using namespace jsonrpc; using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" BOOST_AUTO_TEST_SUITE(connector_http) struct F { HttpServer server; HttpClient client; MockClientConnectionHandler handler; F() : server(TEST_PORT), client(CLIENT_URL) { server.SetHandler(&handler); server.StartListening(); } ~F() { server.StopListening(); } }; bool check_exception1(JsonRpcException const&ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } bool check_exception2(JsonRpcException const&ex) { return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; } BOOST_FIXTURE_TEST_CASE(test_http_success, F) { handler.response = "exampleresponse"; string result; client.SendRPCMessage("examplerequest", result); BOOST_CHECK_EQUAL(handler.request, "examplerequest"); BOOST_CHECK_EQUAL(result, "exampleresponse"); } BOOST_AUTO_TEST_CASE(test_http_server_multiplestart) { HttpServer server(TEST_PORT); BOOST_CHECK_EQUAL(server.StartListening(), true); HttpServer server2(TEST_PORT); BOOST_CHECK_EQUAL(server2.StartListening(), false); BOOST_CHECK_EQUAL(server.StopListening(), true); } BOOST_FIXTURE_TEST_CASE(test_http_client_timeout, F) { handler.timeout = 20; client.SetTimeout(10); string result; BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); handler.timeout = 0; client.SetTimeout(1000); handler.response = "asdf"; client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(result, "asdf"); server.StopListening(); BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); } BOOST_AUTO_TEST_CASE(test_http_client_headers) { TestHttpServer server(TEST_PORT); HttpClient client(CLIENT_URL); BOOST_REQUIRE_EQUAL(server.StartListening(),true); client.AddHeader("X-Auth", "1234"); server.SetResponse("asdf"); string result; client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(result, "asdf"); BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), "1234"); client.RemoveHeader("X-Auth"); client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), ""); server.StopListening(); } BOOST_FIXTURE_TEST_CASE(test_http_get,F) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); CURLcode code = curl_easy_perform(curl); BOOST_REQUIRE_EQUAL(code, CURLE_OK); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); BOOST_CHECK_EQUAL(http_code, 405); curl_easy_cleanup(curl); } BOOST_AUTO_TEST_CASE(test_http_server_endpoints) { MockClientConnectionHandler handler1; MockClientConnectionHandler handler2; handler1.response = "response1"; handler2.response = "response2"; HttpServer server(TEST_PORT); server.SetUrlHandler("/handler1", &handler1); server.SetUrlHandler("/handler2", &handler2); BOOST_REQUIRE_EQUAL(server.StartListening(), true); HttpClient client1("http://localhost:8383/handler1"); HttpClient client2("http://localhost:8383/handler2"); HttpClient client3("http://localhost:8383/handler3"); string response; client1.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response1"); client2.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response2"); BOOST_CHECK_EXCEPTION(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); client3.SetUrl("http://localhost:8383/handler2"); client3.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response2"); server.StopListening(); } BOOST_FIXTURE_TEST_CASE(test_http_server_longpost, F) { int mb = 5; unsigned long size = mb * 1024*1024; char* str = (char*) malloc(size * sizeof(char)); BOOST_REQUIRE(str != NULL); for (unsigned long i=0; i < size; i++) { str[i] = (char)('a'+(i%26)); } str[size-1] = '\0'; handler.response = str; string response; client.SetTimeout(-1); client.SendRPCMessage(str, response); BOOST_CHECK_EQUAL(handler.request, str); BOOST_CHECK_EQUAL(response, handler.response); BOOST_CHECK_EQUAL(response.size(), size-1); free(str); } BOOST_AUTO_TEST_CASE(test_http_server_ssl) { HttpServer server(TEST_PORT, "/a/b/c", "/d/e/f"); BOOST_CHECK_EQUAL(server.StartListening(), false); HttpServer server2(TEST_PORT, "server.pem", "server.key"); BOOST_CHECK_EQUAL(server2.StartListening(), true); server2.StopListening(); } BOOST_AUTO_TEST_SUITE_END() #endif <commit_msg>setting more gracetime for timeout testcase<commit_after>/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_http.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl <peter.knafl@gmail.com> * @license See attached LICENSE.txt ************************************************************************/ #include <boost/test/unit_test.hpp> #ifdef HTTP_TESTING #define BOOST_TEST_MODULE connector_http #include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/client/connectors/httpclient.h> #include <curl/curl.h> #include "mockclientconnectionhandler.h" #include "testhttpserver.h" using namespace jsonrpc; using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" BOOST_AUTO_TEST_SUITE(connector_http) struct F { HttpServer server; HttpClient client; MockClientConnectionHandler handler; F() : server(TEST_PORT), client(CLIENT_URL) { server.SetHandler(&handler); server.StartListening(); } ~F() { server.StopListening(); } }; bool check_exception1(JsonRpcException const&ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } bool check_exception2(JsonRpcException const&ex) { return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; } BOOST_FIXTURE_TEST_CASE(test_http_success, F) { handler.response = "exampleresponse"; string result; client.SendRPCMessage("examplerequest", result); BOOST_CHECK_EQUAL(handler.request, "examplerequest"); BOOST_CHECK_EQUAL(result, "exampleresponse"); } BOOST_AUTO_TEST_CASE(test_http_server_multiplestart) { HttpServer server(TEST_PORT); BOOST_CHECK_EQUAL(server.StartListening(), true); HttpServer server2(TEST_PORT); BOOST_CHECK_EQUAL(server2.StartListening(), false); BOOST_CHECK_EQUAL(server.StopListening(), true); } BOOST_FIXTURE_TEST_CASE(test_http_client_timeout, F) { handler.timeout = 20; client.SetTimeout(10); string result; BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); handler.timeout = 0; client.SetTimeout(10000); handler.response = "asdf"; client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(result, "asdf"); server.StopListening(); BOOST_CHECK_EXCEPTION(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); } BOOST_AUTO_TEST_CASE(test_http_client_headers) { TestHttpServer server(TEST_PORT); HttpClient client(CLIENT_URL); BOOST_REQUIRE_EQUAL(server.StartListening(),true); client.AddHeader("X-Auth", "1234"); server.SetResponse("asdf"); string result; client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(result, "asdf"); BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), "1234"); client.RemoveHeader("X-Auth"); client.SendRPCMessage("", result); BOOST_CHECK_EQUAL(server.GetHeader("X-Auth"), ""); server.StopListening(); } BOOST_FIXTURE_TEST_CASE(test_http_get,F) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); CURLcode code = curl_easy_perform(curl); BOOST_REQUIRE_EQUAL(code, CURLE_OK); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); BOOST_CHECK_EQUAL(http_code, 405); curl_easy_cleanup(curl); } BOOST_AUTO_TEST_CASE(test_http_server_endpoints) { MockClientConnectionHandler handler1; MockClientConnectionHandler handler2; handler1.response = "response1"; handler2.response = "response2"; HttpServer server(TEST_PORT); server.SetUrlHandler("/handler1", &handler1); server.SetUrlHandler("/handler2", &handler2); BOOST_REQUIRE_EQUAL(server.StartListening(), true); HttpClient client1("http://localhost:8383/handler1"); HttpClient client2("http://localhost:8383/handler2"); HttpClient client3("http://localhost:8383/handler3"); string response; client1.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response1"); client2.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response2"); BOOST_CHECK_EXCEPTION(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); client3.SetUrl("http://localhost:8383/handler2"); client3.SendRPCMessage("test", response); BOOST_CHECK_EQUAL(response, "response2"); server.StopListening(); } BOOST_FIXTURE_TEST_CASE(test_http_server_longpost, F) { int mb = 5; unsigned long size = mb * 1024*1024; char* str = (char*) malloc(size * sizeof(char)); BOOST_REQUIRE(str != NULL); for (unsigned long i=0; i < size; i++) { str[i] = (char)('a'+(i%26)); } str[size-1] = '\0'; handler.response = str; string response; client.SetTimeout(-1); client.SendRPCMessage(str, response); BOOST_CHECK_EQUAL(handler.request, str); BOOST_CHECK_EQUAL(response, handler.response); BOOST_CHECK_EQUAL(response.size(), size-1); free(str); } BOOST_AUTO_TEST_CASE(test_http_server_ssl) { HttpServer server(TEST_PORT, "/a/b/c", "/d/e/f"); BOOST_CHECK_EQUAL(server.StartListening(), false); HttpServer server2(TEST_PORT, "server.pem", "server.key"); BOOST_CHECK_EQUAL(server2.StartListening(), true); server2.StopListening(); } BOOST_AUTO_TEST_SUITE_END() #endif <|endoftext|>
<commit_before>#include "node-llvm.h" class jsIRBuilder{ // http://llvm.org/doxygen/classllvm_1_1IRBuilder.html public: static void init(Handle<Object> target){ pIRBuilder.init(&IRBConstructor); pIRBuilder.addMethod("setInsertPoint", &setInsertPoint); pIRBuilder.addMethod("createRet", &createRet); pIRBuilder.addMethod("createRetVoid", &createRetVoid); /*pIRBuilder.addMethod("createAggregateRet", &createAggregateRet); pIRBuilder.addMethod("createBr", &createRetVoid); pIRBuilder.addMethod("createCondBr", &createCondBr); pIRBuilder.addMethod("createSwitch", &createSwitch); // special type pIRBuilder.addMethod("createIndirectBr", &createIndirectBr); pIRBuilder.addMethod("createUnreachable", &createIndirectBr); pIRBuilder.addMethod("createInvoke", &createInvoke); */ pIRBuilder.addMethod("createCall", &createCall); pIRBuilder.addMethod("createAlloca", &createAlloca); pIRBuilder.addMethod("createLoad", &createLoad); // + aligned, volatile pIRBuilder.addMethod("createStore", &createStore); // + aligned, volatile // TODO: GEP // TODO: special: phi // TODO: unary ops // bool HasNUW=false, bool HasNSW=false //pIRBuilder.addMethod("createAdd", &BinOpWrMethod<&IRBuilder::CreateAdd> ); //pIRBuilder.addMethod("createSub", &BinOpWrMethod<&IRBuilder::CreateSub> ); //pIRBuilder.addMethod("createMul", &BinOpWrMethod<&IRBuilder::CreateMul> ); //pIRBuilder.addMethod("createShl", &BinOpWrMethod<&IRBuilder::CreateShl> ); // bool isExact=false //pIRBuilder.addMethod("createUDiv", &BinOpExMethod<&IRBuilder::CreateUDiv> ); //pIRBuilder.addMethod("createSDiv", &BinOpExMethod<&IRBuilder::CreateSDiv> ); //pIRBuilder.addMethod("createLShr", &BinOpExMethod<&IRBuilder::CreateLShr> ); //pIRBuilder.addMethod("createAShr", &BinOpExMethod<&IRBuilder::CreateAShr> ); pIRBuilder.addMethod("createNSWAdd", &BinOpMethod<&IRBuilder::CreateNSWAdd> ); pIRBuilder.addMethod("createNUWAdd", &BinOpMethod<&IRBuilder::CreateNUWAdd> ); pIRBuilder.addMethod("createFAdd", &BinOpMethod<&IRBuilder::CreateFAdd> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createNSWSub", &BinOpMethod<&IRBuilder::CreateNSWSub> ); pIRBuilder.addMethod("createNUWSub", &BinOpMethod<&IRBuilder::CreateNUWSub> ); pIRBuilder.addMethod("createFSub", &BinOpMethod<&IRBuilder::CreateFSub> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createNSWMul", &BinOpMethod<&IRBuilder::CreateNSWMul> ); pIRBuilder.addMethod("createNUWMul", &BinOpMethod<&IRBuilder::CreateNUWMul> ); pIRBuilder.addMethod("createFMul", &BinOpMethod<&IRBuilder::CreateFMul> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createExactUDiv", &BinOpMethod<&IRBuilder::CreateExactUDiv> ); pIRBuilder.addMethod("createExactSDiv", &BinOpMethod<&IRBuilder::CreateExactSDiv> ); pIRBuilder.addMethod("createFDiv", &BinOpMethod<&IRBuilder::CreateFDiv> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createURem", &BinOpMethod<&IRBuilder::CreateURem> ); pIRBuilder.addMethod("createSRem", &BinOpMethod<&IRBuilder::CreateSRem> ); pIRBuilder.addMethod("createFRem", &BinOpMethod<&IRBuilder::CreateFRem> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createAnd", &BinOpMethod<&IRBuilder::CreateAnd> ); pIRBuilder.addMethod("createOr", &BinOpMethod<&IRBuilder::CreateOr> ); pIRBuilder.addMethod("createXor", &BinOpMethod<&IRBuilder::CreateXor> ); pIRBuilder.addMethod("createICmpEQ", &BinOpMethod<&IRBuilder::CreateICmpEQ> ); pIRBuilder.addMethod("createICmpNE", &BinOpMethod<&IRBuilder::CreateICmpNE> ); pIRBuilder.addMethod("createICmpUGT", &BinOpMethod<&IRBuilder::CreateICmpUGT> ); pIRBuilder.addMethod("createICmpUGE", &BinOpMethod<&IRBuilder::CreateICmpUGE> ); pIRBuilder.addMethod("createICmpULT", &BinOpMethod<&IRBuilder::CreateICmpULT> ); pIRBuilder.addMethod("createICmpULE", &BinOpMethod<&IRBuilder::CreateICmpULE> ); pIRBuilder.addMethod("createICmpSGT", &BinOpMethod<&IRBuilder::CreateICmpSGT> ); pIRBuilder.addMethod("createICmpSGE", &BinOpMethod<&IRBuilder::CreateICmpSGE> ); pIRBuilder.addMethod("createICmpSLT", &BinOpMethod<&IRBuilder::CreateICmpSLT> ); pIRBuilder.addMethod("createICmpSLE", &BinOpMethod<&IRBuilder::CreateICmpSLE> ); pIRBuilder.addMethod("createFCmpOEQ", &BinOpMethod<&IRBuilder::CreateFCmpOEQ> ); pIRBuilder.addMethod("createFCmpOGT", &BinOpMethod<&IRBuilder::CreateFCmpOGT> ); pIRBuilder.addMethod("createFCmpOGE", &BinOpMethod<&IRBuilder::CreateFCmpOGE> ); pIRBuilder.addMethod("createFCmpOLT", &BinOpMethod<&IRBuilder::CreateFCmpOLT> ); pIRBuilder.addMethod("createFCmpOLE", &BinOpMethod<&IRBuilder::CreateFCmpOLE> ); pIRBuilder.addMethod("createFCmpONE", &BinOpMethod<&IRBuilder::CreateFCmpONE> ); pIRBuilder.addMethod("createFCmpORD", &BinOpMethod<&IRBuilder::CreateFCmpORD> ); pIRBuilder.addMethod("createFCmpUNO", &BinOpMethod<&IRBuilder::CreateFCmpUNO> ); pIRBuilder.addMethod("createFCmpUEQ", &BinOpMethod<&IRBuilder::CreateFCmpUEQ> ); pIRBuilder.addMethod("createFCmpUGT", &BinOpMethod<&IRBuilder::CreateFCmpUGT> ); pIRBuilder.addMethod("createFCmpUGE", &BinOpMethod<&IRBuilder::CreateFCmpUGE> ); pIRBuilder.addMethod("createFCmpULT", &BinOpMethod<&IRBuilder::CreateFCmpULT> ); pIRBuilder.addMethod("createFCmpULE", &BinOpMethod<&IRBuilder::CreateFCmpULE> ); pIRBuilder.addMethod("createFCmpUNE", &BinOpMethod<&IRBuilder::CreateFCmpUNE> ); //CreateICmp (CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="") //CreateFCmp (CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="") // TODO: there are more (CmpXXX) // TODO: cast (Value*, Type*) functions } static Handle<Value> IRBConstructor(const Arguments& args){ ENTER_CONSTRUCTOR(1); CHECK_N_ARGS(1); UNWRAP_ARG(pContext, context, 0); setConst(args.This(), "context", args[0]); setConst(args.This(), "insertBlock", Undefined()); IRBuilder* b = new IRBuilder(*context); pIRBuilder.wrap(args.This(), b); return scope.Close(args.This()); } static Handle<Value> setInsertPoint(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pBasicBlock, p, 0); // TODO: could also be Instruction setConst(args.This(), "insertBlock", args[0]); self->SetInsertPoint(p); return args[1]; } #define RETURN_INSTR(TP, VAL) \ return scope.Close(TP.create(VAL, args.This()->Get(String::NewSymbol("insertBlock")))); static Handle<Value> createRet(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, v, 0); RETURN_INSTR(pValue, self->CreateRet(v)); } static Handle<Value> createRetVoid(const Arguments& args){ ENTER_METHOD(pIRBuilder, 0); RETURN_INSTR(pValue, self->CreateRetVoid()); } static Handle<Value> createAlloca(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pType, type, 0); auto arraySize = pValue.unwrap(args[1]); // can be null STRING_ARG(name, 2); RETURN_INSTR(pValue, self->CreateAlloca(type, arraySize, name)); } static Handle<Value> createLoad(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, ptr, 0); STRING_ARG(name, 1); RETURN_INSTR(pValue, self->CreateLoad(ptr)); } static Handle<Value> createStore(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, ptr, 0); UNWRAP_ARG(pValue, val, 1); RETURN_INSTR(pValue, self->CreateStore(ptr, val)); } static Handle<Value> createCall(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, fn, 0); ARRAY_UNWRAP_ARG(pValue, llvm::Value, fnargs, 1); STRING_ARG(name, 2); RETURN_INSTR(pValue, self->CreateCall(fn, fnargs, name)); } typedef llvm::Value* (IRBuilder::*UnaryOpFn)(llvm::Value*, const llvm::Twine&); template<UnaryOpFn method> static Handle<Value> UnaryOpMethod(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, v, 0); STRING_ARG(name, 1); RETURN_INSTR(pValue, (self->*method)(v, name)); } typedef llvm::Value* (IRBuilder::*BinaryOpFn)(llvm::Value*, llvm::Value*, const llvm::Twine&); template<BinaryOpFn method> static Handle<Value> BinOpMethod(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, l, 0); UNWRAP_ARG(pValue, r, 1); STRING_ARG(name, 2); RETURN_INSTR(pValue, (self->*method)(l, r, name)); } }; Proto<IRBuilder> pIRBuilder("IRBuilder", &jsIRBuilder::init);<commit_msg>IRBuilder: Wrap typecast methods<commit_after>#include "node-llvm.h" class jsIRBuilder{ // http://llvm.org/doxygen/classllvm_1_1IRBuilder.html public: static void init(Handle<Object> target){ pIRBuilder.init(&IRBConstructor); pIRBuilder.addMethod("setInsertPoint", &setInsertPoint); pIRBuilder.addMethod("createRet", &createRet); pIRBuilder.addMethod("createRetVoid", &createRetVoid); /*pIRBuilder.addMethod("createAggregateRet", &createAggregateRet); pIRBuilder.addMethod("createBr", &createRetVoid); pIRBuilder.addMethod("createCondBr", &createCondBr); pIRBuilder.addMethod("createSwitch", &createSwitch); // special type pIRBuilder.addMethod("createIndirectBr", &createIndirectBr); pIRBuilder.addMethod("createUnreachable", &createIndirectBr); pIRBuilder.addMethod("createInvoke", &createInvoke); */ pIRBuilder.addMethod("createCall", &createCall); pIRBuilder.addMethod("createAlloca", &createAlloca); pIRBuilder.addMethod("createLoad", &createLoad); // + aligned, volatile pIRBuilder.addMethod("createStore", &createStore); // + aligned, volatile // TODO: GEP // TODO: special: phi // TODO: unary ops // bool HasNUW=false, bool HasNSW=false //pIRBuilder.addMethod("createAdd", &BinOpWrMethod<&IRBuilder::CreateAdd> ); //pIRBuilder.addMethod("createSub", &BinOpWrMethod<&IRBuilder::CreateSub> ); //pIRBuilder.addMethod("createMul", &BinOpWrMethod<&IRBuilder::CreateMul> ); //pIRBuilder.addMethod("createShl", &BinOpWrMethod<&IRBuilder::CreateShl> ); // bool isExact=false //pIRBuilder.addMethod("createUDiv", &BinOpExMethod<&IRBuilder::CreateUDiv> ); //pIRBuilder.addMethod("createSDiv", &BinOpExMethod<&IRBuilder::CreateSDiv> ); //pIRBuilder.addMethod("createLShr", &BinOpExMethod<&IRBuilder::CreateLShr> ); //pIRBuilder.addMethod("createAShr", &BinOpExMethod<&IRBuilder::CreateAShr> ); pIRBuilder.addMethod("createNSWAdd", &BinOpMethod<&IRBuilder::CreateNSWAdd> ); pIRBuilder.addMethod("createNUWAdd", &BinOpMethod<&IRBuilder::CreateNUWAdd> ); pIRBuilder.addMethod("createFAdd", &BinOpMethod<&IRBuilder::CreateFAdd> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createNSWSub", &BinOpMethod<&IRBuilder::CreateNSWSub> ); pIRBuilder.addMethod("createNUWSub", &BinOpMethod<&IRBuilder::CreateNUWSub> ); pIRBuilder.addMethod("createFSub", &BinOpMethod<&IRBuilder::CreateFSub> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createNSWMul", &BinOpMethod<&IRBuilder::CreateNSWMul> ); pIRBuilder.addMethod("createNUWMul", &BinOpMethod<&IRBuilder::CreateNUWMul> ); pIRBuilder.addMethod("createFMul", &BinOpMethod<&IRBuilder::CreateFMul> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createExactUDiv", &BinOpMethod<&IRBuilder::CreateExactUDiv> ); pIRBuilder.addMethod("createExactSDiv", &BinOpMethod<&IRBuilder::CreateExactSDiv> ); pIRBuilder.addMethod("createFDiv", &BinOpMethod<&IRBuilder::CreateFDiv> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createURem", &BinOpMethod<&IRBuilder::CreateURem> ); pIRBuilder.addMethod("createSRem", &BinOpMethod<&IRBuilder::CreateSRem> ); pIRBuilder.addMethod("createFRem", &BinOpMethod<&IRBuilder::CreateFRem> ); // MDNode *FPMathTag=0) pIRBuilder.addMethod("createAnd", &BinOpMethod<&IRBuilder::CreateAnd> ); pIRBuilder.addMethod("createOr", &BinOpMethod<&IRBuilder::CreateOr> ); pIRBuilder.addMethod("createXor", &BinOpMethod<&IRBuilder::CreateXor> ); pIRBuilder.addMethod("createICmpEQ", &BinOpMethod<&IRBuilder::CreateICmpEQ> ); pIRBuilder.addMethod("createICmpNE", &BinOpMethod<&IRBuilder::CreateICmpNE> ); pIRBuilder.addMethod("createICmpUGT", &BinOpMethod<&IRBuilder::CreateICmpUGT> ); pIRBuilder.addMethod("createICmpUGE", &BinOpMethod<&IRBuilder::CreateICmpUGE> ); pIRBuilder.addMethod("createICmpULT", &BinOpMethod<&IRBuilder::CreateICmpULT> ); pIRBuilder.addMethod("createICmpULE", &BinOpMethod<&IRBuilder::CreateICmpULE> ); pIRBuilder.addMethod("createICmpSGT", &BinOpMethod<&IRBuilder::CreateICmpSGT> ); pIRBuilder.addMethod("createICmpSGE", &BinOpMethod<&IRBuilder::CreateICmpSGE> ); pIRBuilder.addMethod("createICmpSLT", &BinOpMethod<&IRBuilder::CreateICmpSLT> ); pIRBuilder.addMethod("createICmpSLE", &BinOpMethod<&IRBuilder::CreateICmpSLE> ); pIRBuilder.addMethod("createFCmpOEQ", &BinOpMethod<&IRBuilder::CreateFCmpOEQ> ); pIRBuilder.addMethod("createFCmpOGT", &BinOpMethod<&IRBuilder::CreateFCmpOGT> ); pIRBuilder.addMethod("createFCmpOGE", &BinOpMethod<&IRBuilder::CreateFCmpOGE> ); pIRBuilder.addMethod("createFCmpOLT", &BinOpMethod<&IRBuilder::CreateFCmpOLT> ); pIRBuilder.addMethod("createFCmpOLE", &BinOpMethod<&IRBuilder::CreateFCmpOLE> ); pIRBuilder.addMethod("createFCmpONE", &BinOpMethod<&IRBuilder::CreateFCmpONE> ); pIRBuilder.addMethod("createFCmpORD", &BinOpMethod<&IRBuilder::CreateFCmpORD> ); pIRBuilder.addMethod("createFCmpUNO", &BinOpMethod<&IRBuilder::CreateFCmpUNO> ); pIRBuilder.addMethod("createFCmpUEQ", &BinOpMethod<&IRBuilder::CreateFCmpUEQ> ); pIRBuilder.addMethod("createFCmpUGT", &BinOpMethod<&IRBuilder::CreateFCmpUGT> ); pIRBuilder.addMethod("createFCmpUGE", &BinOpMethod<&IRBuilder::CreateFCmpUGE> ); pIRBuilder.addMethod("createFCmpULT", &BinOpMethod<&IRBuilder::CreateFCmpULT> ); pIRBuilder.addMethod("createFCmpULE", &BinOpMethod<&IRBuilder::CreateFCmpULE> ); pIRBuilder.addMethod("createFCmpUNE", &BinOpMethod<&IRBuilder::CreateFCmpUNE> ); //CreateICmp (CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="") //CreateFCmp (CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="") pIRBuilder.addMethod("createTrunc", &CastOpMethod<&IRBuilder::CreateTrunc> ); pIRBuilder.addMethod("createZExt", &CastOpMethod<&IRBuilder::CreateZExt> ); pIRBuilder.addMethod("createSExt", &CastOpMethod<&IRBuilder::CreateSExt> ); //pIRBuilder.addMethod("createZExtOrTrunc", &CastOpMethod<&IRBuilder::CreateZExtOrTrunc> ); //pIRBuilder.addMethod("createSExtOrTrunc", &CastOpMethod<&IRBuilder::CreateSExtOrTrunc> ); pIRBuilder.addMethod("createFPToUI", &CastOpMethod<&IRBuilder::CreateFPToUI> ); pIRBuilder.addMethod("createFPToSI", &CastOpMethod<&IRBuilder::CreateFPToSI> ); pIRBuilder.addMethod("createUIToFP", &CastOpMethod<&IRBuilder::CreateUIToFP> ); pIRBuilder.addMethod("createSIToFP", &CastOpMethod<&IRBuilder::CreateSIToFP> ); pIRBuilder.addMethod("createFPTrunc", &CastOpMethod<&IRBuilder::CreateFPTrunc> ); pIRBuilder.addMethod("createFPExt", &CastOpMethod<&IRBuilder::CreateFPExt> ); pIRBuilder.addMethod("createPtrToInt", &CastOpMethod<&IRBuilder::CreatePtrToInt> ); pIRBuilder.addMethod("createIntToPtr", &CastOpMethod<&IRBuilder::CreateIntToPtr> ); pIRBuilder.addMethod("createBitCast", &CastOpMethod<&IRBuilder::CreateBitCast> ); pIRBuilder.addMethod("createZExtOrBitCast", &CastOpMethod<&IRBuilder::CreateZExtOrBitCast> ); pIRBuilder.addMethod("createSExtOrBitCast", &CastOpMethod<&IRBuilder::CreateSExtOrBitCast> ); pIRBuilder.addMethod("createTruncOrBitCast", &CastOpMethod<&IRBuilder::CreateTruncOrBitCast> ); //pIRBuilder.addMethod("createCast", &CastOpMethod<&IRBuilder::CreateCast> ); pIRBuilder.addMethod("createPointerCast", &CastOpMethod<&IRBuilder::CreatePointerCast> ); //pIRBuilder.addMethod("createIntCast", &CastOpMethod<&IRBuilder::CreateIntCast> ); pIRBuilder.addMethod("createFPCast", &CastOpMethod<&IRBuilder::CreateFPCast> ); // TODO: cast (Value*, Type*) functions } static Handle<Value> IRBConstructor(const Arguments& args){ ENTER_CONSTRUCTOR(1); CHECK_N_ARGS(1); UNWRAP_ARG(pContext, context, 0); setConst(args.This(), "context", args[0]); setConst(args.This(), "insertBlock", Undefined()); IRBuilder* b = new IRBuilder(*context); pIRBuilder.wrap(args.This(), b); return scope.Close(args.This()); } static Handle<Value> setInsertPoint(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pBasicBlock, p, 0); // TODO: could also be Instruction setConst(args.This(), "insertBlock", args[0]); self->SetInsertPoint(p); return args[1]; } #define RETURN_INSTR(TP, VAL) \ return scope.Close(TP.create(VAL, args.This()->Get(String::NewSymbol("insertBlock")))); static Handle<Value> createRet(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, v, 0); RETURN_INSTR(pValue, self->CreateRet(v)); } static Handle<Value> createRetVoid(const Arguments& args){ ENTER_METHOD(pIRBuilder, 0); RETURN_INSTR(pValue, self->CreateRetVoid()); } static Handle<Value> createAlloca(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pType, type, 0); auto arraySize = pValue.unwrap(args[1]); // can be null STRING_ARG(name, 2); RETURN_INSTR(pValue, self->CreateAlloca(type, arraySize, name)); } static Handle<Value> createLoad(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, ptr, 0); STRING_ARG(name, 1); RETURN_INSTR(pValue, self->CreateLoad(ptr)); } static Handle<Value> createStore(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, ptr, 0); UNWRAP_ARG(pValue, val, 1); RETURN_INSTR(pValue, self->CreateStore(ptr, val)); } static Handle<Value> createCall(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, fn, 0); ARRAY_UNWRAP_ARG(pValue, llvm::Value, fnargs, 1); STRING_ARG(name, 2); RETURN_INSTR(pValue, self->CreateCall(fn, fnargs, name)); } typedef llvm::Value* (IRBuilder::*UnaryOpFn)(llvm::Value*, const llvm::Twine&); template<UnaryOpFn method> static Handle<Value> UnaryOpMethod(const Arguments& args){ ENTER_METHOD(pIRBuilder, 1); UNWRAP_ARG(pValue, v, 0); STRING_ARG(name, 1); RETURN_INSTR(pValue, (self->*method)(v, name)); } typedef llvm::Value* (IRBuilder::*BinaryOpFn)(llvm::Value*, llvm::Value*, const llvm::Twine&); template<BinaryOpFn method> static Handle<Value> BinOpMethod(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, l, 0); UNWRAP_ARG(pValue, r, 1); STRING_ARG(name, 2); RETURN_INSTR(pValue, (self->*method)(l, r, name)); } typedef llvm::Value* (IRBuilder::*CastOpFn)(llvm::Value*, llvm::Type*, const llvm::Twine&); template<CastOpFn method> static Handle<Value> CastOpMethod(const Arguments& args){ ENTER_METHOD(pIRBuilder, 2); UNWRAP_ARG(pValue, v, 0); UNWRAP_ARG(pType, t, 1); STRING_ARG(name, 2); RETURN_INSTR(pValue, (self->*method)(v, t, name)); } }; Proto<IRBuilder> pIRBuilder("IRBuilder", &jsIRBuilder::init);<|endoftext|>
<commit_before>#ifndef KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { // void_t implementation template<typename...> struct voider { using type = void; }; template<typename... Ts> using void_t = typename voider<Ts...>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename Tuple> struct TupleSeqGen : seq_gen<std::tuple_size<Tuple>::value> {}; template<> struct TupleSeqGen<std::tuple<>> : seq_gen<0> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - (n > std::tuple_size<Tuple>::value ? std::tuple_size<Tuple>::value : n)>::type; // SFINAE utilities template<typename T, typename = void> struct has_invoke : std::false_type {}; template<typename T> struct has_invoke<T, void_t<typename T::invoke>> : std::true_type {}; template<typename T, typename = void> struct has_next : std::false_type {}; template<typename T> struct has_next<T, void_t<typename T::Next>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; template<typename T, typename = void> struct has_construct : std::false_type {}; template<typename T> struct has_construct<T, void_t<decltype(&T::construct)>> : std::true_type {}; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Params>> : std::true_type {}; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_template_construct_helper { private: template<typename U, typename... As> static std::true_type test(decltype(&U::template construct<As...>)* = nullptr); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(nullptr)); }; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(std::declval<U>().emplace(std::declval<As>()...)), std::true_type{}) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<template<typename> class, typename, typename, typename...> struct is_invokable_helper; template<template<typename> class Map, typename T, typename... Args, std::size_t... S> struct is_invokable_helper<Map, T, seq<S...>, Args...> { private: template<typename U, typename... As> static decltype( static_cast<void>(std::declval<U>()(std::declval<ServiceType<service_map_t<Map, function_argument_t<S, decay_t<U>>>>>()..., std::declval<As>()...)), std::true_type{} ) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_emplace : has_emplace_helper<T, Args...>::type {}; template<typename T, typename... Args> struct is_brace_constructible : is_brace_constructible_helper<T, Args...>::type {}; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&> { using type = T&; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename... Ts> struct has_template_construct : has_template_construct_helper<Ts...>::type {}; template<typename... Ts> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<Ts...>::value || std::is_constructible<Ts...>::value>; template<typename T, typename... Args> using is_emplaceable = typename std::conditional<std::is_default_constructible<T>::value && has_emplace<T, Args...>::value, std::true_type, std::false_type>::type; template<template<typename> class Map, typename U, typename... Args> struct is_invokable : is_invokable_helper<Map, U, tuple_seq_minus<function_arguments_t<U>, sizeof...(Args)>, Args...>::type {}; } // namespace detail } // namespace kgr #endif // KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <commit_msg>removed useless decay<commit_after>#ifndef KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { // void_t implementation template<typename...> struct voider { using type = void; }; template<typename... Ts> using void_t = typename voider<Ts...>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename Tuple> struct TupleSeqGen : seq_gen<std::tuple_size<Tuple>::value> {}; template<> struct TupleSeqGen<std::tuple<>> : seq_gen<0> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - (n > std::tuple_size<Tuple>::value ? std::tuple_size<Tuple>::value : n)>::type; // SFINAE utilities template<typename T, typename = void> struct has_invoke : std::false_type {}; template<typename T> struct has_invoke<T, void_t<typename T::invoke>> : std::true_type {}; template<typename T, typename = void> struct has_next : std::false_type {}; template<typename T> struct has_next<T, void_t<typename T::Next>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; template<typename T, typename = void> struct has_construct : std::false_type {}; template<typename T> struct has_construct<T, void_t<decltype(&T::construct)>> : std::true_type {}; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Params>> : std::true_type {}; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_template_construct_helper { private: template<typename U, typename... As> static std::true_type test(decltype(&U::template construct<As...>)* = nullptr); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(nullptr)); }; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(std::declval<U>().emplace(std::declval<As>()...)), std::true_type{}) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<template<typename> class, typename, typename, typename...> struct is_invokable_helper; template<template<typename> class Map, typename T, typename... Args, std::size_t... S> struct is_invokable_helper<Map, T, seq<S...>, Args...> { private: template<typename U, typename... As> static decltype( static_cast<void>(std::declval<U>()(std::declval<ServiceType<service_map_t<Map, function_argument_t<S, U>>>>()..., std::declval<As>()...)), std::true_type{} ) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_emplace : has_emplace_helper<T, Args...>::type {}; template<typename T, typename... Args> struct is_brace_constructible : is_brace_constructible_helper<T, Args...>::type {}; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&> { using type = T&; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename... Ts> struct has_template_construct : has_template_construct_helper<Ts...>::type {}; template<typename... Ts> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<Ts...>::value || std::is_constructible<Ts...>::value>; template<typename T, typename... Args> using is_emplaceable = typename std::conditional<std::is_default_constructible<T>::value && has_emplace<T, Args...>::value, std::true_type, std::false_type>::type; template<template<typename> class Map, typename U, typename... Args> struct is_invokable : is_invokable_helper<Map, U, tuple_seq_minus<function_arguments_t<U>, sizeof...(Args)>, Args...>::type {}; } // namespace detail } // namespace kgr #endif // KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include "meta_list.hpp" #include "void_t.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { template<typename...> struct to_false { using type = std::false_type; }; template<typename... Ts> using false_t = typename to_false<Ts...>::type; template<typename...> struct to_int { using type = int; }; // Workaround for visual studio to take the address of a generic lambda template<typename T> T exact(T); template<typename... Ts> using int_t = typename to_int<Ts...>::type; template<typename T> struct identity { using type = T; }; template<typename T> using identity_t = typename identity<T>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t size, std::size_t align> using aligned_storage_t = typename std::aligned_storage<size, align>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename> struct TupleSeqGen; template<typename... Types> struct TupleSeqGen<std::tuple<Types...>> : seq_gen<sizeof...(Types)> {}; template<typename... Types> struct TupleSeqGen<detail::meta_list<Types...>> : seq_gen<sizeof...(Types)> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename F> using function_seq = tuple_seq<function_arguments_t<F>>; template<typename List, int n> using tuple_seq_minus = typename detail::seq_gen<meta_list_size<List>::value - (n > meta_list_size<List>::value ? meta_list_size<List>::value : n)>::type; // SFINAE utilities template<typename From, typename To> using is_explicitly_convertible = std::is_constructible<To, From>; template<typename T, typename = void> struct has_autocall : std::false_type {}; template<typename T> struct has_autocall<T, void_t<typename T::Autocall>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; // Here, usual traits using void_t don't quite work with visual studio for this particular case. template<typename T> struct has_construct_helper { private: template<typename U, typename V = decltype(&U::construct)> static std::true_type test(int); template<typename> static std::false_type test(...); public: using type = decltype(test<T>(0)); }; template<typename T> using has_construct = typename has_construct_helper<T>::type; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Parameters>> : std::true_type {}; template<typename T, typename F> using is_member_autocall = std::integral_constant<bool, !is_invoke_call<F>::value>; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; struct Sink { constexpr Sink() = default; template<typename T> constexpr operator T&& () const; template<typename T> constexpr operator const T& () const; }; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(std::declval<U>().emplace(std::declval<As>()...)), std::true_type{}) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T> using is_service_embeddable = std::integral_constant<bool, std::is_trivially_destructible<T>::value && sizeof(T) <= sizeof(void*) && alignof(T) <= alignof(void*) >; template<typename T, typename... Args> using has_emplace = typename has_emplace_helper<T, Args...>::type; template<typename T, typename... Args> using is_brace_constructible = typename is_brace_constructible_helper<T, Args...>::type; template<typename T, typename... Args> using is_only_brace_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value && !std::is_constructible<T, Args...>::value>; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename T, typename... Args> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value || std::is_constructible<T, Args...>::value>; template<typename T, typename... Args> using is_emplaceable = std::integral_constant<bool, std::is_default_constructible<T>::value && has_emplace<T, Args...>::value>; template<typename T, typename... Args> using is_service_instantiable = std::integral_constant<bool, is_emplaceable<T, Args...>::value || is_someway_constructible<T, kgr::in_place_t, Args...>::value>; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <commit_msg>Better trait style<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include "meta_list.hpp" #include "void_t.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { template<typename...> struct to_false { using type = std::false_type; }; template<typename... Ts> using false_t = typename to_false<Ts...>::type; template<typename...> struct to_int { using type = int; }; // Workaround for visual studio to take the address of a generic lambda template<typename T> T exact(T); template<typename... Ts> using int_t = typename to_int<Ts...>::type; template<typename T> struct identity { using type = T; }; template<typename T> using identity_t = typename identity<T>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t size, std::size_t align> using aligned_storage_t = typename std::aligned_storage<size, align>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename> struct TupleSeqGen; template<typename... Types> struct TupleSeqGen<std::tuple<Types...>> : seq_gen<sizeof...(Types)> {}; template<typename... Types> struct TupleSeqGen<detail::meta_list<Types...>> : seq_gen<sizeof...(Types)> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename F> using function_seq = tuple_seq<function_arguments_t<F>>; template<typename List, int n> using tuple_seq_minus = typename detail::seq_gen<meta_list_size<List>::value - (n > meta_list_size<List>::value ? meta_list_size<List>::value : n)>::type; // SFINAE utilities template<typename From, typename To> using is_explicitly_convertible = std::is_constructible<To, From>; template<typename T, typename = void> struct has_autocall : std::false_type {}; template<typename T> struct has_autocall<T, void_t<typename T::Autocall>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; // Here, usual traits using void_t don't quite work with visual studio for this particular case. template<typename T> struct has_construct_helper { private: template<typename U, typename V = decltype(&U::construct)> static std::true_type test(int); template<typename> static std::false_type test(...); public: using type = decltype(test<T>(0)); }; template<typename T> using has_construct = typename has_construct_helper<T>::type; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Parameters>> : std::true_type {}; template<typename T, typename F> using is_member_autocall = std::integral_constant<bool, !is_invoke_call<F>::value>; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; struct Sink { constexpr Sink() = default; template<typename T> constexpr operator T&& () const; template<typename T> constexpr operator const T& () const; }; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As, int_t<decltype(std::declval<U>().emplace(std::declval<As>()...))> = 0> static std::true_type test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T> using is_service_embeddable = std::integral_constant<bool, std::is_trivially_destructible<T>::value && sizeof(T) <= sizeof(void*) && alignof(T) <= alignof(void*) >; template<typename T, typename... Args> using has_emplace = typename has_emplace_helper<T, Args...>::type; template<typename T, typename... Args> using is_brace_constructible = typename is_brace_constructible_helper<T, Args...>::type; template<typename T, typename... Args> using is_only_brace_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value && !std::is_constructible<T, Args...>::value>; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename T, typename... Args> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value || std::is_constructible<T, Args...>::value>; template<typename T, typename... Args> using is_emplaceable = std::integral_constant<bool, std::is_default_constructible<T>::value && has_emplace<T, Args...>::value>; template<typename T, typename... Args> using is_service_instantiable = std::integral_constant<bool, is_emplaceable<T, Args...>::value || is_someway_constructible<T, kgr::in_place_t, Args...>::value>; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <|endoftext|>
<commit_before>#if defined(__clang__) || defined(__GNUC__) #include "../test.h" #include "nlohmann/src/json.hpp" #include "taocppjson/include/tao/json.hp" #include "taocppjson/contrib/nlohmann/to_value.hpp" #include "taocppjson/contrib/nlohmann/from_value.hpp" using namespace nlohmann; static void GenStat(Stat& stat, const json& v) { switch (v.type()) { case json::value_t::array: for (auto& element : v) GenStat(stat, element); stat.arrayCount++; stat.elementCount += v.size(); break; case json::value_t::object: for (json::const_iterator it = v.begin(); it != v.end(); ++it) { GenStat(stat, it.value()); stat.stringLength += it.key().size(); } stat.objectCount++; stat.memberCount += v.size(); stat.stringCount += v.size(); break; case json::value_t::string: stat.stringCount++; stat.stringLength += v.get<std::string>().size(); break; case json::value_t::number_integer: case json::value_t::number_unsigned: case json::value_t::number_float: stat.numberCount++; break; case json::value_t::boolean: if (v) stat.trueCount++; else stat.falseCount++; break; case json::value_t::null: stat.nullCount++; break; case json::value_t::discarded: throw std::logic_error( "code should be unreachable" ); } } class NlohmannParseResult : public ParseResultBase { public: json root; }; class NlohmannStringResult : public StringResultBase { public: virtual const char* c_str() const { return s.c_str(); } std::string s; }; class TaocppNlohmannTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "taocpp/json & Nlohmann (C++11)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* j, size_t length) const { NlohmannParseResult* pr = new NlohmannParseResult; try { tao::json::nlohmann::to_value<json> handler; tao::json::sax::from_string(j, length, handler); pr->root = std::move( handler.value ); } catch (...) { delete pr; return 0; } return pr; } #endif #if TEST_STRINGIFY virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); NlohmannStringResult* sr = new NlohmannStringResult; std::ostringstream oss; tao::json::sax::to_stream oss_handler(oss); tao::json::nlohmann::from_value(pr->root, oss_handler); sr->s = oss.str(); return sr; } #endif #if TEST_PRETTIFY virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); NlohmannStringResult* sr = new NlohmannStringResult; std::ostringstream oss; tao::json::sax::to_pretty_stream oss_handler(oss, 4); tao::json::nlohmann::from_value(pr->root, oss_handler); sr->s = oss.str(); return sr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(*stat, pr->root); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* j, double* d) const { try { json root = json::parse(j); *d = root[0].get<double>(); return true; } catch (...) { } return false; } virtual bool ParseString(const char* j, std::string& s) const { try { json root = json::parse(j); s = root[0].get<std::string>(); return true; } catch (...) { } return false; } #endif }; REGISTER_TEST(TaocppNlohmannTest); #endif <commit_msg>Fix typo<commit_after>#if defined(__clang__) || defined(__GNUC__) #include "../test.h" #include "nlohmann/src/json.hpp" #include "taocppjson/include/tao/json.hpp" #include "taocppjson/contrib/nlohmann/to_value.hpp" #include "taocppjson/contrib/nlohmann/from_value.hpp" using namespace nlohmann; static void GenStat(Stat& stat, const json& v) { switch (v.type()) { case json::value_t::array: for (auto& element : v) GenStat(stat, element); stat.arrayCount++; stat.elementCount += v.size(); break; case json::value_t::object: for (json::const_iterator it = v.begin(); it != v.end(); ++it) { GenStat(stat, it.value()); stat.stringLength += it.key().size(); } stat.objectCount++; stat.memberCount += v.size(); stat.stringCount += v.size(); break; case json::value_t::string: stat.stringCount++; stat.stringLength += v.get<std::string>().size(); break; case json::value_t::number_integer: case json::value_t::number_unsigned: case json::value_t::number_float: stat.numberCount++; break; case json::value_t::boolean: if (v) stat.trueCount++; else stat.falseCount++; break; case json::value_t::null: stat.nullCount++; break; case json::value_t::discarded: throw std::logic_error( "code should be unreachable" ); } } class NlohmannParseResult : public ParseResultBase { public: json root; }; class NlohmannStringResult : public StringResultBase { public: virtual const char* c_str() const { return s.c_str(); } std::string s; }; class TaocppNlohmannTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "taocpp/json & Nlohmann (C++11)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* j, size_t length) const { NlohmannParseResult* pr = new NlohmannParseResult; try { tao::json::nlohmann::to_value<json> handler; tao::json::sax::from_string(j, length, handler); pr->root = std::move( handler.value ); } catch (...) { delete pr; return 0; } return pr; } #endif #if TEST_STRINGIFY virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); NlohmannStringResult* sr = new NlohmannStringResult; std::ostringstream oss; tao::json::sax::to_stream oss_handler(oss); tao::json::nlohmann::from_value(pr->root, oss_handler); sr->s = oss.str(); return sr; } #endif #if TEST_PRETTIFY virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); NlohmannStringResult* sr = new NlohmannStringResult; std::ostringstream oss; tao::json::sax::to_pretty_stream oss_handler(oss, 4); tao::json::nlohmann::from_value(pr->root, oss_handler); sr->s = oss.str(); return sr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const NlohmannParseResult* pr = static_cast<const NlohmannParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(*stat, pr->root); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* j, double* d) const { try { json root = json::parse(j); *d = root[0].get<double>(); return true; } catch (...) { } return false; } virtual bool ParseString(const char* j, std::string& s) const { try { json root = json::parse(j); s = root[0].get<std::string>(); return true; } catch (...) { } return false; } #endif }; REGISTER_TEST(TaocppNlohmannTest); #endif <|endoftext|>
<commit_before>#ifndef KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { // void_t implementation template<typename...> struct voider { using type = void; }; template<typename... Ts> using void_t = typename voider<Ts...>::type; template<typename...> struct to_false { using type = std::false_type; }; template<typename... Ts> using false_t = typename to_false<Ts...>::type; template<typename...> struct to_int { using type = int; }; template<typename... Ts> using int_t = typename to_int<Ts...>::type; template<typename T> struct identity { using type = T; }; template<typename T> using identity_t = typename identity<T>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename Tuple> struct TupleSeqGen : seq_gen<std::tuple_size<Tuple>::value> {}; template<> struct TupleSeqGen<std::tuple<>> : seq_gen<0> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - (n > std::tuple_size<Tuple>::value ? std::tuple_size<Tuple>::value : n)>::type; // SFINAE utilities template<typename T, typename = void> struct has_autocall : std::false_type {}; template<typename T> struct has_autocall<T, void_t<typename T::autocall>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; template<typename T, typename = void> struct has_construct : std::false_type {}; template<typename T> struct has_construct<T, void_t<decltype(&T::construct)>> : std::true_type {}; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Parameters>> : std::true_type {}; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; struct Sink { constexpr Sink() = default; template<typename T> constexpr operator T&& () const; }; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_template_construct_helper { private: template<typename U, typename... As> static std::true_type test(decltype(&U::template construct<As...>)* = nullptr); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(nullptr)); }; template<typename... Ts> using has_template_construct = typename has_template_construct_helper<Ts...>::type; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(std::declval<U>().emplace(std::declval<As>()...)), std::true_type{}) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<template<typename> class, typename, typename...> struct is_invokable_helper; template<template<typename> class Map, typename T, typename... Args> struct is_invokable_helper<Map, T, Args...> { private: template<typename U, typename... As, std::size_t... S> static std::true_type test(seq<S...>, decltype(std::declval<U>()(std::declval<ServiceType<service_map_t<Map, function_argument_t<S, U>>>>()..., std::declval<As>()...))*); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(tuple_seq_minus<function_arguments_t<T>, sizeof...(Args)>{}, nullptr)); }; template<template<typename> class Map, typename T, typename... Args> struct defer_is_invokable_helper { static constexpr bool value = is_invokable_helper<Map, T, Args...>::type::value; }; template<bool, typename T, typename... Args> struct construct_function_helper { private: template<typename U, typename... As> struct get_template_construct { using type = std::integral_constant<decltype(&U::template construct<As...>), &U::template construct<As...>>; }; template<typename U> struct get_construct { using type = std::integral_constant<decltype(&U::construct), &U::construct>; }; template<typename U, typename... As, enable_if_t<has_construct<U>::value, int> = 0, enable_if_t<!has_template_construct<U, As...>::value, int> = 0> static get_construct<U> test(); template<typename U, typename... As, enable_if_t<has_template_construct<U, As...>::value, int> = 0> static get_template_construct<U, Args...> test(); using inner_type = decltype(test<T, Args...>()); public: using type = typename inner_type::type; }; template<typename T, typename... Args> struct construct_function_helper<false, T, Args...> {}; template<typename T, typename... Args> using has_any_construct = std::integral_constant<bool, has_template_construct<T, Args...>::value || has_construct<T>::value>; template<typename T, typename... Args> using construct_function = typename construct_function_helper<has_any_construct<T, Args...>::value, T, Args...>::type; template<typename T, typename... Args> using construct_function_t = typename construct_function<T, Args...>::value_type; template<typename T, typename... Args> using construct_result_seq = tuple_seq<function_result_t<construct_function_t<T, Args...>>>; template<typename T, typename... Args> using has_emplace = typename has_emplace_helper<T, Args...>::type; template<typename T, typename... Args> using is_brace_constructible = typename is_brace_constructible_helper<T, Args...>::type; template<typename T, typename... Args> using is_only_brace_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value && !std::is_constructible<T, Args...>::value>; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename T, typename... Args> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value || std::is_constructible<T, Args...>::value>; template<typename T, typename... Args> using is_emplaceable = std::integral_constant<bool, std::is_default_constructible<T>::value && has_emplace<T, Args...>::value>; template<typename T, typename... Args> using is_service_instantiable = std::integral_constant<bool, is_emplaceable<T, Args...>::value || is_someway_constructible<T, kgr::in_place_t, Args...>::value>; template<template<typename> class Map, typename U, typename... Args> using is_invokable = std::integral_constant<bool, defer_is_invokable_helper<Map, U, Args...>::value>; } // namespace detail } // namespace kgr #endif // KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <commit_msg>fixed compilation for gcc and clang<commit_after>#ifndef KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #define KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP #include "function_traits.hpp" #include "utils.hpp" #include <type_traits> #include <tuple> namespace kgr { namespace detail { // void_t implementation template<typename...> struct voider { using type = void; }; template<typename... Ts> using void_t = typename voider<Ts...>::type; template<typename...> struct to_false { using type = std::false_type; }; template<typename... Ts> using false_t = typename to_false<Ts...>::type; template<typename...> struct to_int { using type = int; }; template<typename... Ts> using int_t = typename to_int<Ts...>::type; template<typename T> struct identity { using type = T; }; template<typename T> using identity_t = typename identity<T>::type; // things missing from c++11 (to be removed when switching to c++14) template <bool b, typename T = void> using enable_if_t = typename std::enable_if<b, T>::type; template<typename T> using decay_t = typename std::decay<T>::type; template<std::size_t S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type; template<std::size_t ...> struct seq {}; template<std::size_t n, std::size_t ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<std::size_t ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename Tuple> struct TupleSeqGen : seq_gen<std::tuple_size<Tuple>::value> {}; template<> struct TupleSeqGen<std::tuple<>> : seq_gen<0> {}; template<typename Tuple> using tuple_seq = typename TupleSeqGen<Tuple>::type; template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - (n > std::tuple_size<Tuple>::value ? std::tuple_size<Tuple>::value : n)>::type; // SFINAE utilities template<typename T, typename = void> struct has_autocall : std::false_type {}; template<typename T> struct has_autocall<T, void_t<typename T::autocall>> : std::true_type {}; template<typename T, typename = void> struct has_forward : std::false_type {}; template<typename T> struct has_forward<T, void_t<decltype(std::declval<T>().forward())>> : std::true_type {}; template<typename T, typename = void> struct is_service : std::false_type {}; template<typename T> struct is_service<T, enable_if_t<(!std::is_polymorphic<T>::value || std::is_abstract<T>::value) && has_forward<T>::value>> : std::true_type {}; template<typename T, typename = void> struct has_construct : std::false_type {}; template<typename T> struct has_construct<T, void_t<decltype(&T::construct)>> : std::true_type {}; template<typename T, typename = void> struct is_invoke_call : std::false_type {}; template<typename T> struct is_invoke_call<T, void_t<typename T::Parameters>> : std::true_type {}; template<template<typename> class Map, typename T, typename = void> struct is_complete_map : std::false_type {}; template<template<typename> class Map, typename T> struct is_complete_map<Map, T, void_t<typename Map<T>::Service>> : std::true_type {}; struct Sink { constexpr Sink() = default; template<typename T> constexpr operator T&& () const; }; template<typename T, typename... Args> struct is_brace_constructible_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(U{std::declval<As>()...}), std::true_type{}) test(int); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<typename T, typename... Args> struct has_template_construct_helper { private: template<typename U, typename... As> static std::true_type test(decltype(&U::template construct<As...>)* = nullptr); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(nullptr)); }; template<typename... Ts> using has_template_construct = typename has_template_construct_helper<Ts...>::type; template<typename T, typename... Args> struct has_emplace_helper { private: template<typename U, typename... As> static decltype(static_cast<void>(std::declval<U>().emplace(std::declval<As>()...)), std::true_type{}) test(int); template<typename U, typename... As> static std::false_type test(...); public: using type = decltype(test<T, Args...>(0)); }; template<template<typename> class Map, typename T, typename... Args> struct is_invokable_helper { private: template<typename U, typename... As, std::size_t... S> static std::true_type test(seq<S...>, decltype(std::declval<U>()(std::declval<ServiceType<service_map_t<Map, function_argument_t<S, U>>>>()..., std::declval<As>()...))*); template<typename...> static std::false_type test(...); public: using type = decltype(test<T, Args...>(tuple_seq_minus<function_arguments_t<T>, sizeof...(Args)>{}, nullptr)); }; template<template<typename> class Map, typename T, typename... Args> struct defer_is_invokable_helper { static constexpr bool value = is_invokable_helper<Map, T, Args...>::type::value; }; template<bool, typename T, typename... Args> struct construct_function_helper { private: template<typename U, typename... As> struct get_template_construct { using type = std::integral_constant<decltype(&U::template construct<As...>), &U::template construct<As...>>; }; template<typename U> struct get_construct { using type = std::integral_constant<decltype(&U::construct), &U::construct>; }; template<typename U, typename... As, enable_if_t<has_construct<U>::value, int> = 0, enable_if_t<!has_template_construct<U, As...>::value, int> = 0> static get_construct<U> test(); template<typename U, typename... As, enable_if_t<has_template_construct<U, As...>::value, int> = 0> static get_template_construct<U, Args...> test(); using inner_type = decltype(test<T, Args...>()); public: using type = typename inner_type::type; }; template<typename T, typename... Args> struct construct_function_helper<false, T, Args...> {}; template<typename T, typename... Args> using has_any_construct = std::integral_constant<bool, has_template_construct<T, Args...>::value || has_construct<T>::value>; template<typename T, typename... Args> using construct_function = typename construct_function_helper<has_any_construct<T, Args...>::value, T, Args...>::type; template<typename T, typename... Args> using construct_function_t = typename construct_function<T, Args...>::value_type; template<typename T, typename... Args> using construct_result_seq = tuple_seq<function_result_t<construct_function_t<T, Args...>>>; template<typename T, typename... Args> using has_emplace = typename has_emplace_helper<T, Args...>::type; template<typename T, typename... Args> using is_brace_constructible = typename is_brace_constructible_helper<T, Args...>::type; template<typename T, typename... Args> using is_only_brace_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value && !std::is_constructible<T, Args...>::value>; template<typename T> struct remove_rvalue_reference { using type = T; }; template<typename T> struct remove_rvalue_reference<T&&> { using type = T; }; template<typename T> using remove_rvalue_reference_t = typename remove_rvalue_reference<T>::type; template<typename T, typename... Args> using is_someway_constructible = std::integral_constant<bool, is_brace_constructible<T, Args...>::value || std::is_constructible<T, Args...>::value>; template<typename T, typename... Args> using is_emplaceable = std::integral_constant<bool, std::is_default_constructible<T>::value && has_emplace<T, Args...>::value>; template<typename T, typename... Args> using is_service_instantiable = std::integral_constant<bool, is_emplaceable<T, Args...>::value || is_someway_constructible<T, kgr::in_place_t, Args...>::value>; template<template<typename> class Map, typename U, typename... Args> using is_invokable = std::integral_constant<bool, defer_is_invokable_helper<Map, U, Args...>::value>; } // namespace detail } // namespace kgr #endif // KGR_INCLUDE_KANGARU_DETAIL_TRAITS_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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. */ #ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED #define TORRENT_UDP_SOCKET_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/io_service.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/deadline_timer.hpp" #include <vector> #include <boost/function/function4.hpp> namespace libtorrent { class connection_queue; class udp_socket { public: typedef boost::function<void(error_code const& ec , udp::endpoint const&, char const* buf, int size)> callback_t; udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); ~udp_socket(); bool is_open() const { return m_ipv4_sock.is_open() #if TORRENT_USE_IPV6 || m_ipv6_sock.is_open() #endif ; } io_service& get_io_service() { return m_ipv4_sock.get_io_service(); } void send(udp::endpoint const& ep, char const* p, int len, error_code& ec); void bind(udp::endpoint const& ep, error_code& ec); void bind(int port); void close(); int local_port() const { return m_bind_port; } void set_proxy_settings(proxy_settings const& ps); proxy_settings const& get_proxy_settings() { return m_proxy_settings; } bool is_closed() const { return m_abort; } tcp::endpoint local_endpoint() const { udp::endpoint ep = m_ipv4_sock.local_endpoint(); return tcp::endpoint(ep.address(), ep.port()); } protected: struct queued_packet { udp::endpoint ep; buffer buf; }; private: callback_t m_callback; void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred); void on_name_lookup(error_code const& e, tcp::resolver::iterator i); void on_timeout(); void on_connect(int ticket); void on_connected(error_code const& ec); void handshake1(error_code const& e); void handshake2(error_code const& e); void handshake3(error_code const& e); void handshake4(error_code const& e); void socks_forward_udp(mutex::scoped_lock& l); void connect1(error_code const& e); void connect2(error_code const& e); void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec); void unwrap(error_code const& e, char const* buf, int size); mutable mutex m_mutex; udp::socket m_ipv4_sock; udp::endpoint m_v4_ep; char m_v4_buf[1600]; #if TORRENT_USE_IPV6 udp::socket m_ipv6_sock; udp::endpoint m_v6_ep; char m_v6_buf[1600]; #endif int m_bind_port; char m_outstanding; tcp::socket m_socks5_sock; int m_connection_ticket; proxy_settings m_proxy_settings; connection_queue& m_cc; tcp::resolver m_resolver; char m_tmp_buf[100]; bool m_queue_packets; bool m_tunnel_packets; bool m_abort; udp::endpoint m_proxy_addr; // while we're connecting to the proxy // we have to queue the packets, we'll flush // them once we're connected std::list<queued_packet> m_queue; #ifdef TORRENT_DEBUG bool m_started; int m_magic; int m_outstanding_when_aborted; #endif }; struct rate_limited_udp_socket : public udp_socket { rate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); void set_rate_limit(int limit) { m_rate_limit = limit; } bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; } bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0); void close(); private: void on_tick(error_code const& e); deadline_timer m_timer; int m_queue_size_limit; int m_rate_limit; int m_quota; ptime m_last_tick; std::list<queued_packet> m_queue; }; } #endif <commit_msg>ignore failures in when asking for local_endpoint<commit_after>/* Copyright (c) 2007, Arvid Norberg 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. */ #ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED #define TORRENT_UDP_SOCKET_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/io_service.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/deadline_timer.hpp" #include <vector> #include <boost/function/function4.hpp> namespace libtorrent { class connection_queue; class udp_socket { public: typedef boost::function<void(error_code const& ec , udp::endpoint const&, char const* buf, int size)> callback_t; udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); ~udp_socket(); bool is_open() const { return m_ipv4_sock.is_open() #if TORRENT_USE_IPV6 || m_ipv6_sock.is_open() #endif ; } io_service& get_io_service() { return m_ipv4_sock.get_io_service(); } void send(udp::endpoint const& ep, char const* p, int len, error_code& ec); void bind(udp::endpoint const& ep, error_code& ec); void bind(int port); void close(); int local_port() const { return m_bind_port; } void set_proxy_settings(proxy_settings const& ps); proxy_settings const& get_proxy_settings() { return m_proxy_settings; } bool is_closed() const { return m_abort; } tcp::endpoint local_endpoint() const { error_code ec; udp::endpoint ep = m_ipv4_sock.local_endpoint(ec); return tcp::endpoint(ep.address(), ep.port()); } protected: struct queued_packet { udp::endpoint ep; buffer buf; }; private: callback_t m_callback; void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred); void on_name_lookup(error_code const& e, tcp::resolver::iterator i); void on_timeout(); void on_connect(int ticket); void on_connected(error_code const& ec); void handshake1(error_code const& e); void handshake2(error_code const& e); void handshake3(error_code const& e); void handshake4(error_code const& e); void socks_forward_udp(mutex::scoped_lock& l); void connect1(error_code const& e); void connect2(error_code const& e); void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec); void unwrap(error_code const& e, char const* buf, int size); mutable mutex m_mutex; udp::socket m_ipv4_sock; udp::endpoint m_v4_ep; char m_v4_buf[1600]; #if TORRENT_USE_IPV6 udp::socket m_ipv6_sock; udp::endpoint m_v6_ep; char m_v6_buf[1600]; #endif int m_bind_port; char m_outstanding; tcp::socket m_socks5_sock; int m_connection_ticket; proxy_settings m_proxy_settings; connection_queue& m_cc; tcp::resolver m_resolver; char m_tmp_buf[100]; bool m_queue_packets; bool m_tunnel_packets; bool m_abort; udp::endpoint m_proxy_addr; // while we're connecting to the proxy // we have to queue the packets, we'll flush // them once we're connected std::list<queued_packet> m_queue; #ifdef TORRENT_DEBUG bool m_started; int m_magic; int m_outstanding_when_aborted; #endif }; struct rate_limited_udp_socket : public udp_socket { rate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); void set_rate_limit(int limit) { m_rate_limit = limit; } bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; } bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0); void close(); private: void on_tick(error_code const& e); deadline_timer m_timer; int m_queue_size_limit; int m_rate_limit; int m_quota; ptime m_last_tick; std::list<queued_packet> m_queue; }; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OEnumeration.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:32:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "OEnumeration.hxx" using namespace ::com::sun::star; namespace comphelper { OEnumeration::OEnumeration( const ::std::vector< uno::Any > & rContainer ) : m_aContainer( rContainer ), m_aIter( m_aContainer.begin() ) {} OEnumeration::~OEnumeration() {} sal_Bool SAL_CALL OEnumeration::hasMoreElements() throw (uno::RuntimeException) { return ! m_aContainer.empty(); } uno::Any SAL_CALL OEnumeration::nextElement() throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { if( m_aIter == m_aContainer.end()) throw container::NoSuchElementException(); return *m_aIter++; } } // namespace comphelper <commit_msg>INTEGRATION: CWS pchfix02 (1.2.82); FILE MERGED 2006/09/01 17:18:53 kaib 1.2.82.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OEnumeration.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:27:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "OEnumeration.hxx" using namespace ::com::sun::star; namespace comphelper { OEnumeration::OEnumeration( const ::std::vector< uno::Any > & rContainer ) : m_aContainer( rContainer ), m_aIter( m_aContainer.begin() ) {} OEnumeration::~OEnumeration() {} sal_Bool SAL_CALL OEnumeration::hasMoreElements() throw (uno::RuntimeException) { return ! m_aContainer.empty(); } uno::Any SAL_CALL OEnumeration::nextElement() throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { if( m_aIter == m_aContainer.end()) throw container::NoSuchElementException(); return *m_aIter++; } } // namespace comphelper <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/ui_proxy_config_service.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/cros/network_property_ui_data.h" #include "chrome/browser/chromeos/proxy_config_service_impl.h" #include "chromeos/network/onc/onc_utils.h" #include "grit/generated_resources.h" #include "net/proxy/proxy_config.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace { class ClosureEquals { public: explicit ClosureEquals(const base::Closure& closure) : closure_(closure) { } bool operator() (const base::Closure& other) { return closure_.Equals(other); } private: const base::Closure& closure_; }; const char* ModeToString(UIProxyConfig::Mode mode) { switch (mode) { case UIProxyConfig::MODE_DIRECT: return "direct"; case UIProxyConfig::MODE_AUTO_DETECT: return "auto-detect"; case UIProxyConfig::MODE_PAC_SCRIPT: return "pacurl"; case UIProxyConfig::MODE_SINGLE_PROXY: return "single-proxy"; case UIProxyConfig::MODE_PROXY_PER_SCHEME: return "proxy-per-scheme"; } NOTREACHED() << "Unrecognized mode type"; return ""; } bool ParseProxyConfig(const std::string& pref_proxy_config, net::ProxyConfig* proxy_config) { if (pref_proxy_config.empty()) return false; scoped_ptr<base::DictionaryValue> proxy_config_dict( chromeos::onc::ReadDictionaryFromJson(pref_proxy_config)); if (!proxy_config_dict) { LOG(WARNING) << "Failed to parse proxy config."; return false; } ProxyConfigDictionary proxy_config_dict_wrapper(proxy_config_dict.get()); return PrefProxyConfigTrackerImpl::PrefConfigToNetConfig( proxy_config_dict_wrapper, proxy_config); } // Returns true if proxy settings of |network| are editable. bool IsNetworkProxySettingsEditable(const Network& network) { NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary(); const base::DictionaryValue* onc = network_library->FindOncForNetwork(network.unique_id()); if (!onc) return true; NetworkPropertyUIData proxy_settings_ui_data; proxy_settings_ui_data.ParseOncProperty( network.ui_data().onc_source(), onc, onc::network_config::kProxySettings); return proxy_settings_ui_data.IsEditable(); } } // namespace UIProxyConfigService::UIProxyConfigService(PrefService* pref_service) : pref_service_(pref_service) { } UIProxyConfigService::~UIProxyConfigService() { } void UIProxyConfigService::SetCurrentNetwork( const std::string& current_network) { Network* network = NULL; if (!current_network.empty()) { network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_network); LOG_IF(ERROR, !network) << "Can't find requested network " << current_network; } current_ui_network_ = current_network; if (!network) { current_ui_network_.clear(); current_ui_config_ = UIProxyConfig(); return; } DetermineEffectiveConfig(*network); VLOG(1) << "Current ui network: " << network->name() << ", " << ModeToString(current_ui_config_.mode) << ", " << ProxyPrefs::ConfigStateToDebugString(current_ui_config_.state) << ", modifiable:" << current_ui_config_.user_modifiable; // Notify observers. std::vector<base::Closure>::iterator iter = callbacks_.begin(); while (iter != callbacks_.end()) { if (iter->is_null()) { iter = callbacks_.erase(iter); } else { iter->Run(); ++iter; } } } void UIProxyConfigService::MakeActiveNetworkCurrent() { const Network* network = CrosLibrary::Get()->GetNetworkLibrary()->active_network(); SetCurrentNetwork(network ? network->service_path() : std::string()); } void UIProxyConfigService::GetCurrentNetworkName(std::string* network_name) { if (!network_name) return; network_name->clear(); Network* network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_ui_network_); if (!network) { LOG(ERROR) << "Can't find requested network " << current_ui_network_; return; } if (network->name().empty() && network->type() == chromeos::TYPE_ETHERNET) { *network_name = l10n_util::GetStringUTF8(IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET); } else { *network_name = network->name(); } } void UIProxyConfigService::GetProxyConfig(UIProxyConfig* config) { *config = current_ui_config_; } void UIProxyConfigService::SetProxyConfig(const UIProxyConfig& config) { current_ui_config_ = config; if (current_ui_network_.empty()) return; // Update config to shill. std::string value; if (!current_ui_config_.SerializeForNetwork(&value)) return; VLOG(1) << "Set proxy (mode=" << current_ui_config_.mode << ") for " << current_ui_network_; current_ui_config_.state = ProxyPrefs::CONFIG_SYSTEM; // Set ProxyConfig of the current network. Network* network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_ui_network_); if (!network) { NOTREACHED() << "Can't find requested network " << current_ui_network_; return; } network->SetProxyConfig(value); VLOG(1) << "Set proxy for " << (network->name().empty() ? current_ui_network_ : network->name()) << ", value=" << value; } void UIProxyConfigService::AddNotificationCallback(base::Closure callback) { std::vector<base::Closure>::iterator iter = std::find_if( callbacks_.begin(), callbacks_.end(), ClosureEquals(callback)); if (iter == callbacks_.end()) callbacks_.push_back(callback); } void UIProxyConfigService::RemoveNotificationCallback(base::Closure callback) { std::vector<base::Closure>::iterator iter = std::find_if( callbacks_.begin(), callbacks_.end(), ClosureEquals(callback)); if (iter != callbacks_.end()) callbacks_.erase(iter); } void UIProxyConfigService::DetermineEffectiveConfig(const Network& network) { // Get prefs proxy config if available. net::ProxyConfig pref_config; ProxyPrefs::ConfigState pref_state = ProxyConfigServiceImpl::ReadPrefConfig( pref_service_, &pref_config); // Get network proxy config if available. net::ProxyConfig network_config; net::ProxyConfigService::ConfigAvailability network_availability = net::ProxyConfigService::CONFIG_UNSET; if (ParseProxyConfig(network.proxy_config(), &network_config)) { // Network is private or shared with user using shared proxies. VLOG(1) << this << ": using network proxy: " << network.proxy_config(); network_availability = net::ProxyConfigService::CONFIG_VALID; } // Determine effective proxy config, either from prefs or network. ProxyPrefs::ConfigState effective_config_state; net::ProxyConfig effective_config; ProxyConfigServiceImpl::GetEffectiveProxyConfig( pref_state, pref_config, network_availability, network_config, false, &effective_config_state, &effective_config); // Store effective proxy into |current_ui_config_|. current_ui_config_.FromNetProxyConfig(effective_config); current_ui_config_.state = effective_config_state; if (ProxyConfigServiceImpl::PrefPrecedes(effective_config_state)) { current_ui_config_.user_modifiable = false; } else if (!IsNetworkProxySettingsEditable(network)) { // TODO(xiyuan): Figure out the right way to set config state for managed // network. current_ui_config_.state = ProxyPrefs::CONFIG_POLICY; current_ui_config_.user_modifiable = false; } else { current_ui_config_.user_modifiable = !ProxyConfigServiceImpl::IgnoreProxy(pref_service_, network.profile_path(), network.ui_data().onc_source()); } } } // namespace chromeos <commit_msg>Removing unused code for policies recommending proxy settings.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/ui_proxy_config_service.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/proxy_config_service_impl.h" #include "chromeos/network/onc/onc_utils.h" #include "grit/generated_resources.h" #include "net/proxy/proxy_config.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { namespace { class ClosureEquals { public: explicit ClosureEquals(const base::Closure& closure) : closure_(closure) { } bool operator() (const base::Closure& other) { return closure_.Equals(other); } private: const base::Closure& closure_; }; const char* ModeToString(UIProxyConfig::Mode mode) { switch (mode) { case UIProxyConfig::MODE_DIRECT: return "direct"; case UIProxyConfig::MODE_AUTO_DETECT: return "auto-detect"; case UIProxyConfig::MODE_PAC_SCRIPT: return "pacurl"; case UIProxyConfig::MODE_SINGLE_PROXY: return "single-proxy"; case UIProxyConfig::MODE_PROXY_PER_SCHEME: return "proxy-per-scheme"; } NOTREACHED() << "Unrecognized mode type"; return ""; } bool ParseProxyConfig(const std::string& pref_proxy_config, net::ProxyConfig* proxy_config) { if (pref_proxy_config.empty()) return false; scoped_ptr<base::DictionaryValue> proxy_config_dict( chromeos::onc::ReadDictionaryFromJson(pref_proxy_config)); if (!proxy_config_dict) { LOG(WARNING) << "Failed to parse proxy config."; return false; } ProxyConfigDictionary proxy_config_dict_wrapper(proxy_config_dict.get()); return PrefProxyConfigTrackerImpl::PrefConfigToNetConfig( proxy_config_dict_wrapper, proxy_config); } // Returns true if proxy settings of |network| are editable. bool IsNetworkProxySettingsEditable(const Network& network) { onc::ONCSource source = network.ui_data().onc_source(); return source != onc::ONC_SOURCE_DEVICE_POLICY && source != onc::ONC_SOURCE_USER_POLICY; } } // namespace UIProxyConfigService::UIProxyConfigService(PrefService* pref_service) : pref_service_(pref_service) { } UIProxyConfigService::~UIProxyConfigService() { } void UIProxyConfigService::SetCurrentNetwork( const std::string& current_network) { Network* network = NULL; if (!current_network.empty()) { network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_network); LOG_IF(ERROR, !network) << "Can't find requested network " << current_network; } current_ui_network_ = current_network; if (!network) { current_ui_network_.clear(); current_ui_config_ = UIProxyConfig(); return; } DetermineEffectiveConfig(*network); VLOG(1) << "Current ui network: " << network->name() << ", " << ModeToString(current_ui_config_.mode) << ", " << ProxyPrefs::ConfigStateToDebugString(current_ui_config_.state) << ", modifiable:" << current_ui_config_.user_modifiable; // Notify observers. std::vector<base::Closure>::iterator iter = callbacks_.begin(); while (iter != callbacks_.end()) { if (iter->is_null()) { iter = callbacks_.erase(iter); } else { iter->Run(); ++iter; } } } void UIProxyConfigService::MakeActiveNetworkCurrent() { const Network* network = CrosLibrary::Get()->GetNetworkLibrary()->active_network(); SetCurrentNetwork(network ? network->service_path() : std::string()); } void UIProxyConfigService::GetCurrentNetworkName(std::string* network_name) { if (!network_name) return; network_name->clear(); Network* network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_ui_network_); if (!network) { LOG(ERROR) << "Can't find requested network " << current_ui_network_; return; } if (network->name().empty() && network->type() == chromeos::TYPE_ETHERNET) { *network_name = l10n_util::GetStringUTF8(IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET); } else { *network_name = network->name(); } } void UIProxyConfigService::GetProxyConfig(UIProxyConfig* config) { *config = current_ui_config_; } void UIProxyConfigService::SetProxyConfig(const UIProxyConfig& config) { current_ui_config_ = config; if (current_ui_network_.empty()) return; // Update config to shill. std::string value; if (!current_ui_config_.SerializeForNetwork(&value)) return; VLOG(1) << "Set proxy (mode=" << current_ui_config_.mode << ") for " << current_ui_network_; current_ui_config_.state = ProxyPrefs::CONFIG_SYSTEM; // Set ProxyConfig of the current network. Network* network = CrosLibrary::Get()->GetNetworkLibrary()->FindNetworkByPath( current_ui_network_); if (!network) { NOTREACHED() << "Can't find requested network " << current_ui_network_; return; } network->SetProxyConfig(value); VLOG(1) << "Set proxy for " << (network->name().empty() ? current_ui_network_ : network->name()) << ", value=" << value; } void UIProxyConfigService::AddNotificationCallback(base::Closure callback) { std::vector<base::Closure>::iterator iter = std::find_if( callbacks_.begin(), callbacks_.end(), ClosureEquals(callback)); if (iter == callbacks_.end()) callbacks_.push_back(callback); } void UIProxyConfigService::RemoveNotificationCallback(base::Closure callback) { std::vector<base::Closure>::iterator iter = std::find_if( callbacks_.begin(), callbacks_.end(), ClosureEquals(callback)); if (iter != callbacks_.end()) callbacks_.erase(iter); } void UIProxyConfigService::DetermineEffectiveConfig(const Network& network) { // Get prefs proxy config if available. net::ProxyConfig pref_config; ProxyPrefs::ConfigState pref_state = ProxyConfigServiceImpl::ReadPrefConfig( pref_service_, &pref_config); // Get network proxy config if available. net::ProxyConfig network_config; net::ProxyConfigService::ConfigAvailability network_availability = net::ProxyConfigService::CONFIG_UNSET; if (ParseProxyConfig(network.proxy_config(), &network_config)) { // Network is private or shared with user using shared proxies. VLOG(1) << this << ": using network proxy: " << network.proxy_config(); network_availability = net::ProxyConfigService::CONFIG_VALID; } // Determine effective proxy config, either from prefs or network. ProxyPrefs::ConfigState effective_config_state; net::ProxyConfig effective_config; ProxyConfigServiceImpl::GetEffectiveProxyConfig( pref_state, pref_config, network_availability, network_config, false, &effective_config_state, &effective_config); // Store effective proxy into |current_ui_config_|. current_ui_config_.FromNetProxyConfig(effective_config); current_ui_config_.state = effective_config_state; if (ProxyConfigServiceImpl::PrefPrecedes(effective_config_state)) { current_ui_config_.user_modifiable = false; } else if (!IsNetworkProxySettingsEditable(network)) { // TODO(xiyuan): Figure out the right way to set config state for managed // network. current_ui_config_.state = ProxyPrefs::CONFIG_POLICY; current_ui_config_.user_modifiable = false; } else { current_ui_config_.user_modifiable = !ProxyConfigServiceImpl::IgnoreProxy(pref_service_, network.profile_path(), network.ui_data().onc_source()); } } } // namespace chromeos <|endoftext|>
<commit_before><commit_msg>Implement chrome.tabs.captureVisibleTab for linux<commit_after><|endoftext|>
<commit_before>#include "caffe2/operators/order_switch_ops.h" namespace caffe2 { template <> bool NHWC2NCHWOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); auto* Y = Output(0); CAFFE_ENFORCE(X.ndim() == 4); const int N = X.dim32(0), H = X.dim32(1), W = X.dim32(2), C = X.dim32(3); Y->Resize(N, C, H, W); const float* Xdata = X.data<float>(); float* Ydata = Y->mutable_data<float>(); for (int n = 0; n < N; ++n) { for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { for (int c = 0; c < C; ++c) { Ydata[((n * C + c) * H + h) * W + w] = *(Xdata++); } } } } return true; } template <> bool NCHW2NHWCOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); auto* Y = Output(0); CAFFE_ENFORCE(X.ndim() == 4); const int N = X.dim32(0), C = X.dim32(1), H = X.dim32(2), W = X.dim32(3); Y->Resize(N, H, W, C); const float* Xdata = X.data<float>(); float* Ydata = Y->mutable_data<float>(); for (int n = 0; n < N; ++n) { for (int c = 0; c < C; ++c) { for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { Ydata[((n * H + h) * W + w) * C + c] = *(Xdata++); } } } } return true; } REGISTER_CPU_OPERATOR(NHWC2NCHW, NHWC2NCHWOp<float, CPUContext>); REGISTER_CPU_OPERATOR(NCHW2NHWC, NCHW2NHWCOp<float, CPUContext>); OPERATOR_SCHEMA(NHWC2NCHW) .NumInputs(1) .NumOutputs(1) .TensorInferenceFunction([](const OperatorDef& /*unused*/ /*def*/, const vector<TensorShape>& in) { vector<TensorShape> out(1); out[0].add_dims(in[0].dims(0)); out[0].add_dims(in[0].dims(3)); out[0].add_dims(in[0].dims(1)); out[0].add_dims(in[0].dims(2)); return out; }) .SetDoc(R"DOC( The operator switches the order of data in a tensor from NHWC- sample index N, height H, width H and channels C, to the NCHW order. )DOC") .Input(0, "data", "The input data (Tensor<float>) in the NHWC order.") .Output( 0, "output", "The output tensor (Tensor<float>) in the NCHW order."); OPERATOR_SCHEMA(NCHW2NHWC).NumInputs(1).NumOutputs(1) .SetDoc(R"DOC( The operator switches the order of data in a tensor from NCHW- sample index N, channels C, height H and width W, to the NHWC order. )DOC") .Input(0, "data", "The input data (Tensor<float>) in the NCHW order.") .Output(0, "output", "The output tensor (Tensor<float>) in the NHWC order."); class GetNHWC2NCHWGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "NCHW2NHWC", "", vector<string>{GO(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(NHWC2NCHW, GetNHWC2NCHWGradient); class GetNCHW2NHWCGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "NHWC2NCHW", "", vector<string>{GO(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(NCHW2NHWC, GetNCHW2NHWCGradient); } // namespace caffe2 <commit_msg>add dimension check to NHWC2NCHW shape inference<commit_after>#include "caffe2/operators/order_switch_ops.h" namespace caffe2 { template <> bool NHWC2NCHWOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); auto* Y = Output(0); CAFFE_ENFORCE(X.ndim() == 4); const int N = X.dim32(0), H = X.dim32(1), W = X.dim32(2), C = X.dim32(3); Y->Resize(N, C, H, W); const float* Xdata = X.data<float>(); float* Ydata = Y->mutable_data<float>(); for (int n = 0; n < N; ++n) { for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { for (int c = 0; c < C; ++c) { Ydata[((n * C + c) * H + h) * W + w] = *(Xdata++); } } } } return true; } template <> bool NCHW2NHWCOp<float, CPUContext>::RunOnDevice() { auto& X = Input(0); auto* Y = Output(0); CAFFE_ENFORCE(X.ndim() == 4); const int N = X.dim32(0), C = X.dim32(1), H = X.dim32(2), W = X.dim32(3); Y->Resize(N, H, W, C); const float* Xdata = X.data<float>(); float* Ydata = Y->mutable_data<float>(); for (int n = 0; n < N; ++n) { for (int c = 0; c < C; ++c) { for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { Ydata[((n * H + h) * W + w) * C + c] = *(Xdata++); } } } } return true; } REGISTER_CPU_OPERATOR(NHWC2NCHW, NHWC2NCHWOp<float, CPUContext>); REGISTER_CPU_OPERATOR(NCHW2NHWC, NCHW2NHWCOp<float, CPUContext>); OPERATOR_SCHEMA(NHWC2NCHW) .NumInputs(1) .NumOutputs(1) .TensorInferenceFunction([](const OperatorDef& /*unused*/ /*def*/, const vector<TensorShape>& in) { CAFFE_ENFORCE_EQ( in[0].dims_size(), 4, "Input for NHWC2NCHW must be 4 dimensional"); vector<TensorShape> out(1); out[0].add_dims(in[0].dims(0)); out[0].add_dims(in[0].dims(3)); out[0].add_dims(in[0].dims(1)); out[0].add_dims(in[0].dims(2)); return out; }) .SetDoc(R"DOC( The operator switches the order of data in a tensor from NHWC- sample index N, height H, width H and channels C, to the NCHW order. )DOC") .Input(0, "data", "The input data (Tensor<float>) in the NHWC order.") .Output( 0, "output", "The output tensor (Tensor<float>) in the NCHW order."); OPERATOR_SCHEMA(NCHW2NHWC).NumInputs(1).NumOutputs(1) .SetDoc(R"DOC( The operator switches the order of data in a tensor from NCHW- sample index N, channels C, height H and width W, to the NHWC order. )DOC") .Input(0, "data", "The input data (Tensor<float>) in the NCHW order.") .Output(0, "output", "The output tensor (Tensor<float>) in the NHWC order."); class GetNHWC2NCHWGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "NCHW2NHWC", "", vector<string>{GO(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(NHWC2NCHW, GetNHWC2NCHWGradient); class GetNCHW2NHWCGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "NHWC2NCHW", "", vector<string>{GO(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(NCHW2NHWC, GetNCHW2NHWCGradient); } // namespace caffe2 <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "app/l10n_util.h" #include "base/gfx/gtk_util.h" #include "base/rand_util.h" #include "base/string_util.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/common/gtk_util.h" #include "chrome/common/extensions/extension.h" #include "grit/generated_resources.h" class Profile; namespace { const int kRightColumnWidth = 290; // Left or right margin. const int kPanelHorizMargin = 13; GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) { GtkWidget* label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped(format, str.c_str()); gtk_label_set_markup(GTK_LABEL(label), markup); g_free(markup); // Left align it. gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5); return label; } void OnDialogResponse(GtkDialog* dialog, int response_id, ExtensionInstallUI::Delegate* delegate) { if (response_id == GTK_RESPONSE_ACCEPT) { delegate->ContinueInstall(); } else { delegate->AbortInstall(); } gtk_widget_destroy(GTK_WIDGET(dialog)); } void ShowInstallPromptDialog(GtkWindow* parent, SkBitmap* skia_icon, Extension *extension, ExtensionInstallUI::Delegate *delegate) { // Build the dialog. GtkWidget* dialog = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_TITLE).c_str(), parent, GTK_DIALOG_MODAL, GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE, "Install", GTK_RESPONSE_ACCEPT, NULL); gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE); GtkWidget* content_area = GTK_DIALOG(dialog)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); GtkWidget* right_column_area; if (skia_icon) { // Create a two column layout. GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing); gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0); // Put Icon in the left column. GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(skia_icon); GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf); gtk_box_pack_start(GTK_BOX(icon_hbox), icon, TRUE, TRUE, 0); // Create a new vbox for the right column. right_column_area = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0); } else { right_column_area = content_area; } // Prompt. std::string prompt_text = WideToUTF8(l10n_util::GetStringF( IDS_EXTENSION_PROMPT_HEADING, UTF8ToWide(extension->name()))); GtkWidget* prompt_label = MakeMarkupLabel("<span weight=\"bold\">%s</span>", prompt_text); gtk_misc_set_alignment(GTK_MISC(prompt_label), 0.0, 0.5); gtk_label_set_selectable(GTK_LABEL(prompt_label), TRUE); gtk_box_pack_start(GTK_BOX(right_column_area), prompt_label, TRUE, TRUE, 0); // Pick a random warning. std::string warnings[] = { l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_WARNING_1), l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_WARNING_2), l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_WARNING_3) }; std::string warning_text = warnings[ base::RandInt(0, arraysize(warnings) - 1)]; GtkWidget* warning_label = gtk_label_new(warning_text.c_str()); gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE); gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1); gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5); gtk_label_set_selectable(GTK_LABEL(warning_label), TRUE); gtk_box_pack_start(GTK_BOX(right_column_area), warning_label, TRUE, TRUE, 0); // Severe label std::string severe_text = l10n_util::GetStringUTF8( IDS_EXTENSION_PROMPT_WARNING_SEVERE); GtkWidget* severe_label = MakeMarkupLabel("<span weight=\"bold\">%s</span>", severe_text); GdkColor red = GDK_COLOR_RGB(0xff, 0x00, 0x00); gtk_widget_modify_fg(severe_label, GTK_STATE_NORMAL, &red); gtk_misc_set_alignment(GTK_MISC(severe_label), 0.0, 0.5); gtk_label_set_selectable(GTK_LABEL(severe_label), TRUE); gtk_box_pack_start(GTK_BOX(right_column_area), severe_label, TRUE, TRUE, 0); g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), delegate); gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); gtk_widget_show_all(dialog); } } // namespace void ExtensionInstallUI::ShowExtensionInstallPrompt( Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon, const std::wstring& warning_text) { Browser* browser = BrowserList::GetLastActiveWithProfile(profile); if (!browser) { delegate->ContinueInstall(); return; } BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>( browser->window()); if (!browser_window) { delegate->AbortInstall(); return; } ShowInstallPromptDialog(browser_window->window(), icon, extension, delegate); } <commit_msg>Update Linux extension install prompt<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "app/l10n_util.h" #include "base/gfx/gtk_util.h" #include "base/rand_util.h" #include "base/string_util.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/common/gtk_util.h" #include "chrome/common/extensions/extension.h" #include "grit/generated_resources.h" class Profile; namespace { const int kRightColumnWidth = 290; // Left or right margin. const int kPanelHorizMargin = 13; GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) { GtkWidget* label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped(format, str.c_str()); gtk_label_set_markup(GTK_LABEL(label), markup); g_free(markup); // Left align it. gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5); return label; } void OnDialogResponse(GtkDialog* dialog, int response_id, ExtensionInstallUI::Delegate* delegate) { if (response_id == GTK_RESPONSE_ACCEPT) { delegate->ContinueInstall(); } else { delegate->AbortInstall(); } gtk_widget_destroy(GTK_WIDGET(dialog)); } void ShowInstallPromptDialog(GtkWindow* parent, SkBitmap* skia_icon, Extension *extension, ExtensionInstallUI::Delegate *delegate, const std::string& warning_text) { // Build the dialog. GtkWidget* dialog = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_TITLE).c_str(), parent, GTK_DIALOG_MODAL, GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE, "Install", GTK_RESPONSE_ACCEPT, NULL); gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE); // Create a two column layout. GtkWidget* content_area = GTK_DIALOG(dialog)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing); gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0); // Put Icon in the left column. GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(skia_icon); GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf); gtk_box_pack_start(GTK_BOX(icon_hbox), icon, TRUE, TRUE, 0); // Create a new vbox for the right column. GtkWidget* right_column_area = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0); std::string heading_text = WideToUTF8(l10n_util::GetStringF( IDS_EXTENSION_PROMPT_HEADING, UTF8ToWide(extension->name()))); GtkWidget* heading_label = MakeMarkupLabel("<span weight=\"bold\">%s</span>", heading_text); gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5); gtk_label_set_selectable(GTK_LABEL(heading_label), TRUE); gtk_box_pack_start(GTK_BOX(right_column_area), heading_label, TRUE, TRUE, 0); GtkWidget* warning_label = gtk_label_new(warning_text.c_str()); gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE); gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1); gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5); gtk_label_set_selectable(GTK_LABEL(warning_label), TRUE); gtk_box_pack_start(GTK_BOX(right_column_area), warning_label, TRUE, TRUE, 0); g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), delegate); gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); gtk_widget_show_all(dialog); } } // namespace void ExtensionInstallUI::ShowExtensionInstallPrompt( Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon, const std::wstring& warning_text) { Browser* browser = BrowserList::GetLastActiveWithProfile(profile); if (!browser) { delegate->ContinueInstall(); return; } BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>( browser->window()); if (!browser_window) { delegate->AbortInstall(); return; } std::string warning_ascii = WideToASCII(warning_text); ShowInstallPromptDialog(browser_window->window(), icon, extension, delegate, warning_ascii); } <|endoftext|>
<commit_before> #include "thekla_atlas.h" #include "thekla_mesh_load.h" #include <stdio.h> #include <assert.h> using namespace Thekla; int main(int argc, char * argv[]) { if (argc != 2) { printf("Usage: %s input_file.obj\n", argv[0]); return EXIT_FAILURE; } // Load Obj_Mesh. Obj_Load_Options load_options = {0}; Obj_Mesh * obj_mesh = obj_mesh_load(argv[1], &load_options); if (obj_mesh == NULL) { printf("Error loading obj file.\n"); return 1; } // Convert Obj_Mesh to Atlast_Input_Mesh. assert(sizeof(Atlas_Input_Vertex) == sizeof(Obj_Vertex)); assert(sizeof(Atlas_Input_Face) == sizeof(Obj_Face)); Atlas_Input_Mesh input_mesh; input_mesh.vertex_count = obj_mesh->vertex_count; input_mesh.vertex_array = (Atlas_Input_Vertex *)obj_mesh->vertex_array; input_mesh.face_count = obj_mesh->face_count; input_mesh.face_array = (Atlas_Input_Face *)obj_mesh->face_array; // Generate Atlas_Output_Mesh. Atlas_Options atlas_options; atlas_set_default_options(&atlas_options); Atlas_Error error = Atlas_Error_Success; Atlas_Output_Mesh * output_mesh = atlas_generate(&input_mesh, &atlas_options, &error); printf("Atlas mesh has %d verts\n", output_mesh->vertex_count); printf("Atlas mesh has %d triangles\n", output_mesh->index_count / 3); printf("Produced debug_packer_final.tga\n"); // Free meshes. obj_mesh_free(obj_mesh); atlas_free(output_mesh); return 0; } <commit_msg>The test app now uses randomized packing instead of brute force packing.<commit_after> #include "thekla_atlas.h" #include "thekla_mesh_load.h" #include <stdio.h> #include <assert.h> using namespace Thekla; int main(int argc, char * argv[]) { if (argc != 2) { printf("Usage: %s input_file.obj\n", argv[0]); return EXIT_FAILURE; } // Load Obj_Mesh. Obj_Load_Options load_options = {0}; Obj_Mesh * obj_mesh = obj_mesh_load(argv[1], &load_options); if (obj_mesh == NULL) { printf("Error loading obj file.\n"); return 1; } // Convert Obj_Mesh to Atlast_Input_Mesh. assert(sizeof(Atlas_Input_Vertex) == sizeof(Obj_Vertex)); assert(sizeof(Atlas_Input_Face) == sizeof(Obj_Face)); Atlas_Input_Mesh input_mesh; input_mesh.vertex_count = obj_mesh->vertex_count; input_mesh.vertex_array = (Atlas_Input_Vertex *)obj_mesh->vertex_array; input_mesh.face_count = obj_mesh->face_count; input_mesh.face_array = (Atlas_Input_Face *)obj_mesh->face_array; // Generate Atlas_Output_Mesh. Atlas_Options atlas_options; atlas_set_default_options(&atlas_options); // Avoid brute force packing, since it can be unusably slow in some situations. atlas_options.packer_options.witness.packing_quality = 1; Atlas_Error error = Atlas_Error_Success; Atlas_Output_Mesh * output_mesh = atlas_generate(&input_mesh, &atlas_options, &error); printf("Atlas mesh has %d verts\n", output_mesh->vertex_count); printf("Atlas mesh has %d triangles\n", output_mesh->index_count / 3); printf("Produced debug_packer_final.tga\n"); // Free meshes. obj_mesh_free(obj_mesh); atlas_free(output_mesh); return 0; } <|endoftext|>
<commit_before>#include "zmq.hpp" #include "avro/Encoder.hh" #include "avro/Decoder.hh" #include "avro/Specific.hh" #include <string> #include <sstream> #include <iostream> #include "boost/unordered_map.hpp" #include "boost/program_options.hpp" #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "jansson.h" #include "rodsClient.h" #include "irods_server_control_plane.hpp" #include "irods_buffer_encryption.hpp" #include "server_control_plane_command.hpp" #include "irods_buffer_encryption.hpp" #include "irods_exception.hpp" template <typename T> irods::error usage(T& ostream) { ostream << "usage: 'irods-grid action [ option ] target'" << std::endl; ostream << "action: ( required ) status, pause, resume, shutdown" << std::endl; ostream << "option: --force-after=seconds or --wait-forever" << std::endl; ostream << "target: ( required ) --all, --hosts=<fqdn1>,<fqdn2>,..." << std::endl; return ERROR( SYS_INVALID_INPUT_PARAM, "usage" ); } // usage irods::error parse_program_options( int _argc, char* _argv[], irods::control_plane_command& _cmd ) { namespace po = boost::program_options; po::options_description opt_desc( "options" ); opt_desc.add_options() ( "action", "either 'status', 'shutdown', 'pause', or 'resume'" ) ( "help", "show command usage" ) ( "all", "operation applies to all servers in the grid" ) ( "hosts", po::value<std::string>(), "operation applies to a list of hosts in the grid" ) ( "force-after", po::value<size_t>(), "force shutdown after N seconds" ) ( "wait-forever", "wait indefinitely for a graceful shutdown" ) ( "shutdown", "gracefully shutdown a server(s)" ) ( "pause", "refuse new client connections" ) ( "resume", "allow new client connections" ); po::positional_options_description pos_desc; pos_desc.add( "action", 1 ); po::variables_map vm; try { po::store( po::command_line_parser( _argc, _argv ).options( opt_desc ).positional( pos_desc ).run(), vm ); po::notify( vm ); } catch ( po::error& _e ) { std::cerr << std::endl << "Error: " << _e.what() << std::endl << std::endl; return usage(std::cerr); } // capture the 'subcommand' or 'action' to perform on the grid irods::control_plane_command cmd; if ( vm.count( "action" ) ) { try { const std::string& action = vm["action"].as<std::string>(); boost::unordered_map< std::string, std::string > cmd_map; cmd_map[ "status" ] = irods::SERVER_CONTROL_STATUS; cmd_map[ "pause" ] = irods::SERVER_CONTROL_PAUSE; cmd_map[ "resume" ] = irods::SERVER_CONTROL_RESUME; cmd_map[ "shutdown" ] = irods::SERVER_CONTROL_SHUTDOWN; if ( cmd_map.end() == cmd_map.find( action ) ) { std::cerr << "invalid subcommand [" << action << "]" << std::endl; return usage(std::cerr); } _cmd.command = cmd_map[ action ]; } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"action\"] to std::string failed." ); } } else { return usage(std::cout); } if ( vm.count( "force-after" ) ) { try { size_t secs = vm[ "force-after" ].as<size_t>(); std::stringstream ss; ss << secs; _cmd.options[ irods::SERVER_CONTROL_FORCE_AFTER_KW ] = ss.str(); } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"force-after\"] to std::string failed." ); } } else if ( vm.count( "wait-forever" ) ) { _cmd.options[ irods::SERVER_CONTROL_WAIT_FOREVER_KW ] = "keep_waiting"; } // capture either the 'all' servers or the hosts list if ( vm.count( "all" ) ) { _cmd.options[ irods::SERVER_CONTROL_OPTION_KW ] = irods::SERVER_CONTROL_ALL_OPT; } else if ( vm.count( "hosts" ) ) { _cmd.options[ irods::SERVER_CONTROL_OPTION_KW ] = irods::SERVER_CONTROL_HOSTS_OPT; std::vector< std::string > hosts; try { boost::split( hosts, vm[ "hosts" ].as<std::string>(), boost::is_any_of( ", " ), boost::token_compress_on ); } catch ( const boost::bad_function_call& ) { return ERROR( BAD_FUNCTION_CALL, "Boost threw bad_function_call." ); } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"hosts\"] to std::string failed." ); } for ( size_t i = 0; i < hosts.size(); ++i ) { std::stringstream ss; ss << i; _cmd.options[ irods::SERVER_CONTROL_HOST_KW + ss.str() ] = hosts[ i ]; } // for i } else { return usage(std::cerr); } return SUCCESS(); } // parse_program_options irods::error prepare_command_for_transport( const rodsEnv& _env, const irods::control_plane_command& _cmd, irods::buffer_crypt::array_t& _data_to_send ) { // build a encryption context std::string encryption_key( _env.irodsCtrlPlaneKey ); irods::buffer_crypt crypt( encryption_key.size(), // key size 0, // salt size ( we dont send a salt ) _env.irodsCtrlPlaneEncryptionNumHashRounds, _env.irodsCtrlPlaneEncryptionAlgorithm ); // serialize using the generated avro class std::auto_ptr< avro::OutputStream > out = avro::memoryOutputStream(); avro::EncoderPtr e = avro::binaryEncoder(); e->init( *out ); avro::encode( *e, _cmd ); boost::shared_ptr< std::vector< uint8_t > > data = avro::snapshot( *out ); // encrypt outgoing request std::vector< unsigned char > enc_data( data->begin(), data->end() ); irods::buffer_crypt::array_t iv; irods::buffer_crypt::array_t in_buf( enc_data.begin(), enc_data.end() ); irods::buffer_crypt::array_t shared_secret( encryption_key.begin(), encryption_key.end() ); irods::error ret = crypt.encrypt( shared_secret, iv, in_buf, _data_to_send ); if ( !ret.ok() ) { return PASS( ret ); } return SUCCESS(); } // prepare_command_for_transport irods::error decrypt_response( const rodsEnv& _env, const uint8_t* _data_ptr, const size_t _data_size, std::string& _rep_str ) { irods::buffer_crypt::array_t in_buf; in_buf.assign( _data_ptr, _data_ptr + _data_size ); std::string encryption_key( _env.irodsCtrlPlaneKey ); irods::buffer_crypt crypt( encryption_key.size(), // key size 0, // salt size ( we dont send a salt ) _env.irodsCtrlPlaneEncryptionNumHashRounds, _env.irodsCtrlPlaneEncryptionAlgorithm ); irods::buffer_crypt::array_t iv; irods::buffer_crypt::array_t shared_secret( encryption_key.begin(), encryption_key.end() ); irods::buffer_crypt::array_t decoded_data; irods::error ret = crypt.decrypt( shared_secret, iv, in_buf, decoded_data ); if ( !ret.ok() ) { return PASS( ret ); } _rep_str.assign( decoded_data.begin(), decoded_data.begin() + decoded_data.size() ); return SUCCESS(); } // decrypt_response std::string format_grid_status( const std::string& _status) { std::string status = "{\n \"hosts\": [\n"; status += _status; status += "] \n}"; std::string::size_type pos = status.find_last_of( "," ); if ( std::string::npos != pos ) { status.erase( pos, 1 ); } else { // possible error message THROW( -1, std::string("server responded with an error\n") + _status ); } json_error_t j_err; json_t* obj = json_loads( ( char* )status.data(), JSON_REJECT_DUPLICATES, &j_err ); if ( !obj ) { if ( std::string::npos != _status.find( irods::SERVER_PAUSED_ERROR ) ) { THROW( -1, std::string("server paused error\n") + _status ); } THROW( -1, std::string("json_loads failed\n") + j_err.text ); } char* tmp_buf = json_dumps( obj, JSON_INDENT( 4 ) ); json_decref( obj ); status = tmp_buf; free( tmp_buf ); return status; } // format_grid_status irods::error get_and_verify_client_environment( rodsEnv& _env ) { _getRodsEnv( _env ); bool have_error = false; std::string msg = "missing environment entries: "; if( 0 == strlen( _env.irodsCtrlPlaneKey ) ) { have_error = true; msg += "irods_server_control_plane_key"; } if( 0 == _env.irodsCtrlPlaneEncryptionNumHashRounds ) { have_error = true; msg += ", irods_server_control_plane_encryption_num_hash_rounds"; } if( 0 == _env.irodsCtrlPlaneEncryptionAlgorithm ) { have_error = true; msg += ", irods_server_control_plane_encryption_algorithm"; } if( 0 == _env.irodsCtrlPlanePort ) { have_error = true; msg += ", irods_server_control_plane_port"; } if( have_error ) { return ERROR( USER_INVALID_CLIENT_ENVIRONMENT, msg ); } return SUCCESS(); } // verify_client_environment int main( int _argc, char* _argv[] ) { irods::control_plane_command cmd; irods::error ret = parse_program_options( _argc, _argv, cmd ); if ( !ret.ok() ) { return 0; } rodsEnv env; irods::error err = get_and_verify_client_environment( env ); if( !err.ok() ) { std::cerr << err.result(); return 1; } irods::buffer_crypt::array_t data_to_send; ret = prepare_command_for_transport( env, cmd, data_to_send ); if ( !ret.ok() ) { std::cerr << ret.result() << std::endl; return ret.code(); } // this is the client so we connect rather than bind std::stringstream port_sstr; port_sstr << env.irodsCtrlPlanePort; std::string bind_str( "tcp://localhost:" ); bind_str += port_sstr.str(); try { // standard zmq rep-req communication pattern zmq::context_t zmq_ctx( 1 ); zmq::socket_t zmq_skt( zmq_ctx, ZMQ_REQ ); try { zmq_skt.connect( bind_str.c_str() ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error connecting to a socket.\n"; return 1; } // copy binary encoding into a zmq message for transport zmq::message_t rep( data_to_send.size() ); memcpy( rep.data(), data_to_send.data(), data_to_send.size() ); try { zmq_skt.send( rep ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error receiving a message.\n"; return 1; } zmq::message_t req; // wait for the server reponse try { zmq_skt.recv( &req ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error receiving a message.\n"; return 1; } // decrypt the response std::string rep_str; ret = decrypt_response( env, static_cast< const uint8_t* >( req.data() ), req.size(), rep_str ); if ( !ret.ok() ) { irods::error err = PASS( ret ); std::cerr << err.result() << std::endl; return 1; } if ( irods::SERVER_CONTROL_SUCCESS != rep_str ) { if ( irods::SERVER_CONTROL_STATUS == cmd.command ) { try { rep_str = format_grid_status( rep_str ); std::cout << rep_str << std::endl; } catch ( const irods::exception& e_ ) { std::cerr << e_.message_stack()[0]; } } else { std::cout << rep_str << std::endl; } } } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error.\n"; return 1; } return 0; } // main <commit_msg>[#2792] [#2212] CID98992:<commit_after>#include "zmq.hpp" #include "avro/Encoder.hh" #include "avro/Decoder.hh" #include "avro/Specific.hh" #include <string> #include <sstream> #include <iostream> #include "boost/unordered_map.hpp" #include "boost/program_options.hpp" #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "jansson.h" #include "rodsClient.h" #include "irods_server_control_plane.hpp" #include "irods_buffer_encryption.hpp" #include "server_control_plane_command.hpp" #include "irods_buffer_encryption.hpp" #include "irods_exception.hpp" template <typename T> irods::error usage(T& ostream) { ostream << "usage: 'irods-grid action [ option ] target'" << std::endl; ostream << "action: ( required ) status, pause, resume, shutdown" << std::endl; ostream << "option: --force-after=seconds or --wait-forever" << std::endl; ostream << "target: ( required ) --all, --hosts=<fqdn1>,<fqdn2>,..." << std::endl; return ERROR( SYS_INVALID_INPUT_PARAM, "usage" ); } // usage irods::error parse_program_options( int _argc, char* _argv[], irods::control_plane_command& _cmd ) { namespace po = boost::program_options; po::options_description opt_desc( "options" ); opt_desc.add_options() ( "action", "either 'status', 'shutdown', 'pause', or 'resume'" ) ( "help", "show command usage" ) ( "all", "operation applies to all servers in the grid" ) ( "hosts", po::value<std::string>(), "operation applies to a list of hosts in the grid" ) ( "force-after", po::value<size_t>(), "force shutdown after N seconds" ) ( "wait-forever", "wait indefinitely for a graceful shutdown" ) ( "shutdown", "gracefully shutdown a server(s)" ) ( "pause", "refuse new client connections" ) ( "resume", "allow new client connections" ); po::positional_options_description pos_desc; pos_desc.add( "action", 1 ); po::variables_map vm; try { po::store( po::command_line_parser( _argc, _argv ).options( opt_desc ).positional( pos_desc ).run(), vm ); po::notify( vm ); } catch ( po::error& _e ) { std::cerr << std::endl << "Error: " << _e.what() << std::endl << std::endl; return usage(std::cerr); } // capture the 'subcommand' or 'action' to perform on the grid irods::control_plane_command cmd; if ( vm.count( "action" ) ) { try { const std::string& action = vm["action"].as<std::string>(); boost::unordered_map< std::string, std::string > cmd_map; cmd_map[ "status" ] = irods::SERVER_CONTROL_STATUS; cmd_map[ "pause" ] = irods::SERVER_CONTROL_PAUSE; cmd_map[ "resume" ] = irods::SERVER_CONTROL_RESUME; cmd_map[ "shutdown" ] = irods::SERVER_CONTROL_SHUTDOWN; if ( cmd_map.end() == cmd_map.find( action ) ) { std::cerr << "invalid subcommand [" << action << "]" << std::endl; return usage(std::cerr); } _cmd.command = cmd_map[ action ]; } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"action\"] to std::string failed." ); } } else { return usage(std::cout); } if ( vm.count( "force-after" ) ) { try { size_t secs = vm[ "force-after" ].as<size_t>(); std::stringstream ss; ss << secs; _cmd.options[ irods::SERVER_CONTROL_FORCE_AFTER_KW ] = ss.str(); } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"force-after\"] to std::string failed." ); } } else if ( vm.count( "wait-forever" ) ) { _cmd.options[ irods::SERVER_CONTROL_WAIT_FOREVER_KW ] = "keep_waiting"; } // capture either the 'all' servers or the hosts list if ( vm.count( "all" ) ) { _cmd.options[ irods::SERVER_CONTROL_OPTION_KW ] = irods::SERVER_CONTROL_ALL_OPT; } else if ( vm.count( "hosts" ) ) { _cmd.options[ irods::SERVER_CONTROL_OPTION_KW ] = irods::SERVER_CONTROL_HOSTS_OPT; std::vector< std::string > hosts; try { boost::split( hosts, vm[ "hosts" ].as<std::string>(), boost::is_any_of( ", " ), boost::token_compress_on ); } catch ( const boost::bad_function_call& ) { return ERROR( BAD_FUNCTION_CALL, "Boost threw bad_function_call." ); } catch ( const boost::bad_any_cast& ) { return ERROR( INVALID_ANY_CAST, "Attempt to cast vm[\"hosts\"] to std::string failed." ); } for ( size_t i = 0; i < hosts.size(); ++i ) { std::stringstream ss; ss << i; _cmd.options[ irods::SERVER_CONTROL_HOST_KW + ss.str() ] = hosts[ i ]; } // for i } else { return usage(std::cerr); } return SUCCESS(); } // parse_program_options irods::error prepare_command_for_transport( const rodsEnv& _env, const irods::control_plane_command& _cmd, irods::buffer_crypt::array_t& _data_to_send ) { // build a encryption context std::string encryption_key( _env.irodsCtrlPlaneKey ); irods::buffer_crypt crypt( encryption_key.size(), // key size 0, // salt size ( we dont send a salt ) _env.irodsCtrlPlaneEncryptionNumHashRounds, _env.irodsCtrlPlaneEncryptionAlgorithm ); // serialize using the generated avro class std::auto_ptr< avro::OutputStream > out = avro::memoryOutputStream(); avro::EncoderPtr e = avro::binaryEncoder(); e->init( *out ); avro::encode( *e, _cmd ); boost::shared_ptr< std::vector< uint8_t > > data = avro::snapshot( *out ); // encrypt outgoing request std::vector< unsigned char > enc_data( data->begin(), data->end() ); irods::buffer_crypt::array_t iv; irods::buffer_crypt::array_t in_buf( enc_data.begin(), enc_data.end() ); irods::buffer_crypt::array_t shared_secret( encryption_key.begin(), encryption_key.end() ); irods::error ret = crypt.encrypt( shared_secret, iv, in_buf, _data_to_send ); if ( !ret.ok() ) { return PASS( ret ); } return SUCCESS(); } // prepare_command_for_transport irods::error decrypt_response( const rodsEnv& _env, const uint8_t* _data_ptr, const size_t _data_size, std::string& _rep_str ) { irods::buffer_crypt::array_t in_buf; in_buf.assign( _data_ptr, _data_ptr + _data_size ); std::string encryption_key( _env.irodsCtrlPlaneKey ); irods::buffer_crypt crypt( encryption_key.size(), // key size 0, // salt size ( we dont send a salt ) _env.irodsCtrlPlaneEncryptionNumHashRounds, _env.irodsCtrlPlaneEncryptionAlgorithm ); irods::buffer_crypt::array_t iv; irods::buffer_crypt::array_t shared_secret( encryption_key.begin(), encryption_key.end() ); irods::buffer_crypt::array_t decoded_data; irods::error ret = crypt.decrypt( shared_secret, iv, in_buf, decoded_data ); if ( !ret.ok() ) { return PASS( ret ); } _rep_str.assign( decoded_data.begin(), decoded_data.begin() + decoded_data.size() ); return SUCCESS(); } // decrypt_response std::string format_grid_status( const std::string& _status) { std::string status = "{\n \"hosts\": [\n"; status += _status; status += "] \n}"; std::string::size_type pos = status.find_last_of( "," ); if ( std::string::npos != pos ) { status.erase( pos, 1 ); } else { // possible error message THROW( -1, std::string("server responded with an error\n") + _status ); } json_error_t j_err; json_t* obj = json_loads( ( char* )status.data(), JSON_REJECT_DUPLICATES, &j_err ); if ( !obj ) { if ( std::string::npos != _status.find( irods::SERVER_PAUSED_ERROR ) ) { THROW( -1, std::string("server paused error\n") + _status ); } THROW( -1, std::string("json_loads failed\n") + j_err.text ); } char* tmp_buf = json_dumps( obj, JSON_INDENT( 4 ) ); json_decref( obj ); status = tmp_buf; free( tmp_buf ); return status; } // format_grid_status irods::error get_and_verify_client_environment( rodsEnv& _env ) { _getRodsEnv( _env ); bool have_error = false; std::string msg = "missing environment entries: "; if( 0 == strlen( _env.irodsCtrlPlaneKey ) ) { have_error = true; msg += "irods_server_control_plane_key"; } if( 0 == _env.irodsCtrlPlaneEncryptionNumHashRounds ) { have_error = true; msg += ", irods_server_control_plane_encryption_num_hash_rounds"; } if( 0 == strlen( _env.irodsCtrlPlaneEncryptionAlgorithm ) ) { have_error = true; msg += ", irods_server_control_plane_encryption_algorithm"; } if( 0 == _env.irodsCtrlPlanePort ) { have_error = true; msg += ", irods_server_control_plane_port"; } if( have_error ) { return ERROR( USER_INVALID_CLIENT_ENVIRONMENT, msg ); } return SUCCESS(); } // verify_client_environment int main( int _argc, char* _argv[] ) { irods::control_plane_command cmd; irods::error ret = parse_program_options( _argc, _argv, cmd ); if ( !ret.ok() ) { return 0; } rodsEnv env; irods::error err = get_and_verify_client_environment( env ); if( !err.ok() ) { std::cerr << err.result(); return 1; } irods::buffer_crypt::array_t data_to_send; ret = prepare_command_for_transport( env, cmd, data_to_send ); if ( !ret.ok() ) { std::cerr << ret.result() << std::endl; return ret.code(); } // this is the client so we connect rather than bind std::stringstream port_sstr; port_sstr << env.irodsCtrlPlanePort; std::string bind_str( "tcp://localhost:" ); bind_str += port_sstr.str(); try { // standard zmq rep-req communication pattern zmq::context_t zmq_ctx( 1 ); zmq::socket_t zmq_skt( zmq_ctx, ZMQ_REQ ); try { zmq_skt.connect( bind_str.c_str() ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error connecting to a socket.\n"; return 1; } // copy binary encoding into a zmq message for transport zmq::message_t rep( data_to_send.size() ); memcpy( rep.data(), data_to_send.data(), data_to_send.size() ); try { zmq_skt.send( rep ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error receiving a message.\n"; return 1; } zmq::message_t req; // wait for the server reponse try { zmq_skt.recv( &req ); } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error receiving a message.\n"; return 1; } // decrypt the response std::string rep_str; ret = decrypt_response( env, static_cast< const uint8_t* >( req.data() ), req.size(), rep_str ); if ( !ret.ok() ) { irods::error err = PASS( ret ); std::cerr << err.result() << std::endl; return 1; } if ( irods::SERVER_CONTROL_SUCCESS != rep_str ) { if ( irods::SERVER_CONTROL_STATUS == cmd.command ) { try { rep_str = format_grid_status( rep_str ); std::cout << rep_str << std::endl; } catch ( const irods::exception& e_ ) { std::cerr << e_.message_stack()[0]; } } else { std::cout << rep_str << std::endl; } } } catch ( const zmq::error_t& ) { std::cerr << "ZeroMQ encountered an error.\n"; return 1; } return 0; } // main <|endoftext|>
<commit_before>// includes, Qwt #include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_scale_engine.h> // System Includes #include <iostream> // include local #include "plotgapwidget.h" // QT #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QSpacerItem> namespace iu { //----------------------------------------------------------------------------- PlotGapWidget::PlotGapWidget(QWidget* parent, bool x_log_scale, bool y_log_scale) :QWidget(parent) { myPlot_ = new QwtPlot(0); int numDecimals = 2; myPlot_->setCanvasBackground(QColor(255,255,255)); if (x_log_scale) myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); if (y_log_scale) myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); QHBoxLayout* controlLayout = new QHBoxLayout(NULL); QLabel* yMinLabel = new QLabel; yMinLabel->setText("Y-Axis"); controlLayout->addWidget(yMinLabel); yMin_ = new QScienceSpinBox; yMin_->setDecimals(numDecimals); controlLayout->addWidget(yMin_); yMax_ = new QScienceSpinBox; yMax_->setDecimals(numDecimals); controlLayout->addWidget(yMax_); yLog_ = new QCheckBox(); yLog_->setText("Log scale"); if (y_log_scale) yLog_->setChecked(true); else yLog_->setChecked(false); controlLayout->addWidget(yLog_); controlLayout->insertStretch(4); QLabel* xMinLabel = new QLabel; xMinLabel->setText("X-Axis"); controlLayout->addWidget(xMinLabel); xMin_ = new QScienceSpinBox; xMin_->setDecimals(numDecimals); controlLayout->addWidget(xMin_); xMax_ = new QScienceSpinBox; xMax_->setDecimals(numDecimals); controlLayout->addWidget(xMax_); xLog_ = new QCheckBox; xLog_->setText("Log scale"); if (x_log_scale) xLog_->setChecked(true); else xLog_->setChecked(false); controlLayout->addWidget(xLog_); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->addLayout(controlLayout); mainLayout->addWidget(myPlot_); this->setLayout(mainLayout); myPlot_->replot(); // make some connections connect(xMin_, SIGNAL(valueChanged(double)), this, SLOT(updateXMin(double))); connect(xMax_, SIGNAL(valueChanged(double)), this, SLOT(updateXMax(double))); connect(xLog_, SIGNAL(toggled(bool)), this, SLOT(updateXLog(bool))); connect(yMin_, SIGNAL(valueChanged(double)), this, SLOT(updateYMin(double))); connect(yMax_, SIGNAL(valueChanged(double)), this, SLOT(updateYMax(double))); connect(yLog_, SIGNAL(toggled(bool)), this, SLOT(updateYLog(bool))); } //----------------------------------------------------------------------------- PlotGapWidget::~PlotGapWidget() { } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(std::list<int> x_values, std::list<double> y_values, QString name, QColor color) { int elements_list = x_values.size(); double* x_values_array = new double[elements_list]; double* y_values_array = new double[elements_list]; // // skip first element // if (*(x_values.begin()) == 0) // { // x_values.pop_front(); // y_values.pop_front(); // } // copy std::list<int>::iterator itx; int count = 1; for ( itx=x_values.begin() ; itx != x_values.end(); itx++ ) { x_values_array[elements_list-count] = *itx; count++; } count = 1; std::list<double>::iterator ity; for ( ity=y_values.begin() ; ity != y_values.end(); ity++ ) { y_values_array[elements_list-count] = *ity; count++; } printf("OOOOOOOOOOOOOOOOOOOOOOOOO\n"); for (int i=0; i<count-1; i++) { printf("(x,y): %f, %f\n", x_values_array[i], y_values_array[i]); } printf("OOOOOOOOOOOOOOOOOOOOOOOOO\n"); addCurve(x_values_array, y_values_array, elements_list, name, color); delete x_values_array; delete y_values_array; } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(std::list<double> x_values, std::list<double> y_values, QString name, QColor color) { int elements_list = x_values.size(); double* x_values_array = new double[elements_list]; double* y_values_array = new double[elements_list]; // // skip first element // if (*(x_values.begin()) == 0) // { // x_values.pop_front(); // y_values.pop_front(); // } std::list<double>::iterator it; int count = 1; for ( it=x_values.begin() ; it != x_values.end(); it++ ) { x_values_array[elements_list-count] = *it; count++; } count = 1; for ( it=y_values.begin() ; it != y_values.end(); it++ ) { y_values_array[elements_list-count] = *it; count++; } printf("########################\n"); for (int i=0; i<count-1; i++) { printf("(x,y): %f, %f\n", x_values_array[i], y_values_array[i]); } printf("########################\n"); addCurve(x_values_array, y_values_array, elements_list, name, color); delete x_values_array; delete y_values_array; } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(double* x_values_array, double* y_values_array, int elements_list, QString name, QColor color) { QwtPlotCurve *curveDual = new QwtPlotCurve(name); curveDual->setPen(QPen(color)); curveDual->setSamples(x_values_array, y_values_array, elements_list); curveDual->attach(myPlot_); myPlot_->setAxisAutoScale(QwtPlot::xBottom); myPlot_->setAxisAutoScale(QwtPlot::yLeft); myPlot_->replot(); #if (QWT_VERSION >= 0x050200) double xmin = myPlot_->axisScaleDiv(QwtPlot::xBottom)->lowerBound(); double xmax = myPlot_->axisScaleDiv(QwtPlot::xBottom)->upperBound(); double ymin = myPlot_->axisScaleDiv(QwtPlot::yLeft)->lowerBound(); double ymax = myPlot_->axisScaleDiv(QwtPlot::yLeft)->upperBound(); #else double xmin = myPlot_->axisScaleDiv(QwtPlot::xBottom)->lBound(); double xmax = myPlot_->axisScaleDiv(QwtPlot::xBottom)->hBound(); double ymin = myPlot_->axisScaleDiv(QwtPlot::yLeft)->lBound(); double ymax = myPlot_->axisScaleDiv(QwtPlot::yLeft)->hBound(); #endif // xMin_->setMinimum(xmin/10.0); // xMin_->setMaximum(xmax*10.0); // xMax_->setMinimum(xmin/10.0); // xMax_->setMaximum(xmax*10.0); // yMin_->setMinimum(ymin-abs(ymax-ymin)); // yMin_->setMaximum(ymax+abs(ymax-ymin)); // yMax_->setMinimum(ymin-abs(ymax-ymin)); // yMax_->setMaximum(ymax+abs(ymax-ymin)); xMin_->setValue(xmin); xMax_->setValue(xmax); yMin_->setValue(ymin); yMax_->setValue(ymax); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXMin(double value) { myPlot_->setAxisScale(QwtPlot::xBottom, xMin_->value(), xMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXMax(double value) { myPlot_->setAxisScale(QwtPlot::xBottom, xMin_->value(), xMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXLog(bool value) { if (value) myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); else myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYMin(double value) { myPlot_->setAxisScale(QwtPlot::yLeft, yMin_->value(), yMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYMax(double value) { myPlot_->setAxisScale(QwtPlot::yLeft, yMin_->value(), yMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYLog(bool value) { if (value) myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); else myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); myPlot_->replot(); } } // namespace iu <commit_msg><commit_after>// includes, Qwt #include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_scale_engine.h> // System Includes #include <iostream> // include local #include "plotgapwidget.h" // QT #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QSpacerItem> namespace iu { //----------------------------------------------------------------------------- PlotGapWidget::PlotGapWidget(QWidget* parent, bool x_log_scale, bool y_log_scale) :QWidget(parent) { myPlot_ = new QwtPlot(0); int numDecimals = 2; myPlot_->setCanvasBackground(QColor(255,255,255)); if (x_log_scale) myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); if (y_log_scale) myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); QHBoxLayout* controlLayout = new QHBoxLayout(NULL); QLabel* yMinLabel = new QLabel; yMinLabel->setText("Y-Axis"); controlLayout->addWidget(yMinLabel); yMin_ = new QScienceSpinBox; yMin_->setDecimals(numDecimals); controlLayout->addWidget(yMin_); yMax_ = new QScienceSpinBox; yMax_->setDecimals(numDecimals); controlLayout->addWidget(yMax_); yLog_ = new QCheckBox(); yLog_->setText("Log scale"); if (y_log_scale) yLog_->setChecked(true); else yLog_->setChecked(false); controlLayout->addWidget(yLog_); controlLayout->insertStretch(4); QLabel* xMinLabel = new QLabel; xMinLabel->setText("X-Axis"); controlLayout->addWidget(xMinLabel); xMin_ = new QScienceSpinBox; xMin_->setDecimals(numDecimals); controlLayout->addWidget(xMin_); xMax_ = new QScienceSpinBox; xMax_->setDecimals(numDecimals); controlLayout->addWidget(xMax_); xLog_ = new QCheckBox; xLog_->setText("Log scale"); if (x_log_scale) xLog_->setChecked(true); else xLog_->setChecked(false); controlLayout->addWidget(xLog_); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->addLayout(controlLayout); mainLayout->addWidget(myPlot_); this->setLayout(mainLayout); myPlot_->replot(); // make some connections connect(xMin_, SIGNAL(valueChanged(double)), this, SLOT(updateXMin(double))); connect(xMax_, SIGNAL(valueChanged(double)), this, SLOT(updateXMax(double))); connect(xLog_, SIGNAL(toggled(bool)), this, SLOT(updateXLog(bool))); connect(yMin_, SIGNAL(valueChanged(double)), this, SLOT(updateYMin(double))); connect(yMax_, SIGNAL(valueChanged(double)), this, SLOT(updateYMax(double))); connect(yLog_, SIGNAL(toggled(bool)), this, SLOT(updateYLog(bool))); } //----------------------------------------------------------------------------- PlotGapWidget::~PlotGapWidget() { } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(std::list<int> x_values, std::list<double> y_values, QString name, QColor color) { int elements_list = x_values.size(); double* x_values_array = new double[elements_list]; double* y_values_array = new double[elements_list]; // // skip first element // if (*(x_values.begin()) == 0) // { // x_values.pop_front(); // y_values.pop_front(); // } // copy std::list<int>::iterator itx; int count = 1; for ( itx=x_values.begin() ; itx != x_values.end(); itx++ ) { x_values_array[elements_list-count] = *itx; count++; } count = 1; std::list<double>::iterator ity; for ( ity=y_values.begin() ; ity != y_values.end(); ity++ ) { y_values_array[elements_list-count] = *ity; count++; } printf("OOOOOOOOOOOOOOOOOOOOOOOOO\n"); for (int i=0; i<count-1; i++) { printf("(x,y): %f, %f\n", x_values_array[i], y_values_array[i]); } printf("OOOOOOOOOOOOOOOOOOOOOOOOO\n"); addCurve(x_values_array, y_values_array, elements_list, name, color); delete x_values_array; delete y_values_array; } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(std::list<double> x_values, std::list<double> y_values, QString name, QColor color) { int elements_list = x_values.size(); double* x_values_array = new double[elements_list]; double* y_values_array = new double[elements_list]; // // skip first element // if (*(x_values.begin()) == 0) // { // x_values.pop_front(); // y_values.pop_front(); // } std::list<double>::iterator it; int count = 1; for ( it=x_values.begin() ; it != x_values.end(); it++ ) { x_values_array[elements_list-count] = *it; count++; } count = 1; for ( it=y_values.begin() ; it != y_values.end(); it++ ) { y_values_array[elements_list-count] = *it; count++; } printf("########################\n"); for (int i=0; i<count-1; i++) { printf("(x,y): %f, %f\n", x_values_array[i], y_values_array[i]); } printf("########################\n"); addCurve(x_values_array, y_values_array, elements_list, name, color); delete x_values_array; delete y_values_array; } //----------------------------------------------------------------------------- void PlotGapWidget::addCurve(double* x_values_array, double* y_values_array, int elements_list, QString name, QColor color) { QwtPlotCurve *curveDual = new QwtPlotCurve(name); curveDual->setPen(QPen(color)); #if QWT_VERSION < 0x060000 curveDual->setData(x_values_array, y_values_array, elements_list); #else curveDual->setSamples(x_values_array, y_values_array, elements_list); #endif curveDual->attach(myPlot_); myPlot_->setAxisAutoScale(QwtPlot::xBottom); myPlot_->setAxisAutoScale(QwtPlot::yLeft); myPlot_->replot(); #if (QWT_VERSION >= 0x050200) double xmin = myPlot_->axisScaleDiv(QwtPlot::xBottom)->lowerBound(); double xmax = myPlot_->axisScaleDiv(QwtPlot::xBottom)->upperBound(); double ymin = myPlot_->axisScaleDiv(QwtPlot::yLeft)->lowerBound(); double ymax = myPlot_->axisScaleDiv(QwtPlot::yLeft)->upperBound(); #else double xmin = myPlot_->axisScaleDiv(QwtPlot::xBottom)->lBound(); double xmax = myPlot_->axisScaleDiv(QwtPlot::xBottom)->hBound(); double ymin = myPlot_->axisScaleDiv(QwtPlot::yLeft)->lBound(); double ymax = myPlot_->axisScaleDiv(QwtPlot::yLeft)->hBound(); #endif // xMin_->setMinimum(xmin/10.0); // xMin_->setMaximum(xmax*10.0); // xMax_->setMinimum(xmin/10.0); // xMax_->setMaximum(xmax*10.0); // yMin_->setMinimum(ymin-abs(ymax-ymin)); // yMin_->setMaximum(ymax+abs(ymax-ymin)); // yMax_->setMinimum(ymin-abs(ymax-ymin)); // yMax_->setMaximum(ymax+abs(ymax-ymin)); xMin_->setValue(xmin); xMax_->setValue(xmax); yMin_->setValue(ymin); yMax_->setValue(ymax); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXMin(double value) { myPlot_->setAxisScale(QwtPlot::xBottom, xMin_->value(), xMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXMax(double value) { myPlot_->setAxisScale(QwtPlot::xBottom, xMin_->value(), xMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateXLog(bool value) { if (value) myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); else myPlot_->setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYMin(double value) { myPlot_->setAxisScale(QwtPlot::yLeft, yMin_->value(), yMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYMax(double value) { myPlot_->setAxisScale(QwtPlot::yLeft, yMin_->value(), yMax_->value(), 0); myPlot_->replot(); } //----------------------------------------------------------------------------- void PlotGapWidget::updateYLog(bool value) { if (value) myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); else myPlot_->setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); myPlot_->replot(); } } // namespace iu <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "checkbase.h" #include "StringUtils.h" #include <clang/AST/Decl.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ParentMap.h> #include <clang/Rewrite/Frontend/FixItRewriter.h> #include <vector> using namespace clang; using namespace std; CheckBase::CheckBase(const string &name, const CompilerInstance &ci) : m_ci(ci) , m_name(name) , m_lastDecl(nullptr) , m_enabledFixits(0) { ASTContext &context = m_ci.getASTContext(); m_tu = context.getTranslationUnitDecl(); m_lastMethodDecl = nullptr; } CheckBase::~CheckBase() { } void CheckBase::VisitStatement(Stmt *stm) { if (!shouldIgnoreFile(stm->getLocStart())) { VisitStmt(stm); } } void CheckBase::VisitDeclaration(Decl *decl) { if (shouldIgnoreFile(decl->getLocStart())) return; m_lastDecl = decl; auto mdecl = dyn_cast<CXXMethodDecl>(decl); if (mdecl) m_lastMethodDecl = mdecl; VisitDecl(decl); } string CheckBase::name() const { return m_name; } void CheckBase::setParentMap(ParentMap *parentMap) { m_parentMap = parentMap; } void CheckBase::VisitStmt(Stmt *) { } void CheckBase::VisitDecl(Decl *) { } bool CheckBase::shouldIgnoreFile(SourceLocation loc) const { if (!loc.isValid() || sm().isInSystemHeader(loc)) return true; auto filename = sm().getFilename(loc); const std::vector<std::string> files = filesToIgnore(); for (auto &file : files) { bool contains = filename.find(file) != std::string::npos; if (contains) return true; } return false; } std::vector<std::string> CheckBase::filesToIgnore() const { return {}; } void CheckBase::emitWarning(clang::SourceLocation loc, std::string error, bool printWarningTag) { emitWarning(loc, error, {}, printWarningTag); } void CheckBase::emitWarning(clang::SourceLocation loc, std::string error, const vector<FixItHint> &fixits, bool printWarningTag) { if (loc.isMacroID()) { if (warningAlreadyEmitted(loc)) return; // For warnings in macro arguments we get a warning in each place the argument is used within the expanded macro, so filter all the dups m_emittedWarningsInMacro.push_back(loc.getRawEncoding()); } const string tag = " [-Wclazy-" + name() + ']'; if (printWarningTag) error += tag; reallyEmitWarning(loc, error, fixits); for (const auto& l : m_queuedManualInterventionWarnings) { string msg = string("FixIt failed, requires manual intervention: "); if (!l.second.empty()) msg += ' ' + l.second; reallyEmitWarning(l.first, msg + tag, {}); } m_queuedManualInterventionWarnings.clear(); } void CheckBase::reallyEmitWarning(clang::SourceLocation loc, const std::string &error, const vector<FixItHint> &fixits) { FullSourceLoc full(loc, sm()); unsigned id = m_ci.getDiagnostics().getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Warning, error.c_str()); DiagnosticBuilder B = m_ci.getDiagnostics().Report(full, id); for (const FixItHint& fixit : fixits) { if (!fixit.isNull()) B.AddFixItHint(fixit); } } void CheckBase::queueManualFixitWarning(clang::SourceLocation loc, int fixitType, const string &message) { if (isFixitEnabled(fixitType) && !manualFixitAlreadyQueued(loc)) { m_queuedManualInterventionWarnings.push_back({loc, message}); m_emittedManualFixItsWarningsInMacro.push_back(loc.getRawEncoding()); } } bool CheckBase::warningAlreadyEmitted(SourceLocation loc) const { PresumedLoc ploc = sm().getPresumedLoc(loc); for (auto rawLoc : m_emittedWarningsInMacro) { SourceLocation l = SourceLocation::getFromRawEncoding(rawLoc); PresumedLoc p = sm().getPresumedLoc(l); if (Utils::presumedLocationsEqual(p, ploc)) return true; } return false; } bool CheckBase::manualFixitAlreadyQueued(SourceLocation loc) const { PresumedLoc ploc = sm().getPresumedLoc(loc); for (auto loc : m_emittedManualFixItsWarningsInMacro) { SourceLocation l = SourceLocation::getFromRawEncoding(loc); PresumedLoc p = sm().getPresumedLoc(l); if (Utils::presumedLocationsEqual(p, ploc)) return true; } return false; } std::vector<string> CheckBase::supportedOptions() const { return {}; } bool CheckBase::isOptionSet(const std::string &optionName) const { const string qualifiedName = name() + '-' + optionName; return CheckManager::instance()->isOptionSet(qualifiedName); } void CheckBase::setEnabledFixits(int fixits) { m_enabledFixits = fixits; } bool CheckBase::isFixitEnabled(int fixit) const { return (m_enabledFixits & fixit) || CheckManager::instance()->allFixitsEnabled(); } <commit_msg>Use any_of instead of raw loop<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "checkbase.h" #include "StringUtils.h" #include <clang/AST/Decl.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ParentMap.h> #include <clang/Rewrite/Frontend/FixItRewriter.h> #include <vector> using namespace clang; using namespace std; CheckBase::CheckBase(const string &name, const CompilerInstance &ci) : m_ci(ci) , m_name(name) , m_lastDecl(nullptr) , m_enabledFixits(0) { ASTContext &context = m_ci.getASTContext(); m_tu = context.getTranslationUnitDecl(); m_lastMethodDecl = nullptr; } CheckBase::~CheckBase() { } void CheckBase::VisitStatement(Stmt *stm) { if (!shouldIgnoreFile(stm->getLocStart())) { VisitStmt(stm); } } void CheckBase::VisitDeclaration(Decl *decl) { if (shouldIgnoreFile(decl->getLocStart())) return; m_lastDecl = decl; auto mdecl = dyn_cast<CXXMethodDecl>(decl); if (mdecl) m_lastMethodDecl = mdecl; VisitDecl(decl); } string CheckBase::name() const { return m_name; } void CheckBase::setParentMap(ParentMap *parentMap) { m_parentMap = parentMap; } void CheckBase::VisitStmt(Stmt *) { } void CheckBase::VisitDecl(Decl *) { } bool CheckBase::shouldIgnoreFile(SourceLocation loc) const { if (!loc.isValid() || sm().isInSystemHeader(loc)) return true; auto filename = sm().getFilename(loc); return clazy_std::any_of(filesToIgnore(), [filename](const std::string &file) { bool contains = filename.find(file) != std::string::npos; return contains; }); } std::vector<std::string> CheckBase::filesToIgnore() const { return {}; } void CheckBase::emitWarning(clang::SourceLocation loc, std::string error, bool printWarningTag) { emitWarning(loc, error, {}, printWarningTag); } void CheckBase::emitWarning(clang::SourceLocation loc, std::string error, const vector<FixItHint> &fixits, bool printWarningTag) { if (loc.isMacroID()) { if (warningAlreadyEmitted(loc)) return; // For warnings in macro arguments we get a warning in each place the argument is used within the expanded macro, so filter all the dups m_emittedWarningsInMacro.push_back(loc.getRawEncoding()); } const string tag = " [-Wclazy-" + name() + ']'; if (printWarningTag) error += tag; reallyEmitWarning(loc, error, fixits); for (const auto& l : m_queuedManualInterventionWarnings) { string msg = string("FixIt failed, requires manual intervention: "); if (!l.second.empty()) msg += ' ' + l.second; reallyEmitWarning(l.first, msg + tag, {}); } m_queuedManualInterventionWarnings.clear(); } void CheckBase::reallyEmitWarning(clang::SourceLocation loc, const std::string &error, const vector<FixItHint> &fixits) { FullSourceLoc full(loc, sm()); unsigned id = m_ci.getDiagnostics().getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Warning, error.c_str()); DiagnosticBuilder B = m_ci.getDiagnostics().Report(full, id); for (const FixItHint& fixit : fixits) { if (!fixit.isNull()) B.AddFixItHint(fixit); } } void CheckBase::queueManualFixitWarning(clang::SourceLocation loc, int fixitType, const string &message) { if (isFixitEnabled(fixitType) && !manualFixitAlreadyQueued(loc)) { m_queuedManualInterventionWarnings.push_back({loc, message}); m_emittedManualFixItsWarningsInMacro.push_back(loc.getRawEncoding()); } } bool CheckBase::warningAlreadyEmitted(SourceLocation loc) const { PresumedLoc ploc = sm().getPresumedLoc(loc); for (auto rawLoc : m_emittedWarningsInMacro) { SourceLocation l = SourceLocation::getFromRawEncoding(rawLoc); PresumedLoc p = sm().getPresumedLoc(l); if (Utils::presumedLocationsEqual(p, ploc)) return true; } return false; } bool CheckBase::manualFixitAlreadyQueued(SourceLocation loc) const { PresumedLoc ploc = sm().getPresumedLoc(loc); for (auto loc : m_emittedManualFixItsWarningsInMacro) { SourceLocation l = SourceLocation::getFromRawEncoding(loc); PresumedLoc p = sm().getPresumedLoc(l); if (Utils::presumedLocationsEqual(p, ploc)) return true; } return false; } std::vector<string> CheckBase::supportedOptions() const { return {}; } bool CheckBase::isOptionSet(const std::string &optionName) const { const string qualifiedName = name() + '-' + optionName; return CheckManager::instance()->isOptionSet(qualifiedName); } void CheckBase::setEnabledFixits(int fixits) { m_enabledFixits = fixits; } bool CheckBase::isFixitEnabled(int fixit) const { return (m_enabledFixits & fixit) || CheckManager::instance()->allFixitsEnabled(); } <|endoftext|>
<commit_before>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file mockturtle.hpp \brief Main header file for mockturtle \author Mathias Soeken */ #pragma once #include "mockturtle/traits.hpp" #include "mockturtle/io/write_bench.hpp" #include "mockturtle/io/bench_reader.hpp" #include "mockturtle/io/verilog_reader.hpp" #include "mockturtle/io/write_blif.hpp" #include "mockturtle/io/blif_reader.hpp" #include "mockturtle/io/write_dot.hpp" #include "mockturtle/io/write_verilog.hpp" #include "mockturtle/io/pla_reader.hpp" #include "mockturtle/io/aiger_reader.hpp" #include "mockturtle/io/write_dimacs.hpp" #include "mockturtle/algorithms/simulation.hpp" #include "mockturtle/algorithms/dont_cares.hpp" #include "mockturtle/algorithms/equivalence_checking.hpp" #include "mockturtle/algorithms/lut_mapping.hpp" #include "mockturtle/algorithms/bi_decomposition.hpp" #include "mockturtle/algorithms/cut_rewriting.hpp" #include "mockturtle/algorithms/cut_enumeration/spectr_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/cnf_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/gia_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/mf_cut.hpp" #include "mockturtle/algorithms/cleanup.hpp" #include "mockturtle/algorithms/extract_linear.hpp" #include "mockturtle/algorithms/equivalence_classes.hpp" #include "mockturtle/algorithms/xmg_algebraic_rewriting.hpp" #include "mockturtle/algorithms/dsd_decomposition.hpp" #include "mockturtle/algorithms/cnf.hpp" #include "mockturtle/algorithms/miter.hpp" #include "mockturtle/algorithms/collapse_mapped.hpp" #include "mockturtle/algorithms/reconv_cut2.hpp" #include "mockturtle/algorithms/refactoring.hpp" #include "mockturtle/algorithms/node_resynthesis/exact.hpp" #include "mockturtle/algorithms/node_resynthesis/shannon.hpp" #include "mockturtle/algorithms/node_resynthesis/mig_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/bidecomposition.hpp" #include "mockturtle/algorithms/node_resynthesis/akers.hpp" #include "mockturtle/algorithms/node_resynthesis/dsd.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_minmc.hpp" #include "mockturtle/algorithms/node_resynthesis/direct.hpp" #include "mockturtle/algorithms/akers_synthesis.hpp" #include "mockturtle/algorithms/gates_to_nodes.hpp" #include "mockturtle/algorithms/satlut_mapping.hpp" #include "mockturtle/algorithms/mig_algebraic_rewriting.hpp" #include "mockturtle/algorithms/cut_enumeration.hpp" #include "mockturtle/algorithms/cell_window.hpp" #include "mockturtle/algorithms/shannon_decomposition.hpp" #include "mockturtle/algorithms/node_resynthesis.hpp" #include "mockturtle/algorithms/mig_resub.hpp" #include "mockturtle/algorithms/reconv_cut.hpp" #include "mockturtle/algorithms/resubstitution.hpp" #include "mockturtle/algorithms/aig_resub.hpp" #include "mockturtle/utils/stopwatch.hpp" #include "mockturtle/utils/truth_table_cache.hpp" #include "mockturtle/utils/string_utils.hpp" #include "mockturtle/utils/algorithm.hpp" #include "mockturtle/utils/progress_bar.hpp" #include "mockturtle/utils/mixed_radix.hpp" #include "mockturtle/utils/node_map.hpp" #include "mockturtle/utils/cuts.hpp" #include "mockturtle/networks/aig.hpp" #include "mockturtle/networks/events.hpp" #include "mockturtle/networks/klut.hpp" #include "mockturtle/networks/xmg.hpp" #include "mockturtle/networks/xag.hpp" #include "mockturtle/networks/storage.hpp" #include "mockturtle/networks/mig.hpp" #include "mockturtle/properties/migcost.hpp" #include "mockturtle/properties/mccost.hpp" #include "mockturtle/mockturtle.hpp" #include "mockturtle/generators/sorting.hpp" #include "mockturtle/generators/arithmetic.hpp" #include "mockturtle/generators/control.hpp" #include "mockturtle/generators/majority.hpp" #include "mockturtle/generators/random_logic_generator.hpp" #include "mockturtle/generators/modular_arithmetic.hpp" #include "mockturtle/views/mffc_view.hpp" #include "mockturtle/views/immutable_view.hpp" #include "mockturtle/views/topo_view.hpp" #include "mockturtle/views/window_view.hpp" #include "mockturtle/views/fanout_view.hpp" #include "mockturtle/views/names_view.hpp" #include "mockturtle/views/mapping_view.hpp" #include "mockturtle/views/fanout_view.hpp" #include "mockturtle/views/cut_view.hpp" #include "mockturtle/views/depth_view.hpp" <commit_msg>Update global header. (#264)<commit_after>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file mockturtle.hpp \brief Main header file for mockturtle \author Mathias Soeken */ #pragma once #include "mockturtle/traits.hpp" #include "mockturtle/io/write_bench.hpp" #include "mockturtle/io/bench_reader.hpp" #include "mockturtle/io/verilog_reader.hpp" #include "mockturtle/io/write_blif.hpp" #include "mockturtle/io/blif_reader.hpp" #include "mockturtle/io/write_dot.hpp" #include "mockturtle/io/write_verilog.hpp" #include "mockturtle/io/pla_reader.hpp" #include "mockturtle/io/index_list.hpp" #include "mockturtle/io/aiger_reader.hpp" #include "mockturtle/io/write_dimacs.hpp" #include "mockturtle/algorithms/simulation.hpp" #include "mockturtle/algorithms/xag_resub_withDC.hpp" #include "mockturtle/algorithms/xmg_resub.hpp" #include "mockturtle/algorithms/dont_cares.hpp" #include "mockturtle/algorithms/equivalence_checking.hpp" #include "mockturtle/algorithms/equivalence_classes.hpp" #include "mockturtle/algorithms/extract_linear.hpp" #include "mockturtle/algorithms/lut_mapping.hpp" #include "mockturtle/algorithms/bi_decomposition.hpp" #include "mockturtle/algorithms/cut_rewriting.hpp" #include "mockturtle/algorithms/cut_enumeration/spectr_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/cnf_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/gia_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/mf_cut.hpp" #include "mockturtle/algorithms/cleanup.hpp" #include "mockturtle/algorithms/xag_optimization.hpp" #include "mockturtle/algorithms/xmg_algebraic_rewriting.hpp" #include "mockturtle/algorithms/dsd_decomposition.hpp" #include "mockturtle/algorithms/cnf.hpp" #include "mockturtle/algorithms/miter.hpp" #include "mockturtle/algorithms/collapse_mapped.hpp" #include "mockturtle/algorithms/reconv_cut2.hpp" #include "mockturtle/algorithms/refactoring.hpp" #include "mockturtle/algorithms/node_resynthesis/exact.hpp" #include "mockturtle/algorithms/node_resynthesis/shannon.hpp" #include "mockturtle/algorithms/node_resynthesis/mig_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg3_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/bidecomposition.hpp" #include "mockturtle/algorithms/node_resynthesis/akers.hpp" #include "mockturtle/algorithms/node_resynthesis/dsd.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_minmc.hpp" #include "mockturtle/algorithms/node_resynthesis/direct.hpp" #include "mockturtle/algorithms/akers_synthesis.hpp" #include "mockturtle/algorithms/gates_to_nodes.hpp" #include "mockturtle/algorithms/satlut_mapping.hpp" #include "mockturtle/algorithms/mig_algebraic_rewriting.hpp" #include "mockturtle/algorithms/xmg_optimization.hpp" #include "mockturtle/algorithms/cut_enumeration.hpp" #include "mockturtle/algorithms/cell_window.hpp" #include "mockturtle/algorithms/shannon_decomposition.hpp" #include "mockturtle/algorithms/node_resynthesis.hpp" #include "mockturtle/algorithms/linear_resynthesis.hpp" #include "mockturtle/algorithms/mig_resub.hpp" #include "mockturtle/algorithms/reconv_cut.hpp" #include "mockturtle/algorithms/resubstitution.hpp" #include "mockturtle/algorithms/aig_resub.hpp" #include "mockturtle/utils/stopwatch.hpp" #include "mockturtle/utils/truth_table_cache.hpp" #include "mockturtle/utils/string_utils.hpp" #include "mockturtle/utils/algorithm.hpp" #include "mockturtle/utils/progress_bar.hpp" #include "mockturtle/utils/mixed_radix.hpp" #include "mockturtle/utils/node_map.hpp" #include "mockturtle/utils/cuts.hpp" #include "mockturtle/networks/aig.hpp" #include "mockturtle/networks/events.hpp" #include "mockturtle/networks/klut.hpp" #include "mockturtle/networks/xmg.hpp" #include "mockturtle/networks/xag.hpp" #include "mockturtle/networks/storage.hpp" #include "mockturtle/networks/mig.hpp" #include "mockturtle/properties/migcost.hpp" #include "mockturtle/properties/mccost.hpp" #include "mockturtle/properties/xmgcost.hpp" #include "mockturtle/mockturtle.hpp" #include "mockturtle/generators/sorting.hpp" #include "mockturtle/generators/arithmetic.hpp" #include "mockturtle/generators/control.hpp" #include "mockturtle/generators/majority.hpp" #include "mockturtle/generators/majority_n.hpp" #include "mockturtle/generators/random_logic_generator.hpp" #include "mockturtle/generators/modular_arithmetic.hpp" #include "mockturtle/views/mffc_view.hpp" #include "mockturtle/views/immutable_view.hpp" #include "mockturtle/views/topo_view.hpp" #include "mockturtle/views/window_view.hpp" #include "mockturtle/views/names_view.hpp" #include "mockturtle/views/mapping_view.hpp" #include "mockturtle/views/fanout_view.hpp" #include "mockturtle/views/cut_view.hpp" #include "mockturtle/views/depth_view.hpp" <|endoftext|>
<commit_before>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder 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. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <otf2xx/definition/clock_properties.hpp> #include <otf2xx/exception.hpp> #include <cassert> #include <cmath> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: explicit convert(otf2::chrono::ticks ticks_per_second = otf2::chrono::ticks(otf2::chrono::clock::period::den), otf2::chrono::ticks offset = otf2::chrono::ticks(0)) : offset_(offset.count()), factor_(static_cast<double>(clock::period::den) / ticks_per_second.count()), inverse_factor_(ticks_per_second.count() / static_cast<double>(clock::period::den)) { } explicit convert(const otf2::definition::clock_properties& cp) : convert(cp.ticks_per_second(), cp.start_time()) { // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! // The real question here is, whether we can represent the largest timestamp of the // trace with a time_point in our clock if (cp.length().count() > static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor_) { otf2::make_exception("This traces' timepoints cannot be represented in the " "selected otf2::chrono::time_point. Recompile with " "nanoseconds for OTF2XX_CHRONO_DURATION_TYPE."); } // Note: Due to rounding errors and depending on the OTF2XX_CHRONO_DURATION_TYPE, some // OTF2_TimeStamp values might be mapped to the same otf2::chrono::time_point. } convert(const convert&) = default; convert& operator=(const convert&) = default; convert(convert&&) = default; convert& operator=(convert&&) = default; /** * \brief converts from ticks to time point * * \param[in] ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { // VTTI please remember that those two inputs are uint64_t and then look at the next // line assert(ticks.count() >= offset_); auto tp = ticks.count() - offset_; assert(tp <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor_); return time_point(otf2::chrono::duration(static_cast<int64_t>(tp * factor_))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { auto tp = static_cast<uint64_t>(t.time_since_epoch().count()); assert(tp < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / inverse_factor_); // Note 1: Using ceil here has its origins in the observation that casting from double // to int in the other conversion above leads to an implicit round down. Thus, we // counter that here with an explicit round up. // Note 2: Using an multiplication with the inverse yields a better performance. Though, // there might be cases, where a different sequence of multiplication or division // operations would result in lower rounding errors. auto tpi = static_cast<uint64_t>(std::ceil(tp * inverse_factor_)); assert(tpi <= std::numeric_limits<std::uint64_t>::max() - offset_); return ticks(tpi + offset_); } private: uint64_t offset_; double factor_; double inverse_factor_; }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <commit_msg>Add casts required to compile with clang (#66)<commit_after>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder 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. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <otf2xx/definition/clock_properties.hpp> #include <otf2xx/exception.hpp> #include <cassert> #include <cmath> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: explicit convert(otf2::chrono::ticks ticks_per_second = otf2::chrono::ticks(otf2::chrono::clock::period::den), otf2::chrono::ticks offset = otf2::chrono::ticks(0)) : offset_(offset.count()), factor_(static_cast<double>(clock::period::den) / ticks_per_second.count()), inverse_factor_(ticks_per_second.count() / static_cast<double>(clock::period::den)) { } explicit convert(const otf2::definition::clock_properties& cp) : convert(cp.ticks_per_second(), cp.start_time()) { // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! // The real question here is, whether we can represent the largest timestamp of the // trace with a time_point in our clock if (cp.length().count() > static_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::max())) / factor_) { otf2::make_exception("This traces' timepoints cannot be represented in the " "selected otf2::chrono::time_point. Recompile with " "nanoseconds for OTF2XX_CHRONO_DURATION_TYPE."); } // Note: Due to rounding errors and depending on the OTF2XX_CHRONO_DURATION_TYPE, some // OTF2_TimeStamp values might be mapped to the same otf2::chrono::time_point. } convert(const convert&) = default; convert& operator=(const convert&) = default; convert(convert&&) = default; convert& operator=(convert&&) = default; /** * \brief converts from ticks to time point * * \param[in] ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { // VTTI please remember that those two inputs are uint64_t and then look at the next // line assert(ticks.count() >= offset_); auto tp = ticks.count() - offset_; assert(tp <= static_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::max())) / factor_); return time_point(otf2::chrono::duration(static_cast<int64_t>(tp * factor_))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { auto tp = static_cast<uint64_t>(t.time_since_epoch().count()); assert(tp < static_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::max())) / inverse_factor_); // Note 1: Using ceil here has its origins in the observation that casting from double // to int in the other conversion above leads to an implicit round down. Thus, we // counter that here with an explicit round up. // Note 2: Using an multiplication with the inverse yields a better performance. Though, // there might be cases, where a different sequence of multiplication or division // operations would result in lower rounding errors. auto tpi = static_cast<uint64_t>(std::ceil(tp * inverse_factor_)); assert(tpi <= std::numeric_limits<std::uint64_t>::max() - offset_); return ticks(tpi + offset_); } private: uint64_t offset_; double factor_; double inverse_factor_; }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <|endoftext|>
<commit_before>/// /// @file pod_vector.hpp /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POD_VECTOR_HPP #define POD_VECTOR_HPP #include <vector> namespace primesieve { template <typename T> struct type_without_default_initialization { T n; // Empty constructor, disables default initialization type_without_default_initialization() { }; type_without_default_initialization(T x) : n(x) { }; // User defined implicit conversions. Our type should work // like standard integer types. However we only define the // operators that are used in our code. operator T() const { return n; } void operator=(T x) { n = x; } T* operator&() { return &n; } }; /// Plain old data vector, does not default initialize memory. /// Since primesieve may allocate gigabytes of memory and /// afterwards initalize that memory using multiple threads, /// we don't want our vector to default initialize our memory /// otherwise we would initialize the same memory twice. /// /// @TODO: We cast std::vector into pod_vector in /// iterator.cpp, this is undefined behavior! /// Use std::vector::resize_uninitialized() instead /// once it becomes available. /// template <typename T> using pod_vector = std::vector<type_without_default_initialization<T>>; } // namespace #endif <commit_msg>Remove whitespace<commit_after>/// /// @file pod_vector.hpp /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POD_VECTOR_HPP #define POD_VECTOR_HPP #include <vector> namespace primesieve { template <typename T> struct type_without_default_initialization { T n; // Empty constructor, disables default initialization type_without_default_initialization() { }; type_without_default_initialization(T x) : n(x) { }; // User defined implicit conversions. Our type should work // like standard integer types. However we only define the // operators that are used in our code. operator T() const { return n; } void operator=(T x) { n = x; } T* operator&() { return &n; } }; /// Plain old data vector, does not default initialize memory. /// Since primesieve may allocate gigabytes of memory and /// afterwards initalize that memory using multiple threads, /// we don't want our vector to default initialize our memory /// otherwise we would initialize the same memory twice. /// /// @TODO: We cast std::vector into pod_vector in /// iterator.cpp, this is undefined behavior! /// Use std::vector::resize_uninitialized() instead /// once it becomes available. /// template <typename T> using pod_vector = std::vector<type_without_default_initialization<T>>; } // namespace #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemodeviceconfigurations.h" #include <coreplugin/icore.h> #include <QtCore/QSettings> #include <QtCore/QStringBuilder> #include <QtGui/QDesktopServices> #include <algorithm> namespace Qt4ProjectManager { namespace Internal { QString homeDirOnDevice(const QString &uname) { const QString &dir = uname == QLatin1String("root") ? QLatin1String("/root") : QLatin1String("/home/") + uname; qDebug("%s: user name %s is mapped to home dir %s", Q_FUNC_INFO, qPrintable(uname), qPrintable(dir)); return dir; } namespace { const QLatin1String SettingsGroup("MaemoDeviceConfigs"); const QLatin1String IdCounterKey("IdCounter"); const QLatin1String ConfigListKey("ConfigList"); const QLatin1String NameKey("Name"); const QLatin1String TypeKey("Type"); const QLatin1String HostKey("Host"); const QLatin1String SshPortKey("SshPort"); const QLatin1String GdbServerPortKey("GdbServerPort"); const QLatin1String UserNameKey("Uname"); const QLatin1String AuthKey("Authentication"); const QLatin1String KeyFileKey("KeyFile"); const QLatin1String PasswordKey("Password"); const QLatin1String TimeoutKey("Timeout"); const QLatin1String InternalIdKey("InternalId"); const QString DefaultKeyFile = QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + QLatin1String("/.ssh/id_rsa"); const int DefaultSshPort(22); const int DefaultGdbServerPort(10000); const QString DefaultUserName(QLatin1String("developer")); const MaemoDeviceConfig::AuthType DefaultAuthType(MaemoDeviceConfig::Key); const int DefaultTimeout(30); const MaemoDeviceConfig::DeviceType DefaultDeviceType(MaemoDeviceConfig::Physical); }; class DevConfIdMatcher { public: DevConfIdMatcher(quint64 id) : m_id(id) {} bool operator()(const MaemoDeviceConfig &devConfig) { return devConfig.internalId == m_id; } private: const quint64 m_id; }; MaemoDeviceConfig::MaemoDeviceConfig(const QString &name) : name(name), type(DefaultDeviceType), sshPort(DefaultSshPort), gdbServerPort(DefaultGdbServerPort), uname(DefaultUserName), authentication(DefaultAuthType), keyFile(DefaultKeyFile), timeout(DefaultTimeout), internalId(MaemoDeviceConfigurations::instance().m_nextId++) { } MaemoDeviceConfig::MaemoDeviceConfig(const QSettings &settings, quint64 &nextId) : name(settings.value(NameKey).toString()), type(static_cast<DeviceType>(settings.value(TypeKey, DefaultDeviceType).toInt())), host(settings.value(HostKey).toString()), sshPort(settings.value(SshPortKey, DefaultSshPort).toInt()), gdbServerPort(settings.value(GdbServerPortKey, DefaultGdbServerPort).toInt()), uname(settings.value(UserNameKey, DefaultUserName).toString()), authentication(static_cast<AuthType>(settings.value(AuthKey, DefaultAuthType).toInt())), pwd(settings.value(PasswordKey).toString()), keyFile(settings.value(KeyFileKey, DefaultKeyFile).toString()), timeout(settings.value(TimeoutKey, DefaultTimeout).toInt()), internalId(settings.value(InternalIdKey, nextId).toInt()) { if (internalId == nextId) ++nextId; } MaemoDeviceConfig::MaemoDeviceConfig() : internalId(InvalidId) { } bool MaemoDeviceConfig::isValid() const { return internalId != InvalidId; } void MaemoDeviceConfig::save(QSettings &settings) const { settings.setValue(NameKey, name); settings.setValue(TypeKey, type); settings.setValue(HostKey, host); settings.setValue(SshPortKey, sshPort); settings.setValue(GdbServerPortKey, gdbServerPort); settings.setValue(UserNameKey, uname); settings.setValue(AuthKey, authentication); settings.setValue(PasswordKey, pwd); settings.setValue(KeyFileKey, keyFile); settings.setValue(TimeoutKey, timeout); settings.setValue(InternalIdKey, internalId); } void MaemoDeviceConfigurations::setDevConfigs(const QList<MaemoDeviceConfig> &devConfigs) { m_devConfigs = devConfigs; save(); emit updated(); } MaemoDeviceConfigurations &MaemoDeviceConfigurations::instance(QObject *parent) { if (m_instance == 0) m_instance = new MaemoDeviceConfigurations(parent); return *m_instance; } void MaemoDeviceConfigurations::save() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(SettingsGroup); settings->setValue(IdCounterKey, m_nextId); settings->beginWriteArray(ConfigListKey, m_devConfigs.count()); for (int i = 0; i < m_devConfigs.count(); ++i) { settings->setArrayIndex(i); m_devConfigs.at(i).save(*settings); } settings->endArray(); settings->endGroup(); } MaemoDeviceConfigurations::MaemoDeviceConfigurations(QObject *parent) : QObject(parent) { load(); } void MaemoDeviceConfigurations::load() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(SettingsGroup); m_nextId = settings->value(IdCounterKey, 1).toULongLong(); int count = settings->beginReadArray(ConfigListKey); for (int i = 0; i < count; ++i) { settings->setArrayIndex(i); m_devConfigs.append(MaemoDeviceConfig(*settings, m_nextId)); } settings->endArray(); settings->endGroup(); } MaemoDeviceConfig MaemoDeviceConfigurations::find(const QString &name) const { QList<MaemoDeviceConfig>::ConstIterator resultIt = std::find_if(m_devConfigs.constBegin(), m_devConfigs.constEnd(), DevConfNameMatcher(name)); return resultIt == m_devConfigs.constEnd() ? MaemoDeviceConfig() : *resultIt; } MaemoDeviceConfig MaemoDeviceConfigurations::find(int id) const { QList<MaemoDeviceConfig>::ConstIterator resultIt = std::find_if(m_devConfigs.constBegin(), m_devConfigs.constEnd(), DevConfIdMatcher(id)); return resultIt == m_devConfigs.constEnd() ? MaemoDeviceConfig() : *resultIt; } MaemoDeviceConfigurations *MaemoDeviceConfigurations::m_instance = 0; } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>fix maemo build with QT_USE_FAST_CONCATENATION<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemodeviceconfigurations.h" #include <coreplugin/icore.h> #include <QtCore/QSettings> #include <QtCore/QStringBuilder> #include <QtGui/QDesktopServices> #include <algorithm> namespace Qt4ProjectManager { namespace Internal { QString homeDirOnDevice(const QString &uname) { const QString &dir = uname == QLatin1String("root") ? QString::fromLatin1("/root") : QLatin1String("/home/") + uname; qDebug("%s: user name %s is mapped to home dir %s", Q_FUNC_INFO, qPrintable(uname), qPrintable(dir)); return dir; } namespace { const QLatin1String SettingsGroup("MaemoDeviceConfigs"); const QLatin1String IdCounterKey("IdCounter"); const QLatin1String ConfigListKey("ConfigList"); const QLatin1String NameKey("Name"); const QLatin1String TypeKey("Type"); const QLatin1String HostKey("Host"); const QLatin1String SshPortKey("SshPort"); const QLatin1String GdbServerPortKey("GdbServerPort"); const QLatin1String UserNameKey("Uname"); const QLatin1String AuthKey("Authentication"); const QLatin1String KeyFileKey("KeyFile"); const QLatin1String PasswordKey("Password"); const QLatin1String TimeoutKey("Timeout"); const QLatin1String InternalIdKey("InternalId"); const QString DefaultKeyFile = QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + QLatin1String("/.ssh/id_rsa"); const int DefaultSshPort(22); const int DefaultGdbServerPort(10000); const QString DefaultUserName(QLatin1String("developer")); const MaemoDeviceConfig::AuthType DefaultAuthType(MaemoDeviceConfig::Key); const int DefaultTimeout(30); const MaemoDeviceConfig::DeviceType DefaultDeviceType(MaemoDeviceConfig::Physical); }; class DevConfIdMatcher { public: DevConfIdMatcher(quint64 id) : m_id(id) {} bool operator()(const MaemoDeviceConfig &devConfig) { return devConfig.internalId == m_id; } private: const quint64 m_id; }; MaemoDeviceConfig::MaemoDeviceConfig(const QString &name) : name(name), type(DefaultDeviceType), sshPort(DefaultSshPort), gdbServerPort(DefaultGdbServerPort), uname(DefaultUserName), authentication(DefaultAuthType), keyFile(DefaultKeyFile), timeout(DefaultTimeout), internalId(MaemoDeviceConfigurations::instance().m_nextId++) { } MaemoDeviceConfig::MaemoDeviceConfig(const QSettings &settings, quint64 &nextId) : name(settings.value(NameKey).toString()), type(static_cast<DeviceType>(settings.value(TypeKey, DefaultDeviceType).toInt())), host(settings.value(HostKey).toString()), sshPort(settings.value(SshPortKey, DefaultSshPort).toInt()), gdbServerPort(settings.value(GdbServerPortKey, DefaultGdbServerPort).toInt()), uname(settings.value(UserNameKey, DefaultUserName).toString()), authentication(static_cast<AuthType>(settings.value(AuthKey, DefaultAuthType).toInt())), pwd(settings.value(PasswordKey).toString()), keyFile(settings.value(KeyFileKey, DefaultKeyFile).toString()), timeout(settings.value(TimeoutKey, DefaultTimeout).toInt()), internalId(settings.value(InternalIdKey, nextId).toInt()) { if (internalId == nextId) ++nextId; } MaemoDeviceConfig::MaemoDeviceConfig() : internalId(InvalidId) { } bool MaemoDeviceConfig::isValid() const { return internalId != InvalidId; } void MaemoDeviceConfig::save(QSettings &settings) const { settings.setValue(NameKey, name); settings.setValue(TypeKey, type); settings.setValue(HostKey, host); settings.setValue(SshPortKey, sshPort); settings.setValue(GdbServerPortKey, gdbServerPort); settings.setValue(UserNameKey, uname); settings.setValue(AuthKey, authentication); settings.setValue(PasswordKey, pwd); settings.setValue(KeyFileKey, keyFile); settings.setValue(TimeoutKey, timeout); settings.setValue(InternalIdKey, internalId); } void MaemoDeviceConfigurations::setDevConfigs(const QList<MaemoDeviceConfig> &devConfigs) { m_devConfigs = devConfigs; save(); emit updated(); } MaemoDeviceConfigurations &MaemoDeviceConfigurations::instance(QObject *parent) { if (m_instance == 0) m_instance = new MaemoDeviceConfigurations(parent); return *m_instance; } void MaemoDeviceConfigurations::save() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(SettingsGroup); settings->setValue(IdCounterKey, m_nextId); settings->beginWriteArray(ConfigListKey, m_devConfigs.count()); for (int i = 0; i < m_devConfigs.count(); ++i) { settings->setArrayIndex(i); m_devConfigs.at(i).save(*settings); } settings->endArray(); settings->endGroup(); } MaemoDeviceConfigurations::MaemoDeviceConfigurations(QObject *parent) : QObject(parent) { load(); } void MaemoDeviceConfigurations::load() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup(SettingsGroup); m_nextId = settings->value(IdCounterKey, 1).toULongLong(); int count = settings->beginReadArray(ConfigListKey); for (int i = 0; i < count; ++i) { settings->setArrayIndex(i); m_devConfigs.append(MaemoDeviceConfig(*settings, m_nextId)); } settings->endArray(); settings->endGroup(); } MaemoDeviceConfig MaemoDeviceConfigurations::find(const QString &name) const { QList<MaemoDeviceConfig>::ConstIterator resultIt = std::find_if(m_devConfigs.constBegin(), m_devConfigs.constEnd(), DevConfNameMatcher(name)); return resultIt == m_devConfigs.constEnd() ? MaemoDeviceConfig() : *resultIt; } MaemoDeviceConfig MaemoDeviceConfigurations::find(int id) const { QList<MaemoDeviceConfig>::ConstIterator resultIt = std::find_if(m_devConfigs.constBegin(), m_devConfigs.constEnd(), DevConfIdMatcher(id)); return resultIt == m_devConfigs.constEnd() ? MaemoDeviceConfig() : *resultIt; } MaemoDeviceConfigurations *MaemoDeviceConfigurations::m_instance = 0; } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>// Copyright 2013 Yangqing Jia #ifndef CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ #define CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ #include <glog/logging.h> #include <gtest/gtest.h> #include <algorithm> #include <cmath> #include <vector> #include "caffe/layer.hpp" #include "caffe/net.hpp" using std::max; namespace caffe { // The gradient checker adds a L2 normalization loss function on top of the // top blobs, and checks the gradient. template <typename Dtype> class GradientChecker { public: GradientChecker(const Dtype stepsize, const Dtype threshold, const unsigned int seed = 1701, const Dtype kink = 0., const Dtype kink_range = -1) : stepsize_(stepsize), threshold_(threshold), seed_(seed), kink_(kink), kink_range_(kink_range) {} // Checks the gradient of a layer, with provided bottom layers and top // layers. // Note that after the gradient check, we do not guarantee that the data // stored in the layer parameters and the blobs are unchanged. void CheckGradient(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom = -1) { layer->SetUp(*bottom, top); CheckGradientSingle(layer, bottom, top, check_bottom, -1, -1); } void CheckGradientExhaustive(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom = -1); void CheckGradientSingle(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom, int top_id, int top_data_id); // Checks the gradient of a network. This network should not have any data // layers or loss layers, since the function does not explicitly deal with // such cases yet. All input blobs and parameter blobs are going to be // checked, layer-by-layer to avoid numerical problems to accumulate. void CheckGradientNet(const Net<Dtype>& net, const vector<Blob<Dtype>*>& input); protected: Dtype GetObjAndGradient(vector<Blob<Dtype>*>* top, int top_id = -1, int top_data_id = -1); Dtype stepsize_; Dtype threshold_; unsigned int seed_; Dtype kink_; Dtype kink_range_; }; // Detailed implementations are as follows. template <typename Dtype> void GradientChecker<Dtype>::CheckGradientSingle(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom, int top_id, int top_data_id) { // First, figure out what blobs we need to check against. vector<Blob<Dtype>*> blobs_to_check; for (int i = 0; i < layer->blobs().size(); ++i) { blobs_to_check.push_back(layer->blobs()[i].get()); } if (check_bottom < 0) { for (int i = 0; i < bottom->size(); ++i) { blobs_to_check.push_back((*bottom)[i]); } } else { CHECK(check_bottom < bottom->size()); blobs_to_check.push_back((*bottom)[check_bottom]); } // go through the bottom and parameter blobs // LOG(ERROR) << "Checking " << blobs_to_check.size() << " blobs."; for (int blob_id = 0; blob_id < blobs_to_check.size(); ++blob_id) { Blob<Dtype>* current_blob = blobs_to_check[blob_id]; // LOG(ERROR) << "Blob " << blob_id << ": checking " // << current_blob->count() << " parameters."; // go through the values for (int feat_id = 0; feat_id < current_blob->count(); ++feat_id) { // First, obtain the original data Caffe::set_random_seed(seed_); // Get any loss from the layer Dtype computed_objective = layer->Forward(*bottom, top); // Get additional loss from the objective computed_objective += GetObjAndGradient(top, top_id, top_data_id); layer->Backward(*top, true, bottom); Dtype computed_gradient = current_blob->cpu_diff()[feat_id]; // compute score by adding stepsize current_blob->mutable_cpu_data()[feat_id] += stepsize_; Caffe::set_random_seed(seed_); Dtype positive_objective = layer->Forward(*bottom, top); positive_objective += GetObjAndGradient(top, top_id, top_data_id); layer->Backward(*top, true, bottom); // compute score by subtracting stepsize current_blob->mutable_cpu_data()[feat_id] -= stepsize_ * 2; Caffe::set_random_seed(seed_); Dtype negative_objective = layer->Forward(*bottom, top); negative_objective += GetObjAndGradient(top, top_id, top_data_id); layer->Backward(*top, true, bottom); // Recover stepsize current_blob->mutable_cpu_data()[feat_id] += stepsize_; Dtype estimated_gradient = (positive_objective - negative_objective) / stepsize_ / 2.; Dtype feature = current_blob->cpu_data()[feat_id]; // LOG(ERROR) << "debug: " << current_blob->cpu_data()[feat_id] << " " // << current_blob->cpu_diff()[feat_id]; if (kink_ - kink_range_ > feature || feature > kink_ + kink_range_) { // We check relative accuracy, but for too small values, we threshold // the scale factor by 1. Dtype scale = max( max(fabs(computed_gradient), fabs(estimated_gradient)), 1.); EXPECT_NEAR(computed_gradient, estimated_gradient, threshold_ * scale) << "debug: (top_id, top_data_id, blob_id, feat_id)=" << top_id << "," << top_data_id << "," << blob_id << "," << feat_id; } // LOG(ERROR) << "Feature: " << current_blob->cpu_data()[feat_id]; // LOG(ERROR) << "computed gradient: " << computed_gradient // << " estimated_gradient: " << estimated_gradient; } } } template <typename Dtype> void GradientChecker<Dtype>::CheckGradientExhaustive(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom) { layer->SetUp(*bottom, top); // LOG(ERROR) << "Exhaustive Mode."; for (int i = 0; i < top->size(); ++i) { // LOG(ERROR) << "Exhaustive: blob " << i << " size " << top[i]->count(); for (int j = 0; j < (*top)[i]->count(); ++j) { // LOG(ERROR) << "Exhaustive: blob " << i << " data " << j; CheckGradientSingle(layer, bottom, top, check_bottom, i, j); } } } template <typename Dtype> void GradientChecker<Dtype>::CheckGradientNet( const Net<Dtype>& net, const vector<Blob<Dtype>*>& input) { const vector<shared_ptr<Layer<Dtype> > >& layers = net.layers(); vector<vector<Blob<Dtype>*> >& bottom_vecs = net.bottom_vecs(); vector<vector<Blob<Dtype>*> >& top_vecs = net.top_vecs(); for (int i = 0; i < layers.size(); ++i) { net.Forward(input); LOG(ERROR) << "Checking gradient for " << layers[i]->layer_param().name(); CheckGradientExhaustive(*(layers[i].get()), bottom_vecs[i], top_vecs[i]); } } template <typename Dtype> Dtype GradientChecker<Dtype>::GetObjAndGradient(vector<Blob<Dtype>*>* top, int top_id, int top_data_id) { Dtype loss = 0; if (top_id < 0) { // the loss will be half of the sum of squares of all outputs for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* top_blob = (*top)[i]; const Dtype* top_blob_data = top_blob->cpu_data(); Dtype* top_blob_diff = top_blob->mutable_cpu_diff(); int count = top_blob->count(); for (int j = 0; j < count; ++j) { loss += top_blob_data[j] * top_blob_data[j]; } // set the diff: simply the data. memcpy(top_blob_diff, top_blob_data, sizeof(Dtype) * top_blob->count()); } loss /= 2.; } else { // the loss will be the top_data_id-th element in the top_id-th blob. for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* top_blob = (*top)[i]; Dtype* top_blob_diff = top_blob->mutable_cpu_diff(); memset(top_blob_diff, 0, sizeof(Dtype) * top_blob->count()); } loss = (*top)[top_id]->cpu_data()[top_data_id]; (*top)[top_id]->mutable_cpu_diff()[top_data_id] = 1.; } return loss; } } // namespace caffe #endif // CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ <commit_msg>gradient checker optimization with forward pass loss: only need to run backward pass to compute analytic gradient (the thing being checked) now<commit_after>// Copyright 2013 Yangqing Jia #ifndef CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ #define CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ #include <glog/logging.h> #include <gtest/gtest.h> #include <algorithm> #include <cmath> #include <vector> #include "caffe/layer.hpp" #include "caffe/net.hpp" using std::max; namespace caffe { // The gradient checker adds a L2 normalization loss function on top of the // top blobs, and checks the gradient. template <typename Dtype> class GradientChecker { public: GradientChecker(const Dtype stepsize, const Dtype threshold, const unsigned int seed = 1701, const Dtype kink = 0., const Dtype kink_range = -1) : stepsize_(stepsize), threshold_(threshold), seed_(seed), kink_(kink), kink_range_(kink_range) {} // Checks the gradient of a layer, with provided bottom layers and top // layers. // Note that after the gradient check, we do not guarantee that the data // stored in the layer parameters and the blobs are unchanged. void CheckGradient(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom = -1) { layer->SetUp(*bottom, top); CheckGradientSingle(layer, bottom, top, check_bottom, -1, -1); } void CheckGradientExhaustive(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom = -1); void CheckGradientSingle(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom, int top_id, int top_data_id); // Checks the gradient of a network. This network should not have any data // layers or loss layers, since the function does not explicitly deal with // such cases yet. All input blobs and parameter blobs are going to be // checked, layer-by-layer to avoid numerical problems to accumulate. void CheckGradientNet(const Net<Dtype>& net, const vector<Blob<Dtype>*>& input); protected: Dtype GetObjAndGradient(vector<Blob<Dtype>*>* top, int top_id = -1, int top_data_id = -1); Dtype stepsize_; Dtype threshold_; unsigned int seed_; Dtype kink_; Dtype kink_range_; }; // Detailed implementations are as follows. template <typename Dtype> void GradientChecker<Dtype>::CheckGradientSingle(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom, int top_id, int top_data_id) { // First, figure out what blobs we need to check against. vector<Blob<Dtype>*> blobs_to_check; for (int i = 0; i < layer->blobs().size(); ++i) { blobs_to_check.push_back(layer->blobs()[i].get()); } if (check_bottom < 0) { for (int i = 0; i < bottom->size(); ++i) { blobs_to_check.push_back((*bottom)[i]); } } else { CHECK(check_bottom < bottom->size()); blobs_to_check.push_back((*bottom)[check_bottom]); } // go through the bottom and parameter blobs // LOG(ERROR) << "Checking " << blobs_to_check.size() << " blobs."; for (int blob_id = 0; blob_id < blobs_to_check.size(); ++blob_id) { Blob<Dtype>* current_blob = blobs_to_check[blob_id]; // LOG(ERROR) << "Blob " << blob_id << ": checking " // << current_blob->count() << " parameters."; // go through the values for (int feat_id = 0; feat_id < current_blob->count(); ++feat_id) { // First, obtain the original data Caffe::set_random_seed(seed_); // Get any loss from the layer Dtype computed_objective = layer->Forward(*bottom, top); // Get additional loss from the objective computed_objective += GetObjAndGradient(top, top_id, top_data_id); layer->Backward(*top, true, bottom); Dtype computed_gradient = current_blob->cpu_diff()[feat_id]; // compute score by adding stepsize current_blob->mutable_cpu_data()[feat_id] += stepsize_; Caffe::set_random_seed(seed_); Dtype positive_objective = layer->Forward(*bottom, top); positive_objective += GetObjAndGradient(top, top_id, top_data_id); // compute score by subtracting stepsize current_blob->mutable_cpu_data()[feat_id] -= stepsize_ * 2; Caffe::set_random_seed(seed_); Dtype negative_objective = layer->Forward(*bottom, top); negative_objective += GetObjAndGradient(top, top_id, top_data_id); // Recover stepsize current_blob->mutable_cpu_data()[feat_id] += stepsize_; Dtype estimated_gradient = (positive_objective - negative_objective) / stepsize_ / 2.; Dtype feature = current_blob->cpu_data()[feat_id]; // LOG(ERROR) << "debug: " << current_blob->cpu_data()[feat_id] << " " // << current_blob->cpu_diff()[feat_id]; if (kink_ - kink_range_ > feature || feature > kink_ + kink_range_) { // We check relative accuracy, but for too small values, we threshold // the scale factor by 1. Dtype scale = max( max(fabs(computed_gradient), fabs(estimated_gradient)), 1.); EXPECT_NEAR(computed_gradient, estimated_gradient, threshold_ * scale) << "debug: (top_id, top_data_id, blob_id, feat_id)=" << top_id << "," << top_data_id << "," << blob_id << "," << feat_id; } // LOG(ERROR) << "Feature: " << current_blob->cpu_data()[feat_id]; // LOG(ERROR) << "computed gradient: " << computed_gradient // << " estimated_gradient: " << estimated_gradient; } } } template <typename Dtype> void GradientChecker<Dtype>::CheckGradientExhaustive(Layer<Dtype>* layer, vector<Blob<Dtype>*>* bottom, vector<Blob<Dtype>*>* top, int check_bottom) { layer->SetUp(*bottom, top); // LOG(ERROR) << "Exhaustive Mode."; for (int i = 0; i < top->size(); ++i) { // LOG(ERROR) << "Exhaustive: blob " << i << " size " << top[i]->count(); for (int j = 0; j < (*top)[i]->count(); ++j) { // LOG(ERROR) << "Exhaustive: blob " << i << " data " << j; CheckGradientSingle(layer, bottom, top, check_bottom, i, j); } } } template <typename Dtype> void GradientChecker<Dtype>::CheckGradientNet( const Net<Dtype>& net, const vector<Blob<Dtype>*>& input) { const vector<shared_ptr<Layer<Dtype> > >& layers = net.layers(); vector<vector<Blob<Dtype>*> >& bottom_vecs = net.bottom_vecs(); vector<vector<Blob<Dtype>*> >& top_vecs = net.top_vecs(); for (int i = 0; i < layers.size(); ++i) { net.Forward(input); LOG(ERROR) << "Checking gradient for " << layers[i]->layer_param().name(); CheckGradientExhaustive(*(layers[i].get()), bottom_vecs[i], top_vecs[i]); } } template <typename Dtype> Dtype GradientChecker<Dtype>::GetObjAndGradient(vector<Blob<Dtype>*>* top, int top_id, int top_data_id) { Dtype loss = 0; if (top_id < 0) { // the loss will be half of the sum of squares of all outputs for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* top_blob = (*top)[i]; const Dtype* top_blob_data = top_blob->cpu_data(); Dtype* top_blob_diff = top_blob->mutable_cpu_diff(); int count = top_blob->count(); for (int j = 0; j < count; ++j) { loss += top_blob_data[j] * top_blob_data[j]; } // set the diff: simply the data. memcpy(top_blob_diff, top_blob_data, sizeof(Dtype) * top_blob->count()); } loss /= 2.; } else { // the loss will be the top_data_id-th element in the top_id-th blob. for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* top_blob = (*top)[i]; Dtype* top_blob_diff = top_blob->mutable_cpu_diff(); memset(top_blob_diff, 0, sizeof(Dtype) * top_blob->count()); } loss = (*top)[top_id]->cpu_data()[top_data_id]; (*top)[top_id]->mutable_cpu_diff()[top_data_id] = 1.; } return loss; } } // namespace caffe #endif // CAFFE_TEST_GRADIENT_CHECK_UTIL_H_ <|endoftext|>
<commit_before>// // Copyright (c) 2012, Andre Gaschler // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <iostream> #include <memory> #include <stdexcept> #include <random> #include <rl/kin/Kinematics.h> #include <rl/kin/Puma.h> #include <rl/math/Unit.h> int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: rlInverseKinematicsTest KINEMATICSFILE" << std::endl; return EXIT_FAILURE; } try { std::mt19937 randomGenerator(0); std::uniform_real_distribution<rl::math::Real> randomDistribution(-180 * rl::math::DEG2RAD, 180 * rl::math::DEG2RAD); std::shared_ptr<rl::kin::Kinematics> kinematics(rl::kin::Kinematics::create(argv[1])); std::size_t nTests; rl::math::Vector q(6); rl::math::Vector qinv(6); rl::math::Vector qzero(6); std::size_t n; std::size_t wrongs; std::size_t wrongT; std::size_t ngotinverse; for (std::size_t ispuma = 0; ispuma < 2; ++ispuma) { nTests = 0 == ispuma ? 1000 : 100; for (n = 0, wrongs = 0, wrongT = 0, ngotinverse = 0; n < nTests && wrongT < 100 && wrongs < 100; ++n) { for (std::size_t i = 0; i < 6; ++i) { q(i) = randomDistribution(randomGenerator); qzero(i) = 0; } kinematics->setPosition(q); kinematics->updateFrames(); rl::math::Transform t = kinematics->forwardPosition(); // For iterative inverse, set starting point far away kinematics->setPosition(qzero); kinematics->updateFrames(); if (0 == ispuma) { rl::kin::Puma::Arm arm; rl::kin::Puma::Elbow elbow; rl::kin::Puma::Wrist wrist; dynamic_cast<rl::kin::Puma*>(kinematics.get())->parameters(q, arm, elbow, wrist); dynamic_cast<rl::kin::Puma*>(kinematics.get())->setArm(arm); dynamic_cast<rl::kin::Puma*>(kinematics.get())->setElbow(elbow); dynamic_cast<rl::kin::Puma*>(kinematics.get())->setWrist(wrist); } if ( 0 == ispuma ? dynamic_cast< ::rl::kin::Puma*>(kinematics.get())->inversePosition(t, qinv) : dynamic_cast< ::rl::kin::Kinematics*>(kinematics.get())->inversePosition(t, qinv, 0, 100) ) { kinematics->setPosition(qinv); kinematics->updateFrames(); rl::math::Transform tinv = kinematics->forwardPosition(); if ((t.matrix() - tinv.matrix()).norm() > 1e-6) { ++wrongT; } if ((q - qinv).norm() > 1e-4) { ++wrongs; } if (true) //wrongT < 3 && (t.matrix() - tinv.matrix()).norm() > 1e-6) { std::cout << " q = " << q.transpose() << std::endl; std::cout << " T = " << t.matrix() << std::endl; std::cout << " qinv = " << qinv.transpose() << std::endl; std::cout << " Tinv = " << tinv.matrix() << std::endl; std::cout << std::endl; } ++ngotinverse; } } std::cout << "Notice: " << (0 == ispuma ? "Puma direct " : "Iterative ") << "inverse kinematics " << "on file " << argv[1] << " " << "tested with " << n << " cases, " << ngotinverse << " returned a solution, " << "thereof " << wrongs << " in wrong configuration, and " << wrongT << " with completely wrong pose." << std::endl; if (wrongT > 0) { std::cerr << "Error: " << (0 == ispuma ? "Puma direct " : "Iterative ") << "inverse kinematics " << "on file " << argv[1] << " gave incorrect poses." << std::endl; return EXIT_FAILURE; } if (0 == ngotinverse) { std::cerr << "Error: " << (0 == ispuma ? "Puma direct " : "Iterative ") << "inverse kinematics "<< "on file " << argv[1] << " gave no solutions." << std::endl; return EXIT_FAILURE; } } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Update rlInverseKinematicsKinTest<commit_after>// // Copyright (c) 2012, Andre Gaschler // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <iostream> #include <memory> #include <stdexcept> #include <rl/kin/Kinematics.h> #include <rl/kin/Puma.h> int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: rlInverseKinematicsTest KINEMATICSFILE" << std::endl; return EXIT_FAILURE; } try { std::string filename = argv[1]; std::shared_ptr<rl::kin::Kinematics> kinematics(rl::kin::Kinematics::create(filename)); kinematics->seed(0); for (std::size_t n = 0; n < 100; ++n) { rl::math::Vector q1 = kinematics->generatePositionUniform(); kinematics->setPosition(q1); kinematics->updateFrames(); rl::math::Transform t1 = kinematics->forwardPosition(); rl::math::Vector q2 = kinematics->generatePositionUniform(); kinematics->setPosition(q2); rl::math::Vector q3(kinematics->getDof()); bool solved = kinematics->inversePosition( t1, q3, 0, std::numeric_limits< ::rl::math::Real>::infinity(), static_cast<rl::math::Real>(1.0e-3), 1000, std::chrono::seconds(10) ); if (!solved) { std::cerr << "rl::kin::Kinematics::inversePosition on file " << filename << " with no solution." << std::endl; std::cerr << "t1 = " << std::endl << t1.matrix() << std::endl; std::cerr << "q1 = " << q1.transpose() << std::endl; std::cerr << "q2 = " << q2.transpose() << std::endl; return EXIT_FAILURE; } kinematics->setPosition(q3); kinematics->updateFrames(); rl::math::Transform t3 = kinematics->forwardPosition(); if (!t3.isApprox(t1, static_cast<rl::math::Real>(1.03-6))) { std::cerr << "rl::kin::Kinematics::inversePosition on file " << filename << " with incorrect operational position." << std::endl; std::cerr << "norm(t1 - t3) = " << (t1.matrix() - t3.matrix()).norm() << std::endl; std::cerr << "t1 = " << std::endl << t1.matrix() << std::endl; std::cerr << "t3 = " << std::endl << t3.matrix() << std::endl; std::cerr << "q1 = " << q1.transpose() << std::endl; std::cerr << "q2 = " << q2.transpose() << std::endl; std::cerr << "q3 = " << q3.transpose() << std::endl; return EXIT_FAILURE; } if (rl::kin::Puma* puma = dynamic_cast<rl::kin::Puma*>(kinematics.get())) { rl::kin::Puma::Arm arm; rl::kin::Puma::Elbow elbow; rl::kin::Puma::Wrist wrist; puma->parameters(q1, arm, elbow, wrist); puma->setArm(arm); puma->setElbow(elbow); puma->setWrist(wrist); rl::math::Vector q4(puma->getDof()); if (!puma->inversePosition(t1, q4, true)) { std::cerr << "rl::kin::Puma::inversePosition on file " << filename << " with no solution." << std::endl; std::cerr << "t1 = " << std::endl << t1.matrix() << std::endl; std::cerr << "q1 = " << q1.transpose() << std::endl; return EXIT_FAILURE; } puma->setPosition(q4); puma->updateFrames(); rl::math::Transform t4 = puma->forwardPosition(); if (!t4.isApprox(t1, static_cast<rl::math::Real>(1.03-6))) { std::cerr << "rl::kin::Puma::inversePosition on file " << filename << " with incorrect operational position." << std::endl; std::cerr << "norm(t1 - t4) = " << (t1.matrix() - t4.matrix()).norm() << std::endl; std::cerr << "t1 = " << std::endl << t1.matrix() << std::endl; std::cerr << "t4 = " << std::endl << t4.matrix() << std::endl; std::cerr << "q1 = " << q1.transpose() << std::endl; std::cerr << "q4 = " << q4.transpose() << std::endl; return EXIT_FAILURE; } } } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkVectorInverseFFTImageFilter_hxx #define itkVectorInverseFFTImageFilter_hxx #include "itkVectorInverseFFTImageFilter.h" #include <itkVectorIndexSelectionCastImageFilter.h> #include <itkComposeImageFilter.h> #include <itkProgressAccumulator.h> template< typename TInputImage, typename TOutputImage > void itk::VectorInverseFFTImageFilter< TInputImage, TOutputImage > ::GenerateData() { // Create a process accumulator for tracking the progress of this minipipeline auto progress = ProgressAccumulator::New(); progress->SetMiniPipelineFilter(this); typename OutputImageType::Pointer outputPtr = this->GetOutput(); this->AllocateOutputs(); using InputSingleImageType = itk::Image< typename InputImageType::PixelType::ComponentType, ImageDimension >; using VectorCastFilterType = itk::VectorIndexSelectionCastImageFilter< InputImageType, InputSingleImageType >; using FFTInverseFilterType = itk::InverseFFTImageFilter< InputSingleImageType >; using OutputSingleImageType = typename FFTInverseFilterType::OutputImageType; using ComposeFilterType = itk::ComposeImageFilter< OutputSingleImageType, OutputImageType >; auto vectorCastFilter = VectorCastFilterType::New(); vectorCastFilter->SetInput(this->GetInput()); progress->RegisterInternalFilter(vectorCastFilter, 1.0 / this->GetInput()->GetNumberOfComponentsPerPixel()); auto fftInverseFilter = FFTInverseFilterType::New(); auto composeFilter = ComposeFilterType::New(); std::vector< typename OutputSingleImageType::Pointer > inverseFFToutputs; for ( unsigned int c = 0; c < this->GetInput()->GetNumberOfComponentsPerPixel(); c++ ) { vectorCastFilter->SetIndex(c); vectorCastFilter->Update(); fftInverseFilter->SetInput(vectorCastFilter->GetOutput()); fftInverseFilter->Update(); inverseFFToutputs.push_back(fftInverseFilter->GetOutput()); inverseFFToutputs.back()->DisconnectPipeline(); composeFilter->SetInput(c, inverseFFToutputs.back()); } composeFilter->GraftOutput(outputPtr); composeFilter->Update(); this->GraftOutput(composeFilter->GetOutput()); } template< typename TInputImage, typename TOutputImage > void itk::VectorInverseFFTImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } #endif <commit_msg>STYLE: Use namespace itk in itkVectorInverseFFTImageFilter.hxx<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkVectorInverseFFTImageFilter_hxx #define itkVectorInverseFFTImageFilter_hxx #include "itkVectorInverseFFTImageFilter.h" #include <itkVectorIndexSelectionCastImageFilter.h> #include <itkComposeImageFilter.h> #include <itkProgressAccumulator.h> namespace itk { template< typename TInputImage, typename TOutputImage > void VectorInverseFFTImageFilter< TInputImage, TOutputImage > ::GenerateData() { // Create a process accumulator for tracking the progress of this minipipeline auto progress = ProgressAccumulator::New(); progress->SetMiniPipelineFilter(this); typename OutputImageType::Pointer outputPtr = this->GetOutput(); this->AllocateOutputs(); using InputSingleImageType = Image< typename InputImageType::PixelType::ComponentType, ImageDimension >; using VectorCastFilterType = VectorIndexSelectionCastImageFilter< InputImageType, InputSingleImageType >; using FFTInverseFilterType = InverseFFTImageFilter< InputSingleImageType >; using OutputSingleImageType = typename FFTInverseFilterType::OutputImageType; using ComposeFilterType = ComposeImageFilter< OutputSingleImageType, OutputImageType >; auto vectorCastFilter = VectorCastFilterType::New(); vectorCastFilter->SetInput(this->GetInput()); progress->RegisterInternalFilter(vectorCastFilter, 1.0 / this->GetInput()->GetNumberOfComponentsPerPixel()); auto fftInverseFilter = FFTInverseFilterType::New(); auto composeFilter = ComposeFilterType::New(); std::vector< typename OutputSingleImageType::Pointer > inverseFFToutputs; for ( unsigned int c = 0; c < this->GetInput()->GetNumberOfComponentsPerPixel(); c++ ) { vectorCastFilter->SetIndex(c); vectorCastFilter->Update(); fftInverseFilter->SetInput(vectorCastFilter->GetOutput()); fftInverseFilter->Update(); inverseFFToutputs.push_back(fftInverseFilter->GetOutput()); inverseFFToutputs.back()->DisconnectPipeline(); composeFilter->SetInput(c, inverseFFToutputs.back()); } composeFilter->GraftOutput(outputPtr); composeFilter->Update(); this->GraftOutput(composeFilter->GetOutput()); } template< typename TInputImage, typename TOutputImage > void VectorInverseFFTImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace itk #endif <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP #include "traits.hpp" #include "utils.hpp" namespace kgr { namespace detail { /* * This defines the pointer to a forward function. * This is simply a shortcut for not writing the function pointer type everywhere. */ template<typename T> using forward_ptr = service_type<T>(*)(void*); template<typename T> struct forward_storage { forward_ptr<T> forward; }; template<typename T> struct typed_service_storage { void* service; forward_ptr<T> forward; }; template<typename T> struct constant_typed_service_storage { void const* service; forward_ptr<T> forward; }; struct service_storage { private: using function_pointer = void*(*)(void*); public: template<typename T> service_storage(const typed_service_storage<T>& storage) noexcept : _service{storage.service} { static_assert(sizeof(function_pointer) >= sizeof(forward_storage<T>), "The forward storage size exceed the size of a function pointer"); static_assert(alignof(function_pointer) >= alignof(forward_storage<T>), "The forward storage alignement exceed the alignement of a function pointer"); new (&forward_function) forward_storage<T>{storage.forward}; } template<typename T> auto service() noexcept -> T& { return *static_cast<T*>(_service); } template<typename T> auto service() const noexcept -> T const& { return *static_cast<T const*>(_service); } template<typename T> auto cast() const noexcept -> constant_typed_service_storage<T> { return constant_typed_service_storage<T>{_service, reinterpret_cast<const forward_storage<T>*>(&forward_function)->forward}; } template<typename T> auto cast() noexcept -> typed_service_storage<T> { return typed_service_storage<T>{_service, reinterpret_cast<const forward_storage<T>*>(&forward_function)->forward}; } private: void* _service; aligned_storage_t<sizeof(function_pointer), alignof(function_pointer)> forward_function; }; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP <commit_msg>Removed unused constant service storage<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP #include "traits.hpp" #include "utils.hpp" namespace kgr { namespace detail { /* * This defines the pointer to a forward function. * This is simply a shortcut for not writing the function pointer type everywhere. */ template<typename T> using forward_ptr = service_type<T>(*)(void*); template<typename T> struct forward_storage { forward_ptr<T> forward; }; template<typename T> struct typed_service_storage { void* service; forward_ptr<T> forward; }; struct service_storage { private: using function_pointer = void*(*)(void*); public: template<typename T> service_storage(const typed_service_storage<T>& storage) noexcept : _service{storage.service} { static_assert(sizeof(function_pointer) >= sizeof(forward_storage<T>), "The forward storage size exceed the size of a function pointer"); static_assert(alignof(function_pointer) >= alignof(forward_storage<T>), "The forward storage alignement exceed the alignement of a function pointer"); new (&forward_function) forward_storage<T>{storage.forward}; } template<typename T> auto service() noexcept -> T& { return *static_cast<T*>(_service); } template<typename T> auto service() const noexcept -> T const& { return *static_cast<T const*>(_service); } template<typename T> auto cast() noexcept -> typed_service_storage<T> { return typed_service_storage<T>{_service, reinterpret_cast<const forward_storage<T>*>(&forward_function)->forward}; } private: void* _service; aligned_storage_t<sizeof(function_pointer), alignof(function_pointer)> forward_function; }; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SERVICE_STORAGE_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // NOTE: This is an implementation header file and is only meant to be included // from implementation files. It therefore doesn't have an include guard. // mapnik #include <mapnik/expression_node.hpp> #include <mapnik/expression_grammar.hpp> #include <mapnik/unicode.hpp> #include <mapnik/value_types.hpp> #include <mapnik/function_call.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/fusion/adapted/struct.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_function.hpp> #pragma GCC diagnostic pop BOOST_FUSION_ADAPT_STRUCT(mapnik::unary_function_call, (mapnik::unary_function_impl, fun) (mapnik::unary_function_call::argument_type, arg)) BOOST_FUSION_ADAPT_STRUCT(mapnik::binary_function_call, (mapnik::binary_function_impl, fun) (mapnik::binary_function_call::argument_type, arg1) (mapnik::binary_function_call::argument_type, arg2)) // fwd declare namespace mapnik { struct attribute; struct geometry_type_attribute; } namespace mapnik { struct unicode_impl { using result_type = mapnik::value_unicode_string; explicit unicode_impl(mapnik::transcoder const& tr) : tr_(tr) {} mapnik::value_unicode_string operator()(std::string const& str) const { return tr_.transcode(str.c_str()); } mapnik::transcoder const& tr_; }; struct regex_match_impl { using result_type = expr_node; explicit regex_match_impl(mapnik::transcoder const& tr) : tr_(tr) {} template <typename T0,typename T1> expr_node operator() (T0 & node, T1 const& pattern) const; mapnik::transcoder const& tr_; }; struct regex_replace_impl { using result_type = expr_node; explicit regex_replace_impl(mapnik::transcoder const& tr) : tr_(tr) {} template <typename T0,typename T1,typename T2> expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const; mapnik::transcoder const& tr_; }; unary_function_types::unary_function_types() { add ("sin", sin_impl()) ("cos", cos_impl()) ("tan", tan_impl()) ("atan", atan_impl()) ("exp", exp_impl()) ("abs", abs_impl()) ("length",length_impl()) ; } binary_function_types::binary_function_types() { add ("min", binary_function_impl(min_impl)) ("max", binary_function_impl(max_impl)) ("pow", binary_function_impl(pow_impl)) ; } template <typename T0,typename T1> expr_node regex_match_impl::operator() (T0 & node, T1 const& pattern) const { return regex_match_node(tr_,node,pattern); } template <typename T0,typename T1,typename T2> expr_node regex_replace_impl::operator() (T0 & node, T1 const& pattern, T2 const& format) const { return regex_replace_node(tr_,node,pattern,format); } template <typename Iterator> expression_grammar<Iterator>::expression_grammar(std::string const& encoding) : expression_grammar::base_type(expr), tr_(encoding) { qi::_1_type _1; qi::_a_type _a; qi::_b_type _b; qi::_r1_type _r1; qi::no_skip_type no_skip; qi::_val_type _val; qi::lit_type lit; qi::double_type double_; qi::hex_type hex; qi::omit_type omit; qi::alpha_type alpha; qi::alnum_type alnum; standard_wide::char_type char_; standard_wide::no_case_type no_case; using boost::phoenix::construct; using boost::phoenix::if_else; boost::phoenix::function<unicode_impl> unicode = unicode_impl(tr_); boost::phoenix::function<regex_match_impl> regex_match = regex_match_impl(tr_); boost::phoenix::function<regex_replace_impl> regex_replace = regex_replace_impl(tr_); constant.add ("null", mapnik::value_null()) ("false", mapnik::value_bool(false)) ("true", mapnik::value_bool(true)) ("point", mapnik::value_integer(1)) ("linestring", mapnik::value_integer(2)) ("polygon", mapnik::value_integer(3)) ("collection", mapnik::value_integer(4)) ("pi", mapnik::value_double(3.1415926535897932384626433832795)) ("deg_to_rad", mapnik::value_double(0.017453292519943295769236907684886)) ("rad_to_deg", mapnik::value_double(57.295779513082320876798154814105)) ; expr = logical_expr [_val = _1] //| ustring [_val = unicode(_1)] ; logical_expr = not_expr [_val = _1] >> *( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] ) | (( lit("or") | lit("||")) >> not_expr [_val || _1]) ) ; not_expr = cond_expr [_val = _1 ] | ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ]) ; cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1] ; equality_expr = relational_expr [_val = _1] >> *( ( (lit("=") | lit("eq") | lit("is")) >> relational_expr [_val == _1]) | (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1]) ) ; regex_match_expr = lit(".match") >> lit('(') >> quoted_ustring [_val = _1] >> lit(')') ; regex_replace_expr = lit(".replace") >> lit('(') >> quoted_ustring [_a = _1] >> lit(',') >> quoted_ustring [_b = _1] >> lit(')') [_val = regex_replace(_r1,_a,_b)] ; relational_expr = additive_expr[_val = _1] >> *( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ]) | ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ]) | ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ]) | ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ]) ) ; additive_expr = multiplicative_expr [_val = _1] >> * ( '+' >> multiplicative_expr[_val += _1] | '-' >> multiplicative_expr[_val -= _1] ) ; multiplicative_expr = unary_expr [_val = _1] >> *( '*' >> unary_expr [_val *= _1] | '/' >> unary_expr [_val /= _1] | '%' >> unary_expr [_val %= construct<mapnik::expr_node>(_1)] //needed by clang++ with -std=c++11 | regex_match_expr[_val = regex_match(_val, _1)] | regex_replace_expr(_val) [_val = _1] ) ; unary_function_expr = unary_func_type >> '(' > logical_expr > ')' ; binary_function_expr = binary_func_type >> '(' > logical_expr > ',' > logical_expr > ')' ; unary_expr = primary_expr [_val = _1] | '+' >> primary_expr [_val = _1] | '-' >> primary_expr [_val = -_1] ; primary_expr = strict_double [_val = _1] | int__[_val = _1] | no_case[constant] [_val = _1] | quoted_ustring [_val = unicode(_1)] | attr [if_else(_1 == "mapnik::geometry_type", _val = construct<mapnik::geometry_type_attribute>(), _val = construct<mapnik::attribute>(_1))] | global_attr [_val = construct<mapnik::global_attribute>( _1 )] | unary_function_expr [_val = _1] | binary_function_expr [_val = _1] | '(' > logical_expr [_val = _1 ] > ')' // TODO: this is a backward compatibility hack to allow unquoted strings | unquoted_ustring [_val = unicode(_1)] // ^ https://github.com/mapnik/mapnik/pull/3389 ; unesc_char.add("\\a", '\a')("\\b", '\b')("\\f", '\f')("\\n", '\n') ("\\r", '\r')("\\t", '\t')("\\v", '\v')("\\\\", '\\') ("\\\'", '\'')("\\\"", '\"') ; ustring %= no_skip[alpha >> *alnum]; quote_char %= char_('\'') | char_('"'); quoted_ustring %= omit[quote_char[_a = _1]] >> *(unesc_char | "\\x" >> hex | (char_ - lit(_a))) >> lit(_a); unquoted_ustring %= ((alpha >> *alnum) - lit("not")); attr %= '[' >> no_skip[+~char_(']')] >> ']'; global_attr %= '@' >> no_skip[alpha >> * (alnum | char_('-'))]; } } <commit_msg>add `no_skip` directive in unquoted_ustring rule (ref: https://github.com/mapnik/mapnik/pull/3389#issuecomment-204344223)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // NOTE: This is an implementation header file and is only meant to be included // from implementation files. It therefore doesn't have an include guard. // mapnik #include <mapnik/expression_node.hpp> #include <mapnik/expression_grammar.hpp> #include <mapnik/unicode.hpp> #include <mapnik/value_types.hpp> #include <mapnik/function_call.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/fusion/adapted/struct.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_function.hpp> #pragma GCC diagnostic pop BOOST_FUSION_ADAPT_STRUCT(mapnik::unary_function_call, (mapnik::unary_function_impl, fun) (mapnik::unary_function_call::argument_type, arg)) BOOST_FUSION_ADAPT_STRUCT(mapnik::binary_function_call, (mapnik::binary_function_impl, fun) (mapnik::binary_function_call::argument_type, arg1) (mapnik::binary_function_call::argument_type, arg2)) // fwd declare namespace mapnik { struct attribute; struct geometry_type_attribute; } namespace mapnik { struct unicode_impl { using result_type = mapnik::value_unicode_string; explicit unicode_impl(mapnik::transcoder const& tr) : tr_(tr) {} mapnik::value_unicode_string operator()(std::string const& str) const { return tr_.transcode(str.c_str()); } mapnik::transcoder const& tr_; }; struct regex_match_impl { using result_type = expr_node; explicit regex_match_impl(mapnik::transcoder const& tr) : tr_(tr) {} template <typename T0,typename T1> expr_node operator() (T0 & node, T1 const& pattern) const; mapnik::transcoder const& tr_; }; struct regex_replace_impl { using result_type = expr_node; explicit regex_replace_impl(mapnik::transcoder const& tr) : tr_(tr) {} template <typename T0,typename T1,typename T2> expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const; mapnik::transcoder const& tr_; }; unary_function_types::unary_function_types() { add ("sin", sin_impl()) ("cos", cos_impl()) ("tan", tan_impl()) ("atan", atan_impl()) ("exp", exp_impl()) ("abs", abs_impl()) ("length",length_impl()) ; } binary_function_types::binary_function_types() { add ("min", binary_function_impl(min_impl)) ("max", binary_function_impl(max_impl)) ("pow", binary_function_impl(pow_impl)) ; } template <typename T0,typename T1> expr_node regex_match_impl::operator() (T0 & node, T1 const& pattern) const { return regex_match_node(tr_,node,pattern); } template <typename T0,typename T1,typename T2> expr_node regex_replace_impl::operator() (T0 & node, T1 const& pattern, T2 const& format) const { return regex_replace_node(tr_,node,pattern,format); } template <typename Iterator> expression_grammar<Iterator>::expression_grammar(std::string const& encoding) : expression_grammar::base_type(expr), tr_(encoding) { qi::_1_type _1; qi::_a_type _a; qi::_b_type _b; qi::_r1_type _r1; qi::no_skip_type no_skip; qi::_val_type _val; qi::lit_type lit; qi::double_type double_; qi::hex_type hex; qi::omit_type omit; qi::alpha_type alpha; qi::alnum_type alnum; standard_wide::char_type char_; standard_wide::no_case_type no_case; using boost::phoenix::construct; using boost::phoenix::if_else; boost::phoenix::function<unicode_impl> unicode = unicode_impl(tr_); boost::phoenix::function<regex_match_impl> regex_match = regex_match_impl(tr_); boost::phoenix::function<regex_replace_impl> regex_replace = regex_replace_impl(tr_); constant.add ("null", mapnik::value_null()) ("false", mapnik::value_bool(false)) ("true", mapnik::value_bool(true)) ("point", mapnik::value_integer(1)) ("linestring", mapnik::value_integer(2)) ("polygon", mapnik::value_integer(3)) ("collection", mapnik::value_integer(4)) ("pi", mapnik::value_double(3.1415926535897932384626433832795)) ("deg_to_rad", mapnik::value_double(0.017453292519943295769236907684886)) ("rad_to_deg", mapnik::value_double(57.295779513082320876798154814105)) ; expr = logical_expr [_val = _1] //| ustring [_val = unicode(_1)] ; logical_expr = not_expr [_val = _1] >> *( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] ) | (( lit("or") | lit("||")) >> not_expr [_val || _1]) ) ; not_expr = cond_expr [_val = _1 ] | ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ]) ; cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1] ; equality_expr = relational_expr [_val = _1] >> *( ( (lit("=") | lit("eq") | lit("is")) >> relational_expr [_val == _1]) | (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1]) ) ; regex_match_expr = lit(".match") >> lit('(') >> quoted_ustring [_val = _1] >> lit(')') ; regex_replace_expr = lit(".replace") >> lit('(') >> quoted_ustring [_a = _1] >> lit(',') >> quoted_ustring [_b = _1] >> lit(')') [_val = regex_replace(_r1,_a,_b)] ; relational_expr = additive_expr[_val = _1] >> *( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ]) | ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ]) | ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ]) | ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ]) ) ; additive_expr = multiplicative_expr [_val = _1] >> * ( '+' >> multiplicative_expr[_val += _1] | '-' >> multiplicative_expr[_val -= _1] ) ; multiplicative_expr = unary_expr [_val = _1] >> *( '*' >> unary_expr [_val *= _1] | '/' >> unary_expr [_val /= _1] | '%' >> unary_expr [_val %= construct<mapnik::expr_node>(_1)] //needed by clang++ with -std=c++11 | regex_match_expr[_val = regex_match(_val, _1)] | regex_replace_expr(_val) [_val = _1] ) ; unary_function_expr = unary_func_type >> '(' > logical_expr > ')' ; binary_function_expr = binary_func_type >> '(' > logical_expr > ',' > logical_expr > ')' ; unary_expr = primary_expr [_val = _1] | '+' >> primary_expr [_val = _1] | '-' >> primary_expr [_val = -_1] ; primary_expr = strict_double [_val = _1] | int__[_val = _1] | no_case[constant] [_val = _1] | quoted_ustring [_val = unicode(_1)] | attr [if_else(_1 == "mapnik::geometry_type", _val = construct<mapnik::geometry_type_attribute>(), _val = construct<mapnik::attribute>(_1))] | global_attr [_val = construct<mapnik::global_attribute>( _1 )] | unary_function_expr [_val = _1] | binary_function_expr [_val = _1] | '(' > logical_expr [_val = _1 ] > ')' // TODO: this is a backward compatibility hack to allow unquoted strings | unquoted_ustring [_val = unicode(_1)] // ^ https://github.com/mapnik/mapnik/pull/3389 ; unesc_char.add("\\a", '\a')("\\b", '\b')("\\f", '\f')("\\n", '\n') ("\\r", '\r')("\\t", '\t')("\\v", '\v')("\\\\", '\\') ("\\\'", '\'')("\\\"", '\"') ; ustring %= no_skip[alpha >> *alnum]; quote_char %= char_('\'') | char_('"'); quoted_ustring %= omit[quote_char[_a = _1]] >> *(unesc_char | "\\x" >> hex | (char_ - lit(_a))) >> lit(_a); unquoted_ustring %= no_skip[alpha >> *alnum] - lit("not"); attr %= '[' >> no_skip[+~char_(']')] >> ']'; global_attr %= '@' >> no_skip[alpha >> * (alnum | char_('-'))]; } } <|endoftext|>
<commit_before>#include <stan/math/fwd/scal.hpp> #include <gtest/gtest.h> template <typename... Ts> void expect_not_const() { using stan::is_constant_all; bool temp = is_constant_all<Ts>::value; EXPECT_FALSE(temp); } TEST(MetaTraits, isConstant) { using stan::math::fvar; expect_not_const<fvar<double> >(); } <commit_msg>missing ...<commit_after>#include <stan/math/fwd/scal.hpp> #include <gtest/gtest.h> template <typename... Ts> void expect_not_const() { using stan::is_constant_all; bool temp = is_constant_all<Ts...>::value; EXPECT_FALSE(temp); } TEST(MetaTraits, isConstant) { using stan::math::fvar; expect_not_const<fvar<double> >(); } <|endoftext|>
<commit_before>/* * * Copyright 2016 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. * */ /* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when using that endpoint. Because of various transitive includes in uv.h, including windows.h on Windows, uv.h must be included before other system headers. Therefore, sockaddr.h must always be included first */ #include "src/core/lib/iomgr/sockaddr.h" #include <memory.h> #include <stdio.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/thd.h> #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/iomgr/tcp_server.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #define NUM_THREADS 100 #define NUM_OUTER_LOOPS 10 #define NUM_INNER_LOOPS 10 #define DELAY_MILLIS 10 #define POLL_MILLIS 3000 #define NUM_OUTER_LOOPS_SHORT_TIMEOUTS 10 #define NUM_INNER_LOOPS_SHORT_TIMEOUTS 100 #define DELAY_MILLIS_SHORT_TIMEOUTS 1 // in a successful test run, POLL_MILLIS should never be reached beause all runs // should // end after the shorter delay_millis #define POLL_MILLIS_SHORT_TIMEOUTS 30000 static void* tag(int n) { return (void*)(uintptr_t)n; } static int detag(void* p) { return (int)(uintptr_t)p; } void create_loop_destroy(void* addr) { for (int i = 0; i < NUM_OUTER_LOOPS; ++i) { grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_channel* chan = grpc_insecure_channel_create((char*)addr, nullptr, nullptr); for (int j = 0; j < NUM_INNER_LOOPS; ++j) { gpr_timespec later_time = grpc_timeout_milliseconds_to_deadline(DELAY_MILLIS); grpc_connectivity_state state = grpc_channel_check_connectivity_state(chan, 1); grpc_channel_watch_connectivity_state(chan, state, later_time, cq, nullptr); gpr_timespec poll_time = grpc_timeout_milliseconds_to_deadline(POLL_MILLIS); GPR_ASSERT(grpc_completion_queue_next(cq, poll_time, nullptr).type == GRPC_OP_COMPLETE); /* check that the watcher from "watch state" was free'd */ GPR_ASSERT(grpc_channel_num_external_connectivity_watchers(chan) == 0); } grpc_channel_destroy(chan); grpc_completion_queue_destroy(cq); } } struct server_thread_args { char* addr; grpc_server* server; grpc_completion_queue* cq; grpc_pollset* pollset; gpr_mu* mu; gpr_event ready; gpr_atm stop; }; void server_thread(void* vargs) { struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_event ev; gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); ev = grpc_completion_queue_next(args->cq, deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); GPR_ASSERT(detag(ev.tag) == 0xd1e); } static void on_connect(grpc_exec_ctx* exec_ctx, void* vargs, grpc_endpoint* tcp, grpc_pollset* accepting_pollset, grpc_tcp_server_acceptor* acceptor) { gpr_free(acceptor); struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_endpoint_shutdown(exec_ctx, tcp, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected")); grpc_endpoint_destroy(exec_ctx, tcp); gpr_mu_lock(args->mu); GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(exec_ctx, args->pollset, nullptr)); gpr_mu_unlock(args->mu); } void bad_server_thread(void* vargs) { struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_resolved_address resolved_addr; struct sockaddr_storage* addr = (struct sockaddr_storage*)resolved_addr.addr; int port; grpc_tcp_server* s; grpc_error* error = grpc_tcp_server_create(&exec_ctx, nullptr, nullptr, &s); GPR_ASSERT(error == GRPC_ERROR_NONE); memset(&resolved_addr, 0, sizeof(resolved_addr)); addr->ss_family = AF_INET; error = grpc_tcp_server_add_port(s, &resolved_addr, &port); GPR_ASSERT(GRPC_LOG_IF_ERROR("grpc_tcp_server_add_port", error)); GPR_ASSERT(port > 0); gpr_asprintf(&args->addr, "localhost:%d", port); grpc_tcp_server_start(&exec_ctx, s, &args->pollset, 1, on_connect, args); gpr_event_set(&args->ready, (void*)1); gpr_mu_lock(args->mu); while (gpr_atm_acq_load(&args->stop) == 0) { grpc_millis deadline = grpc_exec_ctx_now(&exec_ctx) + 100; grpc_pollset_worker* worker = nullptr; if (!GRPC_LOG_IF_ERROR( "pollset_work", grpc_pollset_work(&exec_ctx, args->pollset, &worker, deadline))) { gpr_atm_rel_store(&args->stop, 1); } gpr_mu_unlock(args->mu); grpc_exec_ctx_finish(&exec_ctx); gpr_mu_lock(args->mu); } gpr_mu_unlock(args->mu); grpc_tcp_server_unref(&exec_ctx, s); grpc_exec_ctx_finish(&exec_ctx); gpr_free(args->addr); } static void done_pollset_shutdown(grpc_exec_ctx* exec_ctx, void* pollset, grpc_error* error) { grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(pollset)); gpr_free(pollset); } int run_concurrent_connectivity_test() { struct server_thread_args args; memset(&args, 0, sizeof(args)); grpc_init(); gpr_thd_id threads[NUM_THREADS]; gpr_thd_id server; char* localhost = gpr_strdup("localhost:54321"); gpr_thd_options options = gpr_thd_options_default(); gpr_thd_options_set_joinable(&options); /* First round, no server */ gpr_log(GPR_DEBUG, "Wave 1"); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, localhost, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_free(localhost); /* Second round, actual grpc server */ gpr_log(GPR_DEBUG, "Wave 2"); int port = grpc_pick_unused_port_or_die(); gpr_asprintf(&args.addr, "localhost:%d", port); args.server = grpc_server_create(nullptr, nullptr); grpc_server_add_insecure_http2_port(args.server, args.addr); args.cq = grpc_completion_queue_create_for_next(nullptr); grpc_server_register_completion_queue(args.server, args.cq, nullptr); grpc_server_start(args.server); gpr_thd_new(&server, server_thread, &args, &options); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } grpc_server_shutdown_and_notify(args.server, args.cq, tag(0xd1e)); gpr_thd_join(server); grpc_server_destroy(args.server); grpc_completion_queue_destroy(args.cq); gpr_free(args.addr); /* Third round, bogus tcp server */ gpr_log(GPR_DEBUG, "Wave 3"); args.pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); grpc_pollset_init(args.pollset, &args.mu); gpr_event_init(&args.ready); gpr_thd_new(&server, bad_server_thread, &args, &options); gpr_event_wait(&args.ready, gpr_inf_future(GPR_CLOCK_MONOTONIC)); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_atm_rel_store(&args.stop, 1); gpr_thd_join(server); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_pollset_shutdown(&exec_ctx, args.pollset, GRPC_CLOSURE_CREATE(done_pollset_shutdown, args.pollset, grpc_schedule_on_exec_ctx)); grpc_exec_ctx_finish(&exec_ctx); grpc_shutdown(); return 0; } void watches_with_short_timeouts(void* addr) { for (int i = 0; i < NUM_OUTER_LOOPS_SHORT_TIMEOUTS; ++i) { grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_channel* chan = grpc_insecure_channel_create((char*)addr, nullptr, nullptr); for (int j = 0; j < NUM_INNER_LOOPS_SHORT_TIMEOUTS; ++j) { gpr_timespec later_time = grpc_timeout_milliseconds_to_deadline(DELAY_MILLIS_SHORT_TIMEOUTS); grpc_connectivity_state state = grpc_channel_check_connectivity_state(chan, 0); GPR_ASSERT(state == GRPC_CHANNEL_IDLE); grpc_channel_watch_connectivity_state(chan, state, later_time, cq, nullptr); gpr_timespec poll_time = grpc_timeout_milliseconds_to_deadline(POLL_MILLIS_SHORT_TIMEOUTS); grpc_event ev = grpc_completion_queue_next(cq, poll_time, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); GPR_ASSERT(ev.success == false); /* check that the watcher from "watch state" was free'd */ GPR_ASSERT(grpc_channel_num_external_connectivity_watchers(chan) == 0); } grpc_channel_destroy(chan); grpc_completion_queue_destroy(cq); } } // This test tries to catch deadlock situations. // With short timeouts on "watches" and long timeouts on cq next calls, // so that a QUEUE_TIMEOUT likely means that something is stuck. int run_concurrent_watches_with_short_timeouts_test() { grpc_init(); gpr_thd_id threads[NUM_THREADS]; char* localhost = gpr_strdup("localhost:54321"); gpr_thd_options options = gpr_thd_options_default(); gpr_thd_options_set_joinable(&options); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], watches_with_short_timeouts, localhost, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_free(localhost); grpc_shutdown(); return 0; } int main(int argc, char** argv) { grpc_test_init(argc, argv); run_concurrent_connectivity_test(); run_concurrent_watches_with_short_timeouts_test(); } <commit_msg>dont let server shutdown run forever<commit_after>/* * * Copyright 2016 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. * */ /* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when using that endpoint. Because of various transitive includes in uv.h, including windows.h on Windows, uv.h must be included before other system headers. Therefore, sockaddr.h must always be included first */ #include "src/core/lib/iomgr/sockaddr.h" #include <memory.h> #include <stdio.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/thd.h> #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/iomgr/tcp_server.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #define NUM_THREADS 100 #define NUM_OUTER_LOOPS 10 #define NUM_INNER_LOOPS 10 #define DELAY_MILLIS 10 #define POLL_MILLIS 3000 #define NUM_OUTER_LOOPS_SHORT_TIMEOUTS 10 #define NUM_INNER_LOOPS_SHORT_TIMEOUTS 100 #define DELAY_MILLIS_SHORT_TIMEOUTS 1 // in a successful test run, POLL_MILLIS should never be reached because all // runs should end after the shorter delay_millis #define POLL_MILLIS_SHORT_TIMEOUTS 30000 // it should never take longer that this to shutdown the server #define SERVER_SHUTDOWN_TIMEOUT 30000 static void* tag(int n) { return (void*)(uintptr_t)n; } static int detag(void* p) { return (int)(uintptr_t)p; } void create_loop_destroy(void* addr) { for (int i = 0; i < NUM_OUTER_LOOPS; ++i) { grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_channel* chan = grpc_insecure_channel_create((char*)addr, nullptr, nullptr); for (int j = 0; j < NUM_INNER_LOOPS; ++j) { gpr_timespec later_time = grpc_timeout_milliseconds_to_deadline(DELAY_MILLIS); grpc_connectivity_state state = grpc_channel_check_connectivity_state(chan, 1); grpc_channel_watch_connectivity_state(chan, state, later_time, cq, nullptr); gpr_timespec poll_time = grpc_timeout_milliseconds_to_deadline(POLL_MILLIS); GPR_ASSERT(grpc_completion_queue_next(cq, poll_time, nullptr).type == GRPC_OP_COMPLETE); /* check that the watcher from "watch state" was free'd */ GPR_ASSERT(grpc_channel_num_external_connectivity_watchers(chan) == 0); } grpc_channel_destroy(chan); grpc_completion_queue_destroy(cq); } } struct server_thread_args { char* addr; grpc_server* server; grpc_completion_queue* cq; grpc_pollset* pollset; gpr_mu* mu; gpr_event ready; gpr_atm stop; }; void server_thread(void* vargs) { struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_event ev; gpr_timespec deadline = grpc_timeout_milliseconds_to_deadline(SERVER_SHUTDOWN_TIMEOUT); ev = grpc_completion_queue_next(args->cq, deadline, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); GPR_ASSERT(detag(ev.tag) == 0xd1e); } static void on_connect(grpc_exec_ctx* exec_ctx, void* vargs, grpc_endpoint* tcp, grpc_pollset* accepting_pollset, grpc_tcp_server_acceptor* acceptor) { gpr_free(acceptor); struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_endpoint_shutdown(exec_ctx, tcp, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected")); grpc_endpoint_destroy(exec_ctx, tcp); gpr_mu_lock(args->mu); GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(exec_ctx, args->pollset, nullptr)); gpr_mu_unlock(args->mu); } void bad_server_thread(void* vargs) { struct server_thread_args* args = (struct server_thread_args*)vargs; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_resolved_address resolved_addr; struct sockaddr_storage* addr = (struct sockaddr_storage*)resolved_addr.addr; int port; grpc_tcp_server* s; grpc_error* error = grpc_tcp_server_create(&exec_ctx, nullptr, nullptr, &s); GPR_ASSERT(error == GRPC_ERROR_NONE); memset(&resolved_addr, 0, sizeof(resolved_addr)); addr->ss_family = AF_INET; error = grpc_tcp_server_add_port(s, &resolved_addr, &port); GPR_ASSERT(GRPC_LOG_IF_ERROR("grpc_tcp_server_add_port", error)); GPR_ASSERT(port > 0); gpr_asprintf(&args->addr, "localhost:%d", port); grpc_tcp_server_start(&exec_ctx, s, &args->pollset, 1, on_connect, args); gpr_event_set(&args->ready, (void*)1); gpr_mu_lock(args->mu); while (gpr_atm_acq_load(&args->stop) == 0) { grpc_millis deadline = grpc_exec_ctx_now(&exec_ctx) + 100; grpc_pollset_worker* worker = nullptr; if (!GRPC_LOG_IF_ERROR( "pollset_work", grpc_pollset_work(&exec_ctx, args->pollset, &worker, deadline))) { gpr_atm_rel_store(&args->stop, 1); } gpr_mu_unlock(args->mu); grpc_exec_ctx_finish(&exec_ctx); gpr_mu_lock(args->mu); } gpr_mu_unlock(args->mu); grpc_tcp_server_unref(&exec_ctx, s); grpc_exec_ctx_finish(&exec_ctx); gpr_free(args->addr); } static void done_pollset_shutdown(grpc_exec_ctx* exec_ctx, void* pollset, grpc_error* error) { grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(pollset)); gpr_free(pollset); } int run_concurrent_connectivity_test() { struct server_thread_args args; memset(&args, 0, sizeof(args)); grpc_init(); gpr_thd_id threads[NUM_THREADS]; gpr_thd_id server; char* localhost = gpr_strdup("localhost:54321"); gpr_thd_options options = gpr_thd_options_default(); gpr_thd_options_set_joinable(&options); /* First round, no server */ gpr_log(GPR_DEBUG, "Wave 1"); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, localhost, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_free(localhost); /* Second round, actual grpc server */ gpr_log(GPR_DEBUG, "Wave 2"); int port = grpc_pick_unused_port_or_die(); gpr_asprintf(&args.addr, "localhost:%d", port); args.server = grpc_server_create(nullptr, nullptr); grpc_server_add_insecure_http2_port(args.server, args.addr); args.cq = grpc_completion_queue_create_for_next(nullptr); grpc_server_register_completion_queue(args.server, args.cq, nullptr); grpc_server_start(args.server); gpr_thd_new(&server, server_thread, &args, &options); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } grpc_server_shutdown_and_notify(args.server, args.cq, tag(0xd1e)); gpr_thd_join(server); grpc_server_destroy(args.server); grpc_completion_queue_destroy(args.cq); gpr_free(args.addr); /* Third round, bogus tcp server */ gpr_log(GPR_DEBUG, "Wave 3"); args.pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); grpc_pollset_init(args.pollset, &args.mu); gpr_event_init(&args.ready); gpr_thd_new(&server, bad_server_thread, &args, &options); gpr_event_wait(&args.ready, gpr_inf_future(GPR_CLOCK_MONOTONIC)); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], create_loop_destroy, args.addr, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_atm_rel_store(&args.stop, 1); gpr_thd_join(server); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_pollset_shutdown(&exec_ctx, args.pollset, GRPC_CLOSURE_CREATE(done_pollset_shutdown, args.pollset, grpc_schedule_on_exec_ctx)); grpc_exec_ctx_finish(&exec_ctx); grpc_shutdown(); return 0; } void watches_with_short_timeouts(void* addr) { for (int i = 0; i < NUM_OUTER_LOOPS_SHORT_TIMEOUTS; ++i) { grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); grpc_channel* chan = grpc_insecure_channel_create((char*)addr, nullptr, nullptr); for (int j = 0; j < NUM_INNER_LOOPS_SHORT_TIMEOUTS; ++j) { gpr_timespec later_time = grpc_timeout_milliseconds_to_deadline(DELAY_MILLIS_SHORT_TIMEOUTS); grpc_connectivity_state state = grpc_channel_check_connectivity_state(chan, 0); GPR_ASSERT(state == GRPC_CHANNEL_IDLE); grpc_channel_watch_connectivity_state(chan, state, later_time, cq, nullptr); gpr_timespec poll_time = grpc_timeout_milliseconds_to_deadline(POLL_MILLIS_SHORT_TIMEOUTS); grpc_event ev = grpc_completion_queue_next(cq, poll_time, nullptr); GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); GPR_ASSERT(ev.success == false); /* check that the watcher from "watch state" was free'd */ GPR_ASSERT(grpc_channel_num_external_connectivity_watchers(chan) == 0); } grpc_channel_destroy(chan); grpc_completion_queue_destroy(cq); } } // This test tries to catch deadlock situations. // With short timeouts on "watches" and long timeouts on cq next calls, // so that a QUEUE_TIMEOUT likely means that something is stuck. int run_concurrent_watches_with_short_timeouts_test() { grpc_init(); gpr_thd_id threads[NUM_THREADS]; char* localhost = gpr_strdup("localhost:54321"); gpr_thd_options options = gpr_thd_options_default(); gpr_thd_options_set_joinable(&options); for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_new(&threads[i], watches_with_short_timeouts, localhost, &options); } for (size_t i = 0; i < NUM_THREADS; ++i) { gpr_thd_join(threads[i]); } gpr_free(localhost); grpc_shutdown(); return 0; } int main(int argc, char** argv) { grpc_test_init(argc, argv); run_concurrent_connectivity_test(); run_concurrent_watches_with_short_timeouts_test(); } <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_TITLE_HPP #define RJ_CORE_MAIN_MENU_TITLE_HPP #include "menu_component.hpp" #include <rectojump/core/render.hpp> #include <mlk/containers/container_utl.h> namespace rj { class game; enum class direction : char {forward, back}; class title : public menu_component { sf::Text m_title{"Recto Jump", m_font, 50}; std::vector<sf::Color> m_title_colors; std::size_t m_current_colorindex{0}; direction m_direction{direction::forward}; public: title(game& g, const sf::Font& font, const vec2f& center) : menu_component{g, font, center} {this->init();} void update(dur) override { m_title.setColor(m_title_colors[m_current_colorindex]); if(m_current_colorindex == m_title_colors.size()) m_direction = direction::back; else if(m_current_colorindex == 0) m_direction = direction::forward; m_direction == direction::forward ? ++m_current_colorindex : --m_current_colorindex; } void render() override {render::render_object(m_game, m_title);} private: void init() override { // title m_title.setOrigin(m_title.getLocalBounds().width / 2.f, m_title.getGlobalBounds().height / 2.f); m_title.setPosition(m_center.x, 150); // title colors for(std::uint8_t r{255}, b{200}; r > 123; --r, --b) m_title_colors.emplace_back(r, 0, b); } }; } #endif // RJ_CORE_MAIN_MENU_TITLE_HPP <commit_msg>fixed bounds issue<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_TITLE_HPP #define RJ_CORE_MAIN_MENU_TITLE_HPP #include "menu_component.hpp" #include <rectojump/core/render.hpp> #include <mlk/containers/container_utl.h> namespace rj { class game; enum class direction : char {forward, back}; class title : public menu_component { sf::Text m_title{"Recto Jump", m_font, 50}; std::vector<sf::Color> m_title_colors; std::size_t m_current_colorindex{0}; direction m_direction{direction::forward}; public: title(game& g, const sf::Font& font, const vec2f& center) : menu_component{g, font, center} {this->init();} void update(dur) override { m_direction == direction::forward ? ++m_current_colorindex : --m_current_colorindex; if(m_current_colorindex == m_title_colors.size() - 1) m_direction = direction::back; else if(m_current_colorindex == 0) m_direction = direction::forward; m_title.setColor(m_title_colors[m_current_colorindex]); } void render() override {render::render_object(m_game, m_title);} private: void init() override { // title m_title.setOrigin(m_title.getLocalBounds().width / 2.f, m_title.getGlobalBounds().height / 2.f); m_title.setPosition(m_center.x, 150); // title colors for(std::uint8_t r{255}, b{200}; r > 123; --r, --b) m_title_colors.emplace_back(r, 0, b); } }; } #endif // RJ_CORE_MAIN_MENU_TITLE_HPP <|endoftext|>
<commit_before>#ifndef LIBBITCOIN_TYPES_H #define LIBBITCOIN_TYPES_H #include <boost/asio.hpp> #include <array> #include <memory> #include <sstream> #include <iomanip> #include <vector> namespace libbitcoin { using std::shared_ptr; using boost::asio::io_service; using boost::asio::ip::tcp; using boost::asio::deadline_timer; class exporter; class blockchain; class transaction_pool; class network; class channel; class handshake; class chrono_clock; typedef std::shared_ptr<exporter> exporter_ptr; typedef std::shared_ptr<blockchain> blockchain_ptr; typedef std::shared_ptr<transaction_pool> transaction_pool_ptr; typedef std::shared_ptr<network> network_ptr; typedef std::shared_ptr<channel> channel_ptr; typedef std::shared_ptr<handshake> handshake_ptr; typedef std::shared_ptr<chrono_clock> chrono_clock_ptr; typedef std::shared_ptr<io_service> service_ptr; typedef std::shared_ptr<io_service::work> work_ptr; typedef std::shared_ptr<io_service::strand> strand_ptr; typedef std::shared_ptr<deadline_timer> deadline_timer_ptr; typedef std::shared_ptr<tcp::socket> socket_ptr; typedef std::shared_ptr<tcp::acceptor> acceptor_ptr; typedef std::array<uint8_t, 32> hash_digest; typedef std::array<uint8_t, 20> short_hash; typedef unsigned char byte; typedef std::vector<byte> data_chunk; // Make hash_digest and short_hash hashable for std::*map variants template <typename HashType> struct std_hash_wrapper { size_t operator()(const HashType& h) const { std::hash<std::string> functor; return functor(std::string(std::begin(h), std::end(h))); } }; struct node_address { std::string hostname; uint8_t port; }; } // libbitcoin // Extend std namespace with our hash wrappers namespace std { using libbitcoin::std_hash_wrapper; using libbitcoin::hash_digest; using libbitcoin::short_hash; template <> struct hash<hash_digest> : public std_hash_wrapper<hash_digest> { }; template <> struct hash<short_hash> : public std_hash_wrapper<short_hash> { }; } // std #endif <commit_msg>8-bit port number? ooops...<commit_after>#ifndef LIBBITCOIN_TYPES_H #define LIBBITCOIN_TYPES_H #include <boost/asio.hpp> #include <array> #include <memory> #include <sstream> #include <iomanip> #include <vector> namespace libbitcoin { using std::shared_ptr; using boost::asio::io_service; using boost::asio::ip::tcp; using boost::asio::deadline_timer; class exporter; class blockchain; class transaction_pool; class network; class channel; class handshake; class chrono_clock; typedef std::shared_ptr<exporter> exporter_ptr; typedef std::shared_ptr<blockchain> blockchain_ptr; typedef std::shared_ptr<transaction_pool> transaction_pool_ptr; typedef std::shared_ptr<network> network_ptr; typedef std::shared_ptr<channel> channel_ptr; typedef std::shared_ptr<handshake> handshake_ptr; typedef std::shared_ptr<chrono_clock> chrono_clock_ptr; typedef std::shared_ptr<io_service> service_ptr; typedef std::shared_ptr<io_service::work> work_ptr; typedef std::shared_ptr<io_service::strand> strand_ptr; typedef std::shared_ptr<deadline_timer> deadline_timer_ptr; typedef std::shared_ptr<tcp::socket> socket_ptr; typedef std::shared_ptr<tcp::acceptor> acceptor_ptr; typedef std::array<uint8_t, 32> hash_digest; typedef std::array<uint8_t, 20> short_hash; typedef unsigned char byte; typedef std::vector<byte> data_chunk; // Make hash_digest and short_hash hashable for std::*map variants template <typename HashType> struct std_hash_wrapper { size_t operator()(const HashType& h) const { std::hash<std::string> functor; return functor(std::string(std::begin(h), std::end(h))); } }; struct node_address { std::string hostname; uint16_t port; }; } // libbitcoin // Extend std namespace with our hash wrappers namespace std { using libbitcoin::std_hash_wrapper; using libbitcoin::hash_digest; using libbitcoin::short_hash; template <> struct hash<hash_digest> : public std_hash_wrapper<hash_digest> { }; template <> struct hash<short_hash> : public std_hash_wrapper<short_hash> { }; } // std #endif <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "RadixSortTests.h" #include "OgreRadixSort.h" #include "OgreMath.h" using namespace Ogre; // Register the test suite //-------------------------------------------------------------------------- void RadixSortTests::SetUp() { srand(0); } //-------------------------------------------------------------------------- void RadixSortTests::TearDown() { } //-------------------------------------------------------------------------- class FloatSortFunctor { public: float operator()(const float& p) const { return p; } }; //-------------------------------------------------------------------------- class IntSortFunctor { public: int operator()(const int& p) const { return p; } }; //-------------------------------------------------------------------------- class UnsignedIntSortFunctor { public: unsigned int operator()(const unsigned int& p) const { return p; } }; //-------------------------------------------------------------------------- TEST_F(RadixSortTests,FloatVector) { std::vector<float> container; FloatSortFunctor func; RadixSort<std::vector<float>, float, float> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((float)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::vector<float>::iterator v = container.begin(); float lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,FloatList) { std::list<float> container; FloatSortFunctor func; RadixSort<std::list<float>, float, float> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((float)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::list<float>::iterator v = container.begin(); float lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,UnsignedIntList) { std::list<unsigned int> container; UnsignedIntSortFunctor func; RadixSort<std::list<unsigned int>, unsigned int, unsigned int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((unsigned int)Math::RangeRandom(0, 1e10)); } sorter.sort(container, func); std::list<unsigned int>::iterator v = container.begin(); unsigned int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,IntList) { std::list<int> container; IntSortFunctor func; RadixSort<std::list<int>, int, int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((int)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::list<int>::iterator v = container.begin(); int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,UnsignedIntVector) { std::vector<unsigned int> container; UnsignedIntSortFunctor func; RadixSort<std::vector<unsigned int>, unsigned int, unsigned int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((unsigned int)Math::RangeRandom(0, 1e10)); } sorter.sort(container, func); std::vector<unsigned int>::iterator v = container.begin(); unsigned int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,IntVector) { std::vector<int> container; IntSortFunctor func; RadixSort<std::vector<int>, int, int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((int)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::vector<int>::iterator v = container.begin(); int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- <commit_msg>Tests: RadixSort - use correct integer limits <commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "RadixSortTests.h" #include "OgreRadixSort.h" #include "OgreMath.h" #include <climits> using namespace Ogre; // Register the test suite //-------------------------------------------------------------------------- void RadixSortTests::SetUp() { srand(0); } //-------------------------------------------------------------------------- void RadixSortTests::TearDown() { } //-------------------------------------------------------------------------- class FloatSortFunctor { public: float operator()(const float& p) const { return p; } }; //-------------------------------------------------------------------------- class IntSortFunctor { public: int operator()(const int& p) const { return p; } }; //-------------------------------------------------------------------------- class UnsignedIntSortFunctor { public: unsigned int operator()(const unsigned int& p) const { return p; } }; //-------------------------------------------------------------------------- TEST_F(RadixSortTests,FloatVector) { std::vector<float> container; FloatSortFunctor func; RadixSort<std::vector<float>, float, float> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((float)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::vector<float>::iterator v = container.begin(); float lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,FloatList) { std::list<float> container; FloatSortFunctor func; RadixSort<std::list<float>, float, float> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((float)Math::RangeRandom(-1e10, 1e10)); } sorter.sort(container, func); std::list<float>::iterator v = container.begin(); float lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,UnsignedIntList) { std::list<unsigned int> container; UnsignedIntSortFunctor func; RadixSort<std::list<unsigned int>, unsigned int, unsigned int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((unsigned int)Math::RangeRandom(0, UINT_MAX)); } sorter.sort(container, func); std::list<unsigned int>::iterator v = container.begin(); unsigned int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,IntList) { std::list<int> container; IntSortFunctor func; RadixSort<std::list<int>, int, int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((int)Math::RangeRandom(INT_MIN, INT_MAX)); } sorter.sort(container, func); std::list<int>::iterator v = container.begin(); int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,UnsignedIntVector) { std::vector<unsigned int> container; UnsignedIntSortFunctor func; RadixSort<std::vector<unsigned int>, unsigned int, unsigned int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((unsigned int)Math::RangeRandom(0, UINT_MAX)); } sorter.sort(container, func); std::vector<unsigned int>::iterator v = container.begin(); unsigned int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- TEST_F(RadixSortTests,IntVector) { std::vector<int> container; IntSortFunctor func; RadixSort<std::vector<int>, int, int> sorter; for (int i = 0; i < 1000; ++i) { container.push_back((int)Math::RangeRandom(INT_MIN, INT_MAX)); } sorter.sort(container, func); std::vector<int>::iterator v = container.begin(); int lastValue = *v++; for (;v != container.end(); ++v) { EXPECT_TRUE(*v >= lastValue); lastValue = *v; } } //-------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright (c) 2009-2017 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Developers // Copyright (c) 2015-2017 Silk Network Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "bantablemodel.h" #include "guiconstants.h" #include "peertablemodel.h" #include "alert.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "net.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDebug> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), peerTableModel(0), banTableModel(0), cachedNumBlocks(0), cachedReindexing(0), cachedImporting(0), numBlocksAtStartup(-1), pollTimer(0) { peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { LOCK(cs_vNodes); if (flags == CONNECTIONS_ALL) // Shortcut if we want total return vNodes.size(); int nNum = 0; Q_FOREACH(CNode* pnode, vNodes) if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) nNum++; return nNum; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); else return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } double ClientModel::getVerificationProgress() const { const CChainParams& chainParams = Params(); LOCK(cs_main); return Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()); } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); // check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state if (cachedNumBlocks != newNumBlocks || cachedReindexing != fReindex || cachedImporting != fImporting) { cachedNumBlocks = newNumBlocks; cachedReindexing = fReindex; cachedImporting = fImporting; emit alertsChanged(getStatusBarWarnings()); // Silk: redraw alerts in case of old sync checkpoint emit numBlocksChanged(newNumBlocks); } emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); emit mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastBlockTipUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress())); nLastBlockTipUpdateNotification = now; } } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2)); } <commit_msg>Fix numBlocksChanged<commit_after>// Copyright (c) 2009-2017 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Developers // Copyright (c) 2015-2017 Silk Network Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "bantablemodel.h" #include "guiconstants.h" #include "peertablemodel.h" #include "alert.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "net.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDebug> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), peerTableModel(0), banTableModel(0), cachedNumBlocks(0), cachedReindexing(0), cachedImporting(0), numBlocksAtStartup(-1), pollTimer(0) { peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { LOCK(cs_vNodes); if (flags == CONNECTIONS_ALL) // Shortcut if we want total return vNodes.size(); int nNum = 0; Q_FOREACH(CNode* pnode, vNodes) if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) nNum++; return nNum; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); else return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } double ClientModel::getVerificationProgress() const { const CChainParams& chainParams = Params(); LOCK(cs_main); return Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()); } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); // check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state if (cachedNumBlocks != newNumBlocks || cachedReindexing != fReindex || cachedImporting != fImporting) { cachedNumBlocks = newNumBlocks; cachedReindexing = fReindex; cachedImporting = fImporting; emit alertsChanged(getStatusBarWarnings()); // Silk: redraw alerts in case of old sync checkpoint emit numBlocksChanged(newNumBlocks); } emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); emit mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastBlockTipUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight)); nLastBlockTipUpdateNotification = now; } } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2)); } <|endoftext|>
<commit_before>// // Created by Dawid Drozd aka Gelldur on 10.10.17. // #include "Label.h" ////////////////////////////////// #include <bee/acme/RGBA.h> using namespace cocos2d; namespace Bee { Label::Label(const std::string& id) : _node{id, new CCLabelTTF{}} { get()->init(); } void Label::setColor(const int color) { Bee::RGBA::setColor(get(), color); } void Label::setOpacity(double value) { Bee::RGBA::setOpacity(get(), value); } void Label::setFont(std::string font) { get()->initWithString("Sample text", font.c_str(), 16); } void Label::setFontSize(const int size) { get()->setFontSize(size); } void Label::setText(std::string text) { get()->setString(text.c_str()); } void Label::setAlign(std::string alignText) { if (alignText == "center") { alignText = "centerVertical|centerHorizontal"; } auto found = alignText.find("|"); if (found == std::string::npos) { if (setAlignOption(alignText) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } } else { auto first = alignText.substr(0, found); if (setAlignOption(first) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } auto second = alignText.substr(found + 1); if (setAlignOption(second) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } } } cocos2d::CCLabelTTF* Label::get() const { auto node = dynamic_cast<CCLabelTTF*>(_node.node.get()); assert(node); return node; } bool Label::setAlignOption(const std::string& alignTextOption) { if (alignTextOption == "top") { get()->setVerticalAlignment(kCCVerticalTextAlignmentTop); return true; } if (alignTextOption == "centerVertical") { get()->setVerticalAlignment(kCCVerticalTextAlignmentCenter); return true; } if (alignTextOption == "bottom") { get()->setVerticalAlignment(kCCVerticalTextAlignmentBottom); return true; } /////////////////////////////////////////////////////////////////// if (alignTextOption == "left") { get()->setHorizontalAlignment(kCCTextAlignmentLeft); return true; } if (alignTextOption == "centerHorizontal") { get()->setHorizontalAlignment(kCCTextAlignmentCenter); return true; } if (alignTextOption == "right") { get()->setHorizontalAlignment(kCCTextAlignmentRight); return true; } return false; } } <commit_msg>Fix Label::setFont<commit_after>// // Created by Dawid Drozd aka Gelldur on 10.10.17. // #include "Label.h" ////////////////////////////////// #include <bee/acme/RGBA.h> using namespace cocos2d; namespace Bee { Label::Label(const std::string& id) : _node{id, new CCLabelTTF{}} { get()->init(); } void Label::setColor(const int color) { Bee::RGBA::setColor(get(), color); } void Label::setOpacity(double value) { Bee::RGBA::setOpacity(get(), value); } void Label::setFont(std::string font) { get()->setFontName(font.c_str()); } void Label::setFontSize(const int size) { get()->setFontSize(size); } void Label::setText(std::string text) { get()->setString(text.c_str()); } void Label::setAlign(std::string alignText) { if (alignText == "center") { alignText = "centerVertical|centerHorizontal"; } auto found = alignText.find("|"); if (found == std::string::npos) { if (setAlignOption(alignText) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } } else { auto first = alignText.substr(0, found); if (setAlignOption(first) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } auto second = alignText.substr(found + 1); if (setAlignOption(second) == false) { CCLOG("Invalid align option: %s", alignText.c_str()); return; } } } cocos2d::CCLabelTTF* Label::get() const { auto node = dynamic_cast<CCLabelTTF*>(_node.node.get()); assert(node); return node; } bool Label::setAlignOption(const std::string& alignTextOption) { if (alignTextOption == "top") { get()->setVerticalAlignment(kCCVerticalTextAlignmentTop); return true; } if (alignTextOption == "centerVertical") { get()->setVerticalAlignment(kCCVerticalTextAlignmentCenter); return true; } if (alignTextOption == "bottom") { get()->setVerticalAlignment(kCCVerticalTextAlignmentBottom); return true; } /////////////////////////////////////////////////////////////////// if (alignTextOption == "left") { get()->setHorizontalAlignment(kCCTextAlignmentLeft); return true; } if (alignTextOption == "centerHorizontal") { get()->setHorizontalAlignment(kCCTextAlignmentCenter); return true; } if (alignTextOption == "right") { get()->setHorizontalAlignment(kCCTextAlignmentRight); return true; } return false; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include <boost/algorithm/string.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/tokenizer.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/version.hpp> #if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900) #warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392 #endif #include "ui_interface.h" #include "qtipcserver.h" using namespace boost::interprocess; using namespace boost::posix_time; using namespace boost; using namespace std; #ifdef MAC_OSX // URI handling not implemented on OSX yet void ipcInit() { } void ipcShutdown() { } #else void ipcShutdown() { message_queue::remove(BITCOINURI_QUEUE_NAME); } void ipcThread(void* parg) { message_queue* mq = (message_queue*)parg; char strBuf[257]; size_t nSize; unsigned int nPriority; loop { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(strBuf, nSize)); Sleep(1000); } if (fShutdown) { ipcShutdown(); break; } } ipcShutdown(); } void ipcInit() { message_queue* mq; char strBuf[257]; size_t nSize; unsigned int nPriority; try { mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, 256); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(strBuf, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove(BITCOINURI_QUEUE_NAME); mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, 256); } catch (interprocess_exception &ex) { return; } if (!CreateThread(ipcThread, mq)) { delete mq; } } #endif <commit_msg>Give the GUI-IPC thread a name as well<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include <boost/algorithm/string.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/tokenizer.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/version.hpp> #if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900) #warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392 #endif #include "ui_interface.h" #include "qtipcserver.h" #include "util.h" using namespace boost::interprocess; using namespace boost::posix_time; using namespace boost; using namespace std; #ifdef MAC_OSX // URI handling not implemented on OSX yet void ipcInit() { } void ipcShutdown() { } #else void ipcShutdown() { message_queue::remove(BITCOINURI_QUEUE_NAME); } void ipcThread(void* parg) { // Make this thread recognisable as the GUI-IPC thread RenameThread("bitcoin-gui-ipc"); message_queue* mq = (message_queue*)parg; char strBuf[257]; size_t nSize; unsigned int nPriority; loop { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(strBuf, nSize)); Sleep(1000); } if (fShutdown) { ipcShutdown(); break; } } ipcShutdown(); } void ipcInit() { message_queue* mq; char strBuf[257]; size_t nSize; unsigned int nPriority; try { mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, 256); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(strBuf, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove(BITCOINURI_QUEUE_NAME); mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, 256); } catch (interprocess_exception &ex) { return; } if (!CreateThread(ipcThread, mq)) { delete mq; } } #endif <|endoftext|>
<commit_before>#pragma once /** @file @brief config file class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <assert.h> #include <string> #include <map> #include <fstream> #include <cybozu/exception.hpp> #include <cybozu/atoi.hpp> namespace cybozu { namespace config_local { inline bool isName(const std::string& str, char *badChar) { for (size_t i = 0, n = str.size(); i < n; i++) { char c = str[i]; if (!('0' <= c && c <= '9') && !('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') && c != '_') { *badChar = c; return false; } } return true; } inline void trimEndSpace(std::string& str) { if (str.empty()) return; size_t i = str.size(); while (i > 0) { char c = str[i - 1]; if (c == ' ' || c == '\t') { i--; } else { break; } } return str.resize(i); } inline void split(std::string& key, std::string& value, const std::string& line) { const char *p = line.c_str(); const char *q = strchr(p, '='); if (q == 0) { throw cybozu::Exception("config:split:no equal") << line; } key = line.substr(0, q - p); trimEndSpace(key); char badChar; if (!cybozu::config_local::isName(key, &badChar)) { throw cybozu::Exception("config:split:bad key") << key << badChar; } const size_t valueTop = q + 1 - p; value = line.substr(valueTop, line.size() - valueTop); } } // config_local /** config class config format is the following <pre> CF = "\r\n" | "\n" NAME = [0-9a-zA-Z_]+ VALUE = [^\\r\\n]* LINE = (EMPTY | COMMENT | SECTION | KEY_VALUE) CF EMPTY = "" COMMENT = ";" [^\\r\\n]* SECTION = "[" NAME "]" SP = [ \t] KEY_VALUE = NAME SP* "=" VALUE </pre> how to use Config <pre> using namespace cybozu; Config config; config.load("config.ini"); Config::Section *section = config.querySection("db"); if (section) { const std::string *value = section->queryValue("name"); std::cout << "name:" << *value << std::endl; } </pre> */ class Config { public: /** section class */ class Section { // auto converter to integer or string class ResultType { const std::string& str_; const std::string& key_; void operator=(const ResultType&); template<typename T> T get() const { bool b; T t = cybozu::atoi(&b, str_); if (!b) { throw cybozu::Exception("config:get:bad integer") << str_ << key_; } return t; } public: ResultType(const std::string& str, const std::string& key) : str_(str) , key_(key) { } operator short() const { return get<short>(); } operator unsigned short() const { return get<unsigned short>(); } operator int() const { return get<int>(); } operator unsigned int() const { return get<unsigned int>(); } operator int64_t() const { return get<int64_t>(); } operator uint64_t() const { return get<uint64_t>(); } operator const std::string&() const { return str_; } }; template<typename T> T getValueInteger(const std::string& key, T defaultValue) const { const std::string *value = queryValue(key); if (value) { bool b; T t = cybozu::atoi(&b, *value); if (!b) { throw cybozu::Exception("config:getValueInteger:bad integer") << *value << key; } return t; } else { return defaultValue; } } public: typedef std::map<std::string, std::string> Map; /** append a pair of (key, value) @param key [in] key @param value [in] value */ void append(const std::string& key, const std::string& value) { char badChar; if (!config_local::isName(key, &badChar)) { throw cybozu::Exception("config:append:bad key") << key << badChar; } std::pair<Map::iterator, bool> ret = map_.insert(Map::value_type(key, value)); if (!ret.second) { throw cybozu::Exception("config:append:key already exists") << key; } } /** query key @param key [in] key @retval 0 not found @retval !0 pointer to value */ const std::string *queryValue(const std::string& key) const { Map::const_iterator i = map_.find(key); return i != map_.end() ? &(i->second) : 0; } /** get key if key exists @param key [in] key @retval value @note throw exception if not found */ Section::ResultType getValue(const std::string& key) const { const std::string *value = queryValue(key); if (value) { return Section::ResultType(*value, key); } else { throw cybozu::Exception("config:getValue") << key; } } /** get key if key exists or use default @param key [in] key @param defaultValue [in] default Value @retval value @note throw exception if not found */ short getValue(const std::string& key, short defaultValue) const { return getValueInteger<short>(key, defaultValue); } unsigned short getValue(const std::string& key, unsigned short defaultValue) const { return getValueInteger<unsigned short>(key, defaultValue); } int getValue(const std::string& key, int defaultValue) const { return getValueInteger<int>(key, defaultValue); } unsigned int getValue(const std::string& key, unsigned int defaultValue) const { return getValueInteger<unsigned int>(key, defaultValue); } int64_t getValue(const std::string& key, int64_t defaultValue) const { return getValueInteger<int64_t >(key, defaultValue); } uint64_t getValue(const std::string& key, uint64_t defaultValue) const { return getValueInteger<uint64_t >(key, defaultValue); } const std::string& getValue(const std::string& key, const std::string& defaultValue) const { const std::string *value = queryValue(key); if (value) { return *value; } else { return defaultValue; } } /** convert section to string */ std::string toString() const { std::string ret; for (Map::const_iterator i = map_.begin(), ie = map_.end(); i != ie; ++i) { ret += i->first + "=" + i->second + "\n"; } return ret; } /** get map */ const Config::Section::Map& getMap() const { return map_; } private: Map map_; }; typedef std::map<std::string, Section> Map; Config() { } /** constructor with loading config file @param name [in] config file name */ explicit Config(const std::string& name) { load(name); } /** append empty Section named as name @param name [in] section name @return pointer to section */ Config::Section* appendSection(const std::string& name) { char badChar; if (!config_local::isName(name, &badChar)) { throw cybozu::Exception("config:appendSection:bad section") << name << badChar; } std::pair<Map::iterator, bool> ret = map_.insert(Map::value_type(name, Section())); return &ret.first->second; } /** append section @param name [in] section name @param section [in] section data */ cybozu::Config& appendSection(const std::string& name, const cybozu::Config::Section& section) { *appendSection(name) = section; return *this; } /** query const section @param name [in] section name @retval 0 not found @retval !0 pointer to section */ const Config::Section* querySection(const std::string& name) const { Map::const_iterator i = map_.find(name); return (i != map_.end()) ? &(i->second) : 0; } /** query section @param name [in] section name @retval 0 not found @retval !0 pointer to section */ Config::Section* querySection(const std::string& name) { return const_cast<Config::Section*>(static_cast<const Config*>(this)->querySection(name)); } /** get const section @param name [in] section name("" means global section) @return section @note throw exception if not found */ const Config::Section& getSection(const std::string& name = "") const { const Config::Section *section = querySection(name); if (section) { return *section; } else { throw cybozu::Exception("config:getSection:no section") << name; } } /** load config file @param name [in] config file name */ void load(const std::string& name) { std::ifstream ifs(name.c_str()); if (!ifs) { throw cybozu::Exception("config:load") << name; } load(ifs); } /** load config file @param is [in] istream */ void load(std::istream& is) { Config::Section *section = appendSection(""); // global section assert(section); std::string line; while (std::getline(is, line)) { size_t n = line.size(); if (n == 0) continue; // skip if empty // remove '\r' at the end of line char c = line[n - 1]; if (c == '\r') { if (n == 1) continue; line.resize(n - 1); n--; } // skip if comment c = line[0]; if (c == ';') continue; // section if (c == '[') { if (line[n - 1] != ']') { throw cybozu::Exception("config:load:bad section") << line; } section = appendSection(line.substr(1, n - 2)); continue; } std::string key, value; config_local::split(key, value, line); section->append(key, value); } } /** get map */ const Config::Map& getMap() const { return map_; } /** convert section to string */ std::string toString() const { std::string ret; for (Map::const_iterator i = map_.begin(), ie = map_.end(); i != ie; ++i) { if (!i->first.empty()) { ret += "[" + i->first + "]\n"; } ret += i->second.toString(); } return ret; } private: Map map_; }; } // end of cybozu <commit_msg>config support '#' comment<commit_after>#pragma once /** @file @brief config file class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <assert.h> #include <string> #include <map> #include <fstream> #include <cybozu/exception.hpp> #include <cybozu/atoi.hpp> namespace cybozu { namespace config_local { inline bool isName(const std::string& str, char *badChar) { for (size_t i = 0, n = str.size(); i < n; i++) { char c = str[i]; if (!('0' <= c && c <= '9') && !('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') && c != '_') { *badChar = c; return false; } } return true; } inline void trimEndSpace(std::string& str) { if (str.empty()) return; size_t i = str.size(); while (i > 0) { char c = str[i - 1]; if (c == ' ' || c == '\t') { i--; } else { break; } } return str.resize(i); } inline void split(std::string& key, std::string& value, const std::string& line) { const char *p = line.c_str(); const char *q = strchr(p, '='); if (q == 0) { throw cybozu::Exception("config:split:no equal") << line; } key = line.substr(0, q - p); trimEndSpace(key); char badChar; if (!cybozu::config_local::isName(key, &badChar)) { throw cybozu::Exception("config:split:bad key") << key << badChar; } const size_t valueTop = q + 1 - p; value = line.substr(valueTop, line.size() - valueTop); } } // config_local /** config class config format is the following <pre> CF = "\r\n" | "\n" NAME = [0-9a-zA-Z_]+ VALUE = [^\\r\\n]* LINE = (EMPTY | COMMENT | SECTION | KEY_VALUE) CF EMPTY = "" COMMENT = "[;#]" [^\\r\\n]* SECTION = "[" NAME "]" SP = [ \t] KEY_VALUE = NAME SP* "=" VALUE </pre> how to use Config <pre> using namespace cybozu; Config config; config.load("config.ini"); Config::Section *section = config.querySection("db"); if (section) { const std::string *value = section->queryValue("name"); std::cout << "name:" << *value << std::endl; } </pre> */ class Config { public: /** section class */ class Section { // auto converter to integer or string class ResultType { const std::string& str_; const std::string& key_; void operator=(const ResultType&); template<typename T> T get() const { bool b; T t = cybozu::atoi(&b, str_); if (!b) { throw cybozu::Exception("config:get:bad integer") << str_ << key_; } return t; } public: ResultType(const std::string& str, const std::string& key) : str_(str) , key_(key) { } operator short() const { return get<short>(); } operator unsigned short() const { return get<unsigned short>(); } operator int() const { return get<int>(); } operator unsigned int() const { return get<unsigned int>(); } operator int64_t() const { return get<int64_t>(); } operator uint64_t() const { return get<uint64_t>(); } operator const std::string&() const { return str_; } }; template<typename T> T getValueInteger(const std::string& key, T defaultValue) const { const std::string *value = queryValue(key); if (value) { bool b; T t = cybozu::atoi(&b, *value); if (!b) { throw cybozu::Exception("config:getValueInteger:bad integer") << *value << key; } return t; } else { return defaultValue; } } public: typedef std::map<std::string, std::string> Map; /** append a pair of (key, value) @param key [in] key @param value [in] value */ void append(const std::string& key, const std::string& value) { char badChar; if (!config_local::isName(key, &badChar)) { throw cybozu::Exception("config:append:bad key") << key << badChar; } std::pair<Map::iterator, bool> ret = map_.insert(Map::value_type(key, value)); if (!ret.second) { throw cybozu::Exception("config:append:key already exists") << key; } } /** query key @param key [in] key @retval 0 not found @retval !0 pointer to value */ const std::string *queryValue(const std::string& key) const { Map::const_iterator i = map_.find(key); return i != map_.end() ? &(i->second) : 0; } /** get key if key exists @param key [in] key @retval value @note throw exception if not found */ Section::ResultType getValue(const std::string& key) const { const std::string *value = queryValue(key); if (value) { return Section::ResultType(*value, key); } else { throw cybozu::Exception("config:getValue") << key; } } /** get key if key exists or use default @param key [in] key @param defaultValue [in] default Value @retval value @note throw exception if not found */ short getValue(const std::string& key, short defaultValue) const { return getValueInteger<short>(key, defaultValue); } unsigned short getValue(const std::string& key, unsigned short defaultValue) const { return getValueInteger<unsigned short>(key, defaultValue); } int getValue(const std::string& key, int defaultValue) const { return getValueInteger<int>(key, defaultValue); } unsigned int getValue(const std::string& key, unsigned int defaultValue) const { return getValueInteger<unsigned int>(key, defaultValue); } int64_t getValue(const std::string& key, int64_t defaultValue) const { return getValueInteger<int64_t >(key, defaultValue); } uint64_t getValue(const std::string& key, uint64_t defaultValue) const { return getValueInteger<uint64_t >(key, defaultValue); } const std::string& getValue(const std::string& key, const std::string& defaultValue) const { const std::string *value = queryValue(key); if (value) { return *value; } else { return defaultValue; } } /** convert section to string */ std::string toString() const { std::string ret; for (Map::const_iterator i = map_.begin(), ie = map_.end(); i != ie; ++i) { ret += i->first + "=" + i->second + "\n"; } return ret; } /** get map */ const Config::Section::Map& getMap() const { return map_; } private: Map map_; }; typedef std::map<std::string, Section> Map; Config() { } /** constructor with loading config file @param name [in] config file name */ explicit Config(const std::string& name) { load(name); } /** append empty Section named as name @param name [in] section name @return pointer to section */ Config::Section* appendSection(const std::string& name) { char badChar; if (!config_local::isName(name, &badChar)) { throw cybozu::Exception("config:appendSection:bad section") << name << badChar; } std::pair<Map::iterator, bool> ret = map_.insert(Map::value_type(name, Section())); return &ret.first->second; } /** append section @param name [in] section name @param section [in] section data */ cybozu::Config& appendSection(const std::string& name, const cybozu::Config::Section& section) { *appendSection(name) = section; return *this; } /** query const section @param name [in] section name @retval 0 not found @retval !0 pointer to section */ const Config::Section* querySection(const std::string& name) const { Map::const_iterator i = map_.find(name); return (i != map_.end()) ? &(i->second) : 0; } /** query section @param name [in] section name @retval 0 not found @retval !0 pointer to section */ Config::Section* querySection(const std::string& name) { return const_cast<Config::Section*>(static_cast<const Config*>(this)->querySection(name)); } /** get const section @param name [in] section name("" means global section) @return section @note throw exception if not found */ const Config::Section& getSection(const std::string& name = "") const { const Config::Section *section = querySection(name); if (section) { return *section; } else { throw cybozu::Exception("config:getSection:no section") << name; } } /** load config file @param name [in] config file name */ void load(const std::string& name) { std::ifstream ifs(name.c_str()); if (!ifs) { throw cybozu::Exception("config:load") << name; } load(ifs); } /** load config file @param is [in] istream */ void load(std::istream& is) { Config::Section *section = appendSection(""); // global section assert(section); std::string line; while (std::getline(is, line)) { size_t n = line.size(); if (n == 0) continue; // skip if empty // remove '\r' at the end of line char c = line[n - 1]; if (c == '\r') { if (n == 1) continue; line.resize(n - 1); n--; } // skip if comment c = line[0]; if (c == ';' || c == '#') continue; // section if (c == '[') { if (line[n - 1] != ']') { throw cybozu::Exception("config:load:bad section") << line; } section = appendSection(line.substr(1, n - 2)); continue; } std::string key, value; config_local::split(key, value, line); section->append(key, value); } } /** get map */ const Config::Map& getMap() const { return map_; } /** convert section to string */ std::string toString() const { std::string ret; for (Map::const_iterator i = map_.begin(), ie = map_.end(); i != ie; ++i) { if (!i->first.empty()) { ret += "[" + i->first + "]\n"; } ret += i->second.toString(); } return ret; } private: Map map_; }; } // end of cybozu <|endoftext|>
<commit_before>/************************************************ * with_lcp.hpp * DICT * * Copyright (c) 2015-2017, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef DICT_WITH_LCP_HPP_ #define DICT_WITH_LCP_HPP_ #include "internal/lcp_trait.hpp" #include "internal/tree_list.hpp" namespace dict { /************************************************ * Declaration: class with_lcp<UPs...> ************************************************/ template <template <typename, typename> class... UpdatingPolicies> struct with_lcp { template <typename TextIndex, typename Trait> class policy; }; // class with_lcp<UPs...> /************************************************ * Declaration: class with_lcp<UPs...>::policy<TI, T> ************************************************/ template <template <typename, typename> class... UPs> template <typename TextIndex, typename Trait> class with_lcp<UPs...>::policy : public internal::chained_updater<UPs...> ::template updater< policy<TextIndex, Trait>, internal::lcp_trait<Trait> > { public: // Public Type(s) using host_type = TextIndex; using size_type = typename Trait::size_type; private: // Private Types(s) using wm_type = typename Trait::wm_type; using event = typename Trait::event; using lcp_trait = internal::lcp_trait<Trait>; using updating_policies = typename internal::chained_updater<UPs...> ::template updater<policy, lcp_trait>; public: // Public Method(s) policy(wm_type const &wt); size_type lcp(size_type i) const; protected: // Protected Method(s) template <typename Sequence> void update(typename event::template after_inserting_first_term<Sequence> const &info); template <typename Sequence> void update(typename event::template after_inserting_term<Sequence> const &info); template <typename Sequence> void update(typename event::template after_inserting_sequence<Sequence> const &); private: // Private Property(ies) wm_type const &wm_; internal::tree_list lcpa_; size_type lcp_; }; // class with_lcp<UPs...>::policy<TI, T> /************************************************ * Implementation: class with_lcp<UPs...>::policy<TI, T> ************************************************/ template <template <typename, typename> class... UPs> template <typename TI, typename T> inline with_lcp<UPs...>::policy<TI, T>::policy(wm_type const &wt) : wm_(wt), lcp_(0) { // do nothing } template <template <typename, typename> class... UPs> template <typename TI, typename T> inline typename with_lcp<UPs...>::template policy<TI, T>::size_type with_lcp<UPs...>::policy<TI, T>::lcp(size_type i) const { return lcpa_[i]; } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> inline void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_first_term<Sequence> const &info) { // lcp_ = 0; lcpa_.insert(lcpa_.begin(), 0); updating_policies::update(typename lcp_trait::event::template after_inserting_lcp<Sequence>{ info.s, 0, 0, 0, 0 }); } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_term<Sequence> const &info) { auto pos = info.pos, psi_pos = info.psi_pos, lf_pos = info.lf_pos; auto const &wm = wm_; auto psi = [pos, lf_pos, &wm](size_type x) { return x == 0 ? pos : wm.psi(x - (x < lf_pos)); }; auto psi_hint = [pos, lf_pos, &wm](size_type x, typename wm_type::value_type hint) { return x == 0 ? pos : wm.psi(x - (x < lf_pos), hint); }; auto term_at_f = [lf_pos, &wm](size_type x) { return x == 0 ? 0 : wm.search(x + 1 - (x < lf_pos)); }; // calculate LCP[pos] auto lcpa_it = lcpa_.find(pos); auto old_lcp = lcpa_it ? *lcpa_it : 0; if (pos > 0 && psi_pos > 0 && psi(pos - 1) == psi_pos - 1) { auto c = term_at_f(pos); if (c != 0 && c == term_at_f(pos - 1)) { ++lcp_; } else { lcp_ = 0; } } else { auto x = pos, y = pos - 1; for (lcp_ = 0; lcp_ < old_lcp; ++lcp_) { x = psi(x); y = psi(y); } auto cx = term_at_f(x); decltype(cx) cy; while (cx != 0 && cx == (cy = term_at_f(y))) { x = psi_hint(x, cx); y = psi_hint(y, cy); cx = term_at_f(x); ++lcp_; } } if (lcpa_it && old_lcp == lcp_) { // re-calculate LCP[pos + 1] auto &lcp = *lcpa_it; auto x = pos + 1, y = pos; for (lcp = 0; lcp < old_lcp; ++lcp) { x = psi(x); y = psi(y); } auto cx = term_at_f(x); decltype(cx) cy; while (cx != 0 && cx == (cy = term_at_f(y))) { x = psi_hint(x, cx); y = psi_hint(y, cy); cx = term_at_f(x); ++lcp; } } lcpa_.insert(lcpa_it, lcp_); updating_policies::update( typename lcp_trait::event::template after_inserting_lcp<Sequence>{ info.s, info.num_inserted, pos, lcp_, lcpa_it ? *lcpa_it : 0 }); } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> inline void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_sequence<Sequence> const &) { // do nothing } } // namespace dict #endif // DICT_WITH_LCP_HPP_ <commit_msg>:art: Better local veriable name<commit_after>/************************************************ * with_lcp.hpp * DICT * * Copyright (c) 2015-2017, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef DICT_WITH_LCP_HPP_ #define DICT_WITH_LCP_HPP_ #include "internal/lcp_trait.hpp" #include "internal/tree_list.hpp" namespace dict { /************************************************ * Declaration: class with_lcp<UPs...> ************************************************/ template <template <typename, typename> class... UpdatingPolicies> struct with_lcp { template <typename TextIndex, typename Trait> class policy; }; // class with_lcp<UPs...> /************************************************ * Declaration: class with_lcp<UPs...>::policy<TI, T> ************************************************/ template <template <typename, typename> class... UPs> template <typename TextIndex, typename Trait> class with_lcp<UPs...>::policy : public internal::chained_updater<UPs...> ::template updater< policy<TextIndex, Trait>, internal::lcp_trait<Trait> > { public: // Public Type(s) using host_type = TextIndex; using size_type = typename Trait::size_type; private: // Private Types(s) using wm_type = typename Trait::wm_type; using event = typename Trait::event; using lcp_trait = internal::lcp_trait<Trait>; using updating_policies = typename internal::chained_updater<UPs...> ::template updater<policy, lcp_trait>; public: // Public Method(s) policy(wm_type const &wt); size_type lcp(size_type i) const; protected: // Protected Method(s) template <typename Sequence> void update(typename event::template after_inserting_first_term<Sequence> const &info); template <typename Sequence> void update(typename event::template after_inserting_term<Sequence> const &info); template <typename Sequence> void update(typename event::template after_inserting_sequence<Sequence> const &); private: // Private Property(ies) wm_type const &wm_; internal::tree_list lcpa_; size_type lcp_; }; // class with_lcp<UPs...>::policy<TI, T> /************************************************ * Implementation: class with_lcp<UPs...>::policy<TI, T> ************************************************/ template <template <typename, typename> class... UPs> template <typename TI, typename T> inline with_lcp<UPs...>::policy<TI, T>::policy(wm_type const &wt) : wm_(wt), lcp_(0) { // do nothing } template <template <typename, typename> class... UPs> template <typename TI, typename T> inline typename with_lcp<UPs...>::template policy<TI, T>::size_type with_lcp<UPs...>::policy<TI, T>::lcp(size_type i) const { return lcpa_[i]; } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> inline void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_first_term<Sequence> const &info) { // lcp_ = 0; lcpa_.insert(lcpa_.begin(), 0); updating_policies::update(typename lcp_trait::event::template after_inserting_lcp<Sequence>{ info.s, 0, 0, 0, 0 }); } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_term<Sequence> const &info) { auto pos = info.pos, psi_pos = info.psi_pos, lf_pos = info.lf_pos; auto const &wm = wm_; auto psi = [pos, lf_pos, &wm](size_type x) { return x == 0 ? pos : wm.psi(x - (x < lf_pos)); }; auto psi_hint = [pos, lf_pos, &wm](size_type x, typename wm_type::value_type hint) { return x == 0 ? pos : wm.psi(x - (x < lf_pos), hint); }; auto term_at_f = [lf_pos, &wm](size_type x) { return x == 0 ? 0 : wm.search(x + 1 - (x < lf_pos)); }; // calculate LCP[pos] auto lcpa_it = lcpa_.find(pos); auto old_lcp = lcpa_it ? *lcpa_it : 0; if (pos > 0 && psi_pos > 0 && psi(pos - 1) == psi_pos - 1) { auto c = term_at_f(pos); if (c != 0 && c == term_at_f(pos - 1)) { ++lcp_; } else { lcp_ = 0; } } else { auto x = pos, y = pos - 1; for (lcp_ = 0; lcp_ < old_lcp; ++lcp_) { x = psi(x); y = psi(y); } auto cx = term_at_f(x); decltype(cx) cy; while (cx != 0 && cx == (cy = term_at_f(y))) { x = psi_hint(x, cx); y = psi_hint(y, cy); cx = term_at_f(x); ++lcp_; } } if (lcpa_it && old_lcp == lcp_) { // re-calculate LCP[pos + 1] auto &next_lcp = *lcpa_it; auto x = pos + 1, y = pos; for (next_lcp = 0; next_lcp < old_lcp; ++next_lcp) { x = psi(x); y = psi(y); } auto cx = term_at_f(x); decltype(cx) cy; while (cx != 0 && cx == (cy = term_at_f(y))) { x = psi_hint(x, cx); y = psi_hint(y, cy); cx = term_at_f(x); ++next_lcp; } } lcpa_.insert(lcpa_it, lcp_); updating_policies::update( typename lcp_trait::event::template after_inserting_lcp<Sequence>{ info.s, info.num_inserted, pos, lcp_, lcpa_it ? *lcpa_it : 0 }); } template <template <typename, typename> class... UPs> template <typename TI, typename T> template <typename Sequence> inline void with_lcp<UPs...>::policy<TI, T>::update( typename event::template after_inserting_sequence<Sequence> const &) { // do nothing } } // namespace dict #endif // DICT_WITH_LCP_HPP_ <|endoftext|>
<commit_before>/** * This file defines facilities to perform concept-based overloading. */ #ifndef DUCK_REQUIRES_HPP #define DUCK_REQUIRES_HPP #include <duck/detail/mpl_extensions.hpp> #include <duck/models.hpp> #include <boost/config.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/copy_if.hpp> #include <boost/mpl/deref.hpp> #include <boost/mpl/find_if.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/pop_back.hpp> #include <boost/mpl/push_front.hpp> #include <boost/mpl/quote.hpp> #include <boost/mpl/vector.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace duck { // Note to self: Storing the visited concepts in a list ordered by concept // specificity could make things much more efficient. /** * Tag to signal the failure of a concept-based overload resolution. * * @note It is important that this stays an incomplete type. */ struct concept_based_overload_resolution_failed #if defined(BOOST_NO_CXX11_DECLTYPE_N3276) { // On GCC, incomplete types can't appear inside decltype. // Instead of failing on valid decltypes, we will trigger a link time // error when `concept_based_overload_resolution_failed` is used. ~concept_based_overload_resolution_failed(); } #endif ; /** * Trait that must be specialized by new concepts to specify a partial order * between concepts. * * @note It is only needed to specialize one side of the trait, i.e. * `is_more_specific_than<A, B> : true` does not require the definition * of `is_more_specific_than<B, A> : false` too. * * @note `is_more_specific_than<A, B>` is conceptually equivalent to `A < B` * where the `<` operator is a partial order meaning `A` is less * specific than `B`. */ template <typename A, typename B, typename Enable = void> struct is_more_specific_than : boost::mpl::not_<is_more_specific_than<B, A, Enable> > { }; /** * Specialization of the `is_more_specific_than` trait for the trivial case * where both concepts are the same, i.e. `is_more_specific_than<A, A>`. In * this trivial case, the trait is obviously false. */ template <typename Concept, typename Enable> struct is_more_specific_than<Concept, Concept, Enable> : boost::mpl::false_ { }; /** * Metafunction class returning the result of calling the function overloaded * by `Family` at the current stage of the overload resolution. * * @note This metafunction class may be specialized by each family of * overload, or the family may define a * `perform_overload<OverloadResolution>` nested metafunction class * accepting arguments to perform the overload. */ template <typename Family, typename OverloadResolution> struct perform_overload { template <typename ...Args> struct apply : boost::mpl::apply< typename Family::template perform_overload<OverloadResolution>, Args... > { }; }; namespace requires_detail { //! Compile-time data structure storing state during an overload resolution. template <typename Family, typename VisitedConcepts = boost::mpl::vector<> > struct overload_resolution { typedef VisitedConcepts visited_concepts; typedef Family family; typedef overload_resolution type; // to make it a metafunction }; /** * Add a `Concept` to the list of concepts visited during the current * overload resolution. */ template <typename Concept, typename OverloadResolution> struct mark_as_visited : overload_resolution< typename OverloadResolution::family, typename boost::mpl::push_front< typename OverloadResolution::visited_concepts, Concept >::type > { }; /** * Metafunction returning whether a `Concept` has already been visited during * the current overload resolution. */ template <typename Concept, typename OverloadResolution> struct has_visited : boost::mpl::contains< typename OverloadResolution::visited_concepts, Concept > { }; /** * Metafunction returning whether a `Concept` is the most specific that was * visited so far during an overload resolution. */ template <typename Concept, typename OverloadResolution> struct is_most_specific_so_far : boost::mpl::none_of< typename OverloadResolution::visited_concepts, is_more_specific_than<Concept, boost::mpl::_1> > { }; /** * Metafunction returning whether a `Concept` is the best match for a `Type` * so far during an overload resolution. */ template <typename Type, typename Concept, typename OverloadResolution> struct is_best_match_so_far : boost::mpl::and_< boost::mpl::not_<has_visited<Concept, OverloadResolution> >, is_most_specific_so_far<Concept, OverloadResolution>, models<Concept, Type> > { }; /** * Metafunction class returning whether a `Concept` is the most specific * concept modeled by a `Type` for which an overload exists according to * the family present in `OverloadResolution`. */ template <typename Type, typename Concept, typename OverloadResolution> class clause_passes { template <typename ...Args> struct result_of_calling_the_function_with : boost::mpl::apply< perform_overload< typename OverloadResolution::family, typename mark_as_visited<Concept, OverloadResolution>::type >, Args... > { }; template <typename ...Args> struct there_are_no_better_overloads : boost::is_same< typename result_of_calling_the_function_with<Args...>::type, concept_based_overload_resolution_failed > { }; public: template <typename ...Args> struct apply : boost::mpl::and_< is_best_match_so_far<Type, Concept, OverloadResolution>, there_are_no_better_overloads<Args...> > { }; }; //! Requires a `Type` to be a model of a `Concept` in a `require` clause. template <typename Concept, typename Type> struct model_of { typedef Concept concept; typedef Type model; }; template <typename T> struct is_model_of_clause : boost::mpl::false_ { }; template <typename Concept, typename Type> struct is_model_of_clause<model_of<Concept, Type> > : boost::mpl::true_ { }; //! Provides the current `OverloadResolution` state to a `require` clause. template <typename Family> struct overload_resolution_state { typedef overload_resolution<Family> type; }; template <typename ...Args> struct overload_resolution_state<overload_resolution<Args...> > { typedef overload_resolution<Args...> type; }; template <typename T> struct is_overload_resolution_state : boost::mpl::false_ { }; template <typename OverloadResolution> struct is_overload_resolution_state< overload_resolution_state<OverloadResolution> > : boost::mpl::true_ { }; /** * Provides the template parameters to pass to the next function that will be * tried in the same overload family. * * @note The overload information is handled by the library and must not be * passed here. */ template <typename ...Params> struct template_parameters; template <typename T> struct is_template_parameters : boost::mpl::false_ { }; template <typename ...Params> struct is_template_parameters<template_parameters<Params...> > : boost::mpl::true_ { }; template <typename ...Blob> struct requires_impl { template <typename F, typename Pack> struct apply_pack; template <typename F, template <typename ...> class Pack, typename ...Args> struct apply_pack<F, Pack<Args...> > : boost::mpl::apply<F, Args...> { }; typedef typename boost::mpl::back< boost::mpl::vector<Blob...> >::type return_type; typedef typename boost::mpl::pop_back< boost::mpl::vector<Blob...> >::type arguments; // Gather all the model_of clauses typedef typename boost::mpl::copy_if< arguments, boost::mpl::quote1<is_model_of_clause> >::type clauses; // Gather the template parameters to be passed to subsequent overloads typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_template_parameters> >::type>::type template_parameters; // Fetch the current overload resolution state typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_overload_resolution_state> >::type>::type::type current_state; struct clause_is_respected { template <typename Clause> struct apply : apply_pack< clause_passes< typename Clause::model, typename Clause::concept, current_state >, template_parameters > { }; }; typedef typename boost::mpl::all_of< clauses, clause_is_respected >::type type; static bool const value = type::value; }; } // end namespace requires_detail // Named parameters for `requires` using requires_detail::model_of; using requires_detail::overload_resolution_state; using requires_detail::template_parameters; /** * Metafunction to perform concept-based overloading. * * Examples of usage: * * typename requires< * model_of<SomeConcept, SomeType>, * model_of<SomeOtherConcept, SomeOtherType>, * * overload_resolution_state<State>, * template_parameters<SomeType, SomeOtherType>, * return_type * >::type */ template <typename ...Args> struct requires : boost::enable_if< requires_detail::requires_impl<Args...>, typename requires_detail::requires_impl<Args...>::return_type > { }; /** * Macro to enable concept overloading on a family of overloads. * * @param FUNCTION The name of the function that is overloaded using concepts. * @param CALL An expression calling the function. This expression can use * the templates parameters provided in `__VA_ARGS__`. * @param ... A list of `typename T` template parameters that will be usable * within the `CALL` expression. The `State` parameter is always * available within the `CALL` expression and it represents the * current state of the overload resolution. * * Once instantiated, this macro will create a type named `FUNCTION` inside a * `tag` namespace. This type should be used as the default overload * resolution state for overloads within this family. */ #define DUCK_ENABLE_CONCEPT_OVERLOADING(FUNCTION, CALL, .../*typenames*/) \ ::duck::concept_based_overload_resolution_failed FUNCTION(...); \ namespace tag { \ /* We can't call the structure FUNCTION because it would clash */ \ /* with the CALL expansion. */ \ struct BOOST_PP_CAT(FUNCTION, _tag) { \ template <typename State> \ struct perform_overload { \ template <__VA_ARGS__> \ struct apply { \ typedef decltype(CALL) type; \ }; \ }; \ }; \ /* Now we can make the alias */ \ typedef BOOST_PP_CAT(FUNCTION, _tag) FUNCTION; \ } \ /**/ } // end namespace duck #endif // !DUCK_REQUIRES_HPP <commit_msg>Fix a vicious bug with ADL:<commit_after>/** * This file defines facilities to perform concept-based overloading. */ #ifndef DUCK_REQUIRES_HPP #define DUCK_REQUIRES_HPP #include <duck/detail/mpl_extensions.hpp> #include <duck/models.hpp> #include <boost/config.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/copy_if.hpp> #include <boost/mpl/deref.hpp> #include <boost/mpl/find_if.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/pop_back.hpp> #include <boost/mpl/push_front.hpp> #include <boost/mpl/quote.hpp> #include <boost/mpl/vector.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace duck { // Note to self: Storing the visited concepts in a list ordered by concept // specificity could make things much more efficient. /** * Tag to signal the failure of a concept-based overload resolution. * * @note It is important that this stays an incomplete type. */ struct concept_based_overload_resolution_failed #if defined(BOOST_NO_CXX11_DECLTYPE_N3276) { // On GCC, incomplete types can't appear inside decltype. // Instead of failing on valid decltypes, we will trigger a link time // error when `concept_based_overload_resolution_failed` is used. ~concept_based_overload_resolution_failed(); } #endif ; /** * Trait that must be specialized by new concepts to specify a partial order * between concepts. * * @note It is only needed to specialize one side of the trait, i.e. * `is_more_specific_than<A, B> : true` does not require the definition * of `is_more_specific_than<B, A> : false` too. * * @note `is_more_specific_than<A, B>` is conceptually equivalent to `A < B` * where the `<` operator is a partial order meaning `A` is less * specific than `B`. */ template <typename A, typename B, typename Enable = void> struct is_more_specific_than : boost::mpl::not_<is_more_specific_than<B, A, Enable> > { }; /** * Specialization of the `is_more_specific_than` trait for the trivial case * where both concepts are the same, i.e. `is_more_specific_than<A, A>`. In * this trivial case, the trait is obviously false. */ template <typename Concept, typename Enable> struct is_more_specific_than<Concept, Concept, Enable> : boost::mpl::false_ { }; /** * Metafunction class returning the result of calling the function overloaded * by `Family` at the current stage of the overload resolution. * * @note This metafunction class may be specialized by each family of * overload, or the family may define a * `perform_overload<OverloadResolution>` nested metafunction class * accepting arguments to perform the overload. */ template <typename Family, typename OverloadResolution> struct perform_overload { template <typename ...Args> struct apply : boost::mpl::apply< typename Family::template perform_overload<OverloadResolution>, Args... > { }; }; namespace requires_detail { //! Compile-time data structure storing state during an overload resolution. template <typename Family, typename VisitedConcepts = boost::mpl::vector<> > struct overload_resolution { typedef VisitedConcepts visited_concepts; typedef Family family; typedef overload_resolution type; // to make it a metafunction }; /** * Add a `Concept` to the list of concepts visited during the current * overload resolution. */ template <typename Concept, typename OverloadResolution> struct mark_as_visited : overload_resolution< typename OverloadResolution::family, typename boost::mpl::push_front< typename OverloadResolution::visited_concepts, Concept >::type > { }; /** * Metafunction returning whether a `Concept` has already been visited during * the current overload resolution. */ template <typename Concept, typename OverloadResolution> struct has_visited : boost::mpl::contains< typename OverloadResolution::visited_concepts, Concept > { }; /** * Metafunction returning whether a `Concept` is the most specific that was * visited so far during an overload resolution. */ template <typename Concept, typename OverloadResolution> struct is_most_specific_so_far : boost::mpl::none_of< typename OverloadResolution::visited_concepts, is_more_specific_than<Concept, boost::mpl::_1> > { }; /** * Metafunction returning whether a `Concept` is the best match for a `Type` * so far during an overload resolution. */ template <typename Type, typename Concept, typename OverloadResolution> struct is_best_match_so_far : boost::mpl::and_< boost::mpl::not_<has_visited<Concept, OverloadResolution> >, is_most_specific_so_far<Concept, OverloadResolution>, models<Concept, Type> > { }; /** * Metafunction class returning whether a `Concept` is the most specific * concept modeled by a `Type` for which an overload exists according to * the family present in `OverloadResolution`. */ template <typename Type, typename Concept, typename OverloadResolution> class clause_passes { template <typename ...Args> struct result_of_calling_the_function_with : boost::mpl::apply< perform_overload< typename OverloadResolution::family, typename mark_as_visited<Concept, OverloadResolution>::type >, Args... > { }; template <typename ...Args> struct there_are_no_better_overloads : boost::is_same< typename result_of_calling_the_function_with<Args...>::type, concept_based_overload_resolution_failed > { }; public: template <typename ...Args> struct apply : boost::mpl::and_< is_best_match_so_far<Type, Concept, OverloadResolution>, there_are_no_better_overloads<Args...> > { }; }; //! Requires a `Type` to be a model of a `Concept` in a `require` clause. template <typename Concept, typename Type> struct model_of { typedef Concept concept; typedef Type model; }; template <typename T> struct is_model_of_clause : boost::mpl::false_ { }; template <typename Concept, typename Type> struct is_model_of_clause<model_of<Concept, Type> > : boost::mpl::true_ { }; //! Provides the current `OverloadResolution` state to a `require` clause. template <typename Family> struct overload_resolution_state { typedef overload_resolution<Family> type; }; template <typename ...Args> struct overload_resolution_state<overload_resolution<Args...> > { typedef overload_resolution<Args...> type; }; template <typename T> struct is_overload_resolution_state : boost::mpl::false_ { }; template <typename OverloadResolution> struct is_overload_resolution_state< overload_resolution_state<OverloadResolution> > : boost::mpl::true_ { }; /** * Provides the template parameters to pass to the next function that will be * tried in the same overload family. * * @note The overload information is handled by the library and must not be * passed here. */ template <typename ...Params> struct template_parameters; template <typename T> struct is_template_parameters : boost::mpl::false_ { }; template <typename ...Params> struct is_template_parameters<template_parameters<Params...> > : boost::mpl::true_ { }; template <typename ...Blob> struct requires_impl { template <typename F, typename Pack> struct apply_pack; template <typename F, template <typename ...> class Pack, typename ...Args> struct apply_pack<F, Pack<Args...> > : boost::mpl::apply<F, Args...> { }; typedef typename boost::mpl::back< boost::mpl::vector<Blob...> >::type return_type; typedef typename boost::mpl::pop_back< boost::mpl::vector<Blob...> >::type arguments; // Gather all the model_of clauses typedef typename boost::mpl::copy_if< arguments, boost::mpl::quote1<is_model_of_clause> >::type clauses; // Gather the template parameters to be passed to subsequent overloads typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_template_parameters> >::type>::type template_parameters; // Fetch the current overload resolution state typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_overload_resolution_state> >::type>::type::type current_state; struct clause_is_respected { template <typename Clause> struct apply : apply_pack< clause_passes< typename Clause::model, typename Clause::concept, current_state >, template_parameters > { }; }; typedef typename boost::mpl::all_of< clauses, clause_is_respected >::type type; static bool const value = type::value; }; } // end namespace requires_detail // Named parameters for `requires` using requires_detail::model_of; using requires_detail::overload_resolution_state; using requires_detail::template_parameters; /** * Metafunction to perform concept-based overloading. * * Examples of usage: * * typename requires< * model_of<SomeConcept, SomeType>, * model_of<SomeOtherConcept, SomeOtherType>, * * overload_resolution_state<State>, * template_parameters<SomeType, SomeOtherType>, * return_type * >::type */ template <typename ...Args> struct requires : boost::enable_if< requires_detail::requires_impl<Args...>, typename requires_detail::requires_impl<Args...>::return_type > { }; /** * Macro to enable concept overloading on a family of overloads. * * @param FUNCTION The name of the function that is overloaded using concepts. * @param CALL An expression calling the function. This expression can use * the templates parameters provided in `__VA_ARGS__`. * @param ... A list of `typename T` template parameters that will be usable * within the `CALL` expression. The `State` parameter is always * available within the `CALL` expression and it represents the * current state of the overload resolution. * * Once instantiated, this macro will create a type named `FUNCTION` inside a * `tag` namespace. This type should be used as the default overload * resolution state for overloads within this family. */ #define DUCK_ENABLE_CONCEPT_OVERLOADING(FUNCTION, CALL, .../*typenames*/) \ ::duck::concept_based_overload_resolution_failed FUNCTION(...); \ /* This MUST be defined in the same namespace as the FUNCTION in */ \ /* order for FUNCTION to be found via ADL later on. */ \ struct BOOST_PP_CAT(FUNCTION, __LINE__) { \ template <typename State> \ struct perform_overload { \ template <__VA_ARGS__> \ struct apply { \ typedef decltype(CALL) type; \ }; \ }; \ }; \ namespace tag { \ typedef BOOST_PP_CAT(FUNCTION, __LINE__) FUNCTION; \ } \ /**/ } // end namespace duck #endif // !DUCK_REQUIRES_HPP <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _ROUTER_HPP_ #define _ROUTER_HPP_ #include <string> #include <vector> #include "module.hpp" #include "flit.hpp" #include "credit.hpp" #include "flitchannel.hpp" #include "channel.hpp" #include "config_utils.hpp" typedef Channel<Credit> CreditChannel; class Router : public Module { protected: int _id; int _inputs; int _outputs; int _input_speedup; int _output_speedup; float _internal_speedup; float _partial_internal_cycles; int _crossbar_delay; int _credit_delay; vector<FlitChannel *> _input_channels; vector<CreditChannel *> _input_credits; vector<FlitChannel *> _output_channels; vector<CreditChannel *> _output_credits; vector<bool> _channel_faults; Credit *_NewCredit( int vcs = 1 ); void _RetireCredit( Credit *c ); public: Router( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ); static Router *NewRouter( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ); void AddInputChannel( FlitChannel *channel, CreditChannel *backchannel ); void AddOutputChannel( FlitChannel *channel, CreditChannel *backchannel ); void Evaluate( ); inline void Update( ) { WriteOutputs( ); } virtual void ReadInputs( ) = 0; virtual void InternalStep( ) = 0; virtual void WriteOutputs( ) = 0; void OutChannelFault( int c, bool fault = true ); bool IsFaultyOutput( int c ) const; int GetID( ) const; virtual int GetCredit(int out, int vc_begin, int vc_end ) const = 0; virtual int GetBuffer(int i = -1) const = 0; virtual int GetReceivedFlits(int i = -1) const = 0; virtual int GetSentFlits(int i = -1) const = 0; virtual void ResetFlitStats() = 0; int NumOutputs(){return _outputs;} }; #endif <commit_msg>change floats to doubles<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _ROUTER_HPP_ #define _ROUTER_HPP_ #include <string> #include <vector> #include "module.hpp" #include "flit.hpp" #include "credit.hpp" #include "flitchannel.hpp" #include "channel.hpp" #include "config_utils.hpp" typedef Channel<Credit> CreditChannel; class Router : public Module { protected: int _id; int _inputs; int _outputs; int _input_speedup; int _output_speedup; double _internal_speedup; double _partial_internal_cycles; int _crossbar_delay; int _credit_delay; vector<FlitChannel *> _input_channels; vector<CreditChannel *> _input_credits; vector<FlitChannel *> _output_channels; vector<CreditChannel *> _output_credits; vector<bool> _channel_faults; Credit *_NewCredit( int vcs = 1 ); void _RetireCredit( Credit *c ); public: Router( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ); static Router *NewRouter( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ); void AddInputChannel( FlitChannel *channel, CreditChannel *backchannel ); void AddOutputChannel( FlitChannel *channel, CreditChannel *backchannel ); void Evaluate( ); inline void Update( ) { WriteOutputs( ); } virtual void ReadInputs( ) = 0; virtual void InternalStep( ) = 0; virtual void WriteOutputs( ) = 0; void OutChannelFault( int c, bool fault = true ); bool IsFaultyOutput( int c ) const; int GetID( ) const; virtual int GetCredit(int out, int vc_begin, int vc_end ) const = 0; virtual int GetBuffer(int i = -1) const = 0; virtual int GetReceivedFlits(int i = -1) const = 0; virtual int GetSentFlits(int i = -1) const = 0; virtual void ResetFlitStats() = 0; int NumOutputs(){return _outputs;} }; #endif <|endoftext|>
<commit_before>#pragma once /* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com) 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 "signal_slot.hpp" namespace nstd { using namespace std::string_literals; template<typename T> class live_property { public: using value_type = T; struct value_changing_context { const live_property &property; const value_type &new_value; bool cancel = false; }; live_property(const std::string &name, const value_type &value = value_type()) : signal_value_changing{ "/live_property/"s + name + "/signal_value_changing"s }, signal_value_changed{ "/live_property/"s + name + "/signal_value_changed"s }, _name{ name }, _value{ value } { } live_property(const live_property &other) { operator= (other._value); } live_property(live_property &&other) { operator=(std::forward<live_property>(other)); } live_property &operator=(value_type &&value) { return move_value(std::forward<value_type>(value)); } live_property &operator=(live_property &&other) { return operator=(std::move(other._value)); } live_property &operator=(const live_property &other) { return operator= (other._value); } live_property &operator=(const value_type &value) { return assign_value(value); } std::string_view name() const { return _name; } const value_type &value() const { return _value; } operator value_type() const { return _value; } live_property &operator +=(const value_type &value) { return move_value(_value + value); } live_property &operator +=(const live_property &other) { return operator += (other._value); } live_property &operator -=(const value_type &value) { return move_value(_value - value); } live_property &operator -=(const live_property &other) { return operator -= (other._value); } live_property &operator *=(const value_type &value) { return move_value(_value * value); } live_property &operator *=(const live_property &other) { return operator *= (other._value); } live_property &operator /=(const value_type &value) { return move_value(_value / value); } live_property &operator /=(const live_property &other) { return operator /= (other._value); } live_property &operator >>=(const value_type &value) { return move_value(_value >> value); } live_property &operator >>=(const live_property &other) { return operator >>= (other._value); } live_property &operator <<=(const value_type &value) { return move_value(_value << value); } live_property &operator <<=(const live_property &other) { return operator <<= (other._value); } live_property &operator &=(const value_type &value) { return move_value(_value & value); } live_property &operator &=(const live_property &other) { return operator &= (other._value); } live_property &operator |=(const value_type &value) { return move_value(_value | value); } live_property &operator |=(const live_property &other) { return operator |= (other._value); } live_property &operator ^=(const value_type &value) { return move_value(_value ^ value); } live_property &operator ^=(const live_property &other) { return operator ^= (other._value); } live_property &operator %=(const value_type &value) { return move_value(_value % value); } live_property &operator %=(const live_property &other) { return operator %= (other._value); } live_property &operator ++() { auto value { _value }; if (emit_changing(++value)) { ++_value; emit_changed(); } return *this; } live_property operator ++(int) { live_property return_value{ _name, _value }; return operator ++(), return_value; } live_property &operator --() { auto value { _value }; if (emit_changing(--value)) { --_value; emit_changed(); } return *this; } live_property operator --(int) { live_property return_value{ _name, _value }; return operator --(), return_value; } nstd::signal_slot::signal<value_changing_context&> signal_value_changing {}; nstd::signal_slot::signal<const live_property&> signal_value_changed {}; private: live_property &assign_value(const value_type &value) { if (emit_changing(value)) { _value = value; emit_changed(); } return *this; } live_property &move_value(value_type &&value) { if (emit_changing(value)) { _value = std::forward<value_type>(value); emit_changed(); } return *this; } bool emit_changing(const value_type &value) { value_changing_context context{ *this, value }; signal_value_changing.emit(context); return !context.cancel; } void emit_changed() { signal_value_changed.emit(*this); } std::string _name {}; value_type _value {}; }; } <commit_msg>a thread safe version of live_property was implemented<commit_after>#pragma once /* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com) 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 "signal_slot.hpp" namespace nstd { using namespace std::string_literals; template<typename T> class live_property { public: using value_type = T; struct value_changing_context { const live_property &property; const value_type &new_value; bool cancel = false; }; live_property(const std::string &name, const value_type &value = value_type()) : signal_value_changing{ u8"/live_property/"s + name + u8"/signal_value_changing"s }, signal_value_changed{ u8"/live_property/"s + name + u8"/signal_value_changed"s }, _name{ name }, _value{ value } { } live_property(const live_property &other) { operator= (other._value); } live_property(live_property &&other) { operator=(std::forward<live_property>(other)); } live_property &operator=(value_type &&value) { return move_value(std::forward<value_type>(value)); } live_property &operator=(live_property &&other) { return operator=(std::move(other._value)); } live_property &operator=(const live_property &other) { return operator= (other._value); } live_property &operator=(const value_type &value) { return assign_value(value); } std::string_view name() const { return _name; } const value_type &value() const { return _value; } operator value_type() const { return _value; } live_property &operator +=(const value_type &value) { return move_value(_value + value); } live_property &operator +=(const live_property &other) { return operator += (other._value); } live_property &operator -=(const value_type &value) { return move_value(_value - value); } live_property &operator -=(const live_property &other) { return operator -= (other._value); } live_property &operator *=(const value_type &value) { return move_value(_value * value); } live_property &operator *=(const live_property &other) { return operator *= (other._value); } live_property &operator /=(const value_type &value) { return move_value(_value / value); } live_property &operator /=(const live_property &other) { return operator /= (other._value); } live_property &operator >>=(const value_type &value) { return move_value(_value >> value); } live_property &operator >>=(const live_property &other) { return operator >>= (other._value); } live_property &operator <<=(const value_type &value) { return move_value(_value << value); } live_property &operator <<=(const live_property &other) { return operator <<= (other._value); } live_property &operator &=(const value_type &value) { return move_value(_value & value); } live_property &operator &=(const live_property &other) { return operator &= (other._value); } live_property &operator |=(const value_type &value) { return move_value(_value | value); } live_property &operator |=(const live_property &other) { return operator |= (other._value); } live_property &operator ^=(const value_type &value) { return move_value(_value ^ value); } live_property &operator ^=(const live_property &other) { return operator ^= (other._value); } live_property &operator %=(const value_type &value) { return move_value(_value % value); } live_property &operator %=(const live_property &other) { return operator %= (other._value); } live_property &operator ++() { auto value { _value }; if (emit_changing(++value)) { ++_value; emit_changed(); } return *this; } live_property operator ++(int) { live_property return_value{ _name, _value }; return operator ++(), return_value; } live_property &operator --() { auto value { _value }; if (emit_changing(--value)) { --_value; emit_changed(); } return *this; } live_property operator --(int) { live_property return_value{ _name, _value }; return operator --(), return_value; } nstd::signal_slot::signal<value_changing_context&> signal_value_changing {}; nstd::signal_slot::signal<const live_property&> signal_value_changed {}; private: live_property &assign_value(const value_type &value) { if (emit_changing(value)) { _value = value; emit_changed(); } return *this; } live_property &move_value(value_type &&value) { if (emit_changing(value)) { _value = std::forward<value_type>(value); emit_changed(); } return *this; } bool emit_changing(const value_type &value) { value_changing_context context{ *this, value }; signal_value_changing.emit(context); return !context.cancel; } void emit_changed() { signal_value_changed.emit(*this); } std::string _name {}; value_type _value {}; }; template<typename T> class live_property_ts { public: using value_type = T; struct value_changing_context { const live_property_ts &property; const value_type &new_value; bool cancel = false; }; live_property_ts(const std::string &name, const value_type &value = value_type()) : signal_value_changing{ u8"/live_property_ts/"s + name + u8"/signal_value_changing"s }, signal_value_changed{ u8"/live_property_ts/"s + name + u8"/signal_value_changed"s }, _name{ name }, _value{ value } { } live_property_ts(const live_property_ts &other) { operator= (other._value); } live_property_ts(live_property_ts &&other) { operator=(std::forward<live_property_ts>(other)); } live_property_ts &operator=(value_type &&value) { std::scoped_lock lock { _lock }; return move_value(std::forward<value_type>(value)); } live_property_ts &operator=(live_property_ts &&other) { std::scoped_lock lock { _lock }; return operator=(std::move(other._value)); } live_property_ts &operator=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator= (other._value); } live_property_ts &operator=(const value_type &value) { std::scoped_lock lock { _lock }; return assign_value(value); } std::string_view name() const { std::scoped_lock lock { _lock }; return _name; } const value_type &value() const { std::scoped_lock lock { _lock }; return _value; } operator value_type() const { std::scoped_lock lock { _lock }; return _value; } live_property_ts &operator +=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value + value); } live_property_ts &operator +=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator += (other._value); } live_property_ts &operator -=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value - value); } live_property_ts &operator -=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator -= (other._value); } live_property_ts &operator *=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value * value); } live_property_ts &operator *=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator *= (other._value); } live_property_ts &operator /=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value / value); } live_property_ts &operator /=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator /= (other._value); } live_property_ts &operator >>=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value >> value); } live_property_ts &operator >>=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator >>= (other._value); } live_property_ts &operator <<=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value << value); } live_property_ts &operator <<=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator <<= (other._value); } live_property_ts &operator &=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value & value); } live_property_ts &operator &=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator &= (other._value); } live_property_ts &operator |=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value | value); } live_property_ts &operator |=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator |= (other._value); } live_property_ts &operator ^=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value ^ value); } live_property_ts &operator ^=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator ^= (other._value); } live_property_ts &operator %=(const value_type &value) { std::scoped_lock lock { _lock }; return move_value(_value % value); } live_property_ts &operator %=(const live_property_ts &other) { std::scoped_lock lock { _lock }; return operator %= (other._value); } live_property_ts &operator ++() { std::scoped_lock lock { _lock }; auto value { _value }; if (emit_changing(++value)) { ++_value; emit_changed(); } return *this; } live_property_ts operator ++(int) { std::scoped_lock lock { _lock }; live_property_ts return_value{ _name, _value }; return operator ++(), return_value; } live_property_ts &operator --() { std::scoped_lock lock { _lock }; auto value { _value }; if (emit_changing(--value)) { --_value; emit_changed(); } return *this; } live_property_ts operator --(int) { std::scoped_lock lock { _lock }; live_property_ts return_value{ _name, _value }; return operator --(), return_value; } nstd::signal_slot::signal<value_changing_context&> signal_value_changing {}; nstd::signal_slot::signal<const live_property_ts&> signal_value_changed {}; private: live_property_ts &assign_value(const value_type &value) { if (emit_changing(value)) { _value = value; emit_changed(); } return *this; } live_property_ts &move_value(value_type &&value) { if (emit_changing(value)) { _value = std::forward<value_type>(value); emit_changed(); } return *this; } bool emit_changing(const value_type &value) { value_changing_context context{ *this, value }; signal_value_changing.emit(context); return !context.cancel; } void emit_changed() { signal_value_changed.emit(*this); } std::string _name {}; value_type _value {}; std::mutex _lock {}; }; } <|endoftext|>
<commit_before>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include <map> #include <string> // FIXME: should be moved into a Jupyter interp struct that then gets returned // from create. int pipeToJupyterFD = -1; namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - size of MIME type string (including the terminating 0) // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); write(pipeToJupyterFD, &sizeLong, 1); long dictSize = contentDict.size(); write(pipeToJupyterFD, &dictSize, sizeof(long)); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; long mimeTypeSize = (long)mimeType.size(); write(pipeToJupyterFD, &mimeTypeSize, sizeof(long)); write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1); const MIMEDataRef& mimeData = iContent.second; write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long)); write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size); } } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) { auto interp = new cling::Interpreter(argc, argv, llvmdir); pipeToJupyterFD = pipefd; return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Stringify a cling::Value static std::string ValueToString(const cling::Value& V) { std::string valueString; { llvm::raw_ostringstream os(valueString); V.print(os); } return valueString; } /// Evaluate a string of code. Returns nullptr on failure. /// Returns a string representation of the expression (can be "") on success. char* cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code, &V); if (Res != cling::Interpreter::kSuccess) return nullptr; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); if (!V.isValid()) return strdup(""); return strdup(valueString(V)); } void cling_eval_free(char* str) { free(str); } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = *(int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <commit_msg>Typos.<commit_after>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <string> #include <cstring> // FIXME: should be moved into a Jupyter interp struct that then gets returned // from create. int pipeToJupyterFD = -1; namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - size of MIME type string (including the terminating 0) // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); write(pipeToJupyterFD, &sizeLong, 1); long dictSize = contentDict.size(); write(pipeToJupyterFD, &dictSize, sizeof(long)); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; long mimeTypeSize = (long)mimeType.size(); write(pipeToJupyterFD, &mimeTypeSize, sizeof(long)); write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1); const MIMEDataRef& mimeData = iContent.second; write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long)); write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size); } } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) { auto interp = new cling::Interpreter(argc, argv, llvmdir); pipeToJupyterFD = pipefd; return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Stringify a cling::Value static std::string ValueToString(const cling::Value& V) { std::string valueString; { llvm::raw_string_ostream os(valueString); V.print(os); } return valueString; } /// Evaluate a string of code. Returns nullptr on failure. /// Returns a string representation of the expression (can be "") on success. char* cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code, &V); if (Res != cling::Interpreter::kSuccess) return nullptr; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); if (!V.isValid()) return strdup(""); return strdup(ValueToString(V).c_str()); } void cling_eval_free(char* str) { free(str); } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = (int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* 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/. */ #ifndef __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <sstream> #include <ctime> #include <limits> #include <iomanip> using namespace std; namespace MiniZinc { inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; exit(EXIT_FAILURE); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=(int*)0, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( 0!=arg.compare( 0, keyword.size(), keyword ) ) continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return false; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); if ( !( iss >> (*pResult) ) ) { if ( fValueOptional ) { --i; return true; } cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; } #endif // __MINIZINC_FLATTENER_H__ <commit_msg>Pointer conversion used to be strict in MSVC 2013 pre-update5<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* 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/. */ #ifndef __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <sstream> #include <ctime> #include <limits> #include <iomanip> using namespace std; namespace MiniZinc { inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; exit(EXIT_FAILURE); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=nullptr, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( 0!=arg.compare( 0, keyword.size(), keyword ) ) continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return false; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); if ( !( iss >> (*pResult) ) ) { if ( fValueOptional ) { --i; return true; } cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; } #endif // __MINIZINC_FLATTENER_H__ <|endoftext|>
<commit_before>/* Copyright 2013, 2015 Rogier van Dalen. This file is part of Rogier van Dalen's Range library for C++. This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file Define a reverse() function, which reverses a range by swapping directions on the fly. */ #ifndef RANGE_REVERSE_HPP_INCLUDED #define RANGE_REVERSE_HPP_INCLUDED #include <type_traits> #include <boost/utility/enable_if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/apply.hpp> #include "utility/returns.hpp" #include "core.hpp" #include "detail/underlying.hpp" namespace range { template <class Underlying> struct reverse_view { static_assert (is_view <Underlying>::value, "reverse_view only works with a view."); friend class ::range::detail::callable::get_underlying; Underlying underlying_; public: template <class Argument> explicit reverse_view (Argument && argument) : underlying_ (std::forward <Argument> (argument)) {} typedef Underlying underlying_type; Underlying & underlying() { return underlying_; } Underlying const & underlying() const { return underlying_; } private: friend class operation::member_access; auto default_direction() const RETURNS (range::default_direction (underlying_)); template <class Direction> typename result_of_or <callable::empty ( direction::callable::reverse (Direction), Underlying const &) >::type empty (Direction const & direction) const { return range::empty (direction::reverse (direction), underlying_); } template <class Direction> typename result_of_or <callable::size ( direction::callable::reverse (Direction), Underlying const &) >::type size (Direction const & direction) const { return range::size (direction::reverse (direction), underlying_); } // first and drop are implemented in namespace operation (below) where it is // easier to distinguish between qualifications. }; struct reverse_view_tag; template <class Underlying> struct tag_of_qualified <reverse_view <Underlying>> { typedef reverse_view_tag type; }; namespace operation { namespace reverse_detail { struct make_reverse_view { template <class Range> auto operator() (Range && range) const RETURNS (range::reverse_view <typename std::decay <Range>::type> (std::forward <Range> (range))); }; } // namespace reverse_detail template <class RangeTag, class Directions, class Range, class Enable = void> struct reverse : helper::call_with_last <1, Directions, reverse_detail::make_reverse_view> {}; } // namespace operation namespace apply { namespace automatic_arguments { template <class Directions, class Other, class Ranges, class Enable = void> struct reverse : operation::unimplemented {}; template <class Directions, class Range> struct reverse <Directions, meta::vector<>, meta::vector <Range>> : operation::reverse < typename range::tag_of <Range>::type, Directions, Range &&> {}; } // namespace automatic_arguments template <class ... Arguments> struct reverse : automatic_arguments::categorise_arguments_default_direction < automatic_arguments::call_with_view <automatic_arguments::reverse >::apply, meta::vector <Arguments ...>>::type {}; } // namespace apply namespace callable { struct reverse : generic <apply::reverse> {}; } // namespace callable /** Return a view of the range with the elements reversed. This works for any direction that the range is used in that has a reverse. For example, first (front, reverse (r)) is equivalent to first (back, r). This simply wraps the range so that the directions for all operations are converted on the fly by direction::reverse(). \param directions The directions that the view should be in. If no directions are given, the default direction is used. \param range The range to be reversed. It is turned into a view before it is stored inside the return type. */ static auto const reverse = callable::reverse(); namespace operation { template <class Direction, class ReverseView> struct first <reverse_view_tag, Direction, ReverseView, typename boost::enable_if <has < callable::first (direction::callable::reverse (Direction), range::detail::callable::get_underlying (ReverseView)) >>::type> { auto operator() (Direction const & direction, ReverseView && reverse_view) const RETURNS (range::first (direction::reverse (direction), range::detail::get_underlying ( std::forward <ReverseView> (reverse_view)))); }; /** Implement "drop". There is no need for specific implementations for drop_one or for different types for Increment: passing them through to the underlying range works. */ template <class Direction, class Increment, class ReverseView> struct drop <reverse_view_tag, Direction, Increment, ReverseView, typename boost::enable_if <has < callable::drop (direction::callable::reverse (Direction), Increment, range::detail::callable::get_underlying (ReverseView)) >>::type> { auto operator() (Direction const & direction, Increment const & increment, ReverseView && reverse_view) const RETURNS (range::reverse (range::drop (direction::reverse (direction), increment, range::detail::get_underlying ( std::forward <ReverseView> (reverse_view))))); }; }} // namespace range::operation #endif // RANGE_REVERSE_HPP_INCLUDED <commit_msg>More explicit constructors for "reverse_view"<commit_after>/* Copyright 2013, 2015 Rogier van Dalen. This file is part of Rogier van Dalen's Range library for C++. This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file Define a reverse() function, which reverses a range by swapping directions on the fly. */ #ifndef RANGE_REVERSE_HPP_INCLUDED #define RANGE_REVERSE_HPP_INCLUDED #include <type_traits> #include <boost/utility/enable_if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/apply.hpp> #include "utility/returns.hpp" #include "core.hpp" #include "detail/underlying.hpp" namespace range { template <class Underlying> struct reverse_view { static_assert (is_view <Underlying>::value, "reverse_view only works with a view."); friend class ::range::detail::callable::get_underlying; Underlying underlying_; public: explicit reverse_view (Underlying && underlying) : underlying_ (std::forward <Underlying> (underlying)) {} explicit reverse_view (Underlying const & underlying) : underlying_ (underlying) {} typedef Underlying underlying_type; Underlying & underlying() { return underlying_; } Underlying const & underlying() const { return underlying_; } private: friend class operation::member_access; auto default_direction() const RETURNS (range::default_direction (underlying_)); template <class Direction> typename result_of_or <callable::empty ( direction::callable::reverse (Direction), Underlying const &) >::type empty (Direction const & direction) const { return range::empty (direction::reverse (direction), underlying_); } template <class Direction> typename result_of_or <callable::size ( direction::callable::reverse (Direction), Underlying const &) >::type size (Direction const & direction) const { return range::size (direction::reverse (direction), underlying_); } // first and drop are implemented in namespace operation (below) where it is // easier to distinguish between qualifications. }; struct reverse_view_tag; template <class Underlying> struct tag_of_qualified <reverse_view <Underlying>> { typedef reverse_view_tag type; }; namespace operation { namespace reverse_detail { struct make_reverse_view { template <class Range> auto operator() (Range && range) const RETURNS (range::reverse_view <typename std::decay <Range>::type> (std::forward <Range> (range))); }; } // namespace reverse_detail template <class RangeTag, class Directions, class Range, class Enable = void> struct reverse : helper::call_with_last <1, Directions, reverse_detail::make_reverse_view> {}; } // namespace operation namespace apply { namespace automatic_arguments { template <class Directions, class Other, class Ranges, class Enable = void> struct reverse : operation::unimplemented {}; template <class Directions, class Range> struct reverse <Directions, meta::vector<>, meta::vector <Range>> : operation::reverse < typename range::tag_of <Range>::type, Directions, Range &&> {}; } // namespace automatic_arguments template <class ... Arguments> struct reverse : automatic_arguments::categorise_arguments_default_direction < automatic_arguments::call_with_view <automatic_arguments::reverse >::apply, meta::vector <Arguments ...>>::type {}; } // namespace apply namespace callable { struct reverse : generic <apply::reverse> {}; } // namespace callable /** Return a view of the range with the elements reversed. This works for any direction that the range is used in that has a reverse. For example, first (front, reverse (r)) is equivalent to first (back, r). This simply wraps the range so that the directions for all operations are converted on the fly by direction::reverse(). \param directions The directions that the view should be in. If no directions are given, the default direction is used. \param range The range to be reversed. It is turned into a view before it is stored inside the return type. */ static auto const reverse = callable::reverse(); namespace operation { template <class Direction, class ReverseView> struct first <reverse_view_tag, Direction, ReverseView, typename boost::enable_if <has < callable::first (direction::callable::reverse (Direction), range::detail::callable::get_underlying (ReverseView)) >>::type> { auto operator() (Direction const & direction, ReverseView && reverse_view) const RETURNS (range::first (direction::reverse (direction), range::detail::get_underlying ( std::forward <ReverseView> (reverse_view)))); }; /** Implement "drop". There is no need for specific implementations for drop_one or for different types for Increment: passing them through to the underlying range works. */ template <class Direction, class Increment, class ReverseView> struct drop <reverse_view_tag, Direction, Increment, ReverseView, typename boost::enable_if <has < callable::drop (direction::callable::reverse (Direction), Increment, range::detail::callable::get_underlying (ReverseView)) >>::type> { auto operator() (Direction const & direction, Increment const & increment, ReverseView && reverse_view) const RETURNS (range::reverse (range::drop (direction::reverse (direction), increment, range::detail::get_underlying ( std::forward <ReverseView> (reverse_view))))); }; }} // namespace range::operation #endif // RANGE_REVERSE_HPP_INCLUDED <|endoftext|>
<commit_before>#ifndef V_SMC_PARTICLE_HPP #define V_SMC_PARTICLE_HPP #include <algorithm> #include <limits> #include <cstddef> #include <mkl_vml.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <vDist/utilities/buffer.hpp> namespace vSMC { enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC}; template <class T> class Particle { public : Particle (std::size_t N, void (*copy)(std::size_t, std::size_t, T &)) : particle_num(N), particle(N), sum_weight(0), weight(N), log_weight(N), replication(N), copy_particle(copy) {} std::size_t size () const { return particle_num; } T &Value () { return particle; } const T &Value () const { return particle; } const double SumWeight () const { return sum_weight; } const double *Weight () const { return weight; } const double *LogWeight () const { return log_weight; } void SetLogWeight (const double *lweight) { cblas_dcopy(particle_num, lweight, 1, log_weight, 1); set_weight(); } void AddLogWeight (const double *lweight) { vdAdd(particle_num, lweight, log_weight, log_weight); set_weight(); } double ESS () const { return sum_weight * sum_weight / cblas_dnrm2(particle_num, weight, 1); } void Resample (ResampleScheme scheme, const gsl_rng *rng) { std::cout << "RESAMPLING" << std::endl; switch (scheme) { case MULTINOMIAL : resample_multinomial(rng); break; case RESIDUAL : resample_residual(rng); break; case STRATIFIED : resample_stratified(rng); break; case SYSTEMATIC : resample_systematic(rng); break; default : resample_residual(rng); } } private : typedef vDist::internal::Buffer<double> dBuffer; typedef vDist::internal::Buffer<unsigned> uBuffer; std::size_t particle_num; T particle; double sum_weight; dBuffer weight; dBuffer log_weight; uBuffer replication; void (*copy_particle) (std::size_t, std::size_t, T &); void set_weight () { double max_weight = -std::numeric_limits<double>::infinity(); cblas_dcopy(particle_num, log_weight, 1, weight, 1); for (std::size_t i = 0; i != particle_num; ++i) max_weight = std::max(max_weight, weight[i]); for (std::size_t i = 0; i != particle_num; ++i) weight[i] -= max_weight; vdExp(particle_num, weight, weight); sum_weight = cblas_dasum(particle_num, weight, 1); } void resample_multinomial (const gsl_rng *rng) { gsl_ran_multinomial(rng, particle_num, particle_num, weight, replication); resample_do(); } void resample_residual (const gsl_rng *rng) { cblas_dscal(particle_num, particle_num, weight, 1); vdFloor(particle_num, weight, weight); std::size_t size = particle_num; size -= sum_weight; gsl_ran_multinomial(rng, particle_num, size, weight, replication); for (std::size_t i = 0; i != particle_num; ++i) replication[i] += weight[i]; resample_do(); } void resample_stratified (const gsl_rng *rng) {} void resample_systematic (const gsl_rng *rng) {} void resample_do () { std::size_t from = 0; std::size_t time = 0; for (std::size_t i = 0; i != particle_num; ++i) { if (!replication[i]) { // replication[i] has zero child if (time == replication[from]) { // all childs of replication[from] are already copied time = 0; ++from; while (!replication[from]) ++from; } copy_particle(from, i, particle); ++time; } } } }; // class Particle } // namespace vSMC #endif // V_SMC_PARTICLE_HPP <commit_msg>set_weight adjust log_weight first and them compute weight<commit_after>#ifndef V_SMC_PARTICLE_HPP #define V_SMC_PARTICLE_HPP #include <algorithm> #include <limits> #include <cstddef> #include <mkl_vml.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <vDist/utilities/buffer.hpp> namespace vSMC { enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC}; template <class T> class Particle { public : Particle (std::size_t N, void (*copy)(std::size_t, std::size_t, T &)) : particle_num(N), particle(N), sum_weight(0), weight(N), log_weight(N), replication(N), copy_particle(copy) {} std::size_t size () const { return particle_num; } T &Value () { return particle; } const T &Value () const { return particle; } const double SumWeight () const { return sum_weight; } const double *Weight () const { return weight; } const double *LogWeight () const { return log_weight; } void SetLogWeight (const double *lweight) { cblas_dcopy(particle_num, lweight, 1, log_weight, 1); set_weight(); } void AddLogWeight (const double *lweight) { vdAdd(particle_num, lweight, log_weight, log_weight); set_weight(); } double ESS () const { return sum_weight * sum_weight / cblas_dnrm2(particle_num, weight, 1); } void Resample (ResampleScheme scheme, const gsl_rng *rng) { std::cout << "RESAMPLING" << std::endl; switch (scheme) { case MULTINOMIAL : resample_multinomial(rng); break; case RESIDUAL : resample_residual(rng); break; case STRATIFIED : resample_stratified(rng); break; case SYSTEMATIC : resample_systematic(rng); break; default : resample_residual(rng); } } private : typedef vDist::internal::Buffer<double> dBuffer; typedef vDist::internal::Buffer<unsigned> uBuffer; std::size_t particle_num; T particle; double sum_weight; dBuffer weight; dBuffer log_weight; uBuffer replication; void (*copy_particle) (std::size_t, std::size_t, T &); void set_weight () { double max_weight = -std::numeric_limits<double>::infinity(); for (std::size_t i = 0; i != particle_num; ++i) max_weight = std::max(max_weight, log_weight[i]); for (std::size_t i = 0; i != particle_num; ++i) log_weight[i] -= max_weight; vdExp(particle_num, log_weight, weight); sum_weight = cblas_dasum(particle_num, weight, 1); } void resample_multinomial (const gsl_rng *rng) { gsl_ran_multinomial(rng, particle_num, particle_num, weight, replication); resample_do(); } void resample_residual (const gsl_rng *rng) { cblas_dscal(particle_num, particle_num, weight, 1); vdFloor(particle_num, weight, weight); std::size_t size = particle_num; size -= sum_weight; gsl_ran_multinomial(rng, particle_num, size, weight, replication); for (std::size_t i = 0; i != particle_num; ++i) replication[i] += weight[i]; resample_do(); } void resample_stratified (const gsl_rng *rng) {} void resample_systematic (const gsl_rng *rng) {} void resample_do () { std::size_t from = 0; std::size_t time = 0; for (std::size_t i = 0; i != particle_num; ++i) { if (!replication[i]) { // replication[i] has zero child if (time == replication[from]) { // all childs of replication[from] are already copied time = 0; ++from; while (!replication[from]) ++from; } copy_particle(from, i, particle); ++time; } } } }; // class Particle } // namespace vSMC #endif // V_SMC_PARTICLE_HPP <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <sstream> #include <algorithm> #include <chrono> #include <thread> #include <cfloat> #include <SDL.h> #include "compiler.h" #include "TCPServer.hpp" #ifdef _WINDOWS #include <tchar.h> int wmain(int argc, _TCHAR* argv[]) { #else int main(int argc, char** argv) { #endif // defaults unsigned int port = 60601; // command line params if (argc >= 2) { port = atoi(argv[1]); } if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } std::cout << "hello sdl" << std::endl; SDL_Window* windowHandle = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (windowHandle == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return 1; } // setup joysticks SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); bool dirty = false; unsigned int numJoysticks = SDL_NumJoysticks(); auto numAxes = new unsigned int[numJoysticks]; auto numButtons = new unsigned int[numJoysticks]; int activeJoystick = 0; // starting with 0 std::cout << numJoysticks << " joystic(s) found." << std::endl; if (numJoysticks == 0) { std::cout << "quitting..." << std::endl; return 1; } for (unsigned int i = 0; i < numJoysticks; i++) { numAxes[i] = 0; numButtons[i] = 0; SDL_Joystick* stick = SDL_JoystickOpen(i); if (stick) { printf("Opened Joystick 0\n"); printf("Name: %s\n", SDL_JoystickNameForIndex(i)); // printf("Devise GUID: %s\n", SDL_JoystickGetGUIDString(i)); printf("Number of Axes: %d\n", SDL_JoystickNumAxes(stick)); printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(stick)); printf("Number of Balls: %d\n", SDL_JoystickNumBalls(stick)); numAxes[i] = SDL_JoystickNumAxes(stick); numButtons[i] = SDL_JoystickNumButtons(stick); } else { printf("Couldn't open Joystick 0\n"); } } auto axesBuffer = new float*[numJoysticks]; auto buttonsBuffer = new float*[numJoysticks]; for (unsigned int i = 0; i < numJoysticks; i++) { axesBuffer[i] = new float[numAxes[i]]; for (unsigned int j = 0; j < numAxes[i]; j++) { axesBuffer[i][j] = 0; } buttonsBuffer[i] = new float[numButtons[i]]; for (unsigned int j = 0; j < numButtons[i]; j++) { buttonsBuffer[i][j] = 0; } } // setup networking boost::asio::io_service io_service; TCPServer server(io_service, 60601); auto lastFrame = 0.0f; auto minFrameDelta = FLT_MAX; auto maxFrameDelta = 0.0f; // run! std::cout << "entering main loop" << std::endl; std::cout << "active joystic is: " << activeJoystick << std::endl; bool running = true; while (running) { try { io_service.poll(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } SDL_JoystickUpdate(); SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { running = false; } else if (e.type == SDL_KEYDOWN) { if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_LEFT) { activeJoystick = (activeJoystick - 1) % numJoysticks; std::cout << "active joystic is: " << activeJoystick << std::endl; } if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_RIGHT) { activeJoystick = (activeJoystick + 1) % numJoysticks; std::cout << "active joystic is: " << activeJoystick << std::endl; } } else if (e.type == SDL_JOYAXISMOTION) { if (e.jaxis.which == activeJoystick) { float oldValue = axesBuffer[activeJoystick][e.jaxis.axis]; float newValue = (float)e.jaxis.value / (float)(0xffff / 2); dirty = dirty || (oldValue != newValue); axesBuffer[activeJoystick][e.jaxis.axis] = newValue; } } else if (e.type == SDL_JOYBUTTONDOWN) { if (e.jaxis.which == activeJoystick) { dirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 1.0f); buttonsBuffer[activeJoystick][e.jbutton.button] = 1.0f; } } else if (e.type == SDL_JOYBUTTONUP) { if (e.jaxis.which == activeJoystick) { dirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 0.0f); buttonsBuffer[activeJoystick][e.jbutton.button] = 0.0f; } } } // transfer frame float time = (float)SDL_GetTicks() / 1000.0f; if (dirty) { for (unsigned int i = 0; i < numAxes[activeJoystick]; i++) { std::stringstream sstr; sstr << "axis-" << i; server.inputAnalog(sstr.str(), axesBuffer[activeJoystick][i], time, -1.0f, 1.0f); } for (unsigned int i = 0; i < numButtons[activeJoystick]; i++) { std::stringstream sstr; sstr << "button-" << i; server.inputDigital(sstr.str(), buttonsBuffer[activeJoystick][i], time); } auto dt = time - lastFrame; minFrameDelta = std::min(minFrameDelta, dt); maxFrameDelta = std::max(maxFrameDelta, dt); std::cout << "dt: " << dt * 1000 << "ms, min dt: " << minFrameDelta * 1000 << "ms, max dt: " << maxFrameDelta << std::endl; lastFrame = time; } dirty = false; // deschedule this thread to save some resources... // time passed to the function is lower bound std::this_thread::sleep_for(std::chrono::milliseconds(1)); } SDL_Quit(); return 0; } <commit_msg>changed the input logger, so that it only transfers changed frames, i.e. I made it event based.<commit_after>#include <iostream> #include <vector> #include <sstream> #include <algorithm> #include <chrono> #include <thread> #include <cfloat> #include <SDL.h> #include "compiler.h" #include "TCPServer.hpp" struct Sample { float value; bool valueChanged; }; #ifdef _WINDOWS #include <tchar.h> int wmain(int argc, _TCHAR* argv[]) { #else int main(int argc, char** argv) { #endif // defaults unsigned int port = 60601; // command line params if (argc >= 2) { port = atoi(argv[1]); } if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } std::cout << "hello sdl" << std::endl; SDL_Window* windowHandle = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (windowHandle == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return 1; } // setup joysticks SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); unsigned int numJoysticks = SDL_NumJoysticks(); auto numAxes = new unsigned int[numJoysticks]; auto numButtons = new unsigned int[numJoysticks]; bool globalDirtyFlag = false; int activeJoystick = 0; // starting with 0 std::cout << numJoysticks << " joystic(s) found." << std::endl; if (numJoysticks == 0) { std::cout << "quitting..." << std::endl; return 1; } for (unsigned int i = 0; i < numJoysticks; i++) { numAxes[i] = 0; numButtons[i] = 0; SDL_Joystick* stick = SDL_JoystickOpen(i); if (stick) { printf("Opened Joystick 0\n"); printf("Name: %s\n", SDL_JoystickNameForIndex(i)); // printf("Devise GUID: %s\n", SDL_JoystickGetGUIDString(i)); printf("Number of Axes: %d\n", SDL_JoystickNumAxes(stick)); printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(stick)); printf("Number of Balls: %d\n", SDL_JoystickNumBalls(stick)); numAxes[i] = SDL_JoystickNumAxes(stick); numButtons[i] = SDL_JoystickNumButtons(stick); } else { printf("Couldn't open Joystick 0\n"); } } auto axesBuffer = new Sample*[numJoysticks]; auto buttonsBuffer = new Sample*[numJoysticks]; for (unsigned int i = 0; i < numJoysticks; i++) { axesBuffer[i] = new Sample[numAxes[i]]; for (unsigned int j = 0; j < numAxes[i]; j++) { Sample sample = {}; sample.valueChanged = false; sample.value = 0.0f; axesBuffer[i][j] = sample; } buttonsBuffer[i] = new Sample[numButtons[i]]; for (unsigned int j = 0; j < numButtons[i]; j++) { Sample sample = {}; sample.valueChanged = false; sample.value = 0.0f; buttonsBuffer[i][j] = sample; } } // setup networking boost::asio::io_service io_service; TCPServer server(io_service, 60601); auto lastFrame = 0.0f; auto minFrameDelta = FLT_MAX; auto maxFrameDelta = 0.0f; // run! std::cout << "entering main loop" << std::endl; std::cout << "active joystic is: " << activeJoystick << std::endl; bool running = true; while (running) { try { io_service.poll(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } SDL_JoystickUpdate(); SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { running = false; } else if (e.type == SDL_KEYDOWN) { if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_LEFT) { activeJoystick = (activeJoystick - 1) % numJoysticks; std::cout << "active joystic is: " << activeJoystick << std::endl; } if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_RIGHT) { activeJoystick = (activeJoystick + 1) % numJoysticks; std::cout << "active joystic is: " << activeJoystick << std::endl; } } else if (e.type == SDL_JOYAXISMOTION) { if (e.jaxis.which == activeJoystick) { float oldValue = axesBuffer[activeJoystick][e.jaxis.axis].value; float newValue = (float)e.jaxis.value / (float)(0xffff / 2); auto dirty = (oldValue != newValue); if (dirty) { Sample sample = {}; sample.valueChanged = true; sample.value = newValue; axesBuffer[activeJoystick][e.jaxis.axis] = sample; } globalDirtyFlag = globalDirtyFlag || dirty; } } else if (e.type == SDL_JOYBUTTONDOWN) { if (e.jaxis.which == activeJoystick) { Sample sample = {}; sample.valueChanged = true; sample.value = 1.0f; buttonsBuffer[activeJoystick][e.jbutton.button] = sample; globalDirtyFlag = true; } } else if (e.type == SDL_JOYBUTTONUP) { if (e.jaxis.which == activeJoystick) { Sample sample = {}; sample.valueChanged = true; sample.value = 0.0f; buttonsBuffer[activeJoystick][e.jbutton.button] = sample; globalDirtyFlag = true; } } } // transfer frame float time = (float)SDL_GetTicks() / 1000.0f; for (unsigned int i = 0; i < numAxes[activeJoystick]; i++) { if (axesBuffer[activeJoystick][i].valueChanged) { std::stringstream sstr; sstr << "axis-" << i; server.inputAnalog(sstr.str(), axesBuffer[activeJoystick][i].value, time, -1.0f, 1.0f); axesBuffer[activeJoystick][i].valueChanged = false; } } for (unsigned int i = 0; i < numButtons[activeJoystick]; i++) { if (buttonsBuffer[activeJoystick][i].valueChanged) { std::stringstream sstr; sstr << "button-" << i; server.inputDigital(sstr.str(), buttonsBuffer[activeJoystick][i].value, time); buttonsBuffer[activeJoystick][i].valueChanged = false; } } if (globalDirtyFlag) { auto dt = time - lastFrame; minFrameDelta = std::min(minFrameDelta, dt); maxFrameDelta = std::max(maxFrameDelta, dt); std::cout << "dt: " << dt * 1000 << "ms, min dt: " << minFrameDelta * 1000 << "ms, max dt: " << maxFrameDelta << std::endl; lastFrame = time; globalDirtyFlag = false; } // deschedule this thread to save some resources... // time passed to the function is lower bound std::this_thread::sleep_for(std::chrono::milliseconds(1)); } SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * entity_bind.cpp - bindings for Ogre::Entity ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgreEntity.h> #include "ogre_manager.h" EntityHandle create_entity(const char* entity_name, const char* mesh_file) { Ogre::Entity* entity = Ogre::Root::getSingletonPtr()->getSceneManager(OgreManager::getSingletonPtr()->get_active_scene_manager_name())->createEntity(entity_name, mesh_file); return reinterpret_cast<EntityHandle>(entity); } void entity_set_cast_shadows(EntityHandle handle, int enabled) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); entity->setCastShadows(enabled); } int entity_get_cast_shadows(EntityHandle handle) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); return entity->getCastShadows(); } int entity_get_receives_shadows(EntityHandle handle) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); return entity->getReceivesShadows(); } void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); entity->setMaterialName(Ogre::String(material_name), Ogre::String(group_name)); } // How do we handle the fact that Ogre::Entity is an Ogre::MovableObject ? // Duplicate? /* Ogre::Entity::operator=(Ogre::Entity const&) Ogre::Entity::Entity(Ogre::Entity const&) Ogre::Entity::~Entity() Ogre::Entity::getMesh() const Ogre::Entity::getSubEntity(unsigned int) const Ogre::Entity::getSubEntity(std::string const&) const Ogre::Entity::getNumSubEntities() const Ogre::Entity::clone(std::string const&) const Ogre::Entity::setMaterialName(std::string const&, std::string const&) Ogre::Entity::setMaterial(Ogre::MaterialPtr const&) Ogre::Entity::_notifyCurrentCamera(Ogre::Camera*) Ogre::Entity::setRenderQueueGroup(unsigned char) Ogre::Entity::setRenderQueueGroupAndPriority(unsigned char, unsigned short) Ogre::Entity::getBoundingBox() const Ogre::Entity::getChildObjectsBoundingBox() const Ogre::Entity::_updateRenderQueue(Ogre::RenderQueue*) Ogre::Entity::getMovableType() const Ogre::Entity::getAnimationState(std::string const&) const Ogre::Entity::getAllAnimationStates() const Ogre::Entity::setDisplaySkeleton(bool) Ogre::Entity::getDisplaySkeleton() const Ogre::Entity::getManualLodLevel(unsigned int) const Ogre::Entity::getNumManualLodLevels() const Ogre::Entity::getCurrentLodIndex() Ogre::Entity::setMeshLodBias(float, unsigned short, unsigned short) Ogre::Entity::setMaterialLodBias(float, unsigned short, unsigned short) Ogre::Entity::setPolygonModeOverrideable(bool) Ogre::Entity::attachObjectToBone(std::string const&, Ogre::MovableObject*, Ogre::Quaternion const&, Ogre::Vector3 const&) Ogre::Entity::detachObjectFromBone(std::string const&) Ogre::Entity::detachObjectFromBone(Ogre::MovableObject*) Ogre::Entity::detachAllObjectsFromBone() Ogre::Entity::getAttachedObjectIterator() Ogre::Entity::getBoundingRadius() const Ogre::Entity::getWorldBoundingBox(bool) const Ogre::Entity::getWorldBoundingSphere(bool) const Ogre::Entity::getEdgeList() Ogre::Entity::hasEdgeList() Ogre::Entity::getShadowVolumeRenderableIterator(Ogre::ShadowTechnique, Ogre::Light const*, Ogre::HardwareIndexBufferSharedPtr*, bool, float, unsigned long) Ogre::Entity::_getBoneMatrices() const Ogre::Entity::_getNumBoneMatrices() const Ogre::Entity::hasSkeleton() const Ogre::Entity::getSkeleton() const Ogre::Entity::isHardwareAnimationEnabled() Ogre::Entity::_notifyAttached(Ogre::Node*, bool) Ogre::Entity::getSoftwareAnimationRequests() const Ogre::Entity::getSoftwareAnimationNormalsRequests() const Ogre::Entity::addSoftwareAnimationRequest(bool) Ogre::Entity::removeSoftwareAnimationRequest(bool) Ogre::Entity::shareSkeletonInstanceWith(Ogre::Entity*) Ogre::Entity::hasVertexAnimation() const Ogre::Entity::stopSharingSkeletonInstance() Ogre::Entity::sharesSkeletonInstance() const Ogre::Entity::getSkeletonInstanceSharingSet() const Ogre::Entity::refreshAvailableAnimationState() Ogre::Entity::_updateAnimation() Ogre::Entity::_isAnimated() const Ogre::Entity::_isSkeletonAnimated() const Ogre::Entity::_getSkelAnimVertexData() const Ogre::Entity::_getSoftwareVertexAnimVertexData() const Ogre::Entity::_getHardwareVertexAnimVertexData() const Ogre::Entity::_getSkelAnimTempBufferInfo() Ogre::Entity::_getVertexAnimTempBufferInfo() Ogre::Entity::getTypeFlags() const Ogre::Entity::getVertexDataForBinding() Ogre::Entity::chooseVertexDataForBinding(bool) Ogre::Entity::_getBuffersMarkedForAnimation() const Ogre::Entity::_markBuffersUsedForAnimation() Ogre::Entity::isInitialised() const Ogre::Entity::_initialise(bool) Ogre::Entity::_deinitialise() Ogre::Entity::backgroundLoadingComplete(Ogre::Resource*) Ogre::Entity::visitRenderables(Ogre::Renderable::Visitor*, bool) Ogre::Entity::_getMeshLodFactorTransformed() const Ogre::Entity::setSkipAnimationStateUpdate(bool) Ogre::Entity::getSkipAnimationStateUpdate() const Ogre::Entity::setAlwaysUpdateMainSkeleton(bool) Ogre::Entity::getAlwaysUpdateMainSkeleton() const Ogre::Entity::EntityShadowRenderable::operator=(Ogre::Entity::EntityShadowRenderable const&) Ogre::Entity::EntityShadowRenderable::EntityShadowRenderable(Ogre::Entity::EntityShadowRenderable const&) Ogre::Entity::EntityShadowRenderable::EntityShadowRenderable(Ogre::Entity*, Ogre::HardwareIndexBufferSharedPtr*, Ogre::VertexData const*, bool, Ogre::SubEntity*, bool) Ogre::Entity::EntityShadowRenderable::~EntityShadowRenderable() Ogre::Entity::EntityShadowRenderable::_createSeparateLightCap() Ogre::Entity::EntityShadowRenderable::getWorldTransforms(Ogre::Matrix4*) const Ogre::Entity::EntityShadowRenderable::getPositionBuffer() Ogre::Entity::EntityShadowRenderable::getWBuffer() Ogre::Entity::EntityShadowRenderable::rebindPositionBuffer(Ogre::VertexData const*, bool) Ogre::Entity::EntityShadowRenderable::isVisible() const */ /* Ogre::MovableObject::Listener Ogre::MovableObject::operator=(Ogre::MovableObject const&) Ogre::MovableObject::MovableObject(Ogre::MovableObject const&) Ogre::MovableObject::MovableObject() Ogre::MovableObject::MovableObject(std::string const&) Ogre::MovableObject::~MovableObject() Ogre::MovableObject::_notifyCreator(Ogre::MovableObjectFactory*) Ogre::MovableObject::_getCreator() const Ogre::MovableObject::_notifyManager(Ogre::SceneManager*) Ogre::MovableObject::_getManager() const Ogre::MovableObject::getName() const Ogre::MovableObject::getMovableType() const Ogre::MovableObject::getParentNode() const Ogre::MovableObject::getParentSceneNode() const Ogre::MovableObject::isParentTagPoint() const Ogre::MovableObject::_notifyAttached(Ogre::Node*, bool) Ogre::MovableObject::isAttached() const Ogre::MovableObject::detachFromParent() Ogre::MovableObject::isInScene() const Ogre::MovableObject::_notifyMoved() Ogre::MovableObject::_notifyCurrentCamera(Ogre::Camera*) Ogre::MovableObject::getBoundingBox() const Ogre::MovableObject::getBoundingRadius() const Ogre::MovableObject::getWorldBoundingBox(bool) const Ogre::MovableObject::getWorldBoundingSphere(bool) const Ogre::MovableObject::_updateRenderQueue(Ogre::RenderQueue*) Ogre::MovableObject::setVisible(bool) Ogre::MovableObject::getVisible() const Ogre::MovableObject::isVisible() const Ogre::MovableObject::setRenderingDistance(float) Ogre::MovableObject::getRenderingDistance() const Ogre::MovableObject::setUserAny(Ogre::Any const&) Ogre::MovableObject::getUserAny() const Ogre::MovableObject::getUserObjectBindings() Ogre::MovableObject::getUserObjectBindings() const Ogre::MovableObject::setRenderQueueGroup(unsigned char) Ogre::MovableObject::setRenderQueueGroupAndPriority(unsigned char, unsigned short) Ogre::MovableObject::getRenderQueueGroup() const Ogre::MovableObject::_getParentNodeFullTransform() const Ogre::MovableObject::setQueryFlags(unsigned int) Ogre::MovableObject::addQueryFlags(unsigned int) Ogre::MovableObject::removeQueryFlags(unsigned long) Ogre::MovableObject::getQueryFlags() const Ogre::MovableObject::setDefaultQueryFlags(unsigned int) Ogre::MovableObject::getDefaultQueryFlags() Ogre::MovableObject::setVisibilityFlags(unsigned int) Ogre::MovableObject::addVisibilityFlags(unsigned int) Ogre::MovableObject::removeVisibilityFlags(unsigned int) Ogre::MovableObject::getVisibilityFlags() const Ogre::MovableObject::setDefaultVisibilityFlags(unsigned int) Ogre::MovableObject::getDefaultVisibilityFlags() Ogre::MovableObject::setListener(Ogre::MovableObject::Listener*) Ogre::MovableObject::getListener() const Ogre::MovableObject::queryLights() const Ogre::MovableObject::getLightMask() const Ogre::MovableObject::setLightMask(unsigned int) Ogre::MovableObject::_getLightList() Ogre::MovableObject::getEdgeList() Ogre::MovableObject::hasEdgeList() Ogre::MovableObject::getShadowVolumeRenderableIterator(Ogre::ShadowTechnique, Ogre::Light const*, Ogre::HardwareIndexBufferSharedPtr*, bool, float, unsigned long) Ogre::MovableObject::getLightCapBounds() const Ogre::MovableObject::getDarkCapBounds(Ogre::Light const&, float) const Ogre::MovableObject::getReceivesShadows() Ogre::MovableObject::getPointExtrusionDistance(Ogre::Light const*) const Ogre::MovableObject::getTypeFlags() const Ogre::MovableObject::visitRenderables(Ogre::Renderable::Visitor*, bool) Ogre::MovableObject::setDebugDisplayEnabled(bool) Ogre::MovableObject::isDebugDisplayEnabled() const Ogre::MovableObject::Listener::operator=(Ogre::MovableObject::Listener const&) Ogre::MovableObject::Listener::Listener(Ogre::MovableObject::Listener const&) Ogre::MovableObject::Listener::Listener() Ogre::MovableObject::Listener::~Listener() Ogre::MovableObject::Listener::objectDestroyed(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectAttached(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectDetached(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectMoved(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectRendering(Ogre::MovableObject const*, Ogre::Camera const*) Ogre::MovableObject::Listener::objectQueryLights(Ogre::MovableObject const*) */ <commit_msg>wrapped Entity::getBoundingBox<commit_after>/****************************************************************************** * entity_bind.cpp - bindings for Ogre::Entity ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgreEntity.h> #include "ogre_manager.h" EntityHandle create_entity(const char* entity_name, const char* mesh_file) { Ogre::Entity* entity = Ogre::Root::getSingletonPtr()->getSceneManager(OgreManager::getSingletonPtr()->get_active_scene_manager_name())->createEntity(entity_name, mesh_file); return reinterpret_cast<EntityHandle>(entity); } void entity_set_cast_shadows(EntityHandle handle, int enabled) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); entity->setCastShadows(enabled); } int entity_get_cast_shadows(EntityHandle handle) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); return entity->getCastShadows(); } int entity_get_receives_shadows(EntityHandle handle) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); return entity->getReceivesShadows(); } void entity_set_material_name(EntityHandle handle, const char* material_name, const char* group_name) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); entity->setMaterialName(Ogre::String(material_name), Ogre::String(group_name)); } //Ogre::Entity::getBoundingBox() const AxisAlignedBoxHandle entity_get_bounding_box(EntityHandle handle) { Ogre::Entity* entity = reinterpret_cast<Ogre::Entity*>(handle); Ogre::AxisAlignedBox& box = const_cast<Ogre::AxisAlignedBox&>(entity->getBoundingBox()); return reinterpret_cast<AxisAlignedBoxHandle>(&box); } // How do we handle the fact that Ogre::Entity is an Ogre::MovableObject ? // Duplicate? /* Ogre::Entity::operator=(Ogre::Entity const&) Ogre::Entity::Entity(Ogre::Entity const&) Ogre::Entity::~Entity() Ogre::Entity::getMesh() const Ogre::Entity::getSubEntity(unsigned int) const Ogre::Entity::getSubEntity(std::string const&) const Ogre::Entity::getNumSubEntities() const Ogre::Entity::clone(std::string const&) const Ogre::Entity::setMaterialName(std::string const&, std::string const&) Ogre::Entity::setMaterial(Ogre::MaterialPtr const&) Ogre::Entity::_notifyCurrentCamera(Ogre::Camera*) Ogre::Entity::setRenderQueueGroup(unsigned char) Ogre::Entity::setRenderQueueGroupAndPriority(unsigned char, unsigned short) Ogre::Entity::getChildObjectsBoundingBox() const Ogre::Entity::_updateRenderQueue(Ogre::RenderQueue*) Ogre::Entity::getMovableType() const Ogre::Entity::getAnimationState(std::string const&) const Ogre::Entity::getAllAnimationStates() const Ogre::Entity::setDisplaySkeleton(bool) Ogre::Entity::getDisplaySkeleton() const Ogre::Entity::getManualLodLevel(unsigned int) const Ogre::Entity::getNumManualLodLevels() const Ogre::Entity::getCurrentLodIndex() Ogre::Entity::setMeshLodBias(float, unsigned short, unsigned short) Ogre::Entity::setMaterialLodBias(float, unsigned short, unsigned short) Ogre::Entity::setPolygonModeOverrideable(bool) Ogre::Entity::attachObjectToBone(std::string const&, Ogre::MovableObject*, Ogre::Quaternion const&, Ogre::Vector3 const&) Ogre::Entity::detachObjectFromBone(std::string const&) Ogre::Entity::detachObjectFromBone(Ogre::MovableObject*) Ogre::Entity::detachAllObjectsFromBone() Ogre::Entity::getAttachedObjectIterator() Ogre::Entity::getBoundingRadius() const Ogre::Entity::getWorldBoundingBox(bool) const Ogre::Entity::getWorldBoundingSphere(bool) const Ogre::Entity::getEdgeList() Ogre::Entity::hasEdgeList() Ogre::Entity::getShadowVolumeRenderableIterator(Ogre::ShadowTechnique, Ogre::Light const*, Ogre::HardwareIndexBufferSharedPtr*, bool, float, unsigned long) Ogre::Entity::_getBoneMatrices() const Ogre::Entity::_getNumBoneMatrices() const Ogre::Entity::hasSkeleton() const Ogre::Entity::getSkeleton() const Ogre::Entity::isHardwareAnimationEnabled() Ogre::Entity::_notifyAttached(Ogre::Node*, bool) Ogre::Entity::getSoftwareAnimationRequests() const Ogre::Entity::getSoftwareAnimationNormalsRequests() const Ogre::Entity::addSoftwareAnimationRequest(bool) Ogre::Entity::removeSoftwareAnimationRequest(bool) Ogre::Entity::shareSkeletonInstanceWith(Ogre::Entity*) Ogre::Entity::hasVertexAnimation() const Ogre::Entity::stopSharingSkeletonInstance() Ogre::Entity::sharesSkeletonInstance() const Ogre::Entity::getSkeletonInstanceSharingSet() const Ogre::Entity::refreshAvailableAnimationState() Ogre::Entity::_updateAnimation() Ogre::Entity::_isAnimated() const Ogre::Entity::_isSkeletonAnimated() const Ogre::Entity::_getSkelAnimVertexData() const Ogre::Entity::_getSoftwareVertexAnimVertexData() const Ogre::Entity::_getHardwareVertexAnimVertexData() const Ogre::Entity::_getSkelAnimTempBufferInfo() Ogre::Entity::_getVertexAnimTempBufferInfo() Ogre::Entity::getTypeFlags() const Ogre::Entity::getVertexDataForBinding() Ogre::Entity::chooseVertexDataForBinding(bool) Ogre::Entity::_getBuffersMarkedForAnimation() const Ogre::Entity::_markBuffersUsedForAnimation() Ogre::Entity::isInitialised() const Ogre::Entity::_initialise(bool) Ogre::Entity::_deinitialise() Ogre::Entity::backgroundLoadingComplete(Ogre::Resource*) Ogre::Entity::visitRenderables(Ogre::Renderable::Visitor*, bool) Ogre::Entity::_getMeshLodFactorTransformed() const Ogre::Entity::setSkipAnimationStateUpdate(bool) Ogre::Entity::getSkipAnimationStateUpdate() const Ogre::Entity::setAlwaysUpdateMainSkeleton(bool) Ogre::Entity::getAlwaysUpdateMainSkeleton() const Ogre::Entity::EntityShadowRenderable::operator=(Ogre::Entity::EntityShadowRenderable const&) Ogre::Entity::EntityShadowRenderable::EntityShadowRenderable(Ogre::Entity::EntityShadowRenderable const&) Ogre::Entity::EntityShadowRenderable::EntityShadowRenderable(Ogre::Entity*, Ogre::HardwareIndexBufferSharedPtr*, Ogre::VertexData const*, bool, Ogre::SubEntity*, bool) Ogre::Entity::EntityShadowRenderable::~EntityShadowRenderable() Ogre::Entity::EntityShadowRenderable::_createSeparateLightCap() Ogre::Entity::EntityShadowRenderable::getWorldTransforms(Ogre::Matrix4*) const Ogre::Entity::EntityShadowRenderable::getPositionBuffer() Ogre::Entity::EntityShadowRenderable::getWBuffer() Ogre::Entity::EntityShadowRenderable::rebindPositionBuffer(Ogre::VertexData const*, bool) Ogre::Entity::EntityShadowRenderable::isVisible() const */ /* Ogre::MovableObject::Listener Ogre::MovableObject::operator=(Ogre::MovableObject const&) Ogre::MovableObject::MovableObject(Ogre::MovableObject const&) Ogre::MovableObject::MovableObject() Ogre::MovableObject::MovableObject(std::string const&) Ogre::MovableObject::~MovableObject() Ogre::MovableObject::_notifyCreator(Ogre::MovableObjectFactory*) Ogre::MovableObject::_getCreator() const Ogre::MovableObject::_notifyManager(Ogre::SceneManager*) Ogre::MovableObject::_getManager() const Ogre::MovableObject::getName() const Ogre::MovableObject::getMovableType() const Ogre::MovableObject::getParentNode() const Ogre::MovableObject::getParentSceneNode() const Ogre::MovableObject::isParentTagPoint() const Ogre::MovableObject::_notifyAttached(Ogre::Node*, bool) Ogre::MovableObject::isAttached() const Ogre::MovableObject::detachFromParent() Ogre::MovableObject::isInScene() const Ogre::MovableObject::_notifyMoved() Ogre::MovableObject::_notifyCurrentCamera(Ogre::Camera*) Ogre::MovableObject::getBoundingBox() const Ogre::MovableObject::getBoundingRadius() const Ogre::MovableObject::getWorldBoundingBox(bool) const Ogre::MovableObject::getWorldBoundingSphere(bool) const Ogre::MovableObject::_updateRenderQueue(Ogre::RenderQueue*) Ogre::MovableObject::setVisible(bool) Ogre::MovableObject::getVisible() const Ogre::MovableObject::isVisible() const Ogre::MovableObject::setRenderingDistance(float) Ogre::MovableObject::getRenderingDistance() const Ogre::MovableObject::setUserAny(Ogre::Any const&) Ogre::MovableObject::getUserAny() const Ogre::MovableObject::getUserObjectBindings() Ogre::MovableObject::getUserObjectBindings() const Ogre::MovableObject::setRenderQueueGroup(unsigned char) Ogre::MovableObject::setRenderQueueGroupAndPriority(unsigned char, unsigned short) Ogre::MovableObject::getRenderQueueGroup() const Ogre::MovableObject::_getParentNodeFullTransform() const Ogre::MovableObject::setQueryFlags(unsigned int) Ogre::MovableObject::addQueryFlags(unsigned int) Ogre::MovableObject::removeQueryFlags(unsigned long) Ogre::MovableObject::getQueryFlags() const Ogre::MovableObject::setDefaultQueryFlags(unsigned int) Ogre::MovableObject::getDefaultQueryFlags() Ogre::MovableObject::setVisibilityFlags(unsigned int) Ogre::MovableObject::addVisibilityFlags(unsigned int) Ogre::MovableObject::removeVisibilityFlags(unsigned int) Ogre::MovableObject::getVisibilityFlags() const Ogre::MovableObject::setDefaultVisibilityFlags(unsigned int) Ogre::MovableObject::getDefaultVisibilityFlags() Ogre::MovableObject::setListener(Ogre::MovableObject::Listener*) Ogre::MovableObject::getListener() const Ogre::MovableObject::queryLights() const Ogre::MovableObject::getLightMask() const Ogre::MovableObject::setLightMask(unsigned int) Ogre::MovableObject::_getLightList() Ogre::MovableObject::getEdgeList() Ogre::MovableObject::hasEdgeList() Ogre::MovableObject::getShadowVolumeRenderableIterator(Ogre::ShadowTechnique, Ogre::Light const*, Ogre::HardwareIndexBufferSharedPtr*, bool, float, unsigned long) Ogre::MovableObject::getLightCapBounds() const Ogre::MovableObject::getDarkCapBounds(Ogre::Light const&, float) const Ogre::MovableObject::getReceivesShadows() Ogre::MovableObject::getPointExtrusionDistance(Ogre::Light const*) const Ogre::MovableObject::getTypeFlags() const Ogre::MovableObject::visitRenderables(Ogre::Renderable::Visitor*, bool) Ogre::MovableObject::setDebugDisplayEnabled(bool) Ogre::MovableObject::isDebugDisplayEnabled() const Ogre::MovableObject::Listener::operator=(Ogre::MovableObject::Listener const&) Ogre::MovableObject::Listener::Listener(Ogre::MovableObject::Listener const&) Ogre::MovableObject::Listener::Listener() Ogre::MovableObject::Listener::~Listener() Ogre::MovableObject::Listener::objectDestroyed(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectAttached(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectDetached(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectMoved(Ogre::MovableObject*) Ogre::MovableObject::Listener::objectRendering(Ogre::MovableObject const*, Ogre::Camera const*) Ogre::MovableObject::Listener::objectQueryLights(Ogre::MovableObject const*) */ <|endoftext|>
<commit_before><commit_msg>Fix 'close' menu action not quitting gracefully (fix #1401)<commit_after><|endoftext|>
<commit_before>// lua.hpp // Lua header files for C++ // <<extern "C">> not supplied automatically because Lua also compiles as C++ extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } <commit_msg>Remove c++ header for Lua.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #ifdef HAVE_CVS_IDENT #ident "$Id: main.cc,v 1.43 2006/04/28 15:44:37 steve Exp $" #endif # include "config.h" # include "parse_misc.h" # include "compile.h" # include "schedule.h" # include "vpi_priv.h" # include "statistics.h" # include <stdio.h> # include <stdlib.h> # include <string.h> # include <unistd.h> #if defined(HAVE_SYS_RESOURCE_H) # include <sys/time.h> # include <sys/resource.h> # if defined(LINUX) # include <asm/page.h> # endif #endif // defined(HAVE_SYS_RESOURCE_H) #if defined(HAVE_GETOPT_H) # include <getopt.h> #endif #if defined(__MINGW32__) # include <windows.h> #endif #if defined(__MINGW32__) && !defined(HAVE_GETOPT_H) extern "C" int getopt(int argc, char*argv[], const char*fmt); extern "C" int optind; extern "C" const char*optarg; #endif #if !defined(HAVE_LROUND) /* * If the system doesn't provide the lround function, then we provide * it ourselves here. It is simply the nearest integer, rounded away * from zero. */ # include <math.h> extern "C" long int lround(double x) { if (x >= 0.0) return (long)floor(x+0.5); else return (long)ceil(x-0.5); } #endif bool verbose_flag = false; static char log_buffer[4096]; #if defined(HAVE_SYS_RESOURCE_H) static void my_getrusage(struct rusage *a) { getrusage(RUSAGE_SELF, a); # if defined(LINUX) { FILE *statm; unsigned siz, rss, shd; statm = fopen("/proc/self/statm", "r"); if (!statm) { perror("/proc/self/statm"); return; } if (3<=fscanf(statm, "%u%u%u", &siz, &rss, &shd)) { a->ru_maxrss = PAGE_SIZE * siz; a->ru_idrss = PAGE_SIZE * rss; a->ru_ixrss = PAGE_SIZE * shd; } fclose(statm); } # endif } static void print_rusage(struct rusage *a, struct rusage *b) { double delta = a->ru_utime.tv_sec + a->ru_utime.tv_usec/1E6 + a->ru_stime.tv_sec + a->ru_stime.tv_usec/1E6 - b->ru_utime.tv_sec - b->ru_utime.tv_usec/1E6 - b->ru_stime.tv_sec - b->ru_stime.tv_usec/1E6 ; vpi_mcd_printf(1, " ... %G seconds," " %.1f/%.1f/%.1f KBytes size/rss/shared\n", delta, a->ru_maxrss/1024.0, (a->ru_idrss+a->ru_isrss)/1024.0, a->ru_ixrss/1024.0 ); } #else // ! defined(HAVE_SYS_RESOURCE_H) // Provide dummies struct rusage { int x; }; inline static void my_getrusage(struct rusage *) { } inline static void print_rusage(struct rusage *, struct rusage *){}; #endif // ! defined(HAVE_SYS_RESOURCE_H) unsigned module_cnt = 0; const char*module_tab[64]; extern void vpi_mcd_init(FILE *log); extern void vvp_vpi_init(void); int main(int argc, char*argv[]) { int opt; unsigned flag_errors = 0; const char*design_path = 0; struct rusage cycles[3]; const char *logfile_name = 0x0; FILE *logfile = 0x0; extern void vpi_set_vlog_info(int, char**); #ifdef __MINGW32__ /* In the Windows world, we get the first module path component relative the location where the binary lives. */ { char path[4096], *s; GetModuleFileName(NULL,path,1024); /* Get to the end. Search back twice for backslashes */ s = path + strlen(path); while (*s != '\\') s--; s--; while (*s != '\\') s--; strcpy(s,"\\lib\\ivl"); vpip_module_path[0] = strdup(path); } #endif while ((opt = getopt(argc, argv, "+hl:M:m:sv")) != EOF) switch (opt) { case 'h': fprintf(stderr, "Usage: vvp [options] input-file [+plusargs...]\n" "Options:\n" " -h Print this help message.\n" " -l file Logfile, '-' for <stderr>\n" " -M path VPI module directory\n" " -M - Clear VPI module path\n" " -m module Load vpi module.\n" " -s $stop right away.\n" " -v Verbose progress messages.\n" ); exit(0); case 'l': logfile_name = optarg; break; case 'M': if (strcmp(optarg,"-") == 0) { vpip_module_path_cnt = 0; vpip_module_path[0] = 0; } else { vpip_module_path[vpip_module_path_cnt++] = optarg; } break; case 'm': module_tab[module_cnt++] = optarg; break; case 's': schedule_stop(0); break; case 'v': verbose_flag = true; break; default: flag_errors += 1; } if (flag_errors) return flag_errors; if (optind == argc) { fprintf(stderr, "%s: no input file.\n", argv[0]); return -1; } design_path = argv[optind]; /* This is needed to get the MCD I/O routines ready for anything. It is done early because it is plausible that the compile might affect it, and it is cheap to do. */ if (logfile_name) { if (!strcmp(logfile_name, "-")) logfile = stderr; else { logfile = fopen(logfile_name, "w"); if (!logfile) { perror(logfile_name); exit(1); } setvbuf(logfile, log_buffer, _IOLBF, sizeof(log_buffer)); } } vpi_mcd_init(logfile); if (verbose_flag) { my_getrusage(cycles+0); vpi_mcd_printf(1, "Compiling VVP ...\n"); } vvp_vpi_init(); /* Make the extended arguments available to the simulation. */ vpi_set_vlog_info(argc-optind, argv+optind); compile_init(); for (unsigned idx = 0 ; idx < module_cnt ; idx += 1) vpip_load_module(module_tab[idx]); if (int rc = compile_design(design_path)) return rc; if (verbose_flag) { vpi_mcd_printf(1, "Compile cleanup...\n"); } compile_cleanup(); if (compile_errors > 0) { vpi_mcd_printf(1, "%s: Program not runnable, %u errors.\n", design_path, compile_errors); return compile_errors; } if (verbose_flag) { vpi_mcd_printf(1, " ... %8lu functors\n", count_functors); vpi_mcd_printf(1, " %8lu table\n", count_functors_table); vpi_mcd_printf(1, " %8lu bufif\n", count_functors_bufif); vpi_mcd_printf(1, " %8lu resolv\n",count_functors_resolv); vpi_mcd_printf(1, " %8lu variable\n", count_functors_var); vpi_mcd_printf(1, " ... %8lu opcodes (%lu bytes)\n", count_opcodes, (unsigned long)size_opcodes); vpi_mcd_printf(1, " ... %8lu nets\n", count_vpi_nets); vpi_mcd_printf(1, " ... %8lu memories\n", count_vpi_memories); vpi_mcd_printf(1, " ... %8lu scopes\n", count_vpi_scopes); } if (verbose_flag) { my_getrusage(cycles+1); print_rusage(cycles+1, cycles+0); vpi_mcd_printf(1, "Running ...\n"); } schedule_simulate(); if (verbose_flag) { my_getrusage(cycles+2); print_rusage(cycles+2, cycles+1); vpi_mcd_printf(1, "Event counts: (event pool = %lu)\n", count_event_pool); vpi_mcd_printf(1, " %8lu thread schedule events\n", count_thread_events); vpi_mcd_printf(1, " %8lu propagation events\n", count_prop_events); vpi_mcd_printf(1, " %8lu assign events\n", count_assign_events); vpi_mcd_printf(1, " %8lu other events\n", count_gen_events); } return 0; } /* * $Log: main.cc,v $ * Revision 1.43 2006/04/28 15:44:37 steve * Include math.h with lround implementation. * * Revision 1.42 2006/04/28 15:40:30 steve * lround takes double, not float. * * Revision 1.41 2006/04/27 05:04:59 steve * Detect missing lround function. * * Revision 1.40 2005/01/29 06:28:19 steve * Add the -s flag to start up interactive. * * Revision 1.39 2004/10/04 01:10:59 steve * Clean up spurious trailing white space. * * Revision 1.38 2003/06/25 04:04:19 steve * Fix mingw portability problems. * * Revision 1.37 2003/06/13 19:51:08 steve * Include verbose messages in log output. * * Revision 1.36 2003/05/15 16:51:09 steve * Arrange for mcd id=00_00_00_01 to go to stdout * as well as a user specified log file, set log * file to buffer lines. * * Add vpi_flush function, and clear up some cunfused * return codes from other vpi functions. * * Adjust $display and vcd/lxt messages to use the * standard output/log file. * * Revision 1.35 2003/03/13 04:36:57 steve * Remove the obsolete functor delete functions. * * Revision 1.34 2003/02/07 02:45:05 steve * Mke getopt ignore options after the file name. * * Revision 1.33 2003/01/18 23:55:35 steve * Add a means to clear the module search path. * * Revision 1.32 2003/01/06 23:57:26 steve * Schedule wait lists of threads as a single event, * to save on events. Also, improve efficiency of * event_s allocation. Add some event statistics to * get an idea where performance is really going. * * Revision 1.31 2002/09/18 03:34:07 steve * printf size warning. * * Revision 1.30 2002/08/12 01:35:08 steve * conditional ident string using autoconfig. * * Revision 1.29 2002/07/15 00:21:42 steve * Fix initialization of symbol table string heap. * * Revision 1.28 2002/07/05 20:08:44 steve * Count different types of functors. * * Revision 1.27 2002/07/05 17:14:15 steve * Names of vpi objects allocated as vpip_strings. * * Revision 1.26 2002/07/05 03:47:06 steve * Track opcode memory space. * * Revision 1.25 2002/07/05 02:50:58 steve * Remove the vpi object symbol table after compile. * * Revision 1.24 2002/04/12 02:44:02 steve * Formally define extended arguments to vvp. * * Revision 1.23 2002/03/01 05:43:14 steve * Add cleanup to verbose messages. * * Revision 1.22 2002/01/09 03:15:23 steve * Add vpi_get_vlog_info support. * * Revision 1.21 2001/10/20 01:03:42 steve * Print memory usage information if requested (Stephan Boettcher) */ <commit_msg> Get page size from sysconf.<commit_after>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #ifdef HAVE_CVS_IDENT #ident "$Id: main.cc,v 1.44 2007/02/16 23:30:14 steve Exp $" #endif # include "config.h" # include "parse_misc.h" # include "compile.h" # include "schedule.h" # include "vpi_priv.h" # include "statistics.h" # include <stdio.h> # include <stdlib.h> # include <string.h> # include <unistd.h> #if defined(HAVE_SYS_RESOURCE_H) # include <sys/time.h> # include <sys/resource.h> # if defined(LINUX) # include <asm/page.h> # endif #endif // defined(HAVE_SYS_RESOURCE_H) #if defined(HAVE_GETOPT_H) # include <getopt.h> #endif #if defined(__MINGW32__) # include <windows.h> #endif #if defined(__MINGW32__) && !defined(HAVE_GETOPT_H) extern "C" int getopt(int argc, char*argv[], const char*fmt); extern "C" int optind; extern "C" const char*optarg; #endif #if !defined(HAVE_LROUND) /* * If the system doesn't provide the lround function, then we provide * it ourselves here. It is simply the nearest integer, rounded away * from zero. */ # include <math.h> extern "C" long int lround(double x) { if (x >= 0.0) return (long)floor(x+0.5); else return (long)ceil(x-0.5); } #endif bool verbose_flag = false; static char log_buffer[4096]; #if defined(HAVE_SYS_RESOURCE_H) static void my_getrusage(struct rusage *a) { getrusage(RUSAGE_SELF, a); # if defined(LINUX) { FILE *statm; unsigned siz, rss, shd; long page_size = sysconf(_SC_PAGESIZE); if (page_size==-1) page_size=0; statm = fopen("/proc/self/statm", "r"); if (!statm) { perror("/proc/self/statm"); return; } if (3<=fscanf(statm, "%u%u%u", &siz, &rss, &shd)) { a->ru_maxrss = page_size * siz; a->ru_idrss = page_size * rss; a->ru_ixrss = page_size * shd; } fclose(statm); } # endif } static void print_rusage(struct rusage *a, struct rusage *b) { double delta = a->ru_utime.tv_sec + a->ru_utime.tv_usec/1E6 + a->ru_stime.tv_sec + a->ru_stime.tv_usec/1E6 - b->ru_utime.tv_sec - b->ru_utime.tv_usec/1E6 - b->ru_stime.tv_sec - b->ru_stime.tv_usec/1E6 ; vpi_mcd_printf(1, " ... %G seconds," " %.1f/%.1f/%.1f KBytes size/rss/shared\n", delta, a->ru_maxrss/1024.0, (a->ru_idrss+a->ru_isrss)/1024.0, a->ru_ixrss/1024.0 ); } #else // ! defined(HAVE_SYS_RESOURCE_H) // Provide dummies struct rusage { int x; }; inline static void my_getrusage(struct rusage *) { } inline static void print_rusage(struct rusage *, struct rusage *){}; #endif // ! defined(HAVE_SYS_RESOURCE_H) unsigned module_cnt = 0; const char*module_tab[64]; extern void vpi_mcd_init(FILE *log); extern void vvp_vpi_init(void); int main(int argc, char*argv[]) { int opt; unsigned flag_errors = 0; const char*design_path = 0; struct rusage cycles[3]; const char *logfile_name = 0x0; FILE *logfile = 0x0; extern void vpi_set_vlog_info(int, char**); #ifdef __MINGW32__ /* In the Windows world, we get the first module path component relative the location where the binary lives. */ { char path[4096], *s; GetModuleFileName(NULL,path,1024); /* Get to the end. Search back twice for backslashes */ s = path + strlen(path); while (*s != '\\') s--; s--; while (*s != '\\') s--; strcpy(s,"\\lib\\ivl"); vpip_module_path[0] = strdup(path); } #endif while ((opt = getopt(argc, argv, "+hl:M:m:sv")) != EOF) switch (opt) { case 'h': fprintf(stderr, "Usage: vvp [options] input-file [+plusargs...]\n" "Options:\n" " -h Print this help message.\n" " -l file Logfile, '-' for <stderr>\n" " -M path VPI module directory\n" " -M - Clear VPI module path\n" " -m module Load vpi module.\n" " -s $stop right away.\n" " -v Verbose progress messages.\n" ); exit(0); case 'l': logfile_name = optarg; break; case 'M': if (strcmp(optarg,"-") == 0) { vpip_module_path_cnt = 0; vpip_module_path[0] = 0; } else { vpip_module_path[vpip_module_path_cnt++] = optarg; } break; case 'm': module_tab[module_cnt++] = optarg; break; case 's': schedule_stop(0); break; case 'v': verbose_flag = true; break; default: flag_errors += 1; } if (flag_errors) return flag_errors; if (optind == argc) { fprintf(stderr, "%s: no input file.\n", argv[0]); return -1; } design_path = argv[optind]; /* This is needed to get the MCD I/O routines ready for anything. It is done early because it is plausible that the compile might affect it, and it is cheap to do. */ if (logfile_name) { if (!strcmp(logfile_name, "-")) logfile = stderr; else { logfile = fopen(logfile_name, "w"); if (!logfile) { perror(logfile_name); exit(1); } setvbuf(logfile, log_buffer, _IOLBF, sizeof(log_buffer)); } } vpi_mcd_init(logfile); if (verbose_flag) { my_getrusage(cycles+0); vpi_mcd_printf(1, "Compiling VVP ...\n"); } vvp_vpi_init(); /* Make the extended arguments available to the simulation. */ vpi_set_vlog_info(argc-optind, argv+optind); compile_init(); for (unsigned idx = 0 ; idx < module_cnt ; idx += 1) vpip_load_module(module_tab[idx]); if (int rc = compile_design(design_path)) return rc; if (verbose_flag) { vpi_mcd_printf(1, "Compile cleanup...\n"); } compile_cleanup(); if (compile_errors > 0) { vpi_mcd_printf(1, "%s: Program not runnable, %u errors.\n", design_path, compile_errors); return compile_errors; } if (verbose_flag) { vpi_mcd_printf(1, " ... %8lu functors\n", count_functors); vpi_mcd_printf(1, " %8lu table\n", count_functors_table); vpi_mcd_printf(1, " %8lu bufif\n", count_functors_bufif); vpi_mcd_printf(1, " %8lu resolv\n",count_functors_resolv); vpi_mcd_printf(1, " %8lu variable\n", count_functors_var); vpi_mcd_printf(1, " ... %8lu opcodes (%lu bytes)\n", count_opcodes, (unsigned long)size_opcodes); vpi_mcd_printf(1, " ... %8lu nets\n", count_vpi_nets); vpi_mcd_printf(1, " ... %8lu memories\n", count_vpi_memories); vpi_mcd_printf(1, " ... %8lu scopes\n", count_vpi_scopes); } if (verbose_flag) { my_getrusage(cycles+1); print_rusage(cycles+1, cycles+0); vpi_mcd_printf(1, "Running ...\n"); } schedule_simulate(); if (verbose_flag) { my_getrusage(cycles+2); print_rusage(cycles+2, cycles+1); vpi_mcd_printf(1, "Event counts: (event pool = %lu)\n", count_event_pool); vpi_mcd_printf(1, " %8lu thread schedule events\n", count_thread_events); vpi_mcd_printf(1, " %8lu propagation events\n", count_prop_events); vpi_mcd_printf(1, " %8lu assign events\n", count_assign_events); vpi_mcd_printf(1, " %8lu other events\n", count_gen_events); } return 0; } /* * $Log: main.cc,v $ * Revision 1.44 2007/02/16 23:30:14 steve * Get page size from sysconf. * * Revision 1.43 2006/04/28 15:44:37 steve * Include math.h with lround implementation. * * Revision 1.42 2006/04/28 15:40:30 steve * lround takes double, not float. * * Revision 1.41 2006/04/27 05:04:59 steve * Detect missing lround function. * * Revision 1.40 2005/01/29 06:28:19 steve * Add the -s flag to start up interactive. * * Revision 1.39 2004/10/04 01:10:59 steve * Clean up spurious trailing white space. * * Revision 1.38 2003/06/25 04:04:19 steve * Fix mingw portability problems. * * Revision 1.37 2003/06/13 19:51:08 steve * Include verbose messages in log output. * * Revision 1.36 2003/05/15 16:51:09 steve * Arrange for mcd id=00_00_00_01 to go to stdout * as well as a user specified log file, set log * file to buffer lines. * * Add vpi_flush function, and clear up some cunfused * return codes from other vpi functions. * * Adjust $display and vcd/lxt messages to use the * standard output/log file. * * Revision 1.35 2003/03/13 04:36:57 steve * Remove the obsolete functor delete functions. * * Revision 1.34 2003/02/07 02:45:05 steve * Mke getopt ignore options after the file name. * * Revision 1.33 2003/01/18 23:55:35 steve * Add a means to clear the module search path. * * Revision 1.32 2003/01/06 23:57:26 steve * Schedule wait lists of threads as a single event, * to save on events. Also, improve efficiency of * event_s allocation. Add some event statistics to * get an idea where performance is really going. * * Revision 1.31 2002/09/18 03:34:07 steve * printf size warning. * * Revision 1.30 2002/08/12 01:35:08 steve * conditional ident string using autoconfig. * * Revision 1.29 2002/07/15 00:21:42 steve * Fix initialization of symbol table string heap. * * Revision 1.28 2002/07/05 20:08:44 steve * Count different types of functors. * * Revision 1.27 2002/07/05 17:14:15 steve * Names of vpi objects allocated as vpip_strings. * * Revision 1.26 2002/07/05 03:47:06 steve * Track opcode memory space. * * Revision 1.25 2002/07/05 02:50:58 steve * Remove the vpi object symbol table after compile. * * Revision 1.24 2002/04/12 02:44:02 steve * Formally define extended arguments to vvp. * * Revision 1.23 2002/03/01 05:43:14 steve * Add cleanup to verbose messages. * * Revision 1.22 2002/01/09 03:15:23 steve * Add vpi_get_vlog_info support. * * Revision 1.21 2001/10/20 01:03:42 steve * Print memory usage information if requested (Stephan Boettcher) */ <|endoftext|>
<commit_before>/** * @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetOptionsGeneratorTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetOptionsGeneratorToolsTest #include "JPetOptionsGenerator/JPetOptionsGeneratorTools.h" #include "JPetCmdParser/JPetCmdParser.h" #include "JPetCommonTools/JPetCommonTools.h" #include <boost/test/unit_test.hpp> #include <cstdlib> #include <iostream> using boost::any_cast; using namespace std; using namespace jpet_options_tools; using namespace jpet_options_generator_tools; OptsStrAny getOptions(const std::string& commandLine) { auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("help,h", "Displays this help message.")("type,t", po::value<std::string>()->required(), "Type of file: hld, zip, root or scope.")( "file,f", po::value<std::vector<std::string>>()->required()->multitoken(), "File(s) to open.")("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.")( "range,r", po::value<std::vector<int>>()->multitoken()->default_value({-1, -1}, ""), "Range of events to process e.g. -r 1 1000 .")( "unpackerConfigFile,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.")( "unpackerCalibFile,c", po::value<std::string>(), "ROOT file with TRB calibration used by the unpacker program.")( "runId,i", po::value<int>(), "Run id.")("progressBar,b", po::bool_switch()->default_value(false), "Progress bar.")("localDB,l", po::value<std::string>(), "The file to use as the parameter database.")( "localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved.")("userCfg,u", po::value<std::string>(), "Json file with optional user parameters."); po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); auto options = addTypeSuffixes(transformToStrAnyMap(variablesMap)); options = addMissingDefaultOptions(options); auto transformationMap = generateTransformationMap(options); options = transformOptions(transformationMap, options); return options; } BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE(checkIfFunctionToGenerateTransformationMapWork) { OptsStrAny options; auto transformationMap = generateTransformationMap(options); BOOST_REQUIRE(transformationMap.count("outputPath_std::string")); BOOST_REQUIRE(transformationMap.count("range_std::vector<int>")); BOOST_REQUIRE(transformationMap.count("type_std::string")); } BOOST_AUTO_TEST_CASE(checkIfFunctionToTransformOptionsWork) { OptsStrAny options; auto transformationMap = generateTransformationMap(options); std::map<std::string, boost::any> emptyOptions; BOOST_REQUIRE(transformOptions(transformationMap, emptyOptions).empty()); std::string pathForCorrection = "a/b/c/d"; std::vector<int> range = {1, 2}; std::string inputFileType = "inputFileType"; std::map<std::string, boost::any> optionForTransformation; optionForTransformation["outputPath_std::string"] = pathForCorrection; optionForTransformation["range_std::vector<int>"] = range; optionForTransformation["type_std::string"] = inputFileType; auto mapAfterTransformation = transformOptions(transformationMap, optionForTransformation); BOOST_REQUIRE_EQUAL(any_cast<std::string>(mapAfterTransformation.at("outputPath_std::string")), (pathForCorrection + '/')); BOOST_REQUIRE_EQUAL(any_cast<int>(mapAfterTransformation.at("lastEvent_int")), 2); BOOST_REQUIRE_EQUAL(any_cast<int>(mapAfterTransformation.at("firstEvent_int")), 1); BOOST_REQUIRE_EQUAL(any_cast<std::string>(mapAfterTransformation.at("inputFileType_std::string")), inputFileType); } BOOST_AUTO_TEST_CASE(checkIfFunctionGetConfigFileNameWork) { auto commandLine = "main.x -u example.json"; auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); ; po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); BOOST_REQUIRE_EQUAL(getConfigFileName(transformToStrAnyMap(variablesMap)), "example.json"); auto commandLine2 = "main.x "; auto args_char2 = JPetCommonTools::createArgs(commandLine2); auto argc2 = args_char2.size(); auto argv2 = args_char2.data(); po::options_description description2("Allowed options"); description2.add_options()("userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); ; po::variables_map variablesMap2; po::store(po::parse_command_line(argc2, argv2, description2), variablesMap2); po::notify(variablesMap2); BOOST_REQUIRE_EQUAL(getConfigFileName(transformToStrAnyMap(variablesMap2)), ""); } BOOST_AUTO_TEST_CASE(checkIfFunctionToAddOptionsFromCfgFileWork) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.hld -t hld -r 2 -r 4 -p unitTestData/JPetCmdParserTest/data.hld -i 231 -b 1 -l " "unitTestData/JPetCmdParserTest/input.json -L output.json -u unitTestData/JPetOptionsToolsTest/newInputTestCfg.json"; auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("file_std::vector<std::string>,f", po::value<std::vector<std::string>>(), "File(s) to open")("type_std::string,t", po::value<std::string>(), "type of file: hld, zip, root or scope")( "range_std::vector<int>,r", po::value<std::vector<int>>(), "Range of events to process.")("param_std::string,p", po::value<std::string>(), "File with TRB numbers.")( "runId_int,i", po::value<int>(), "Run id.")("progressBar_bool,b", po::bool_switch()->default_value(false), "Progress bar.")( "localDB_std::string,l", po::value<std::string>(), "The file to use as the parameter database.")("localDBCreate_std::string,L", po::value<std::string>(), "Where to save the parameter database.")( "userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); auto options = transformToStrAnyMap(variablesMap); auto cfgFileName = getConfigFileName(options); if (!cfgFileName.empty()) { addNewOptionsFromCfgFile(cfgFileName, options); } BOOST_REQUIRE(options.count("myOption_std::string")); BOOST_REQUIRE(options.count("myAnotherOption_std::string")); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_emptyControlSettings) { std::vector<std::string> tmp = {"aa", "bb"}; std::map<std::string, boost::any> inOpts = { {"my_string", std::string("my_value")}, {"my_int", int(12)}, }; std::map<std::string, boost::any> controlSettings; auto result = generateOptionsForTask(inOpts, controlSettings); for (auto it_r = result.cbegin(), end_r = result.cend(), it_inOpts = inOpts.cbegin(), end_inOpts = inOpts.cend(); it_r != end_r || it_inOpts != end_inOpts;) { BOOST_REQUIRE_EQUAL(it_r->first, it_inOpts->first); ++it_r; ++it_inOpts; } BOOST_REQUIRE_EQUAL(any_cast<std::string>(result["my_string"]), any_cast<std::string>(inOpts["my_string"])); BOOST_REQUIRE_EQUAL(any_cast<int>(result["my_int"]), any_cast<int>(inOpts["my_int"])); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_hldRoot_after_hld) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.hld.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("hldRoot")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kHldRoot); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_root_after_hldRoot) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("root")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kRoot); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), 2); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), 100); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_root_after_Root) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("root")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kRoot); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), 2); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), 100); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_resetEventRange) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"resetEventRange_bool", bool(true)}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), -1); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), -1); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_outputPath) { auto commandLine = "main.x -f data.root -t root -r 2 100 -i 231 "; auto inOpts = getOptions(commandLine); inOpts["inputFile_std::string"] = *(getInputFiles(inOpts).begin()); std::map<std::string, boost::any> controlSettings = {{"outputPath_std::string", std::string("../../")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFile_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(resultsOpt, "inputFile_std::string"), std::string("../../data.root")); } BOOST_AUTO_TEST_CASE(setResetEventRangeOption_test) { std::map<std::string, boost::any> options; setResetEventRangeOption(options, true); BOOST_REQUIRE(isOptionSet(options, "resetEventRange_bool")); BOOST_REQUIRE(getOptionAsBool(options, "resetEventRange_bool")); setResetEventRangeOption(options, false); BOOST_REQUIRE(!getOptionAsBool(options, "resetEventRange_bool")); } BOOST_AUTO_TEST_CASE(setOutputFileType_test) { std::map<std::string, boost::any> options; setOutputFileType(options, "root"); BOOST_REQUIRE(isOptionSet(options, "outputFileType_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(options, "outputFileType_std::string"), "root"); } BOOST_AUTO_TEST_CASE(setOutputPath_test) { std::map<std::string, boost::any> options; setOutputPath(options, "/here/and/there"); BOOST_REQUIRE(isOptionSet(options, "outputPath_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(options, "outputPath_std::string"), "/here/and/there"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix cppcheck issue<commit_after>/** * @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetOptionsGeneratorTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetOptionsGeneratorToolsTest #include "JPetOptionsGenerator/JPetOptionsGeneratorTools.h" #include "JPetCmdParser/JPetCmdParser.h" #include "JPetCommonTools/JPetCommonTools.h" #include <boost/test/unit_test.hpp> #include <cstdlib> #include <iostream> using boost::any_cast; using namespace std; using namespace jpet_options_tools; using namespace jpet_options_generator_tools; OptsStrAny getOptions(const std::string& commandLine) { auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("help,h", "Displays this help message.")("type,t", po::value<std::string>()->required(), "Type of file: hld, zip, root or scope.")( "file,f", po::value<std::vector<std::string>>()->required()->multitoken(), "File(s) to open.")("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.")( "range,r", po::value<std::vector<int>>()->multitoken()->default_value({-1, -1}, ""), "Range of events to process e.g. -r 1 1000 .")( "unpackerConfigFile,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.")( "unpackerCalibFile,c", po::value<std::string>(), "ROOT file with TRB calibration used by the unpacker program.")( "runId,i", po::value<int>(), "Run id.")("progressBar,b", po::bool_switch()->default_value(false), "Progress bar.")("localDB,l", po::value<std::string>(), "The file to use as the parameter database.")( "localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved.")("userCfg,u", po::value<std::string>(), "Json file with optional user parameters."); po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); auto options = addTypeSuffixes(transformToStrAnyMap(variablesMap)); options = addMissingDefaultOptions(options); auto transformationMap = generateTransformationMap(options); options = transformOptions(transformationMap, options); return options; } BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE(checkIfFunctionToGenerateTransformationMapWork) { OptsStrAny options; auto transformationMap = generateTransformationMap(options); BOOST_REQUIRE(transformationMap.count("outputPath_std::string")); BOOST_REQUIRE(transformationMap.count("range_std::vector<int>")); BOOST_REQUIRE(transformationMap.count("type_std::string")); } BOOST_AUTO_TEST_CASE(checkIfFunctionToTransformOptionsWork) { OptsStrAny options; auto transformationMap = generateTransformationMap(options); std::map<std::string, boost::any> emptyOptions; BOOST_REQUIRE(transformOptions(transformationMap, emptyOptions).empty()); std::string pathForCorrection = "a/b/c/d"; std::vector<int> range = {1, 2}; std::string inputFileType = "inputFileType"; std::map<std::string, boost::any> optionForTransformation; optionForTransformation["outputPath_std::string"] = pathForCorrection; optionForTransformation["range_std::vector<int>"] = range; optionForTransformation["type_std::string"] = inputFileType; auto mapAfterTransformation = transformOptions(transformationMap, optionForTransformation); BOOST_REQUIRE_EQUAL(any_cast<std::string>(mapAfterTransformation.at("outputPath_std::string")), (pathForCorrection + '/')); BOOST_REQUIRE_EQUAL(any_cast<int>(mapAfterTransformation.at("lastEvent_int")), 2); BOOST_REQUIRE_EQUAL(any_cast<int>(mapAfterTransformation.at("firstEvent_int")), 1); BOOST_REQUIRE_EQUAL(any_cast<std::string>(mapAfterTransformation.at("inputFileType_std::string")), inputFileType); } BOOST_AUTO_TEST_CASE(checkIfFunctionGetConfigFileNameWork) { auto commandLine = "main.x -u example.json"; auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); ; po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); BOOST_REQUIRE_EQUAL(getConfigFileName(transformToStrAnyMap(variablesMap)), "example.json"); auto commandLine2 = "main.x "; auto args_char2 = JPetCommonTools::createArgs(commandLine2); auto argc2 = args_char2.size(); auto argv2 = args_char2.data(); po::options_description description2("Allowed options"); description2.add_options()("userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); ; po::variables_map variablesMap2; po::store(po::parse_command_line(argc2, argv2, description2), variablesMap2); po::notify(variablesMap2); BOOST_REQUIRE_EQUAL(getConfigFileName(transformToStrAnyMap(variablesMap2)), ""); } BOOST_AUTO_TEST_CASE(checkIfFunctionToAddOptionsFromCfgFileWork) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.hld -t hld -r 2 -r 4 -p unitTestData/JPetCmdParserTest/data.hld -i 231 -b 1 -l " "unitTestData/JPetCmdParserTest/input.json -L output.json -u unitTestData/JPetOptionsToolsTest/newInputTestCfg.json"; auto args_char = JPetCommonTools::createArgs(commandLine); auto argc = args_char.size(); auto argv = args_char.data(); po::options_description description("Allowed options"); description.add_options()("file_std::vector<std::string>,f", po::value<std::vector<std::string>>(), "File(s) to open")("type_std::string,t", po::value<std::string>(), "type of file: hld, zip, root or scope")( "range_std::vector<int>,r", po::value<std::vector<int>>(), "Range of events to process.")("param_std::string,p", po::value<std::string>(), "File with TRB numbers.")( "runId_int,i", po::value<int>(), "Run id.")("progressBar_bool,b", po::bool_switch()->default_value(false), "Progress bar.")( "localDB_std::string,l", po::value<std::string>(), "The file to use as the parameter database.")("localDBCreate_std::string,L", po::value<std::string>(), "Where to save the parameter database.")( "userCfg_std::string,u", po::value<std::string>(), "Json file with optional user parameters."); po::variables_map variablesMap; po::store(po::parse_command_line(argc, argv, description), variablesMap); po::notify(variablesMap); auto options = transformToStrAnyMap(variablesMap); auto cfgFileName = getConfigFileName(options); if (!cfgFileName.empty()) { addNewOptionsFromCfgFile(cfgFileName, options); } BOOST_REQUIRE(options.count("myOption_std::string")); BOOST_REQUIRE(options.count("myAnotherOption_std::string")); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_emptyControlSettings) { std::map<std::string, boost::any> inOpts = { {"my_string", std::string("my_value")}, {"my_int", int(12)}, }; std::map<std::string, boost::any> controlSettings; auto result = generateOptionsForTask(inOpts, controlSettings); for (auto it_r = result.cbegin(), end_r = result.cend(), it_inOpts = inOpts.cbegin(), end_inOpts = inOpts.cend(); it_r != end_r || it_inOpts != end_inOpts;) { BOOST_REQUIRE_EQUAL(it_r->first, it_inOpts->first); ++it_r; ++it_inOpts; } BOOST_REQUIRE_EQUAL(any_cast<std::string>(result["my_string"]), any_cast<std::string>(inOpts["my_string"])); BOOST_REQUIRE_EQUAL(any_cast<int>(result["my_int"]), any_cast<int>(inOpts["my_int"])); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_hldRoot_after_hld) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.hld.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("hldRoot")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kHldRoot); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_root_after_hldRoot) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("root")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kRoot); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), 2); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), 100); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_root_after_Root) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"outputFileType_std::string", std::string("root")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFileType_std::string")); BOOST_REQUIRE_EQUAL(FileTypeChecker::getInputFileType(resultsOpt), FileTypeChecker::kRoot); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), 2); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), 100); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_resetEventRange) { auto commandLine = "main.x -f unitTestData/JPetCmdParserTest/data.root -t root -r 2 100 -i 231"; auto inOpts = getOptions(commandLine); std::map<std::string, boost::any> controlSettings = {{"resetEventRange_bool", bool(true)}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "firstEvent_int")); BOOST_REQUIRE(isOptionSet(resultsOpt, "lastEvent_int")); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "firstEvent_int"), -1); BOOST_REQUIRE_EQUAL(getOptionAsInt(resultsOpt, "lastEvent_int"), -1); } BOOST_AUTO_TEST_CASE(generateOptionsForTask_outputPath) { auto commandLine = "main.x -f data.root -t root -r 2 100 -i 231 "; auto inOpts = getOptions(commandLine); inOpts["inputFile_std::string"] = *(getInputFiles(inOpts).begin()); std::map<std::string, boost::any> controlSettings = {{"outputPath_std::string", std::string("../../")}}; auto resultsOpt = generateOptionsForTask(inOpts, controlSettings); BOOST_REQUIRE(isOptionSet(resultsOpt, "inputFile_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(resultsOpt, "inputFile_std::string"), std::string("../../data.root")); } BOOST_AUTO_TEST_CASE(setResetEventRangeOption_test) { std::map<std::string, boost::any> options; setResetEventRangeOption(options, true); BOOST_REQUIRE(isOptionSet(options, "resetEventRange_bool")); BOOST_REQUIRE(getOptionAsBool(options, "resetEventRange_bool")); setResetEventRangeOption(options, false); BOOST_REQUIRE(!getOptionAsBool(options, "resetEventRange_bool")); } BOOST_AUTO_TEST_CASE(setOutputFileType_test) { std::map<std::string, boost::any> options; setOutputFileType(options, "root"); BOOST_REQUIRE(isOptionSet(options, "outputFileType_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(options, "outputFileType_std::string"), "root"); } BOOST_AUTO_TEST_CASE(setOutputPath_test) { std::map<std::string, boost::any> options; setOutputPath(options, "/here/and/there"); BOOST_REQUIRE(isOptionSet(options, "outputPath_std::string")); BOOST_REQUIRE_EQUAL(getOptionAsString(options, "outputPath_std::string"), "/here/and/there"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "windowmanager.h" #include <QtCore/QDir> #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QProcess> #include <QtCore/QByteArray> #include <QtCore/QLibraryInfo> #include <QtCore/QVariant> #include <QtCore/QDateTime> #include <QtCore/QMap> // AppLaunch: Launch gui applications, keep them running a while // (grabbing their top level from the window manager) and send // them a Close event via window manager. Verify that they do not // not crash nor produces unexpected error output. // Note: Do not play with the machine while it is running as otherwise // the top-level find algorithm might get confused (especially on Windows). // Environment variables are checked to turned off some tests // It is currently implemented for X11 and Windows, pending an // implementation of the WindowManager class and deployment on // the other platforms. enum { defaultUpTimeMS = 3000, defaultTopLevelWindowTimeoutMS = 30000, defaultTerminationTimeoutMS = 35000 }; // List the examples to test (Gui examples only). struct Example { QByteArray name; QByteArray directory; QByteArray binary; unsigned priority; // 0-highest int upTimeMS; }; QList<Example> examples; QList<Example> demos; // Data struct used in tests, specifying paths and timeouts struct AppLaunchData { AppLaunchData(); void clear(); QString binary; QStringList args; QString workingDirectory; int upTimeMS; int topLevelWindowTimeoutMS; int terminationTimeoutMS; bool splashScreen; }; AppLaunchData::AppLaunchData() : upTimeMS(defaultUpTimeMS), topLevelWindowTimeoutMS(defaultTopLevelWindowTimeoutMS), terminationTimeoutMS(defaultTerminationTimeoutMS), splashScreen(false) { } void AppLaunchData::clear() { binary.clear(); args.clear(); workingDirectory.clear(); upTimeMS = defaultUpTimeMS; topLevelWindowTimeoutMS = defaultTopLevelWindowTimeoutMS; terminationTimeoutMS = defaultTerminationTimeoutMS; splashScreen = false; } Q_DECLARE_METATYPE(AppLaunchData) class tst_GuiAppLauncher : public QObject { Q_OBJECT public: // Test name (static const char title!) + data typedef QPair<const char*, AppLaunchData> TestDataEntry; typedef QList<TestDataEntry> TestDataEntries; enum { TestTools = 0x1, TestDemo = 0x2, TestExamples = 0x4, TestAll = TestTools|TestDemo|TestExamples }; tst_GuiAppLauncher(); private Q_SLOTS: void initTestCase(); void run(); void run_data(); void cleanupTestCase(); private: QString workingDir() const; private: bool runApp(const AppLaunchData &data, QString *errorMessage) const; TestDataEntries testData() const; const unsigned m_testMask; const unsigned m_examplePriority; const QString m_dir; const QSharedPointer<WindowManager> m_wm; }; // Test mask from environment as test lib does not allow options. static inline unsigned testMask() { unsigned testMask = tst_GuiAppLauncher::TestAll; if (!qgetenv("QT_TEST_NOTOOLS").isEmpty()) testMask &= ~ tst_GuiAppLauncher::TestTools; if (!qgetenv("QT_TEST_NOEXAMPLES").isEmpty()) testMask &= ~tst_GuiAppLauncher::TestExamples; if (!qgetenv("QT_TEST_NODEMOS").isEmpty()) testMask &= ~tst_GuiAppLauncher::TestDemo; return testMask; } static inline unsigned testExamplePriority() { const QByteArray priorityD = qgetenv("QT_TEST_EXAMPLE_PRIORITY"); if (!priorityD.isEmpty()) { bool ok; const unsigned rc = priorityD.toUInt(&ok); if (ok) return rc; } return 5; } tst_GuiAppLauncher::tst_GuiAppLauncher() : m_testMask(testMask()), m_examplePriority(testExamplePriority()), m_dir(QLatin1String(SRCDIR)), m_wm(WindowManager::create()) { } void tst_GuiAppLauncher::initTestCase() { QString message = QString::fromLatin1("### App Launcher test on %1 in %2"). arg(QDateTime::currentDateTime().toString(), QDir::currentPath()); qDebug("%s", qPrintable(message)); qWarning("### PLEASE LEAVE THE MACHINE UNATTENDED WHILE THIS TEST IS RUNNING\n"); // Does a window manager exist on the platform? if (!m_wm->openDisplay(&message)) { QSKIP(message.toLatin1().constData()); } // Paranoia: Do we have our test file? const QDir workDir(m_dir); if (!workDir.exists()) { message = QString::fromLatin1("Invalid working directory %1").arg(m_dir); QFAIL(message.toLocal8Bit().constData()); } } void tst_GuiAppLauncher::run() { QString errorMessage; QFETCH(AppLaunchData, data); const bool rc = runApp(data, &errorMessage); if (!rc) // Wait for windows to disappear after kill WindowManager::sleepMS(500); QVERIFY2(rc, qPrintable(errorMessage)); } // Cross platform galore! static inline QString guiBinary(QString in) { #ifdef Q_OS_MAC return in + QLatin1String(".app/Contents/MacOS/") + in; #endif in[0] = in.at(0).toLower(); #ifdef Q_OS_WIN in += QLatin1String(".exe"); #endif return in; } void tst_GuiAppLauncher::run_data() { QTest::addColumn<AppLaunchData>("data"); foreach(const TestDataEntry &data, testData()) { qDebug() << data.first << data.second.binary; QTest::newRow(data.first) << data.second; } } static QList<Example> readDataEntriesFromFile(const QString &fileName) { QList<Example> ret; QFile file(fileName); if (!file.open(QFile::ReadOnly)) return ret; QByteArray line; QRegExp lineMatcher("\"([^\"]*)\", *\"([^\"]*)\", *\"([^\"]*)\", *([-0-9]*), *([-0-9]*)"); for (line = file.readLine(); !line.isEmpty(); line = file.readLine()) { int matchPos = lineMatcher.indexIn(QString::fromLatin1(line)); if (matchPos < 0) break; Example example; example.name = lineMatcher.cap(1).toLatin1(); example.directory = lineMatcher.cap(2).toLatin1(); example.binary = lineMatcher.cap(3).toLatin1(); example.priority = lineMatcher.cap(4).toUInt(); example.upTimeMS = lineMatcher.cap(5).toInt(); ret << example; } return ret; } // Read out the examples array structures and convert to test data. static tst_GuiAppLauncher::TestDataEntries exampleData(unsigned priority, const QString &path, const QList<Example> exArray, unsigned n) { tst_GuiAppLauncher::TestDataEntries rc; const QChar slash = QLatin1Char('/'); AppLaunchData data; for (unsigned e = 0; e < n; e++) { const Example &example = exArray[e]; if (example.priority <= priority) { data.clear(); const QString examplePath = path + slash + example.directory; data.binary = examplePath + slash; #ifdef Q_OS_WIN // FIXME: support debug version too? data.binary += QLatin1String("release/"); #endif data.binary += guiBinary(example.binary); data.workingDirectory = examplePath; if (example.upTimeMS > 0) data.upTimeMS = example.upTimeMS; rc.append(tst_GuiAppLauncher::TestDataEntry(example.name.constData(), data)); } } return rc; } tst_GuiAppLauncher::TestDataEntries tst_GuiAppLauncher::testData() const { TestDataEntries rc; const QChar slash = QLatin1Char('/'); const QString binPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + slash; const QString path = qgetenv("QT_MODULE_TO_TEST"); AppLaunchData data; if (m_testMask & TestTools) { data.binary = binPath + guiBinary(QLatin1String("Designer")); data.args.append(m_dir + QLatin1String("test.ui")); rc.append(TestDataEntry("Qt Designer", data)); data.clear(); data.binary = binPath + guiBinary(QLatin1String("Linguist")); data.splashScreen = true; data.upTimeMS = 5000; // Slow loading data.args.append(m_dir + QLatin1String("test.ts")); rc.append(TestDataEntry("Qt Linguist", data)); } if (m_testMask & TestDemo) { data.clear(); data.upTimeMS = 5000; // Startup animation data.binary = binPath + guiBinary(QLatin1String("qtdemo")); rc.append(TestDataEntry("Qt Demo", data)); if (!path.isEmpty()) { demos = readDataEntriesFromFile(path + "/tests/auto/guiapplauncher/demos.txt"); rc += exampleData(m_examplePriority, path, demos, demos.size()); } } if (m_testMask & TestExamples) { if (!path.isEmpty()) { examples = readDataEntriesFromFile(path + "/tests/auto/guiapplauncher/examples.txt"); rc += exampleData(m_examplePriority, path, examples, examples.size()); } } qDebug("Running %d tests...", rc.size()); return rc; } static inline void ensureTerminated(QProcess *p) { if (p->state() != QProcess::Running) return; p->terminate(); if (p->waitForFinished(300)) return; p->kill(); if (!p->waitForFinished(500)) qWarning("Unable to terminate process"); } static const QStringList &stderrWhiteList() { static QStringList rc; if (rc.empty()) { rc << QLatin1String("QPainter::begin: Paint device returned engine == 0, type: 2") << QLatin1String("QPainter::setRenderHint: Painter must be active to set rendering hints") << QLatin1String("QPainter::setPen: Painter not active") << QLatin1String("QPainter::setBrush: Painter not active") << QLatin1String("QPainter::end: Painter not active, aborted"); } return rc; } bool tst_GuiAppLauncher::runApp(const AppLaunchData &data, QString *errorMessage) const { qDebug("Launching: %s\n", qPrintable(data.binary)); QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); if (!data.workingDirectory.isEmpty()) process.setWorkingDirectory(data.workingDirectory); process.start(data.binary, data.args); process.closeWriteChannel(); if (!process.waitForStarted()) { *errorMessage = QString::fromLatin1("Unable to execute %1: %2").arg(data.binary, process.errorString()); return false; } // Get window id. const QString winId = m_wm->waitForTopLevelWindow(data.splashScreen ? 2 : 1, process.pid(), data.topLevelWindowTimeoutMS, errorMessage); if (winId.isEmpty()) { ensureTerminated(&process); return false; } qDebug("Window: %s\n", qPrintable(winId)); // Wait a bit, then send close WindowManager::sleepMS(data.upTimeMS); if (m_wm->sendCloseEvent(winId, process.pid(), errorMessage)) { qDebug("Sent close to window: %s\n", qPrintable(winId)); } else { ensureTerminated(&process); return false; } // Terminate if (!process.waitForFinished(data.terminationTimeoutMS)) { *errorMessage = QString::fromLatin1("%1: Timeout %2ms").arg(data.binary).arg(data.terminationTimeoutMS); ensureTerminated(&process); return false; } if (process.exitStatus() != QProcess::NormalExit) { *errorMessage = QString::fromLatin1("%1: Startup crash").arg(data.binary); return false; } const int exitCode = process.exitCode(); // check stderr const QStringList stderrOutput = QString::fromLocal8Bit(process.readAllStandardOutput()).split(QLatin1Char('\n')); foreach(const QString &stderrLine, stderrOutput) { // Skip expected QPainter warnings from oxygen. if (stderrWhiteList().contains(stderrLine)) { qWarning("%s: stderr: %s\n", qPrintable(data.binary), qPrintable(stderrLine)); } else { if (!stderrLine.isEmpty()) { // Split oddity gives empty messages *errorMessage = QString::fromLatin1("%1: Unexpected output (ex=%2): '%3'").arg(data.binary).arg(exitCode).arg(stderrLine); return false; } } } if (exitCode != 0) { *errorMessage = QString::fromLatin1("%1: Exit code %2").arg(data.binary).arg(exitCode); return false; } return true; } void tst_GuiAppLauncher::cleanupTestCase() { } QTEST_APPLESS_MAIN(tst_GuiAppLauncher) #include "tst_guiapplauncher.moc" <commit_msg>QtQA: guiapplauncher: Do not launch deprecated qtdemo<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "windowmanager.h" #include <QtCore/QDir> #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QProcess> #include <QtCore/QByteArray> #include <QtCore/QLibraryInfo> #include <QtCore/QVariant> #include <QtCore/QDateTime> #include <QtCore/QMap> // AppLaunch: Launch gui applications, keep them running a while // (grabbing their top level from the window manager) and send // them a Close event via window manager. Verify that they do not // not crash nor produces unexpected error output. // Note: Do not play with the machine while it is running as otherwise // the top-level find algorithm might get confused (especially on Windows). // Environment variables are checked to turned off some tests // It is currently implemented for X11 and Windows, pending an // implementation of the WindowManager class and deployment on // the other platforms. enum { defaultUpTimeMS = 3000, defaultTopLevelWindowTimeoutMS = 30000, defaultTerminationTimeoutMS = 35000 }; // List the examples to test (Gui examples only). struct Example { QByteArray name; QByteArray directory; QByteArray binary; unsigned priority; // 0-highest int upTimeMS; }; QList<Example> examples; // Data struct used in tests, specifying paths and timeouts struct AppLaunchData { AppLaunchData(); void clear(); QString binary; QStringList args; QString workingDirectory; int upTimeMS; int topLevelWindowTimeoutMS; int terminationTimeoutMS; bool splashScreen; }; AppLaunchData::AppLaunchData() : upTimeMS(defaultUpTimeMS), topLevelWindowTimeoutMS(defaultTopLevelWindowTimeoutMS), terminationTimeoutMS(defaultTerminationTimeoutMS), splashScreen(false) { } void AppLaunchData::clear() { binary.clear(); args.clear(); workingDirectory.clear(); upTimeMS = defaultUpTimeMS; topLevelWindowTimeoutMS = defaultTopLevelWindowTimeoutMS; terminationTimeoutMS = defaultTerminationTimeoutMS; splashScreen = false; } Q_DECLARE_METATYPE(AppLaunchData) class tst_GuiAppLauncher : public QObject { Q_OBJECT public: // Test name (static const char title!) + data typedef QPair<const char*, AppLaunchData> TestDataEntry; typedef QList<TestDataEntry> TestDataEntries; enum { TestTools = 0x1, TestExamples = 0x2, TestAll = TestTools|TestExamples }; tst_GuiAppLauncher(); private Q_SLOTS: void initTestCase(); void run(); void run_data(); void cleanupTestCase(); private: QString workingDir() const; private: bool runApp(const AppLaunchData &data, QString *errorMessage) const; TestDataEntries testData() const; const unsigned m_testMask; const unsigned m_examplePriority; const QString m_dir; const QSharedPointer<WindowManager> m_wm; }; // Test mask from environment as test lib does not allow options. static inline unsigned testMask() { unsigned testMask = tst_GuiAppLauncher::TestAll; if (!qgetenv("QT_TEST_NOTOOLS").isEmpty()) testMask &= ~ tst_GuiAppLauncher::TestTools; if (!qgetenv("QT_TEST_NOEXAMPLES").isEmpty()) testMask &= ~tst_GuiAppLauncher::TestExamples; return testMask; } static inline unsigned testExamplePriority() { const QByteArray priorityD = qgetenv("QT_TEST_EXAMPLE_PRIORITY"); if (!priorityD.isEmpty()) { bool ok; const unsigned rc = priorityD.toUInt(&ok); if (ok) return rc; } return 5; } tst_GuiAppLauncher::tst_GuiAppLauncher() : m_testMask(testMask()), m_examplePriority(testExamplePriority()), m_dir(QLatin1String(SRCDIR)), m_wm(WindowManager::create()) { } void tst_GuiAppLauncher::initTestCase() { QString message = QString::fromLatin1("### App Launcher test on %1 in %2"). arg(QDateTime::currentDateTime().toString(), QDir::currentPath()); qDebug("%s", qPrintable(message)); qWarning("### PLEASE LEAVE THE MACHINE UNATTENDED WHILE THIS TEST IS RUNNING\n"); // Does a window manager exist on the platform? if (!m_wm->openDisplay(&message)) { QSKIP(message.toLatin1().constData()); } // Paranoia: Do we have our test file? const QDir workDir(m_dir); if (!workDir.exists()) { message = QString::fromLatin1("Invalid working directory %1").arg(m_dir); QFAIL(message.toLocal8Bit().constData()); } } void tst_GuiAppLauncher::run() { QString errorMessage; QFETCH(AppLaunchData, data); const bool rc = runApp(data, &errorMessage); if (!rc) // Wait for windows to disappear after kill WindowManager::sleepMS(500); QVERIFY2(rc, qPrintable(errorMessage)); } // Cross platform galore! static inline QString guiBinary(QString in) { #ifdef Q_OS_MAC return in + QLatin1String(".app/Contents/MacOS/") + in; #endif in[0] = in.at(0).toLower(); #ifdef Q_OS_WIN in += QLatin1String(".exe"); #endif return in; } void tst_GuiAppLauncher::run_data() { QTest::addColumn<AppLaunchData>("data"); foreach(const TestDataEntry &data, testData()) { qDebug() << data.first << data.second.binary; QTest::newRow(data.first) << data.second; } } static QList<Example> readDataEntriesFromFile(const QString &fileName) { QList<Example> ret; QFile file(fileName); if (!file.open(QFile::ReadOnly)) return ret; QByteArray line; QRegExp lineMatcher("\"([^\"]*)\", *\"([^\"]*)\", *\"([^\"]*)\", *([-0-9]*), *([-0-9]*)"); for (line = file.readLine(); !line.isEmpty(); line = file.readLine()) { int matchPos = lineMatcher.indexIn(QString::fromLatin1(line)); if (matchPos < 0) break; Example example; example.name = lineMatcher.cap(1).toLatin1(); example.directory = lineMatcher.cap(2).toLatin1(); example.binary = lineMatcher.cap(3).toLatin1(); example.priority = lineMatcher.cap(4).toUInt(); example.upTimeMS = lineMatcher.cap(5).toInt(); ret << example; } return ret; } // Read out the examples array structures and convert to test data. static tst_GuiAppLauncher::TestDataEntries exampleData(unsigned priority, const QString &path, const QList<Example> exArray, unsigned n) { tst_GuiAppLauncher::TestDataEntries rc; const QChar slash = QLatin1Char('/'); AppLaunchData data; for (unsigned e = 0; e < n; e++) { const Example &example = exArray[e]; if (example.priority <= priority) { data.clear(); const QString examplePath = path + slash + example.directory; data.binary = examplePath + slash; #ifdef Q_OS_WIN // FIXME: support debug version too? data.binary += QLatin1String("release/"); #endif data.binary += guiBinary(example.binary); data.workingDirectory = examplePath; if (example.upTimeMS > 0) data.upTimeMS = example.upTimeMS; rc.append(tst_GuiAppLauncher::TestDataEntry(example.name.constData(), data)); } } return rc; } tst_GuiAppLauncher::TestDataEntries tst_GuiAppLauncher::testData() const { TestDataEntries rc; const QChar slash = QLatin1Char('/'); const QString binPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + slash; const QString path = qgetenv("QT_MODULE_TO_TEST"); AppLaunchData data; if (m_testMask & TestTools) { data.binary = binPath + guiBinary(QLatin1String("Designer")); data.args.append(m_dir + QLatin1String("test.ui")); rc.append(TestDataEntry("Qt Designer", data)); data.clear(); data.binary = binPath + guiBinary(QLatin1String("Linguist")); data.splashScreen = true; data.upTimeMS = 5000; // Slow loading data.args.append(m_dir + QLatin1String("test.ts")); rc.append(TestDataEntry("Qt Linguist", data)); } if (m_testMask & TestExamples) { if (!path.isEmpty()) { examples = readDataEntriesFromFile(path + "/tests/auto/guiapplauncher/examples.txt"); rc += exampleData(m_examplePriority, path, examples, examples.size()); } } qDebug("Running %d tests...", rc.size()); return rc; } static inline void ensureTerminated(QProcess *p) { if (p->state() != QProcess::Running) return; p->terminate(); if (p->waitForFinished(300)) return; p->kill(); if (!p->waitForFinished(500)) qWarning("Unable to terminate process"); } static const QStringList &stderrWhiteList() { static QStringList rc; if (rc.empty()) { rc << QLatin1String("QPainter::begin: Paint device returned engine == 0, type: 2") << QLatin1String("QPainter::setRenderHint: Painter must be active to set rendering hints") << QLatin1String("QPainter::setPen: Painter not active") << QLatin1String("QPainter::setBrush: Painter not active") << QLatin1String("QPainter::end: Painter not active, aborted"); } return rc; } bool tst_GuiAppLauncher::runApp(const AppLaunchData &data, QString *errorMessage) const { qDebug("Launching: %s\n", qPrintable(data.binary)); QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); if (!data.workingDirectory.isEmpty()) process.setWorkingDirectory(data.workingDirectory); process.start(data.binary, data.args); process.closeWriteChannel(); if (!process.waitForStarted()) { *errorMessage = QString::fromLatin1("Unable to execute %1: %2").arg(data.binary, process.errorString()); return false; } // Get window id. const QString winId = m_wm->waitForTopLevelWindow(data.splashScreen ? 2 : 1, process.pid(), data.topLevelWindowTimeoutMS, errorMessage); if (winId.isEmpty()) { ensureTerminated(&process); return false; } qDebug("Window: %s\n", qPrintable(winId)); // Wait a bit, then send close WindowManager::sleepMS(data.upTimeMS); if (m_wm->sendCloseEvent(winId, process.pid(), errorMessage)) { qDebug("Sent close to window: %s\n", qPrintable(winId)); } else { ensureTerminated(&process); return false; } // Terminate if (!process.waitForFinished(data.terminationTimeoutMS)) { *errorMessage = QString::fromLatin1("%1: Timeout %2ms").arg(data.binary).arg(data.terminationTimeoutMS); ensureTerminated(&process); return false; } if (process.exitStatus() != QProcess::NormalExit) { *errorMessage = QString::fromLatin1("%1: Startup crash").arg(data.binary); return false; } const int exitCode = process.exitCode(); // check stderr const QStringList stderrOutput = QString::fromLocal8Bit(process.readAllStandardOutput()).split(QLatin1Char('\n')); foreach(const QString &stderrLine, stderrOutput) { // Skip expected QPainter warnings from oxygen. if (stderrWhiteList().contains(stderrLine)) { qWarning("%s: stderr: %s\n", qPrintable(data.binary), qPrintable(stderrLine)); } else { if (!stderrLine.isEmpty()) { // Split oddity gives empty messages *errorMessage = QString::fromLatin1("%1: Unexpected output (ex=%2): '%3'").arg(data.binary).arg(exitCode).arg(stderrLine); return false; } } } if (exitCode != 0) { *errorMessage = QString::fromLatin1("%1: Exit code %2").arg(data.binary).arg(exitCode); return false; } return true; } void tst_GuiAppLauncher::cleanupTestCase() { } QTEST_APPLESS_MAIN(tst_GuiAppLauncher) #include "tst_guiapplauncher.moc" <|endoftext|>
<commit_before>#include<stdio.h> #include<iostream> #include<ros/ros.h> #include<steer_drive_controller/steer_drive_controller.h> // ros_control #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> // gazebo #include <control_toolbox/pid.h> #include <gazebo_ros_control/robot_hw_sim.h> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/common/common.hh> int configureVelocityJointInterface(hardware_interface::VelocityJointInterface&); class SteerBot: //public gazebo_ros_control::RobotHWSim public hardware_interface::RobotHW { // methods public: SteerBot(ros::NodeHandle &_nh) : ns_("steer_drive_controller/") { this->CleanUp(); this->GetJointNames(_nh); this->Resize(); this->RegisterHardwareInterfaces(); } bool initSim(const std::string& _robot_namespace, ros::NodeHandle _nh, gazebo::physics::ModelPtr _model, const urdf::Model* const _urdf_model, std::vector<transmission_interface::TransmissionInfo> _transmissions) { using gazebo::physics::JointPtr; this->CleanUp(); // simulation joints sim_joints_ = _model->GetJoints(); int n_dof = sim_joints_.size(); this->GetJointNames(_nh); this->Resize(); this->RegisterHardwareInterfaces(); } void readSim(ros::Time time, ros::Duration period) { } void writeSim(ros::Time time, ros::Duration period) { } void read() { std::ostringstream os; for (unsigned int i = 0; i < cnt_wheel_joints_ - 1; ++i) { os << wheel_joint_vel_cmd_[i] << ", "; } os << wheel_joint_vel_cmd_[cnt_wheel_joints_ - 1]; ROS_INFO_STREAM("Commands for wheel joints: " << os.str()); } ros::Duration getPeriod() const {return ros::Duration(0.01);} void write() { bool running_ = true; if (running_) { for (unsigned int i = 0; i < cnt_wheel_joints_; ++i) { // Note that pos_[i] will be NaN for one more cycle after we start(), // but that is consistent with the knowledge we have about the state // of the robot. wheel_joint_pos_[i] += wheel_joint_vel_[i]*getPeriod().toSec(); // update position wheel_joint_vel_[i] = wheel_joint_vel_cmd_[i]; // might add smoothing here later } } #if 0 else { std::fill_n(joint_pos_, cnt_wheel_joints_, std::numeric_limits<double>::quiet_NaN()); std::fill_n(joint_vel_, cnt_wheel_joints_, std::numeric_limits<double>::quiet_NaN()); } #endif } private: void CleanUp() { // wheel joints wheel_joint_names_.clear(); wheel_joint_pos_.clear(); wheel_joint_vel_.clear(); wheel_joint_eff_.clear(); wheel_joint_vel_cmd_.clear(); // rear wheel joint wheel_jnt_pos_ = 0; wheel_jnt_vel_ = 0; wheel_jnt_eff_ = 0; wheel_jnt_vel_cmd_ = 0; // steer joints steer_joint_names_.clear(); steer_joint_pos_.clear(); steer_joint_vel_.clear(); steer_joint_eff_.clear(); steer_joint_vel_cmd_.clear(); // front steer joint steer_jnt_pos_ = 0; steer_jnt_vel_ = 0; steer_jnt_eff_ = 0; steer_jnt_pos_cmd_ = 0; } void Resize() { // wheel joints wheel_joint_pos_.resize(cnt_wheel_joints_); wheel_joint_vel_.resize(cnt_wheel_joints_); wheel_joint_eff_.resize(cnt_wheel_joints_); wheel_joint_vel_cmd_.resize(cnt_wheel_joints_); // steer joints steer_joint_pos_.resize(cnt_steer_joints_); steer_joint_vel_.resize(cnt_steer_joints_); steer_joint_eff_.resize(cnt_steer_joints_); steer_joint_vel_cmd_.resize(cnt_steer_joints_); } void GetJointNames(ros::NodeHandle &_nh) { this->GetWheelJointNames(_nh); this->GetSteerJointNames(_nh); } void GetWheelJointNames(ros::NodeHandle &_nh) { // wheel names std::vector<std::string> right_wheel_joint_names; std::vector<std::string> left_wheel_joint_names; _nh.getParam(ns_ + "right_wheel", right_wheel_joint_names); _nh.getParam(ns_ + "left_wheel", left_wheel_joint_names); wheel_joint_names_ = right_wheel_joint_names; std::copy(left_wheel_joint_names.begin(), left_wheel_joint_names.end(), std::back_inserter(wheel_joint_names_)); cnt_wheel_joints_ = wheel_joint_names_.size(); // rear wheel name std::string wheel_joint_name; _nh.getParam(ns_ + "rear_wheel", wheel_joint_name); wheel_joint_name_ = wheel_joint_name; } void GetSteerJointNames(ros::NodeHandle &_nh) { // steer names std::vector<std::string> right_steer_joint_names; std::vector<std::string> left_steer_joint_names; _nh.getParam(ns_ + "right_steer", right_steer_joint_names); _nh.getParam(ns_ + "left_steer", left_steer_joint_names); steer_joint_names_ = right_steer_joint_names; std::copy(left_steer_joint_names.begin(), left_steer_joint_names.end(), std::back_inserter(steer_joint_names_)); cnt_steer_joints_ = steer_joint_names_.size(); // front steer name std::string steer_joint_name; _nh.getParam(ns_ + "front_steer", steer_joint_name); wheel_joint_name_ = steer_joint_name; } void RegisterHardwareInterfaces() { this->RegisterSteerInterfaces(); this->RegisterWheelInterfaces(); } void RegisterWheelInterfaces() { // map members to hardware interfaces for (size_t i = 0; i < cnt_wheel_joints_; ++i) { // joint states hardware_interface::JointStateHandle state_handle(wheel_joint_names_[i], &wheel_joint_pos_[i], &wheel_joint_vel_[i], &wheel_joint_eff_[i]); wheel_joint_state_interface_.registerHandle(state_handle); // joint velocity command hardware_interface::JointHandle vel_handle(wheel_joint_state_interface_.getHandle(wheel_joint_names_[i]), &wheel_joint_vel_cmd_[i]); wheel_vel_joint_interface_.registerHandle(vel_handle); ROS_DEBUG_STREAM("Registered joint '" << wheel_joint_names_[i] << " ' in the VelocityJointInterface"); } // register mapped interface to ros_control registerInterface(&wheel_joint_state_interface_); registerInterface(&wheel_vel_joint_interface_); } void RegisterSteerInterfaces() { // map members to hardware interfaces for (size_t i = 0; i < cnt_steer_joints_; ++i) { // joint states hardware_interface::JointStateHandle state_handle(steer_joint_names_[i], &steer_joint_pos_[i], &steer_joint_vel_[i], &steer_joint_eff_[i]); steer_joint_state_interface_.registerHandle(state_handle); // joint position command hardware_interface::JointHandle pos_handle(steer_joint_state_interface_.getHandle(steer_joint_names_[i]), &steer_joint_vel_cmd_[i]); steer_pos_joint_interface_.registerHandle(pos_handle); ROS_DEBUG_STREAM("Registered joint '" << steer_joint_names_[i] << " ' in the PositionJointInterface"); } // register mapped interface to ros_control registerInterface(&steer_joint_state_interface_); registerInterface(&steer_pos_joint_interface_); } // member variables public: hardware_interface::VelocityJointInterface wheel_vel_joint_interface_; hardware_interface::PositionJointInterface steer_pos_joint_interface_; private: ros::NodeHandle nh_; std::string ns_; // std::vector<std::string> wheel_joint_names_; std::vector<std::string> steer_joint_names_; std::string wheel_joint_name_; std::string steer_joint_name_; // interface variables //-- wheel int cnt_wheel_joints_; std::vector<double> wheel_joint_pos_; std::vector<double> wheel_joint_vel_; std::vector<double> wheel_joint_eff_; std::vector<double> wheel_joint_vel_cmd_; //-- rear wheel double wheel_jnt_pos_; double wheel_jnt_vel_; double wheel_jnt_eff_; double wheel_jnt_vel_cmd_; //-- steer int cnt_steer_joints_; std::vector<double> steer_joint_pos_; std::vector<double> steer_joint_vel_; std::vector<double> steer_joint_eff_; std::vector<double> steer_joint_vel_cmd_; //-- front steer double steer_jnt_pos_; double steer_jnt_vel_; double steer_jnt_eff_; double steer_jnt_pos_cmd_; // hardware_interface::JointStateInterface wheel_joint_state_interface_; hardware_interface::JointStateInterface steer_joint_state_interface_; // gazebo std::vector<gazebo::physics::JointPtr> sim_joints_; }; int main(int argc, char **argv) { ros::init(argc, argv, "steer_drive_test"); ros::NodeHandle nh_main; ros::NodeHandle nh_control; SteerBot* steer_drive_bot = new SteerBot(nh_control); steer_drive_controller::SteerDriveController rb_controller; #if 0 bool rt_code = rb_controller.init(//&steer_drive_bot->wheel_vel_joint_interface_, steer_drive_bot, nh_main, nh_control); #endif std::set<std::string> claimed_resources; // Gets populated during initRequest call bool rt_code = rb_controller.init(steer_drive_bot, nh_main, nh_control);//, claimed_resources); ros::Rate rate(100); ros::Time last_time = ros::Time::now(); while(nh_main.ok()) { ros::Time now = ros::Time::now(); ros::Duration period = now - last_time; last_time = now; steer_drive_bot->read(); rb_controller.update(now, period); steer_drive_bot->write(); ros::spinOnce(); rate.sleep(); } return 0; } <commit_msg>[WIP] joint_state_interface周りをちょっと修正<commit_after>#include<stdio.h> #include<iostream> #include<ros/ros.h> #include<steer_drive_controller/steer_drive_controller.h> // ros_control #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> // gazebo #include <control_toolbox/pid.h> #include <gazebo_ros_control/robot_hw_sim.h> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/common/common.hh> int configureVelocityJointInterface(hardware_interface::VelocityJointInterface&); class SteerBot: //public gazebo_ros_control::RobotHWSim public hardware_interface::RobotHW { // methods public: SteerBot(ros::NodeHandle &_nh) : ns_("steer_drive_controller/") { this->CleanUp(); this->GetJointNames(_nh); this->Resize(); this->RegisterHardwareInterfaces(); } bool initSim(const std::string& _robot_namespace, ros::NodeHandle _nh, gazebo::physics::ModelPtr _model, const urdf::Model* const _urdf_model, std::vector<transmission_interface::TransmissionInfo> _transmissions) { using gazebo::physics::JointPtr; this->CleanUp(); // simulation joints sim_joints_ = _model->GetJoints(); int n_dof = sim_joints_.size(); this->GetJointNames(_nh); this->Resize(); this->RegisterHardwareInterfaces(); } void readSim(ros::Time time, ros::Duration period) { } void writeSim(ros::Time time, ros::Duration period) { } void read() { std::ostringstream os; for (unsigned int i = 0; i < cnt_wheel_joints_ - 1; ++i) { os << wheel_joint_vel_cmd_[i] << ", "; } os << wheel_joint_vel_cmd_[cnt_wheel_joints_ - 1]; ROS_INFO_STREAM("Commands for wheel joints: " << os.str()); } ros::Duration getPeriod() const {return ros::Duration(0.01);} void write() { bool running_ = true; if (running_) { for (unsigned int i = 0; i < cnt_wheel_joints_; ++i) { // Note that pos_[i] will be NaN for one more cycle after we start(), // but that is consistent with the knowledge we have about the state // of the robot. wheel_joint_pos_[i] += wheel_joint_vel_[i]*getPeriod().toSec(); // update position wheel_joint_vel_[i] = wheel_joint_vel_cmd_[i]; // might add smoothing here later } } #if 0 else { std::fill_n(joint_pos_, cnt_wheel_joints_, std::numeric_limits<double>::quiet_NaN()); std::fill_n(joint_vel_, cnt_wheel_joints_, std::numeric_limits<double>::quiet_NaN()); } #endif } private: void CleanUp() { // wheel joints wheel_joint_names_.clear(); wheel_joint_pos_.clear(); wheel_joint_vel_.clear(); wheel_joint_eff_.clear(); wheel_joint_vel_cmd_.clear(); // rear wheel joint wheel_jnt_pos_ = 0; wheel_jnt_vel_ = 0; wheel_jnt_eff_ = 0; wheel_jnt_vel_cmd_ = 0; // steer joints steer_joint_names_.clear(); steer_joint_pos_.clear(); steer_joint_vel_.clear(); steer_joint_eff_.clear(); steer_joint_vel_cmd_.clear(); // front steer joint steer_jnt_pos_ = 0; steer_jnt_vel_ = 0; steer_jnt_eff_ = 0; steer_jnt_pos_cmd_ = 0; } void Resize() { // wheel joints wheel_joint_pos_.resize(cnt_wheel_joints_); wheel_joint_vel_.resize(cnt_wheel_joints_); wheel_joint_eff_.resize(cnt_wheel_joints_); wheel_joint_vel_cmd_.resize(cnt_wheel_joints_); // steer joints steer_joint_pos_.resize(cnt_steer_joints_); steer_joint_vel_.resize(cnt_steer_joints_); steer_joint_eff_.resize(cnt_steer_joints_); steer_joint_vel_cmd_.resize(cnt_steer_joints_); } void GetJointNames(ros::NodeHandle &_nh) { this->GetWheelJointNames(_nh); this->GetSteerJointNames(_nh); _nh.getParam(ns_ + "rear_wheel", wheel_jnt_name_); _nh.getParam(ns_ + "front_steer", steer_jnt_name_); } void GetWheelJointNames(ros::NodeHandle &_nh) { // wheel names std::vector<std::string> right_wheel_joint_names; std::vector<std::string> left_wheel_joint_names; _nh.getParam(ns_ + "right_wheel", right_wheel_joint_names); _nh.getParam(ns_ + "left_wheel", left_wheel_joint_names); wheel_joint_names_ = right_wheel_joint_names; std::copy(left_wheel_joint_names.begin(), left_wheel_joint_names.end(), std::back_inserter(wheel_joint_names_)); cnt_wheel_joints_ = wheel_joint_names_.size(); // rear wheel name std::string wheel_joint_name; /* _nh.getParam(ns_ + "rear_wheel", wheel_joint_name); wheel_joint_name_ = wheel_joint_name; */ } void GetSteerJointNames(ros::NodeHandle &_nh) { // steer names std::vector<std::string> right_steer_joint_names; std::vector<std::string> left_steer_joint_names; _nh.getParam(ns_ + "right_steer", right_steer_joint_names); _nh.getParam(ns_ + "left_steer", left_steer_joint_names); steer_joint_names_ = right_steer_joint_names; std::copy(left_steer_joint_names.begin(), left_steer_joint_names.end(), std::back_inserter(steer_joint_names_)); cnt_steer_joints_ = steer_joint_names_.size(); // front steer name std::string steer_joint_name; /* _nh.getParam(ns_ + "front_steer", steer_joint_name); wheel_joint_name_ = steer_joint_name; */ } void RegisterHardwareInterfaces() { this->RegisterSteerInterfaces(); hardware_interface::JointStateHandle state_handle_steer(wheel_jnt_name_, &wheel_jnt_pos_, &wheel_jnt_vel_, &wheel_jnt_eff_); wheel_joint_state_interface_.registerHandle(state_handle_steer); // joint velocity command hardware_interface::JointHandle vel_handle(wheel_joint_state_interface_.getHandle(wheel_jnt_name_), &wheel_jnt_vel_cmd_); wheel_vel_joint_interface_.registerHandle(vel_handle); ROS_DEBUG_STREAM("Registered joint '" << wheel_joint_name_ << " ' in the VelocityJointInterface"); this->RegisterWheelInterfaces(); hardware_interface::JointStateHandle state_handle_wheel(steer_jnt_name_, &steer_jnt_pos_, &steer_jnt_vel_, &steer_jnt_eff_); steer_joint_state_interface_.registerHandle(state_handle_wheel); // joint position command hardware_interface::JointHandle pos_handle(steer_joint_state_interface_.getHandle(steer_jnt_name_), &steer_jnt_pos_cmd_); steer_pos_joint_interface_.registerHandle(pos_handle); ROS_DEBUG_STREAM("Registered joint '" << steer_joint_name_ << " ' in the PositionJointInterface"); } void RegisterWheelInterfaces() { // map members to hardware interfaces for (size_t i = 0; i < cnt_wheel_joints_; ++i) { // joint states hardware_interface::JointStateHandle state_handle(wheel_joint_names_[i], &wheel_joint_pos_[i], &wheel_joint_vel_[i], &wheel_joint_eff_[i]); wheel_joint_state_interface_.registerHandle(state_handle); // joint velocity command hardware_interface::JointHandle vel_handle(wheel_joint_state_interface_.getHandle(wheel_joint_names_[i]), &wheel_joint_vel_cmd_[i]); wheel_vel_joint_interface_.registerHandle(vel_handle); ROS_DEBUG_STREAM("Registered joint '" << wheel_joint_names_[i] << " ' in the VelocityJointInterface"); } // register mapped interface to ros_control registerInterface(&wheel_joint_state_interface_); registerInterface(&wheel_vel_joint_interface_); } void RegisterSteerInterfaces() { // map members to hardware interfaces for (size_t i = 0; i < cnt_steer_joints_; ++i) { // joint states hardware_interface::JointStateHandle state_handle(steer_joint_names_[i], &steer_joint_pos_[i], &steer_joint_vel_[i], &steer_joint_eff_[i]); steer_joint_state_interface_.registerHandle(state_handle); // joint position command hardware_interface::JointHandle pos_handle(steer_joint_state_interface_.getHandle(steer_joint_names_[i]), &steer_joint_vel_cmd_[i]); steer_pos_joint_interface_.registerHandle(pos_handle); ROS_DEBUG_STREAM("Registered joint '" << steer_joint_names_[i] << " ' in the PositionJointInterface"); } // register mapped interface to ros_control registerInterface(&steer_joint_state_interface_); registerInterface(&steer_pos_joint_interface_); } // member variables public: hardware_interface::VelocityJointInterface wheel_vel_joint_interface_; hardware_interface::PositionJointInterface steer_pos_joint_interface_; private: ros::NodeHandle nh_; std::string ns_; // std::vector<std::string> wheel_joint_names_; std::vector<std::string> steer_joint_names_; std::string wheel_jnt_name_; std::string steer_jnt_name_; // interface variables //-- wheel int cnt_wheel_joints_; std::vector<double> wheel_joint_pos_; std::vector<double> wheel_joint_vel_; std::vector<double> wheel_joint_eff_; std::vector<double> wheel_joint_vel_cmd_; //-- rear wheel double wheel_jnt_pos_; double wheel_jnt_vel_; double wheel_jnt_eff_; double wheel_jnt_vel_cmd_; //-- steer int cnt_steer_joints_; std::vector<double> steer_joint_pos_; std::vector<double> steer_joint_vel_; std::vector<double> steer_joint_eff_; std::vector<double> steer_joint_vel_cmd_; //-- front steer double steer_jnt_pos_; double steer_jnt_vel_; double steer_jnt_eff_; double steer_jnt_pos_cmd_; // hardware_interface::JointStateInterface wheel_joint_state_interface_; hardware_interface::JointStateInterface steer_joint_state_interface_; // gazebo std::vector<gazebo::physics::JointPtr> sim_joints_; }; int main(int argc, char **argv) { ros::init(argc, argv, "steer_drive_test"); ros::NodeHandle nh_main; ros::NodeHandle nh_control; SteerBot* steer_drive_bot = new SteerBot(nh_control); steer_drive_controller::SteerDriveController rb_controller; #if 0 bool rt_code = rb_controller.init(//&steer_drive_bot->wheel_vel_joint_interface_, steer_drive_bot, nh_main, nh_control); #endif std::set<std::string> claimed_resources; // Gets populated during initRequest call bool rt_code = rb_controller.init(steer_drive_bot, nh_main, nh_control);//, claimed_resources); ros::Rate rate(100); ros::Time last_time = ros::Time::now(); while(nh_main.ok()) { ros::Time now = ros::Time::now(); ros::Duration period = now - last_time; last_time = now; steer_drive_bot->read(); rb_controller.update(now, period); steer_drive_bot->write(); ros::spinOnce(); rate.sleep(); } return 0; } <|endoftext|>
<commit_before>#include "typecheck.h" #pragma warning(push, 0) #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include <llvm/Support/SaveAndRestore.h> #pragma warning(pop) #include "../ast/module.h" #include "../driver/driver.h" #include "../package-manager/manifest.h" #include "../parser/parse.h" using namespace cx; TypeDecl* Typechecker::getTypeDecl(const BasicType& type) { if (auto* typeDecl = type.getDecl()) { return typeDecl; } auto decls = findDecls(type.getQualifiedName()); if (!decls.empty()) { ASSERT(decls.size() == 1); return llvm::dyn_cast_or_null<TypeDecl>(decls[0]); } decls = findDecls(type.getName()); if (decls.empty()) return nullptr; ASSERT(decls.size() == 1); auto instantiation = llvm::cast<TypeTemplate>(decls[0])->instantiate(type.getGenericArgs()); getCurrentModule()->addToSymbolTable(*instantiation); declsToTypecheck.push_back(instantiation); return instantiation; } static std::error_code importModuleSourcesInDirectoryRecursively(const llvm::Twine& directoryPath, Module& module, const CompileOptions& options) { std::error_code error; std::vector<std::string> paths; for (llvm::sys::fs::recursive_directory_iterator it(directoryPath, error), end; it != end; it.increment(error)) { if (error) break; if (llvm::sys::path::extension(it->path()) == ".cx") { paths.push_back(it->path()); } } if (!error) { llvm::sort(paths); for (auto& path : paths) { Parser parser(path, module, options); parser.parse(); } } if (module.getSourceFiles().empty()) { REPORT_ERROR(SourceLocation(), "Module '" << module.getName() << "' import failed: no source files found in '" << directoryPath << "' or its subdirectories"); } return error; } llvm::ErrorOr<const Module&> Typechecker::importModule(SourceFile* importer, const PackageManifest* manifest, llvm::StringRef moduleName) { auto it = Module::getAllImportedModulesMap().find(moduleName); if (it != Module::getAllImportedModulesMap().end()) { if (importer) importer->addImportedModule(it->second); return *it->second; } auto module = new Module(moduleName); std::error_code error; if (manifest) { for (auto& dependency : manifest->getDeclaredDependencies()) { if (dependency.getPackageIdentifier() == moduleName) { error = importModuleSourcesInDirectoryRecursively(dependency.getFileSystemPath(), *module, options); goto done; } } } for (llvm::StringRef importPath : options.importSearchPaths) { auto modulePath = (importPath + "/" + moduleName).str(); if (llvm::sys::fs::is_directory(modulePath)) { error = importModuleSourcesInDirectoryRecursively(modulePath, *module, options); goto done; } } done: if (error) return error; if (importer) importer->addImportedModule(module); Module::getAllImportedModulesMap()[module->getName()] = module; typecheckModule(*module, nullptr); return *module; } void Typechecker::postProcess() { llvm::SaveAndRestore setPostProcessing(isPostProcessing, true); while (!declsToTypecheck.empty()) { auto currentDeclsToTypecheck = std::move(declsToTypecheck); for (auto* decl : currentDeclsToTypecheck) { switch (decl->getKind()) { case DeclKind::FunctionDecl: case DeclKind::MethodDecl: case DeclKind::ConstructorDecl: case DeclKind::DestructorDecl: typecheckFunctionDecl(*llvm::cast<FunctionDecl>(decl)); break; case DeclKind::FunctionTemplate: typecheckFunctionTemplate(*llvm::cast<FunctionTemplate>(decl)); break; case DeclKind::TypeDecl: typecheckTypeDecl(*llvm::cast<TypeDecl>(decl)); break; default: llvm_unreachable("invalid deferred decl"); } } } } static void checkUnusedDecls(const Module& module) { for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { if (decl->isReferenced()) continue; if (decl->isFunctionDecl() || decl->isFunctionTemplate()) { if (decl->isMain()) continue; WARN(decl->getLocation(), "unused declaration '" << decl->getName() << "'"); } } } } void Typechecker::typecheckModule(Module& module, const PackageManifest* manifest) { auto stdModule = importModule(nullptr, nullptr, "std"); if (!stdModule) { ABORT("couldn't import the standard library: " << stdModule.getError().message()); } // Typecheck implemented interfaces so that inherited methods and fields are added to the implementing type before they're referenced. for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { currentModule = &module; currentSourceFile = &sourceFile; if (auto typeDecl = llvm::dyn_cast<TypeDecl>(decl)) { llvm::StringMap<Type> genericArgs = { { "This", typeDecl->getType() } }; for (Type interface : typeDecl->getInterfaces()) { typecheckType(interface, typeDecl->getAccessLevel()); std::vector<FieldDecl> inheritedFields; for (auto& field : interface.getDecl()->getFields()) { inheritedFields.push_back(field.instantiate(genericArgs, *typeDecl)); } typeDecl->getFields().insert(typeDecl->getFields().begin(), inheritedFields.begin(), inheritedFields.end()); for (auto member : interface.getDecl()->getMethods()) { auto methodDecl = llvm::cast<MethodDecl>(member); if (methodDecl->hasBody()) { auto copy = methodDecl->instantiate(genericArgs, {}, *typeDecl); getCurrentModule()->addToSymbolTable(*copy); typeDecl->addMethod(copy); } } } } } } // Infer the types of global variables for use before their declaration. for (auto& sourceFile : module.getSourceFiles()) { currentModule = &module; currentSourceFile = &sourceFile; for (auto& decl : sourceFile.getTopLevelDecls()) { if (auto* varDecl = llvm::dyn_cast<VarDecl>(decl)) { try { typecheckVarDecl(*varDecl); } catch (const CompileError& error) { error.print(); } } } postProcess(); } for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { currentModule = &module; currentSourceFile = &sourceFile; if (!decl->isVarDecl()) { try { typecheckTopLevelDecl(*decl, manifest); } catch (const CompileError& error) { error.print(); } postProcess(); } } } if (module.getName() != "std" && isWarningEnabled("unused")) { checkUnusedDecls(module); } currentModule = nullptr; currentSourceFile = nullptr; } bool Typechecker::isWarningEnabled(llvm::StringRef warning) const { return !llvm::is_contained(options.disabledWarnings, warning); } static llvm::SmallVector<Decl*, 1> findDeclsInModules(llvm::StringRef name, llvm::ArrayRef<Module*> modules) { llvm::SmallVector<Decl*, 1> decls; for (auto& module : modules) { llvm::ArrayRef<Decl*> matches = module->getSymbolTable().find(name); decls.append(matches.begin(), matches.end()); } return decls; } static Decl* findDeclInModules(llvm::StringRef name, SourceLocation location, llvm::ArrayRef<Module*> modules) { auto decls = findDeclsInModules(name, modules); if (decls.empty()) { return nullptr; } else { if (decls.size() > 1) ERROR(location, "ambiguous reference to '" << name << "'"); return decls[0]; } } Decl* Typechecker::findDecl(llvm::StringRef name, SourceLocation location) const { ASSERT(!name.empty()); if (Decl* match = findDeclInModules(name, location, currentModule)) { return match; } if (currentFunction) { if (auto* typeDecl = currentFunction->getTypeDecl()) { for (auto& field : typeDecl->getFields()) { if (field.getName() == name) { return &field; } } } } if (Decl* match = findDeclInModules(name, location, Module::getStdlibModule())) { return match; } if (currentSourceFile) { if (Decl* match = findDeclInModules(name, location, currentSourceFile->getImportedModules())) { return match; } } else { if (Decl* match = findDeclInModules(name, location, Module::getAllImportedModules())) { return match; } } ERROR(location, "unknown identifier '" << name << "'"); } static void append(std::vector<Decl*>& target, llvm::ArrayRef<Decl*> source) { for (auto& element : source) { // TODO: Should this ever be false? I.e. should the same decl ever be in multiple different modules? if (!llvm::is_contained(target, element)) { target.push_back(element); } } } std::vector<Decl*> Typechecker::findDecls(llvm::StringRef name, TypeDecl* receiverTypeDecl, bool inAllImportedModules) const { std::vector<Decl*> decls; if (!receiverTypeDecl && currentFunction) { receiverTypeDecl = currentFunction->getTypeDecl(); } if (receiverTypeDecl) { for (auto& decl : receiverTypeDecl->getMethods()) { if (auto* functionDecl = llvm::dyn_cast<FunctionDecl>(decl)) { if (functionDecl->getName() == name) { decls.emplace_back(decl); } } else if (auto* functionTemplate = llvm::dyn_cast<FunctionTemplate>(decl)) { if (functionTemplate->getQualifiedName() == name) { decls.emplace_back(decl); } } } for (auto& field : receiverTypeDecl->getFields()) { // TODO: Only one comparison should be needed. if (field.getName() == name || field.getQualifiedName() == name) { decls.emplace_back(&field); } } } if (currentModule->getName() != "std") { append(decls, findDeclsInModules(name, currentModule)); } append(decls, findDeclsInModules(name, Module::getStdlibModule())); if (currentSourceFile && !inAllImportedModules) { append(decls, findDeclsInModules(name, currentSourceFile->getImportedModules())); } else { append(decls, findDeclsInModules(name, Module::getAllImportedModules())); } return decls; } <commit_msg>When C headers redefine a macro, use the last definition instead of erroring<commit_after>#include "typecheck.h" #pragma warning(push, 0) #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include <llvm/Support/SaveAndRestore.h> #pragma warning(pop) #include "../ast/module.h" #include "../driver/driver.h" #include "../package-manager/manifest.h" #include "../parser/parse.h" using namespace cx; TypeDecl* Typechecker::getTypeDecl(const BasicType& type) { if (auto* typeDecl = type.getDecl()) { return typeDecl; } auto decls = findDecls(type.getQualifiedName()); if (!decls.empty()) { ASSERT(decls.size() == 1); return llvm::dyn_cast_or_null<TypeDecl>(decls[0]); } decls = findDecls(type.getName()); if (decls.empty()) return nullptr; ASSERT(decls.size() == 1); auto instantiation = llvm::cast<TypeTemplate>(decls[0])->instantiate(type.getGenericArgs()); getCurrentModule()->addToSymbolTable(*instantiation); declsToTypecheck.push_back(instantiation); return instantiation; } static std::error_code importModuleSourcesInDirectoryRecursively(const llvm::Twine& directoryPath, Module& module, const CompileOptions& options) { std::error_code error; std::vector<std::string> paths; for (llvm::sys::fs::recursive_directory_iterator it(directoryPath, error), end; it != end; it.increment(error)) { if (error) break; if (llvm::sys::path::extension(it->path()) == ".cx") { paths.push_back(it->path()); } } if (!error) { llvm::sort(paths); for (auto& path : paths) { Parser parser(path, module, options); parser.parse(); } } if (module.getSourceFiles().empty()) { REPORT_ERROR(SourceLocation(), "Module '" << module.getName() << "' import failed: no source files found in '" << directoryPath << "' or its subdirectories"); } return error; } llvm::ErrorOr<const Module&> Typechecker::importModule(SourceFile* importer, const PackageManifest* manifest, llvm::StringRef moduleName) { auto it = Module::getAllImportedModulesMap().find(moduleName); if (it != Module::getAllImportedModulesMap().end()) { if (importer) importer->addImportedModule(it->second); return *it->second; } auto module = new Module(moduleName); std::error_code error; if (manifest) { for (auto& dependency : manifest->getDeclaredDependencies()) { if (dependency.getPackageIdentifier() == moduleName) { error = importModuleSourcesInDirectoryRecursively(dependency.getFileSystemPath(), *module, options); goto done; } } } for (llvm::StringRef importPath : options.importSearchPaths) { auto modulePath = (importPath + "/" + moduleName).str(); if (llvm::sys::fs::is_directory(modulePath)) { error = importModuleSourcesInDirectoryRecursively(modulePath, *module, options); goto done; } } done: if (error) return error; if (importer) importer->addImportedModule(module); Module::getAllImportedModulesMap()[module->getName()] = module; typecheckModule(*module, nullptr); return *module; } void Typechecker::postProcess() { llvm::SaveAndRestore setPostProcessing(isPostProcessing, true); while (!declsToTypecheck.empty()) { auto currentDeclsToTypecheck = std::move(declsToTypecheck); for (auto* decl : currentDeclsToTypecheck) { switch (decl->getKind()) { case DeclKind::FunctionDecl: case DeclKind::MethodDecl: case DeclKind::ConstructorDecl: case DeclKind::DestructorDecl: typecheckFunctionDecl(*llvm::cast<FunctionDecl>(decl)); break; case DeclKind::FunctionTemplate: typecheckFunctionTemplate(*llvm::cast<FunctionTemplate>(decl)); break; case DeclKind::TypeDecl: typecheckTypeDecl(*llvm::cast<TypeDecl>(decl)); break; default: llvm_unreachable("invalid deferred decl"); } } } } static void checkUnusedDecls(const Module& module) { for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { if (decl->isReferenced()) continue; if (decl->isFunctionDecl() || decl->isFunctionTemplate()) { if (decl->isMain()) continue; WARN(decl->getLocation(), "unused declaration '" << decl->getName() << "'"); } } } } void Typechecker::typecheckModule(Module& module, const PackageManifest* manifest) { auto stdModule = importModule(nullptr, nullptr, "std"); if (!stdModule) { ABORT("couldn't import the standard library: " << stdModule.getError().message()); } // Typecheck implemented interfaces so that inherited methods and fields are added to the implementing type before they're referenced. for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { currentModule = &module; currentSourceFile = &sourceFile; if (auto typeDecl = llvm::dyn_cast<TypeDecl>(decl)) { llvm::StringMap<Type> genericArgs = { { "This", typeDecl->getType() } }; for (Type interface : typeDecl->getInterfaces()) { typecheckType(interface, typeDecl->getAccessLevel()); std::vector<FieldDecl> inheritedFields; for (auto& field : interface.getDecl()->getFields()) { inheritedFields.push_back(field.instantiate(genericArgs, *typeDecl)); } typeDecl->getFields().insert(typeDecl->getFields().begin(), inheritedFields.begin(), inheritedFields.end()); for (auto member : interface.getDecl()->getMethods()) { auto methodDecl = llvm::cast<MethodDecl>(member); if (methodDecl->hasBody()) { auto copy = methodDecl->instantiate(genericArgs, {}, *typeDecl); getCurrentModule()->addToSymbolTable(*copy); typeDecl->addMethod(copy); } } } } } } // Infer the types of global variables for use before their declaration. for (auto& sourceFile : module.getSourceFiles()) { currentModule = &module; currentSourceFile = &sourceFile; for (auto& decl : sourceFile.getTopLevelDecls()) { if (auto* varDecl = llvm::dyn_cast<VarDecl>(decl)) { try { typecheckVarDecl(*varDecl); } catch (const CompileError& error) { error.print(); } } } postProcess(); } for (auto& sourceFile : module.getSourceFiles()) { for (auto& decl : sourceFile.getTopLevelDecls()) { currentModule = &module; currentSourceFile = &sourceFile; if (!decl->isVarDecl()) { try { typecheckTopLevelDecl(*decl, manifest); } catch (const CompileError& error) { error.print(); } postProcess(); } } } if (module.getName() != "std" && isWarningEnabled("unused")) { checkUnusedDecls(module); } currentModule = nullptr; currentSourceFile = nullptr; } bool Typechecker::isWarningEnabled(llvm::StringRef warning) const { return !llvm::is_contained(options.disabledWarnings, warning); } static llvm::SmallVector<Decl*, 1> findDeclsInModules(llvm::StringRef name, llvm::ArrayRef<Module*> modules) { llvm::SmallVector<Decl*, 1> decls; for (auto& module : modules) { llvm::ArrayRef<Decl*> matches = module->getSymbolTable().find(name); decls.append(matches.begin(), matches.end()); } return decls; } static Decl* findDeclInModules(llvm::StringRef name, SourceLocation location, llvm::ArrayRef<Module*> modules) { auto decls = findDeclsInModules(name, modules); if (decls.size() == 1) { return decls[0]; } else if (decls.empty()) { return nullptr; } else if (llvm::all_of(decls, [](Decl* decl) { return decl->getModule() && decl->getModule()->getName().endswith_lower(".h"); })) { // For duplicate definitions in C headers, return the last definition. TODO: Check that their value is the same. return decls.back(); } else { ERROR(location, "ambiguous reference to '" << name << "'"); } } Decl* Typechecker::findDecl(llvm::StringRef name, SourceLocation location) const { ASSERT(!name.empty()); if (Decl* match = findDeclInModules(name, location, currentModule)) { return match; } if (currentFunction) { if (auto* typeDecl = currentFunction->getTypeDecl()) { for (auto& field : typeDecl->getFields()) { if (field.getName() == name) { return &field; } } } } if (Decl* match = findDeclInModules(name, location, Module::getStdlibModule())) { return match; } if (currentSourceFile) { if (Decl* match = findDeclInModules(name, location, currentSourceFile->getImportedModules())) { return match; } } else { if (Decl* match = findDeclInModules(name, location, Module::getAllImportedModules())) { return match; } } ERROR(location, "unknown identifier '" << name << "'"); } static void append(std::vector<Decl*>& target, llvm::ArrayRef<Decl*> source) { for (auto& element : source) { // TODO: Should this ever be false? I.e. should the same decl ever be in multiple different modules? if (!llvm::is_contained(target, element)) { target.push_back(element); } } } std::vector<Decl*> Typechecker::findDecls(llvm::StringRef name, TypeDecl* receiverTypeDecl, bool inAllImportedModules) const { std::vector<Decl*> decls; if (!receiverTypeDecl && currentFunction) { receiverTypeDecl = currentFunction->getTypeDecl(); } if (receiverTypeDecl) { for (auto& decl : receiverTypeDecl->getMethods()) { if (auto* functionDecl = llvm::dyn_cast<FunctionDecl>(decl)) { if (functionDecl->getName() == name) { decls.emplace_back(decl); } } else if (auto* functionTemplate = llvm::dyn_cast<FunctionTemplate>(decl)) { if (functionTemplate->getQualifiedName() == name) { decls.emplace_back(decl); } } } for (auto& field : receiverTypeDecl->getFields()) { // TODO: Only one comparison should be needed. if (field.getName() == name || field.getQualifiedName() == name) { decls.emplace_back(&field); } } } if (currentModule->getName() != "std") { append(decls, findDeclsInModules(name, currentModule)); } append(decls, findDeclsInModules(name, Module::getStdlibModule())); if (currentSourceFile && !inAllImportedModules) { append(decls, findDeclsInModules(name, currentSourceFile->getImportedModules())); } else { append(decls, findDeclsInModules(name, Module::getAllImportedModules())); } return decls; } <|endoftext|>
<commit_before> #include "serialport.h" #include <list> #include "win/disphelper.h" #ifdef WIN32 std::list<int> g_closingHandles; int bufferSize; void ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) { switch(errorCode) { case ERROR_FILE_NOT_FOUND: sprintf(errorStr, "%s: File not found", prefix); break; case ERROR_INVALID_HANDLE: sprintf(errorStr, "%s: Invalid handle", prefix); break; case ERROR_ACCESS_DENIED: sprintf(errorStr, "%s: Access denied", prefix); break; case ERROR_OPERATION_ABORTED: sprintf(errorStr, "%s: operation aborted", prefix); break; default: sprintf(errorStr, "%s: Unknown error code %d", prefix, errorCode); break; } } void EIO_Open(uv_work_t* req) { OpenBaton* data = static_cast<OpenBaton*>(req->data); HANDLE file = CreateFile( data->path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (file == INVALID_HANDLE_VALUE) { char temp[100]; sprintf(temp, "Opening %s", data->path); ErrorCodeToString(temp, GetLastError(), data->errorString); return; } bufferSize = data->bufferSize; DCB dcb = { 0 }; dcb.DCBlength = sizeof(DCB); if(!BuildCommDCB("9600,n,8,1", &dcb)) { ErrorCodeToString("BuildCommDCB", GetLastError(), data->errorString); return; } dcb.fBinary = true; dcb.BaudRate = data->baudRate; dcb.ByteSize = data->dataBits; switch(data->parity) { case SERIALPORT_PARITY_NONE: dcb.Parity = NOPARITY; break; case SERIALPORT_PARITY_MARK: dcb.Parity = MARKPARITY; break; case SERIALPORT_PARITY_EVEN: dcb.Parity = EVENPARITY; break; case SERIALPORT_PARITY_ODD: dcb.Parity = ODDPARITY; break; case SERIALPORT_PARITY_SPACE: dcb.Parity = SPACEPARITY; break; } switch(data->stopBits) { case SERIALPORT_STOPBITS_ONE: dcb.StopBits = ONESTOPBIT; break; case SERIALPORT_STOPBITS_ONE_FIVE: dcb.StopBits = ONE5STOPBITS; break; case SERIALPORT_STOPBITS_TWO: dcb.StopBits = TWOSTOPBITS; break; } if(!SetCommState(file, &dcb)) { ErrorCodeToString("SetCommState", GetLastError(), data->errorString); return; } // set the com port to return immediatly after a read COMMTIMEOUTS commTimeouts = {0}; commTimeouts.ReadIntervalTimeout = MAXDWORD; commTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD; commTimeouts.ReadTotalTimeoutConstant = 1000; commTimeouts.WriteTotalTimeoutConstant = 1000; commTimeouts.WriteTotalTimeoutMultiplier = 1000; if(!SetCommTimeouts(file, &commTimeouts)) { ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString); return; } data->result = (int)file; } struct WatchPortBaton { public: HANDLE fd; DWORD bytesRead; char buffer[100]; char errorString[1000]; DWORD errorCode; bool disconnected; v8::Persistent<v8::Value> dataCallback; v8::Persistent<v8::Value> errorCallback; v8::Persistent<v8::Value> disconnectedCallback; }; void EIO_WatchPort(uv_work_t* req) { WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data); data->disconnected = false; while(true){ OVERLAPPED ov = {0}; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(!ReadFile(data->fd, data->buffer, bufferSize, &data->bytesRead, &ov)) { data->errorCode = GetLastError(); if(data->errorCode == ERROR_OPERATION_ABORTED) { data->disconnected = true; return; } if(data->errorCode != ERROR_IO_PENDING) { ErrorCodeToString("Reading from COM port (ReadFile)", GetLastError(), data->errorString); return; } DWORD waitResult = WaitForSingleObject(ov.hEvent, 1000); if(waitResult == WAIT_TIMEOUT) { data->bytesRead = 0; data->errorCode = 0; return; } if(waitResult != WAIT_OBJECT_0) { DWORD lastError = GetLastError(); ErrorCodeToString("Reading from COM port (WaitForSingleObject)", lastError, data->errorString); return; } if(!GetOverlappedResult((HANDLE)data->fd, &ov, &data->bytesRead, TRUE)) { DWORD lastError = GetLastError(); if(lastError == ERROR_OPERATION_ABORTED) { data->disconnected = true; return; } ErrorCodeToString("Reading from COM port (GetOverlappedResult)", lastError, data->errorString); return; } } if(data->bytesRead > 0) { return; } } } bool IsClosingHandle(int fd) { for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); it++) { if(fd == *it) { g_closingHandles.remove(fd); return true; } } return false; } void EIO_AfterWatchPort(uv_work_t* req) { WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data); if(data->disconnected) { v8::Handle<v8::Value> argv[1]; v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv); goto cleanup; } if(data->bytesRead > 0) { v8::Handle<v8::Value> argv[1]; argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_; v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv); } else if(data->errorCode > 0) { if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) { goto cleanup; } else { v8::Handle<v8::Value> argv[1]; argv[0] = v8::Exception::Error(v8::String::New(data->errorString)); v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv); Sleep(100); // prevent the errors from occurring too fast } } AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback); cleanup: data->dataCallback.Dispose(); data->errorCallback.Dispose(); delete data; delete req; } void AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) { WatchPortBaton* baton = new WatchPortBaton(); memset(baton, 0, sizeof(WatchPortBaton)); baton->fd = (HANDLE)fd; baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback); baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback); baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_WatchPort, EIO_AfterWatchPort); } void EIO_Write(uv_work_t* req) { QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data); WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton); OVERLAPPED ov = {0}; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DWORD bytesWritten; if(!WriteFile((HANDLE)data->fd, data->bufferData, data->bufferLength, &bytesWritten, &ov)) { DWORD lastError = GetLastError(); if(lastError != ERROR_IO_PENDING) { ErrorCodeToString("Writing to COM port (WriteFile)", lastError, data->errorString); return; } if(WaitForSingleObject(ov.hEvent, 1000) != WAIT_OBJECT_0) { DWORD lastError = GetLastError(); ErrorCodeToString("Writing to COM port (WaitForSingleObject)", lastError, data->errorString); return; } if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWritten, TRUE)) { DWORD lastError = GetLastError(); ErrorCodeToString("Writing to COM port (GetOverlappedResult)", lastError, data->errorString); return; } } data->result = bytesWritten; } void EIO_Close(uv_work_t* req) { CloseBaton* data = static_cast<CloseBaton*>(req->data); g_closingHandles.push_back(data->fd); if(!CloseHandle((HANDLE)data->fd)) { ErrorCodeToString("closing connection", GetLastError(), data->errorString); return; } } /* * listComPorts.c -- list COM ports * * http://github.com/todbot/usbSearch/ * * 2012, Tod E. Kurt, http://todbot.com/blog/ * * * Uses DispHealper : http://disphelper.sourceforge.net/ * * Notable VIDs & PIDs combos: * VID 0403 - FTDI * * VID 0403 / PID 6001 - Arduino Diecimila * */ void EIO_List(uv_work_t* req) { ListBaton* data = static_cast<ListBaton*>(req->data); DISPATCH_OBJ(wmiSvc); DISPATCH_OBJ(colDevices); dhInitialize(TRUE); dhToggleExceptions(TRUE); dhGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2", NULL, &wmiSvc); dhGetValue(L"%o", &colDevices, wmiSvc, L".ExecQuery(%S)", L"Select * from Win32_PnPEntity"); int port_count = 0; FOR_EACH(objDevice, colDevices, NULL) { char* name = NULL; char* pnpid = NULL; char* manu = NULL; char* match; dhGetValue(L"%s", &name, objDevice, L".Name"); dhGetValue(L"%s", &pnpid, objDevice, L".PnPDeviceID"); if( (match = strstr( name, "(COM" )) != NULL ) { // look for "(COM23)" // 'Manufacturuer' can be null, so only get it if we need it dhGetValue(L"%s", &manu, objDevice, L".Manufacturer"); port_count++; char* comname = strtok( match, "()"); ListResultItem* resultItem = new ListResultItem(); resultItem->comName = comname; resultItem->manufacturer = manu; resultItem->pnpId = pnpid; data->results.push_back(resultItem); dhFreeString(manu); } dhFreeString(name); dhFreeString(pnpid); } NEXT(objDevice); SAFE_RELEASE(colDevices); SAFE_RELEASE(wmiSvc); dhUninitialize(TRUE); } void EIO_Flush(uv_work_t* req) { FlushBaton* data = static_cast<FlushBaton*>(req->data); if(!FlushFileBuffers((HANDLE)data->fd)) { ErrorCodeToString("flushing connection", GetLastError(), data->errorString); return; } } #endif <commit_msg>Cancel timed out read operation to fix random crashes in Node's IoCompletionPort handler<commit_after> #include "serialport.h" #include <list> #include "win/disphelper.h" #ifdef WIN32 std::list<int> g_closingHandles; int bufferSize; void ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) { switch(errorCode) { case ERROR_FILE_NOT_FOUND: sprintf(errorStr, "%s: File not found", prefix); break; case ERROR_INVALID_HANDLE: sprintf(errorStr, "%s: Invalid handle", prefix); break; case ERROR_ACCESS_DENIED: sprintf(errorStr, "%s: Access denied", prefix); break; case ERROR_OPERATION_ABORTED: sprintf(errorStr, "%s: operation aborted", prefix); break; default: sprintf(errorStr, "%s: Unknown error code %d", prefix, errorCode); break; } } void EIO_Open(uv_work_t* req) { OpenBaton* data = static_cast<OpenBaton*>(req->data); HANDLE file = CreateFile( data->path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (file == INVALID_HANDLE_VALUE) { char temp[100]; sprintf(temp, "Opening %s", data->path); ErrorCodeToString(temp, GetLastError(), data->errorString); return; } bufferSize = data->bufferSize; DCB dcb = { 0 }; dcb.DCBlength = sizeof(DCB); if(!BuildCommDCB("9600,n,8,1", &dcb)) { ErrorCodeToString("BuildCommDCB", GetLastError(), data->errorString); return; } dcb.fBinary = true; dcb.BaudRate = data->baudRate; dcb.ByteSize = data->dataBits; switch(data->parity) { case SERIALPORT_PARITY_NONE: dcb.Parity = NOPARITY; break; case SERIALPORT_PARITY_MARK: dcb.Parity = MARKPARITY; break; case SERIALPORT_PARITY_EVEN: dcb.Parity = EVENPARITY; break; case SERIALPORT_PARITY_ODD: dcb.Parity = ODDPARITY; break; case SERIALPORT_PARITY_SPACE: dcb.Parity = SPACEPARITY; break; } switch(data->stopBits) { case SERIALPORT_STOPBITS_ONE: dcb.StopBits = ONESTOPBIT; break; case SERIALPORT_STOPBITS_ONE_FIVE: dcb.StopBits = ONE5STOPBITS; break; case SERIALPORT_STOPBITS_TWO: dcb.StopBits = TWOSTOPBITS; break; } if(!SetCommState(file, &dcb)) { ErrorCodeToString("SetCommState", GetLastError(), data->errorString); return; } // set the com port to return immediatly after a read COMMTIMEOUTS commTimeouts = {0}; commTimeouts.ReadIntervalTimeout = MAXDWORD; commTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD; commTimeouts.ReadTotalTimeoutConstant = 1000; commTimeouts.WriteTotalTimeoutConstant = 1000; commTimeouts.WriteTotalTimeoutMultiplier = 1000; if(!SetCommTimeouts(file, &commTimeouts)) { ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString); return; } data->result = (int)file; } struct WatchPortBaton { public: HANDLE fd; DWORD bytesRead; char buffer[100]; char errorString[1000]; DWORD errorCode; bool disconnected; v8::Persistent<v8::Value> dataCallback; v8::Persistent<v8::Value> errorCallback; v8::Persistent<v8::Value> disconnectedCallback; }; void EIO_WatchPort(uv_work_t* req) { WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data); data->disconnected = false; while(true){ OVERLAPPED ov = {0}; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(!ReadFile(data->fd, data->buffer, bufferSize, &data->bytesRead, &ov)) { data->errorCode = GetLastError(); if(data->errorCode == ERROR_OPERATION_ABORTED) { data->disconnected = true; return; } if(data->errorCode != ERROR_IO_PENDING) { ErrorCodeToString("Reading from COM port (ReadFile)", GetLastError(), data->errorString); return; } DWORD waitResult = WaitForSingleObject(ov.hEvent, 1000); if(waitResult == WAIT_TIMEOUT) { CancelIo(data->fd); data->bytesRead = 0; data->errorCode = 0; return; } if(waitResult != WAIT_OBJECT_0) { DWORD lastError = GetLastError(); ErrorCodeToString("Reading from COM port (WaitForSingleObject)", lastError, data->errorString); return; } if(!GetOverlappedResult((HANDLE)data->fd, &ov, &data->bytesRead, TRUE)) { DWORD lastError = GetLastError(); if(lastError == ERROR_OPERATION_ABORTED) { data->disconnected = true; return; } ErrorCodeToString("Reading from COM port (GetOverlappedResult)", lastError, data->errorString); return; } } if(data->bytesRead > 0) { return; } } } bool IsClosingHandle(int fd) { for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); it++) { if(fd == *it) { g_closingHandles.remove(fd); return true; } } return false; } void EIO_AfterWatchPort(uv_work_t* req) { WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data); if(data->disconnected) { v8::Handle<v8::Value> argv[1]; v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv); goto cleanup; } if(data->bytesRead > 0) { v8::Handle<v8::Value> argv[1]; argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_; v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv); } else if(data->errorCode > 0) { if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) { goto cleanup; } else { v8::Handle<v8::Value> argv[1]; argv[0] = v8::Exception::Error(v8::String::New(data->errorString)); v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv); Sleep(100); // prevent the errors from occurring too fast } } AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback); cleanup: data->dataCallback.Dispose(); data->errorCallback.Dispose(); delete data; delete req; } void AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) { WatchPortBaton* baton = new WatchPortBaton(); memset(baton, 0, sizeof(WatchPortBaton)); baton->fd = (HANDLE)fd; baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback); baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback); baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback); uv_work_t* req = new uv_work_t(); req->data = baton; uv_queue_work(uv_default_loop(), req, EIO_WatchPort, EIO_AfterWatchPort); } void EIO_Write(uv_work_t* req) { QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data); WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton); OVERLAPPED ov = {0}; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DWORD bytesWritten; if(!WriteFile((HANDLE)data->fd, data->bufferData, data->bufferLength, &bytesWritten, &ov)) { DWORD lastError = GetLastError(); if(lastError != ERROR_IO_PENDING) { ErrorCodeToString("Writing to COM port (WriteFile)", lastError, data->errorString); return; } if(WaitForSingleObject(ov.hEvent, 1000) != WAIT_OBJECT_0) { DWORD lastError = GetLastError(); ErrorCodeToString("Writing to COM port (WaitForSingleObject)", lastError, data->errorString); return; } if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWritten, TRUE)) { DWORD lastError = GetLastError(); ErrorCodeToString("Writing to COM port (GetOverlappedResult)", lastError, data->errorString); return; } } data->result = bytesWritten; } void EIO_Close(uv_work_t* req) { CloseBaton* data = static_cast<CloseBaton*>(req->data); g_closingHandles.push_back(data->fd); if(!CloseHandle((HANDLE)data->fd)) { ErrorCodeToString("closing connection", GetLastError(), data->errorString); return; } } /* * listComPorts.c -- list COM ports * * http://github.com/todbot/usbSearch/ * * 2012, Tod E. Kurt, http://todbot.com/blog/ * * * Uses DispHealper : http://disphelper.sourceforge.net/ * * Notable VIDs & PIDs combos: * VID 0403 - FTDI * * VID 0403 / PID 6001 - Arduino Diecimila * */ void EIO_List(uv_work_t* req) { ListBaton* data = static_cast<ListBaton*>(req->data); DISPATCH_OBJ(wmiSvc); DISPATCH_OBJ(colDevices); dhInitialize(TRUE); dhToggleExceptions(TRUE); dhGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2", NULL, &wmiSvc); dhGetValue(L"%o", &colDevices, wmiSvc, L".ExecQuery(%S)", L"Select * from Win32_PnPEntity"); int port_count = 0; FOR_EACH(objDevice, colDevices, NULL) { char* name = NULL; char* pnpid = NULL; char* manu = NULL; char* match; dhGetValue(L"%s", &name, objDevice, L".Name"); dhGetValue(L"%s", &pnpid, objDevice, L".PnPDeviceID"); if( (match = strstr( name, "(COM" )) != NULL ) { // look for "(COM23)" // 'Manufacturuer' can be null, so only get it if we need it dhGetValue(L"%s", &manu, objDevice, L".Manufacturer"); port_count++; char* comname = strtok( match, "()"); ListResultItem* resultItem = new ListResultItem(); resultItem->comName = comname; resultItem->manufacturer = manu; resultItem->pnpId = pnpid; data->results.push_back(resultItem); dhFreeString(manu); } dhFreeString(name); dhFreeString(pnpid); } NEXT(objDevice); SAFE_RELEASE(colDevices); SAFE_RELEASE(wmiSvc); dhUninitialize(TRUE); } void EIO_Flush(uv_work_t* req) { FlushBaton* data = static_cast<FlushBaton*>(req->data); if(!FlushFileBuffers((HANDLE)data->fd)) { ErrorCodeToString("flushing connection", GetLastError(), data->errorString); return; } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: moduldlg.hxx,v $ * * $Revision: 1.21 $ * * last change: $Author: ihi $ $Date: 2006-12-20 14:15:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _MODULDLG_HXX #define _MODULDLG_HXX #ifndef _SVHEADER_HXX #include <svheader.hxx> #endif #include <bastype2.hxx> #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SVTABBX_HXX //autogen #include <svtools/svtabbx.hxx> #endif #ifndef _SV_TABDLG_HXX //autogen #include <vcl/tabdlg.hxx> #endif #ifndef _SV_TABPAGE_HXX //autogen #include <vcl/tabpage.hxx> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include "com/sun/star/task/XInteractionHandler.hpp" #endif #include <vcl/tabctrl.hxx> #include <vcl/lstbox.hxx> class StarBASIC; #define NEWOBJECTMODE_LIB 1 #define NEWOBJECTMODE_MOD 2 #define NEWOBJECTMODE_DLG 3 #define NEWOBJECTMODE_METH 4 class NewObjectDialog : public ModalDialog { private: FixedText aText; Edit aEdit; OKButton aOKButton; CancelButton aCancelButton; DECL_LINK(OkButtonHandler, Button *); public: NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false); ~NewObjectDialog(); String GetObjectName() const { return aEdit.GetText(); } void SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );} }; class ExportDialog : public ModalDialog { private: RadioButton maExportAsPackageButton; RadioButton maExportAsBasicButton; OKButton maOKButton; CancelButton maCancelButton; sal_Bool mbExportAsPackage; DECL_LINK(OkButtonHandler, Button *); public: ExportDialog( Window * pParent ); ~ExportDialog(); sal_Bool isExportAsPackage( void ) { return mbExportAsPackage; } }; class ExtBasicTreeListBox : public BasicTreeListBox { protected: virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); virtual DragDropMode NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry ); virtual BOOL NotifyAcceptDrop( SvLBoxEntry* pEntry ); virtual BOOL NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos ); virtual BOOL NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos ); BOOL NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove ); public: ExtBasicTreeListBox( Window* pParent, const ResId& rRes ); ~ExtBasicTreeListBox(); }; #define LIBMODE_CHOOSER 1 #define LIBMODE_MANAGER 2 class BasicCheckBox : public SvTabListBox { private: USHORT nMode; SvLBoxButtonData* pCheckButton; SfxObjectShell* m_pShell; void Init(); public: BasicCheckBox( Window* pParent, const ResId& rResId ); ~BasicCheckBox(); SvLBoxEntry* InsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND ); void RemoveEntry( ULONG nPos ); SvLBoxEntry* FindEntry( const String& rName ); void SelectEntryPos( ULONG nPos, BOOL bSelect = TRUE ); ULONG GetSelectEntryPos() const; ULONG GetCheckedEntryCount() const; void CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE ); BOOL IsChecked( ULONG nPos ) const; virtual void InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind ); virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); void SetShell( SfxObjectShell* pShell ) { m_pShell = pShell; } void SetMode( USHORT n ); USHORT GetMode() const { return nMode; } }; class LibDialog: public ModalDialog { private: OKButton aOKButton; CancelButton aCancelButton; FixedText aStorageName; BasicCheckBox aLibBox; FixedLine aFixedLine; CheckBox aReferenceBox; CheckBox aReplaceBox; public: LibDialog( Window* pParent ); ~LibDialog(); void SetStorageName( const String& rName ); BasicCheckBox& GetLibBox() { return aLibBox; } BOOL IsReference() const { return aReferenceBox.IsChecked(); } BOOL IsReplace() const { return aReplaceBox.IsChecked(); } void EnableReference( BOOL b ) { aReferenceBox.Enable( b ); } void EnableReplace( BOOL b ) { aReplaceBox.Enable( b ); } }; class OrganizeDialog : public TabDialog { private: TabControl aTabCtrl; BasicEntryDescriptor m_aCurEntry; public: OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc ); ~OrganizeDialog(); virtual short Execute(); DECL_LINK( ActivatePageHdl, TabControl * ); }; class ObjectPage: public TabPage { protected: FixedText aLibText; ExtBasicTreeListBox aBasicBox; PushButton aEditButton; CancelButton aCloseButton; PushButton aNewModButton; PushButton aNewDlgButton; PushButton aDelButton; DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * ); DECL_LINK( ButtonHdl, Button * ); void CheckButtons(); bool GetSelection( SfxObjectShell*& rpShell, String& rLibName ); void DeleteCurrent(); void NewModule(); void NewDialog(); void EndTabDialog( USHORT nRet ); TabDialog* pTabDlg; virtual void ActivatePage(); virtual void DeactivatePage(); public: ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode ); void SetCurrentEntry( BasicEntryDescriptor& rDesc ); void SetTabDlg( TabDialog* p ) { pTabDlg = p;} }; class SvxPasswordDialog; class LibPage: public TabPage { protected: FixedText aBasicsText; ListBox aBasicsBox; FixedText aLibText; BasicCheckBox aLibBox; PushButton aEditButton; CancelButton aCloseButton; PushButton aPasswordButton; PushButton aExportButton; PushButton aNewLibButton; PushButton aInsertLibButton; PushButton aDelButton; SfxObjectShell* m_pCurShell; LibraryLocation m_eCurLocation; DECL_LINK( TreeListHighlightHdl, SvTreeListBox * ); DECL_LINK( BasicSelectHdl, ListBox * ); DECL_LINK( ButtonHdl, Button * ); DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * ); void CheckButtons(); void DeleteCurrent(); void NewLib(); void InsertLib(); void implExportLib( const String& aLibName, const String& aTargetURL, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler ); void Export(); void ExportAsPackage( const String& aLibName ); void ExportAsBasic( const String& aLibName ); void EndTabDialog( USHORT nRet ); void FillListBox(); void InsertListBoxEntry( SfxObjectShell* pShell, LibraryLocation eLocation ); void SetCurLib(); SvLBoxEntry* ImpInsertLibEntry( const String& rLibName, ULONG nPos ); virtual void ActivatePage(); virtual void DeactivatePage(); TabDialog* pTabDlg; public: LibPage( Window* pParent ); virtual ~LibPage(); void SetTabDlg( TabDialog* p ) { pTabDlg = p;} }; // Helper functions SbModule* createModImpl( Window* pWin, SfxObjectShell* pShell, BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false ); void createLibImpl( Window* pWin, SfxObjectShell* pShell, BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox ); #endif // _MODULDLG_HXX <commit_msg>INTEGRATION: CWS ab33 (1.21.6); FILE MERGED 2007/01/10 16:34:47 ab 1.21.6.1: #i69280# Removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: moduldlg.hxx,v $ * * $Revision: 1.22 $ * * last change: $Author: vg $ $Date: 2007-01-16 16:32:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _MODULDLG_HXX #define _MODULDLG_HXX #ifndef _SVHEADER_HXX #include <svheader.hxx> #endif #include <bastype2.hxx> #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SVTABBX_HXX //autogen #include <svtools/svtabbx.hxx> #endif #ifndef _SV_TABDLG_HXX //autogen #include <vcl/tabdlg.hxx> #endif #ifndef _SV_TABPAGE_HXX //autogen #include <vcl/tabpage.hxx> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include "com/sun/star/task/XInteractionHandler.hpp" #endif #include <vcl/tabctrl.hxx> #include <vcl/lstbox.hxx> class StarBASIC; #define NEWOBJECTMODE_LIB 1 #define NEWOBJECTMODE_MOD 2 #define NEWOBJECTMODE_DLG 3 #define NEWOBJECTMODE_METH 4 class NewObjectDialog : public ModalDialog { private: FixedText aText; Edit aEdit; OKButton aOKButton; CancelButton aCancelButton; DECL_LINK(OkButtonHandler, Button *); public: NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false); ~NewObjectDialog(); String GetObjectName() const { return aEdit.GetText(); } void SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );} }; class ExportDialog : public ModalDialog { private: RadioButton maExportAsPackageButton; RadioButton maExportAsBasicButton; OKButton maOKButton; CancelButton maCancelButton; sal_Bool mbExportAsPackage; DECL_LINK(OkButtonHandler, Button *); public: ExportDialog( Window * pParent ); ~ExportDialog(); sal_Bool isExportAsPackage( void ) { return mbExportAsPackage; } }; class ExtBasicTreeListBox : public BasicTreeListBox { protected: virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); virtual DragDropMode NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry ); virtual BOOL NotifyAcceptDrop( SvLBoxEntry* pEntry ); virtual BOOL NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos ); virtual BOOL NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos ); BOOL NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry, SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove ); public: ExtBasicTreeListBox( Window* pParent, const ResId& rRes ); ~ExtBasicTreeListBox(); }; #define LIBMODE_CHOOSER 1 #define LIBMODE_MANAGER 2 class BasicCheckBox : public SvTabListBox { private: USHORT nMode; SvLBoxButtonData* pCheckButton; SfxObjectShell* m_pShell; void Init(); public: BasicCheckBox( Window* pParent, const ResId& rResId ); ~BasicCheckBox(); SvLBoxEntry* DoInsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND ); void RemoveEntry( ULONG nPos ); SvLBoxEntry* FindEntry( const String& rName ); void SelectEntryPos( ULONG nPos, BOOL bSelect = TRUE ); ULONG GetSelectEntryPos() const; ULONG GetCheckedEntryCount() const; void CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE ); BOOL IsChecked( ULONG nPos ) const; virtual void InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind ); virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& rSel ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); void SetShell( SfxObjectShell* pShell ) { m_pShell = pShell; } void SetMode( USHORT n ); USHORT GetMode() const { return nMode; } }; class LibDialog: public ModalDialog { private: OKButton aOKButton; CancelButton aCancelButton; FixedText aStorageName; BasicCheckBox aLibBox; FixedLine aFixedLine; CheckBox aReferenceBox; CheckBox aReplaceBox; public: LibDialog( Window* pParent ); ~LibDialog(); void SetStorageName( const String& rName ); BasicCheckBox& GetLibBox() { return aLibBox; } BOOL IsReference() const { return aReferenceBox.IsChecked(); } BOOL IsReplace() const { return aReplaceBox.IsChecked(); } void EnableReference( BOOL b ) { aReferenceBox.Enable( b ); } void EnableReplace( BOOL b ) { aReplaceBox.Enable( b ); } }; class OrganizeDialog : public TabDialog { private: TabControl aTabCtrl; BasicEntryDescriptor m_aCurEntry; public: OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc ); ~OrganizeDialog(); virtual short Execute(); DECL_LINK( ActivatePageHdl, TabControl * ); }; class ObjectPage: public TabPage { protected: FixedText aLibText; ExtBasicTreeListBox aBasicBox; PushButton aEditButton; CancelButton aCloseButton; PushButton aNewModButton; PushButton aNewDlgButton; PushButton aDelButton; DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * ); DECL_LINK( ButtonHdl, Button * ); void CheckButtons(); bool GetSelection( SfxObjectShell*& rpShell, String& rLibName ); void DeleteCurrent(); void NewModule(); void NewDialog(); void EndTabDialog( USHORT nRet ); TabDialog* pTabDlg; virtual void ActivatePage(); virtual void DeactivatePage(); public: ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode ); void SetCurrentEntry( BasicEntryDescriptor& rDesc ); void SetTabDlg( TabDialog* p ) { pTabDlg = p;} }; class SvxPasswordDialog; class LibPage: public TabPage { protected: FixedText aBasicsText; ListBox aBasicsBox; FixedText aLibText; BasicCheckBox aLibBox; PushButton aEditButton; CancelButton aCloseButton; PushButton aPasswordButton; PushButton aExportButton; PushButton aNewLibButton; PushButton aInsertLibButton; PushButton aDelButton; SfxObjectShell* m_pCurShell; LibraryLocation m_eCurLocation; DECL_LINK( TreeListHighlightHdl, SvTreeListBox * ); DECL_LINK( BasicSelectHdl, ListBox * ); DECL_LINK( ButtonHdl, Button * ); DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * ); void CheckButtons(); void DeleteCurrent(); void NewLib(); void InsertLib(); void implExportLib( const String& aLibName, const String& aTargetURL, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler ); void Export(); void ExportAsPackage( const String& aLibName ); void ExportAsBasic( const String& aLibName ); void EndTabDialog( USHORT nRet ); void FillListBox(); void InsertListBoxEntry( SfxObjectShell* pShell, LibraryLocation eLocation ); void SetCurLib(); SvLBoxEntry* ImpInsertLibEntry( const String& rLibName, ULONG nPos ); virtual void ActivatePage(); virtual void DeactivatePage(); TabDialog* pTabDlg; public: LibPage( Window* pParent ); virtual ~LibPage(); void SetTabDlg( TabDialog* p ) { pTabDlg = p;} }; // Helper functions SbModule* createModImpl( Window* pWin, SfxObjectShell* pShell, BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false ); void createLibImpl( Window* pWin, SfxObjectShell* pShell, BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox ); #endif // _MODULDLG_HXX <|endoftext|>