text
stringlengths
54
60.6k
<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/thread_table.h" #include "perfetto/base/logging.h" #include "src/trace_processor/query_constraints.h" #include "src/trace_processor/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { using namespace sqlite_utils; } // namespace ThreadTable::ThreadTable(sqlite3*, const TraceStorage* storage) : storage_(storage) {} void ThreadTable::RegisterTable(sqlite3* db, const TraceStorage* storage) { Table::Register<ThreadTable>(db, storage, "thread"); } base::Optional<Table::Schema> ThreadTable::Init(int, const char* const*) { return Schema( { Table::Column(Column::kUtid, "utid", ColumnType::kInt), Table::Column(Column::kUpid, "upid", ColumnType::kInt), Table::Column(Column::kName, "name", ColumnType::kString), Table::Column(Column::kTid, "tid", ColumnType::kInt), }, {Column::kUtid}); } std::unique_ptr<Table::Cursor> ThreadTable::CreateCursor( const QueryConstraints& qc, sqlite3_value** argv) { return std::unique_ptr<Table::Cursor>(new Cursor(storage_, qc, argv)); } int ThreadTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { info->estimated_cost = static_cast<uint32_t>(storage_->thread_count()); // If the query has a constraint on the |utid| field, return a reduced cost // because we can do that filter efficiently. const auto& constraints = qc.constraints(); if (constraints.size() == 1 && constraints.front().iColumn == Column::kUtid) { info->estimated_cost = IsOpEq(constraints.front().op) ? 1 : 10; } return SQLITE_OK; } ThreadTable::Cursor::Cursor(const TraceStorage* storage, const QueryConstraints& qc, sqlite3_value** argv) : storage_(storage) { min = 0; max = static_cast<uint32_t>(storage_->thread_count()); desc = false; current = min; for (size_t j = 0; j < qc.constraints().size(); j++) { const auto& cs = qc.constraints()[j]; if (cs.iColumn == Column::kUtid) { UniqueTid constraint_utid = static_cast<UniqueTid>(sqlite3_value_int(argv[j])); // Filter the range of utids that we are interested in, based on the // constraints in the query. Everything between min and max (inclusive) // will be returned. if (IsOpEq(cs.op)) { min = constraint_utid; max = constraint_utid; } else if (IsOpGe(cs.op) || IsOpGt(cs.op)) { min = IsOpGt(cs.op) ? constraint_utid + 1 : constraint_utid; } else if (IsOpLe(cs.op) || IsOpLt(cs.op)) { max = IsOpLt(cs.op) ? constraint_utid - 1 : constraint_utid; } } } for (const auto& ob : qc.order_by()) { if (ob.iColumn == Column::kUtid) { desc = ob.desc; current = desc ? max : min; } } } int ThreadTable::Cursor::Column(sqlite3_context* context, int N) { const auto& thread = storage_->GetThread(current); switch (N) { case Column::kUtid: { sqlite3_result_int64(context, current); break; } case Column::kUpid: { sqlite3_result_int64(context, thread.upid.value_or(0)); break; } case Column::kName: { const auto& name = storage_->GetString(thread.name_id); sqlite3_result_text(context, name.c_str(), static_cast<int>(name.length()), kSqliteStatic); break; } case Column::kTid: { sqlite3_result_int64(context, thread.tid); break; } default: { PERFETTO_FATAL("Unknown column %d", N); break; } } return SQLITE_OK; } int ThreadTable::Cursor::Next() { if (desc) { --current; } else { ++current; } return SQLITE_OK; } int ThreadTable::Cursor::Eof() { return desc ? current < min : current > max; } } // namespace trace_processor } // namespace perfetto <commit_msg>trace_processor: fix null vs 0 bug in thread table am: 1aa852a0ca am: b0a6e82b0e<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/thread_table.h" #include "perfetto/base/logging.h" #include "src/trace_processor/query_constraints.h" #include "src/trace_processor/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { using namespace sqlite_utils; } // namespace ThreadTable::ThreadTable(sqlite3*, const TraceStorage* storage) : storage_(storage) {} void ThreadTable::RegisterTable(sqlite3* db, const TraceStorage* storage) { Table::Register<ThreadTable>(db, storage, "thread"); } base::Optional<Table::Schema> ThreadTable::Init(int, const char* const*) { return Schema( { Table::Column(Column::kUtid, "utid", ColumnType::kInt), Table::Column(Column::kUpid, "upid", ColumnType::kInt), Table::Column(Column::kName, "name", ColumnType::kString), Table::Column(Column::kTid, "tid", ColumnType::kInt), }, {Column::kUtid}); } std::unique_ptr<Table::Cursor> ThreadTable::CreateCursor( const QueryConstraints& qc, sqlite3_value** argv) { return std::unique_ptr<Table::Cursor>(new Cursor(storage_, qc, argv)); } int ThreadTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { info->estimated_cost = static_cast<uint32_t>(storage_->thread_count()); // If the query has a constraint on the |utid| field, return a reduced cost // because we can do that filter efficiently. const auto& constraints = qc.constraints(); if (constraints.size() == 1 && constraints.front().iColumn == Column::kUtid) { info->estimated_cost = IsOpEq(constraints.front().op) ? 1 : 10; } return SQLITE_OK; } ThreadTable::Cursor::Cursor(const TraceStorage* storage, const QueryConstraints& qc, sqlite3_value** argv) : storage_(storage) { min = 0; max = static_cast<uint32_t>(storage_->thread_count()); desc = false; current = min; for (size_t j = 0; j < qc.constraints().size(); j++) { const auto& cs = qc.constraints()[j]; if (cs.iColumn == Column::kUtid) { UniqueTid constraint_utid = static_cast<UniqueTid>(sqlite3_value_int(argv[j])); // Filter the range of utids that we are interested in, based on the // constraints in the query. Everything between min and max (inclusive) // will be returned. if (IsOpEq(cs.op)) { min = constraint_utid; max = constraint_utid; } else if (IsOpGe(cs.op) || IsOpGt(cs.op)) { min = IsOpGt(cs.op) ? constraint_utid + 1 : constraint_utid; } else if (IsOpLe(cs.op) || IsOpLt(cs.op)) { max = IsOpLt(cs.op) ? constraint_utid - 1 : constraint_utid; } } } for (const auto& ob : qc.order_by()) { if (ob.iColumn == Column::kUtid) { desc = ob.desc; current = desc ? max : min; } } } int ThreadTable::Cursor::Column(sqlite3_context* context, int N) { const auto& thread = storage_->GetThread(current); switch (N) { case Column::kUtid: { sqlite3_result_int64(context, current); break; } case Column::kUpid: { if (thread.upid.has_value()) { sqlite3_result_int64(context, thread.upid.value()); } else { sqlite3_result_null(context); } break; } case Column::kName: { const auto& name = storage_->GetString(thread.name_id); sqlite3_result_text(context, name.c_str(), static_cast<int>(name.length()), kSqliteStatic); break; } case Column::kTid: { sqlite3_result_int64(context, thread.tid); break; } default: { PERFETTO_FATAL("Unknown column %d", N); break; } } return SQLITE_OK; } int ThreadTable::Cursor::Next() { if (desc) { --current; } else { ++current; } return SQLITE_OK; } int ThreadTable::Cursor::Eof() { return desc ? current < min : current > max; } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>// FbRun.cc // Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen<at>users.sourceforge.net) // // 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. // $Id: FbRun.cc,v 1.23 2003/12/31 01:34:33 fluxgen Exp $ #include "FbRun.hh" #include "App.hh" #include "EventManager.hh" #include "Color.hh" #include "KeyUtil.hh" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_XPM #include <X11/xpm.h> #include "fbrun.xpm" #endif // HAVE_XPM #include <X11/Xlib.h> #include <X11/keysym.h> #include <X11/Xutil.h> #include <X11/cursorfont.h> #include <unistd.h> #include <iostream> #include <iterator> #include <fstream> #include <cassert> using namespace std; FbRun::FbRun(int x, int y, size_t width): FbTk::TextBox(DefaultScreen(FbTk::App::instance()->display()), m_font, ""), m_font("fixed"), m_display(FbTk::App::instance()->display()), m_bevel(4), m_gc(*this), m_end(false), m_current_history_item(0), m_cursor(XCreateFontCursor(FbTk::App::instance()->display(), XC_xterm)) { setGC(m_gc.gc()); setCursor(m_cursor); // setting nomaximize in local resize resize(width, font().height() + m_bevel); // setup class name XClassHint *class_hint = XAllocClassHint(); if (class_hint == 0) throw string("Out of memory"); class_hint->res_name = "fbrun"; class_hint->res_class = "FbRun"; XSetClassHint(m_display, window(), class_hint); XFree(class_hint); #ifdef HAVE_XPM Pixmap mask = 0; Pixmap pm; XpmCreatePixmapFromData(m_display, window(), fbrun_xpm, &pm, &mask, 0); // attribs if (mask != 0) XFreePixmap(m_display, mask); m_pixmap = pm; #endif // HAVE_XPM if (m_pixmap.drawable()) { XWMHints wmhints; wmhints.flags = IconPixmapHint; wmhints.icon_pixmap = m_pixmap.drawable(); XSetWMHints(m_display, window(), &wmhints); } } FbRun::~FbRun() { hide(); } void FbRun::run(const std::string &command) { FbTk::App::instance()->end(); // end application m_end = true; // mark end of processing // fork and execute program if (!fork()) { setsid(); execl("/bin/sh", "/bin/sh", "-c", command.c_str(), 0); exit(0); //exit child } hide(); // hide gui // save command history to file if (text().size() != 0) { // no need to save empty command // don't allow duplicates into the history file, first // look for a duplicate if (m_current_history_item < m_history.size() && text() == m_history[m_current_history_item]) { // m_current_history_item is the duplicate } else { m_current_history_item = 0; for (; m_current_history_item < m_history.size(); ++m_current_history_item) { if (m_history[m_current_history_item] == text()) break; } } // now m_current_history_item points at the duplicate, or // at m_history.size() if no duplicate fstream inoutfile(m_history_file.c_str(), ios::in|ios::out); if (inoutfile) { int i = 0; // read past history items before current for (string line; !inoutfile.eof() && i < m_current_history_item; i++) getline(inoutfile, line); // write the history items that come after current for (i++; i < m_history.size(); i++) inoutfile<<m_history[i]<<endl; // and append the current one back to the end inoutfile<<text()<<endl; } else cerr<<"FbRun Warning: Can't write command history to file: "<<m_history_file<<endl; } } bool FbRun::loadHistory(const char *filename) { if (filename == 0) return false; ifstream infile(filename); if (!infile) { //even though we fail to load file, we should try save to it m_history_file = filename; return false; } // clear old history and load new one from file m_history.clear(); // each line is a command string line; while (!infile.eof()) { getline(infile, line); if (line.size()) // don't add empty lines m_history.push_back(line); } // set no current histor to display m_current_history_item = m_history.size(); // set history file m_history_file = filename; return true; } bool FbRun::loadFont(const string &fontname) { if (!m_font.load(fontname.c_str())) return false; // resize to fit new font height resize(width(), font().height() + m_bevel); return true; } void FbRun::setForegroundColor(const FbTk::Color &color) { m_gc.setForeground(color); } void FbRun::setTitle(const string &title) { setName(title.c_str()); } void FbRun::resize(unsigned int width, unsigned int height) { FbTk::TextBox::resize(width, height); setNoMaximize(); } void FbRun::redrawLabel() { clear(); } void FbRun::keyPressEvent(XKeyEvent &ke) { // strip numlock, capslock and scrolllock mask ke.state = FbTk::KeyUtil::instance().cleanMods(ke.state); FbTk::TextBox::keyPressEvent(ke); KeySym ks; char keychar[1]; XLookupString(&ke, keychar, 1, &ks, 0); // a modifier key by itself doesn't do anything if (IsModifierKey(ks)) return; if (ke.state) { // a modifier key is down if (ke.state == ControlMask) { switch (ks) { case XK_p: prevHistoryItem(); break; case XK_n: nextHistoryItem(); break; } } else if (ke.state == (Mod1Mask | ShiftMask)) { switch (ks) { case XK_less: firstHistoryItem(); break; case XK_greater: lastHistoryItem(); break; } } } else { // no modifier key switch (ks) { case XK_Escape: m_end = true; hide(); FbTk::App::instance()->end(); // end program break; case XK_Return: run(text()); break; case XK_Up: prevHistoryItem(); break; case XK_Down: nextHistoryItem(); break; case XK_Tab: tabCompleteHistory(); break; } } clear(); } void FbRun::setNoMaximize() { // we don't need to maximize this window XSizeHints sh; sh.flags = PMaxSize | PMinSize; sh.max_width = width(); sh.max_height = height(); sh.min_width = width(); sh.min_height = height(); XSetWMNormalHints(m_display, window(), &sh); } void FbRun::prevHistoryItem() { if (m_history.size() == 0 || m_current_history_item == 0) { XBell(m_display, 0); } else { m_current_history_item--; setText(m_history[m_current_history_item]); } } void FbRun::nextHistoryItem() { if (m_current_history_item == m_history.size()) { XBell(m_display, 0); } else { m_current_history_item++; if (m_current_history_item == m_history.size()) { m_current_history_item = m_history.size(); setText(""); } else setText(m_history[m_current_history_item]); } } void FbRun::firstHistoryItem() { if (m_history.size() == 0 || m_current_history_item == 0) { XBell(m_display, 0); } else { m_current_history_item = 0; setText(m_history[m_current_history_item]); } } void FbRun::lastHistoryItem() { // actually one past the end if (m_history.size() == 0) { XBell(m_display, 0); } else { m_current_history_item = m_history.size(); setText(""); } } void FbRun::tabCompleteHistory() { if (m_current_history_item == 0) { XBell(m_display, 0); } else { int history_item = m_current_history_item - 1; string prefix = text().substr(0, cursorPosition()); while (history_item > - 1) { if (m_history[history_item].find(prefix) == 0) { m_current_history_item = history_item; setText(m_history[m_current_history_item]); break; } history_item--; } if (history_item == -1) XBell(m_display, 0); } } void FbRun::insertCharacter(char keychar) { char val[2] = {keychar, 0}; insertText(val); } <commit_msg>cycle tabcompletion, patch from Mathias Gumz<commit_after>// FbRun.cc // Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen<at>users.sourceforge.net) // // 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. // $Id: FbRun.cc,v 1.24 2004/02/25 18:37:47 fluxgen Exp $ #include "FbRun.hh" #include "App.hh" #include "EventManager.hh" #include "Color.hh" #include "KeyUtil.hh" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_XPM #include <X11/xpm.h> #include "fbrun.xpm" #endif // HAVE_XPM #include <X11/Xlib.h> #include <X11/keysym.h> #include <X11/Xutil.h> #include <X11/cursorfont.h> #include <unistd.h> #include <iostream> #include <iterator> #include <fstream> #include <cassert> using namespace std; FbRun::FbRun(int x, int y, size_t width): FbTk::TextBox(DefaultScreen(FbTk::App::instance()->display()), m_font, ""), m_font("fixed"), m_display(FbTk::App::instance()->display()), m_bevel(4), m_gc(*this), m_end(false), m_current_history_item(0), m_cursor(XCreateFontCursor(FbTk::App::instance()->display(), XC_xterm)) { setGC(m_gc.gc()); setCursor(m_cursor); // setting nomaximize in local resize resize(width, font().height() + m_bevel); // setup class name XClassHint *class_hint = XAllocClassHint(); if (class_hint == 0) throw string("Out of memory"); class_hint->res_name = "fbrun"; class_hint->res_class = "FbRun"; XSetClassHint(m_display, window(), class_hint); XFree(class_hint); #ifdef HAVE_XPM Pixmap mask = 0; Pixmap pm; XpmCreatePixmapFromData(m_display, window(), fbrun_xpm, &pm, &mask, 0); // attribs if (mask != 0) XFreePixmap(m_display, mask); m_pixmap = pm; #endif // HAVE_XPM if (m_pixmap.drawable()) { XWMHints wmhints; wmhints.flags = IconPixmapHint; wmhints.icon_pixmap = m_pixmap.drawable(); XSetWMHints(m_display, window(), &wmhints); } } FbRun::~FbRun() { hide(); } void FbRun::run(const std::string &command) { FbTk::App::instance()->end(); // end application m_end = true; // mark end of processing // fork and execute program if (!fork()) { setsid(); execl("/bin/sh", "/bin/sh", "-c", command.c_str(), 0); exit(0); //exit child } hide(); // hide gui // save command history to file if (text().size() != 0) { // no need to save empty command // don't allow duplicates into the history file, first // look for a duplicate if (m_current_history_item < m_history.size() && text() == m_history[m_current_history_item]) { // m_current_history_item is the duplicate } else { m_current_history_item = 0; for (; m_current_history_item < m_history.size(); ++m_current_history_item) { if (m_history[m_current_history_item] == text()) break; } } // now m_current_history_item points at the duplicate, or // at m_history.size() if no duplicate fstream inoutfile(m_history_file.c_str(), ios::in|ios::out); if (inoutfile) { int i = 0; // read past history items before current for (string line; !inoutfile.eof() && i < m_current_history_item; i++) getline(inoutfile, line); // write the history items that come after current for (i++; i < m_history.size(); i++) inoutfile<<m_history[i]<<endl; // and append the current one back to the end inoutfile<<text()<<endl; } else cerr<<"FbRun Warning: Can't write command history to file: "<<m_history_file<<endl; } } bool FbRun::loadHistory(const char *filename) { if (filename == 0) return false; ifstream infile(filename); if (!infile) { //even though we fail to load file, we should try save to it m_history_file = filename; return false; } // clear old history and load new one from file m_history.clear(); // each line is a command string line; while (!infile.eof()) { getline(infile, line); if (line.size()) // don't add empty lines m_history.push_back(line); } // set no current histor to display m_current_history_item = m_history.size(); // set history file m_history_file = filename; return true; } bool FbRun::loadFont(const string &fontname) { if (!m_font.load(fontname.c_str())) return false; // resize to fit new font height resize(width(), font().height() + m_bevel); return true; } void FbRun::setForegroundColor(const FbTk::Color &color) { m_gc.setForeground(color); } void FbRun::setTitle(const string &title) { setName(title.c_str()); } void FbRun::resize(unsigned int width, unsigned int height) { FbTk::TextBox::resize(width, height); setNoMaximize(); } void FbRun::redrawLabel() { clear(); } void FbRun::keyPressEvent(XKeyEvent &ke) { // strip numlock, capslock and scrolllock mask ke.state = FbTk::KeyUtil::instance().cleanMods(ke.state); int cp= cursorPosition(); FbTk::TextBox::keyPressEvent(ke); KeySym ks; char keychar[1]; XLookupString(&ke, keychar, 1, &ks, 0); // a modifier key by itself doesn't do anything if (IsModifierKey(ks)) return; if (ke.state) { // a modifier key is down if (ke.state == ControlMask) { switch (ks) { case XK_p: prevHistoryItem(); break; case XK_n: nextHistoryItem(); break; } } else if (ke.state == (Mod1Mask | ShiftMask)) { switch (ks) { case XK_less: firstHistoryItem(); break; case XK_greater: lastHistoryItem(); break; } } } else { // no modifier key switch (ks) { case XK_Escape: m_end = true; hide(); FbTk::App::instance()->end(); // end program break; case XK_Return: run(text()); break; case XK_Up: prevHistoryItem(); break; case XK_Down: nextHistoryItem(); break; case XK_Tab: tabCompleteHistory(); setCursorPosition(cp); break; } } clear(); } void FbRun::setNoMaximize() { // we don't need to maximize this window XSizeHints sh; sh.flags = PMaxSize | PMinSize; sh.max_width = width(); sh.max_height = height(); sh.min_width = width(); sh.min_height = height(); XSetWMNormalHints(m_display, window(), &sh); } void FbRun::prevHistoryItem() { if (m_history.size() == 0 || m_current_history_item == 0) { XBell(m_display, 0); } else { m_current_history_item--; setText(m_history[m_current_history_item]); } } void FbRun::nextHistoryItem() { if (m_current_history_item == m_history.size()) { XBell(m_display, 0); } else { m_current_history_item++; if (m_current_history_item == m_history.size()) { m_current_history_item = m_history.size(); setText(""); } else setText(m_history[m_current_history_item]); } } void FbRun::firstHistoryItem() { if (m_history.size() == 0 || m_current_history_item == 0) { XBell(m_display, 0); } else { m_current_history_item = 0; setText(m_history[m_current_history_item]); } } void FbRun::lastHistoryItem() { // actually one past the end if (m_history.size() == 0) { XBell(m_display, 0); } else { m_current_history_item = m_history.size(); setText(""); } } void FbRun::tabCompleteHistory() { if (m_current_history_item == 0) { XBell(m_display, 0); } else { int history_item = m_current_history_item - 1; string prefix = text().substr(0, cursorPosition()); while (history_item != m_current_history_item ) { if (history_item == -1 ) history_item+= m_history.size(); if (m_history[history_item].find(prefix) == 0) { m_current_history_item = history_item; setText(m_history[m_current_history_item]); break; } history_item--; } if (history_item == m_current_history_item) XBell(m_display, 0); } } void FbRun::insertCharacter(char keychar) { char val[2] = {keychar, 0}; insertText(val); } <|endoftext|>
<commit_before>#ifndef _LAPACK_WRAP_HPP_ #define _LAPACK_WRAP_HPP_ #include "mkl.h" #include <stdexcept> extern "C" { void dgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); void sgemm_(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); void daxpy_(int *n, double *alpha, double *A, int *incx, double *C, int *incy); void saxpy_(int *n, float *alpha, float *A, int *incx, float *C, int *incy); void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); void dtrmm_(char *side, char *uplo, char *transt, char *diag, int *m, int *n, double *alpha, double *T, int *ldt, double *B, int *ldb); void strmm_(char *side, char *uplo, char *transt, char *diag, int *m, int *n, float *alpha, float *T, int *ldt, float *B, int *ldb); // void dlaswp_(int *N, double *A, int *lda, int *K1, int *K2, int *ipiv, int *incx); // void slaswp_(int *N, float *A, int *lda, int *K1, int *K2, int *ipiv, int *incx); } // These are wrappers around lapack routines. namespace lapack { void Trmm(char side, char uplo, char transt, char diag, int m, int n, double alpha, double *T, int ldt, double *B, int ldb) { dtrmm_(&side, &uplo, &transt, &diag, &m, &n, &alpha, T, &ldt, B, &ldb); } void Trmm(char side, char uplo, char transt, char diag, int m, int n, float alpha, float *T, int ldt, float *B, int ldb) { strmm_(&side, &uplo, &transt, &diag, &m, &n, &alpha, T, &ldt, B, &ldb); } void Larft(char direct, char storev, int m, int n, double *V, int ldv, double *tau, double *T, int ldt) { dlarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } void Larft(char direct, char storev, int m, int n, float *V, int ldv, float *tau, float *T, int ldt) { slarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } void Geqrf(int m, int n, float *A, int lda, float *tau) { // First perform the workspace query. float *work = new float[1]; int lwork = -1; int info; sgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad sgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new float[lwork]; // QR routine that does the work. sgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad sgeqrf_ call"); } delete [] work; } void Geqrf(int m, int n, double *A, int lda, double *tau) { // First perform the workspace query. double *work = new double[1]; int lwork = -1; int info; dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad dgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new double[lwork]; // QR routine that does the work. dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad dgeqrf_ call"); } delete [] work; } void Getrf(double *data, int m, int n, int lda, int *pivots) { int info; dgetrf_(&m, &n, data, &lda, pivots, &info); if (info != 0) { throw std::runtime_error("Bad dgetrf_ call"); } } void Getrf(float *data, int m, int n, int lda, int *pivots) { int info; sgetrf_(&m, &n, data, &lda, pivots, &info); if (info != 0) { throw std::runtime_error("Bad sgetrf_ call"); } } void Laswp(int num_cols, double *data, int lda, int piv_start, int piv_end, int *pivots, int incx) { dlaswp_(&num_cols, data, &lda, &piv_start, &piv_end, pivots, &incx); } void Laswp(int num_cols, float *data, int lda, int piv_start, int piv_end, int *pivots, int incx) { slaswp_(&num_cols, data, &lda, &piv_start, &piv_end, pivots, &incx); } void Trsm(char side, char uplo, char transa, char diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb) { dtrsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, A, &lda, B, &ldb); } void Trsm(char side, char uplo, char transa, char diag, int m, int n, float alpha, float *A, int lda, float *B, int ldb) { strsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, A, &lda, B, &ldb); } void Getrs(char trans, int n, int nrhs, double *A, int lda, int *ipiv, double *b, int ldb) { int info; dgetrs_(&trans, &n, &nrhs, A, &lda, ipiv, b, &ldb, &info); if (info != 0) { throw std::runtime_error("Bad dgetrs_ call"); } } void Getrs(char trans, int n, int nrhs, float *A, int lda, int *ipiv, float *b, int ldb) { int info; sgetrs_(&trans, &n, &nrhs, A, &lda, ipiv, b, &ldb, &info); if (info != 0) { throw std::runtime_error("Bad sgetrs_ call"); } } } // end namespace lapack #endif // _LAPACK_WRAP_HPP_ <commit_msg>More wrapper functions...<commit_after>#ifndef _LAPACK_WRAP_HPP_ #define _LAPACK_WRAP_HPP_ #include "mkl.h" #include <functional> #include <stdexcept> extern "C" { void dgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); void sgemm_(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); void daxpy_(int *n, double *alpha, double *A, int *incx, double *C, int *incy); void saxpy_(int *n, float *alpha, float *A, int *incx, float *C, int *incy); void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); void dtrmm_(char *side, char *uplo, char *transt, char *diag, int *m, int *n, double *alpha, double *T, int *ldt, double *B, int *ldb); void strmm_(char *side, char *uplo, char *transt, char *diag, int *m, int *n, float *alpha, float *T, int *ldt, float *B, int *ldb); // void dlaswp_(int *N, double *A, int *lda, int *K1, int *K2, int *ipiv, int *incx); // void slaswp_(int *N, float *A, int *lda, int *K1, int *K2, int *ipiv, int *incx); } // These are wrappers around lapack routines. namespace lapack { // This is a wrapper around workspace queries. The query function takes // the work, lwork, and info variables and performs a workspace query. // After the query, the work array is allocated. template <typename Scalar> void WorkspaceQueryAndAlloc(std::function<void (Scalar* &, int&, int&)> query_func, Scalar* &work, int& lwork, int& info) { work = new Scalar[1]; lwork = -1; query_func(work, lwork, info); if (info != 0) { throw std::runtime_error("Bad workspace query"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new Scalar[lwork]; } void Trmm(char side, char uplo, char transt, char diag, int m, int n, double alpha, double *T, int ldt, double *B, int ldb) { dtrmm_(&side, &uplo, &transt, &diag, &m, &n, &alpha, T, &ldt, B, &ldb); } void Trmm(char side, char uplo, char transt, char diag, int m, int n, float alpha, float *T, int ldt, float *B, int ldb) { strmm_(&side, &uplo, &transt, &diag, &m, &n, &alpha, T, &ldt, B, &ldb); } void Larft(char direct, char storev, int m, int n, double *V, int ldv, double *tau, double *T, int ldt) { dlarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } void Larft(char direct, char storev, int m, int n, float *V, int ldv, float *tau, float *T, int ldt) { slarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } void Geqrf(int m, int n, float *A, int lda, float *tau) { // First perform the workspace query. std::function<void (float* &, int&, int&)> query = [&] (float *work, int& lwork, int& info) { sgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); }; float *work; int lwork; int info; WorkspaceQueryAndAlloc(query, work, lwork, info); // QR routine that does the work. sgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad sgeqrf_ call"); } delete [] work; } void Geqrf(int m, int n, double *A, int lda, double *tau) { // First perform the workspace query. std::function<void (double* &, int&, int&)> query = [&] (double *work, int& lwork, int& info) { dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); }; double *work; int lwork; int info; WorkspaceQueryAndAlloc(query, work, lwork, info); // QR routine that does the work. dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad dgeqrf_ call"); } delete [] work; } void Getrf(double *data, int m, int n, int lda, int *pivots) { int info; dgetrf_(&m, &n, data, &lda, pivots, &info); if (info != 0) { throw std::runtime_error("Bad dgetrf_ call"); } } void Getrf(float *data, int m, int n, int lda, int *pivots) { int info; sgetrf_(&m, &n, data, &lda, pivots, &info); if (info != 0) { throw std::runtime_error("Bad sgetrf_ call"); } } void Laswp(int num_cols, double *data, int lda, int piv_start, int piv_end, int *pivots, int incx) { dlaswp_(&num_cols, data, &lda, &piv_start, &piv_end, pivots, &incx); } void Laswp(int num_cols, float *data, int lda, int piv_start, int piv_end, int *pivots, int incx) { slaswp_(&num_cols, data, &lda, &piv_start, &piv_end, pivots, &incx); } void Trsm(char side, char uplo, char transa, char diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb) { dtrsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, A, &lda, B, &ldb); } void Trsm(char side, char uplo, char transa, char diag, int m, int n, float alpha, float *A, int lda, float *B, int ldb) { strsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, A, &lda, B, &ldb); } void Getrs(char trans, int n, int nrhs, double *A, int lda, int *ipiv, double *b, int ldb) { int info; dgetrs_(&trans, &n, &nrhs, A, &lda, ipiv, b, &ldb, &info); if (info != 0) { throw std::runtime_error("Bad dgetrs_ call"); } } void Getrs(char trans, int n, int nrhs, float *A, int lda, int *ipiv, float *b, int ldb) { int info; sgetrs_(&trans, &n, &nrhs, A, &lda, ipiv, b, &ldb, &info); if (info != 0) { throw std::runtime_error("Bad sgetrs_ call"); } } void Ormqr(char side, char trans, int m, int n, int k, double *A, int lda, double *tau, double *C, int ldc) { std::function<void (double* &, int&, int&)> query = [&] (double *work, int& lwork, int& info) { dormqr_(&side, &trans, &m, &n, &k, A, &lda, tau, C, &ldc, work, &lwork, &info); }; double *work; int lwork; int info; WorkspaceQueryAndAlloc(query, work, lwork, info); dormqr_(&side, &trans, &m, &n, &k, A, &lda, tau, C, &ldc, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad dormqr_ call"); } delete [] work; } void Ormqr(char side, char trans, int m, int n, int k, float *A, int lda, float *tau, float *C, int ldc) { std::function<void (float* &, int&, int&)> query = [&] (float *work, int& lwork, int& info) { sormqr_(&side, &trans, &m, &n, &k, A, &lda, tau, C, &ldc, work, &lwork, &info); }; float *work; int lwork; int info; WorkspaceQueryAndAlloc(query, work, lwork, info); sormqr_(&side, &trans, &m, &n, &k, A, &lda, tau, C, &ldc, work, &lwork, &info); if (info != 0) { throw std::runtime_error("Bad dormqr_ call"); } delete [] work; } } // end namespace lapack #endif // _LAPACK_WRAP_HPP_ <|endoftext|>
<commit_before>// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cassert> #include <fstream> #include <iostream> #include <strstream> #include <util/PlatformUtils.hpp> #include <XalanTransformer/XalanTransformer.hpp> //This is here for the Windows threads. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #define THREADFUNCTIONRETURN DWORD WINAPI #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::ios_base; using std::ostrstream; using std::string; #endif // Used to hold compiled stylesheet and XML source document. const XalanCompiledStylesheet* glbCompiledStylesheet = 0; const XalanParsedSource* glbParsedSource = 0; int glbError = 0; // Print messages tracking the progress of each thread, and the // beginning and end of the entire operation. void outputMessage( DWORD id, const char msg[]) { ostrstream threadMsg; threadMsg << "\n" << msg << " Thread: " << id << '\0'; cout << threadMsg.str(); threadMsg.freeze(false); } THREADFUNCTIONRETURN theThread(LPVOID param) { // This routine uses a compiled stylesheet (glbCompiledStylesheet), // and a binary source tree (glbParsedSource) to perform the // transformation. int theResult = 0; const int number = reinterpret_cast<int>(param); const DWORD theThreadID = GetCurrentThreadId(); outputMessage(theThreadID, "Starting "); // Create a XalanTransformer. XalanTransformer theXalanTransformer; // Generate the output file name for this thread. ostrstream theFormatterOut; theFormatterOut << "birds" << number << ".out" << '\0'; // Generate the XML output object. const XSLTResultTarget theResultTarget(XalanDOMString(theFormatterOut.str())); // Unfreeze the ostrstream, so memory is returned... theFormatterOut.freeze(false); outputMessage(theThreadID, "Transforming"); // Do the transform. theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget); if(theResult != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; glbError = theResult; } outputMessage(theThreadID, "Finishing"); return (theResult); } // Create and run the threads... // Print messages tracking the progress of each thread and of the // overall operation... void doThreads(int nThreads) { #if !defined(XALAN_NO_NAMESPACES) using std::vector; #endif vector<HANDLE> hThreads; hThreads.reserve(nThreads); cout << endl << "Clock before starting threads: " << clock() << endl; int i = 0; for (; i < nThreads; ++i) { DWORD threadID; const HANDLE hThread = CreateThread( 0, 4096, // Stack size for thread. theThread, // pointer to thread function reinterpret_cast<LPVOID>(i), // argument for new thread 0, // creation flags &threadID); assert(hThread != 0); hThreads.push_back(hThread); } WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE); cout << endl << "Clock after threads: " << clock() << endl; for (i = 0; i < nThreads; ++i) { CloseHandle(hThreads[i]); } } int main( int argc, const char* /* argv */[]) { if (argc != 1) { cerr << "Usage: ThreadTest" << endl << endl; } else { // Call the static initializer for Xerces. XMLPlatformUtils::Initialize(); // Initialize Xalan. XalanTransformer::initialize(); { // Create a XalanTransformer. We won't actually use this to transform -- // it's just acting likely a factory for the compiled stylesheet and // pre-parsed source. XalanTransformer theXalanTransformer; glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet); if (glbError != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; } else { assert(glbCompiledStylesheet != 0); // Compile the XML source document as well. All threads will use // this binary representation of the source tree. glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource); if (glbError != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; } else { assert(glbParsedSource != 0); // Create and run the threads... // Each thread uses the same document and // stylesheet to perform a transformation. doThreads(10); } } } // Terminate Xalan. XalanTransformer::terminate(); // Call the static terminator for Xerces. XMLPlatformUtils::Terminate(); } return glbError; } <commit_msg>Added missing include file.<commit_after>// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cassert> #include <ctime> #include <fstream> #include <iostream> #include <strstream> #include <util/PlatformUtils.hpp> #include <XalanTransformer/XalanTransformer.hpp> //This is here for the Windows threads. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #define THREADFUNCTIONRETURN DWORD WINAPI #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::cout; using std::endl; using std::ifstream; using std::ios_base; using std::ostrstream; using std::string; #endif // Used to hold compiled stylesheet and XML source document. const XalanCompiledStylesheet* glbCompiledStylesheet = 0; const XalanParsedSource* glbParsedSource = 0; int glbError = 0; // Print messages tracking the progress of each thread, and the // beginning and end of the entire operation. void outputMessage( DWORD id, const char msg[]) { ostrstream threadMsg; threadMsg << "\n" << msg << " Thread: " << id << '\0'; cout << threadMsg.str(); threadMsg.freeze(false); } THREADFUNCTIONRETURN theThread(LPVOID param) { // This routine uses a compiled stylesheet (glbCompiledStylesheet), // and a binary source tree (glbParsedSource) to perform the // transformation. int theResult = 0; const int number = reinterpret_cast<int>(param); const DWORD theThreadID = GetCurrentThreadId(); outputMessage(theThreadID, "Starting "); // Create a XalanTransformer. XalanTransformer theXalanTransformer; // Generate the output file name for this thread. ostrstream theFormatterOut; theFormatterOut << "birds" << number << ".out" << '\0'; // Generate the XML output object. const XSLTResultTarget theResultTarget(XalanDOMString(theFormatterOut.str())); // Unfreeze the ostrstream, so memory is returned... theFormatterOut.freeze(false); outputMessage(theThreadID, "Transforming"); // Do the transform. theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget); if(theResult != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; glbError = theResult; } outputMessage(theThreadID, "Finishing"); return (theResult); } // Create and run the threads... // Print messages tracking the progress of each thread and of the // overall operation... void doThreads(int nThreads) { #if !defined(XALAN_NO_NAMESPACES) using std::vector; #endif vector<HANDLE> hThreads; hThreads.reserve(nThreads); cout << endl << "Clock before starting threads: " << clock() << endl; int i = 0; for (; i < nThreads; ++i) { DWORD threadID; const HANDLE hThread = CreateThread( 0, 4096, // Stack size for thread. theThread, // pointer to thread function reinterpret_cast<LPVOID>(i), // argument for new thread 0, // creation flags &threadID); assert(hThread != 0); hThreads.push_back(hThread); } WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE); cout << endl << "Clock after threads: " << clock() << endl; for (i = 0; i < nThreads; ++i) { CloseHandle(hThreads[i]); } } int main( int argc, const char* /* argv */[]) { if (argc != 1) { cerr << "Usage: ThreadTest" << endl << endl; } else { // Call the static initializer for Xerces. XMLPlatformUtils::Initialize(); // Initialize Xalan. XalanTransformer::initialize(); { // Create a XalanTransformer. We won't actually use this to transform -- // it's just acting likely a factory for the compiled stylesheet and // pre-parsed source. XalanTransformer theXalanTransformer; glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet); if (glbError != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; } else { assert(glbCompiledStylesheet != 0); // Compile the XML source document as well. All threads will use // this binary representation of the source tree. glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource); if (glbError != 0) { cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError() << endl << endl; } else { assert(glbParsedSource != 0); // Create and run the threads... // Each thread uses the same document and // stylesheet to perform a transformation. doThreads(10); } } } // Terminate Xalan. XalanTransformer::terminate(); // Call the static terminator for Xerces. XMLPlatformUtils::Terminate(); } return glbError; } <|endoftext|>
<commit_before>#pragma once #include "depthai-shared/common/Extrinsics.hpp" namespace dai { struct CameraInfo { CameraInfo() : width(0), height(0), measuredFovDeg(0) {} uint16_t width, height; std::vector<std::vector<float>> intrinsicMatrix; std::vector<float> distortionCoeff; Extrinsics extrinsics; double measuredFovDeg; // fov in deg // TODO(sachin): Should I add type of distortion model here ? NLOHMANN_DEFINE_TYPE_INTRUSIVE(CameraInfo, intrinsicMatrix, width, height, distortionCoeff, extrinsics, measuredFovDeg); }; } // namespace dai<commit_msg>changed fov to float<commit_after>#pragma once #include "depthai-shared/common/Extrinsics.hpp" namespace dai { struct CameraInfo { CameraInfo() : width(0), height(0), measuredFovDeg(0) {} uint16_t width, height; std::vector<std::vector<float>> intrinsicMatrix; std::vector<float> distortionCoeff; Extrinsics extrinsics; float measuredFovDeg; // fov in deg // TODO(sachin): Should I add type of distortion model here ? NLOHMANN_DEFINE_TYPE_INTRUSIVE(CameraInfo, intrinsicMatrix, width, height, distortionCoeff, extrinsics, measuredFovDeg); }; } // namespace dai<|endoftext|>
<commit_before>#include "trajopt/configuration_space.hpp" #include <boost/foreach.hpp> #include "trajopt/rave_utils.hpp" #include "utils/math.hpp" using namespace OpenRAVE; using namespace util; // TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues namespace trajopt { void RobotAndDOF::SetDOFValues(const DblVec& dofs) { if (affinedofs != 0) { OR::Transform T; OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true); robot->SetTransform(T); robot->SetDOFValues(dofs, false, joint_inds); } else { robot->SetDOFValues(dofs, false, joint_inds); } } DblVec RobotAndDOF::GetDOFValues() { DblVec out; robot->GetDOFValues(out, joint_inds); if (affinedofs != 0) { out.resize(GetDOF()); OR::Transform T = robot->GetTransform(); OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis); } return out; } void RobotAndDOF::SetRobotActiveDOFs() { RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); // since robot is just a kinbody vector<int> current_active = robot1->GetActiveDOFIndices(); if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin())) robot1->SetActiveDOFs(joint_inds, affinedofs); } void RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const { robot->GetDOFLimits(lower, upper, joint_inds); const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z}; for (int i=0; i < 3; ++i) { if (affinedofs & translation_dofs[i]) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } if (affinedofs & DOF_RotationMask) { if (affinedofs & DOF_RotationAxis) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } else if (affinedofs & DOF_Rotation3D) { for (int i=0; i < 3; ++i) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } else if (affinedofs & DOF_Rotation3D) { for (int i=0; i < 3; ++i) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } else if (affinedofs & DOF_RotationQuat) { for (int i=0; i < 4; ++i) { lower.push_back(-1); upper.push_back(1); } } else throw OR::openrave_exception("invalid rotation dofs", ORE_InvalidArguments); } } int RobotAndDOF::GetDOF() const { return joint_inds.size() + RaveGetAffineDOF(affinedofs); } DblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const { Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save(); const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs(); vector<double> jacdata; boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata); return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); } DblMatrix RobotAndDOF::RotationJacobian(int link_ind) const { Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save(); const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs(); vector<double> jacdata; boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata); return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); } bool RobotAndDOF::DoesAffect(const KinBody::Link& link) { if (affinedofs > 0) return true; else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link)); else return false; } std::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() { vector<int> inds; std::vector<KinBody::LinkPtr> out; GetAffectedLinks(out,false,inds); return out; } void RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) { links.clear(); link_inds.clear(); BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) { if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) { links.push_back(link); link_inds.push_back(link->GetIndex()); } } vector<KinBodyPtr> grabbed; boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed); BOOST_FOREACH(const KinBodyPtr& body, grabbed) { KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body); assert(grabberLink); BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) { if (link->GetGeometries().size() > 0) { links.push_back(link); link_inds.push_back(grabberLink->GetIndex()); } } } } vector<KinBodyPtr> RobotAndDOF::GetBodies() { std::set<KinBodyPtr> bodies; robot->GetAttached(bodies); return vector<KinBodyPtr> (bodies.begin(), bodies.end()); } DblVec RobotAndDOF::RandomDOFValues() { int ndof = GetDOF(); DblVec lower, upper; GetDOFLimits(lower, upper); DblVec out(ndof); for (int i=0; i < ndof; ++i) { // TODO this is only right for a circular joint!! lower[i] = fmax(lower[i], -2*M_PI); upper[i] = fmin(upper[i], 2*M_PI); out[i] = lower[i] + randf() * (upper[i] - lower[i]); } return out; } } <commit_msg>Fixed bug that broke base only planning<commit_after>#include "trajopt/configuration_space.hpp" #include <boost/foreach.hpp> #include "trajopt/rave_utils.hpp" #include "utils/math.hpp" using namespace OpenRAVE; using namespace util; // TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues namespace trajopt { void RobotAndDOF::SetDOFValues(const DblVec& dofs) { if (affinedofs != 0) { OR::Transform T; OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true); robot->SetTransform(T); if (joint_inds.size() > 0) robot->SetDOFValues(dofs, false, joint_inds); } else { robot->SetDOFValues(dofs, false, joint_inds); } } DblVec RobotAndDOF::GetDOFValues() { DblVec out; if (joint_inds.size() > 0): robot->GetDOFValues(out, joint_inds); if (affinedofs != 0) { out.resize(GetDOF()); OR::Transform T = robot->GetTransform(); OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis); } return out; } void RobotAndDOF::SetRobotActiveDOFs() { RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); // since robot is just a kinbody vector<int> current_active = robot1->GetActiveDOFIndices(); if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin())) robot1->SetActiveDOFs(joint_inds, affinedofs); } void RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const { if (joint_inds.size() > 0) robot->GetDOFLimits(lower, upper, joint_inds); const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z}; for (int i=0; i < 3; ++i) { if (affinedofs & translation_dofs[i]) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } if (affinedofs & DOF_RotationMask) { if (affinedofs & DOF_RotationAxis) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } else if (affinedofs & DOF_Rotation3D) { for (int i=0; i < 3; ++i) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } else if (affinedofs & DOF_Rotation3D) { for (int i=0; i < 3; ++i) { lower.push_back(-INFINITY); upper.push_back(INFINITY); } } else if (affinedofs & DOF_RotationQuat) { for (int i=0; i < 4; ++i) { lower.push_back(-1); upper.push_back(1); } } else throw OR::openrave_exception("invalid rotation dofs", ORE_InvalidArguments); } } int RobotAndDOF::GetDOF() const { return joint_inds.size() + RaveGetAffineDOF(affinedofs); } DblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const { Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save(); const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs(); vector<double> jacdata; boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata); return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); } DblMatrix RobotAndDOF::RotationJacobian(int link_ind) const { Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save(); const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs(); vector<double> jacdata; boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata); return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); } bool RobotAndDOF::DoesAffect(const KinBody::Link& link) { if (affinedofs > 0) return true; else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link)); else return false; } std::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() { vector<int> inds; std::vector<KinBody::LinkPtr> out; GetAffectedLinks(out,false,inds); return out; } void RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) { links.clear(); link_inds.clear(); BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) { if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) { links.push_back(link); link_inds.push_back(link->GetIndex()); } } vector<KinBodyPtr> grabbed; boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed); BOOST_FOREACH(const KinBodyPtr& body, grabbed) { KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body); assert(grabberLink); BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) { if (link->GetGeometries().size() > 0) { links.push_back(link); link_inds.push_back(grabberLink->GetIndex()); } } } } vector<KinBodyPtr> RobotAndDOF::GetBodies() { std::set<KinBodyPtr> bodies; robot->GetAttached(bodies); return vector<KinBodyPtr> (bodies.begin(), bodies.end()); } DblVec RobotAndDOF::RandomDOFValues() { int ndof = GetDOF(); DblVec lower, upper; GetDOFLimits(lower, upper); DblVec out(ndof); for (int i=0; i < ndof; ++i) { // TODO this is only right for a circular joint!! lower[i] = fmax(lower[i], -2*M_PI); upper[i] = fmin(upper[i], 2*M_PI); out[i] = lower[i] + randf() * (upper[i] - lower[i]); } return out; } } <|endoftext|>
<commit_before>// --------------------------------------------------------------------- // // Copyright (C) 2017 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // The test is used to check the restriction_is_additive flags. The // face degrees of freedom of a BDM element must be non-additive as // they have continuity requirements, however the interior DOFs must // be additive, e.g. for order 1 elements all DOFs are non-additive, // while for the order 2 element in 2d we have 12 non-additive face DOFs // and 2 additive interior ones. The test should output a vector // consisting of faces_per_cell * dofs_per_face zeros, followed by // interior_dofs ones. #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/fe/fe_bdm.h> #include <fstream> #include <string> std::ofstream logfile ("output"); template<int dim> void test (const unsigned int degree) { FE_BDM<dim> fe_bdm(degree); deallog << "Degree=" << degree << ", restriction is additive flags:" << std::endl; for (unsigned int i=0; i<fe_bdm.dofs_per_cell; ++i) std::cout << fe_bdm.restriction_is_additive(i) << " "; deallog << std::endl; } int main() { initlog(); deallog << "Dimension 2: " << std::endl; for (unsigned int i=1; i<4; ++i) test<2>(i); deallog << "Dimension 3: " << std::endl; for (unsigned int i=1; i<4; ++i) test<3>(i); return 0; } <commit_msg>fix tests/fe/bdm_16<commit_after>// --------------------------------------------------------------------- // // Copyright (C) 2017 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // The test is used to check the restriction_is_additive flags. The // face degrees of freedom of a BDM element must be non-additive as // they have continuity requirements, however the interior DOFs must // be additive, e.g. for order 1 elements all DOFs are non-additive, // while for the order 2 element in 2d we have 12 non-additive face DOFs // and 2 additive interior ones. The test should output a vector // consisting of faces_per_cell * dofs_per_face zeros, followed by // interior_dofs ones. #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/fe/fe_bdm.h> #include <fstream> #include <string> std::ofstream logfile ("output"); template<int dim> void test (const unsigned int degree) { FE_BDM<dim> fe_bdm(degree); deallog << "Degree=" << degree << ", restriction is additive flags:" << std::endl; for (unsigned int i=0; i<fe_bdm.dofs_per_cell; ++i) deallog << fe_bdm.restriction_is_additive(i) << " "; deallog << std::endl; } int main() { initlog(); deallog << "Dimension 2: " << std::endl; for (unsigned int i=1; i<4; ++i) test<2>(i); deallog << "Dimension 3: " << std::endl; for (unsigned int i=1; i<4; ++i) test<3>(i); return 0; } <|endoftext|>
<commit_before>#include "../sys_uniform_value.hpp" #include "screen.hpp" #include "../glx_if.hpp" #include "../systeminfo.hpp" #include "../sys_uniform.hpp" namespace rs { namespace util { const IdValue PostEffect::U_RectScale = IEffect::GlxId::GenUnifId("u_rectScale"); // --------------------- PostEffect --------------------- PostEffect::PostEffect(IdValue idTech, rs::Priority dprio): _idTech(idTech) { _dtag.priority = dprio; setRect({-1,1,-1,1}); } void PostEffect::setTechPassId(IdValue idTech) { _idTech = idTech; } void PostEffect::_applyParam(IEffect& e) const { for(auto& p : _param) p.second(e); } void PostEffect::setParamFunc(IdValue id, const ParamF& f) { auto itr = std::find_if(_param.begin(), _param.end(), [id](auto& p){ return p.first == id; }); if(itr == _param.end()) _param.emplace_back(id, f); else *itr = std::make_pair(id, f); } void PostEffect::clearParam() { _param.clear(); } void PostEffect::setRect(const spn::RectF& r) { _drawRect = r; } void PostEffect::onDraw(IEffect& e) const { e.setTechPassId(_idTech); _applyParam(e); e.setVDecl(DrawDecl<vdecl::screen>::GetVDecl()); e.setVStream(_rect11.getVertex(), 0); auto ib = _rect11.getIndex(); e.setIStream(ib); e.setUniform(U_RectScale, spn::Vec4{ (_drawRect.x0+_drawRect.x1)/2, (_drawRect.y0+_drawRect.y1)/2, _drawRect.width()/2, _drawRect.height()/2}); // 重ねて描画 e.drawIndexed(GL_TRIANGLES, ib->get()->getNElem(), 0); } // --------------------- Viewport --------------------- Viewport::Viewport(Priority dprio) { _dtag.priority = dprio; setByRatio({0,1,0,1}); } void Viewport::setByRatio(const spn::RectF& r) { _bPixel = false; _rect = r; } void Viewport::setByPixel(const spn::RectF& r) { _bPixel = true; _rect = r; } void Viewport::onDraw(IEffect& e) const { e.setViewport(_bPixel, _rect); } // --------------------- FBSwitch --------------------- FBSwitch::FBSwitch(rs::Priority dprio, rs::HFb hFb, const ClearParam_OP& cp): _hlFb(hFb), _cparam(cp) { _dtag.priority = dprio; } void FBSwitch::setClearParam(const ClearParam_OP& p) { _cparam = p; } // これ自体の描画はしない void FBSwitch::onDraw(IEffect& e) const { if(_hlFb) e.setFramebuffer(_hlFb); else e.resetFramebuffer(); if(_cparam) e.clearFramebuffer(*_cparam); // ビューポートはフルスクリーンで初期化 Viewport(0x0000).onDraw(e); } // --------------------- FBClear --------------------- FBClear::FBClear(rs::Priority dprio, const rs::draw::ClearParam& p): _param(p) { _dtag.priority = dprio; } void FBClear::onDraw(IEffect& e) const { e.clearFramebuffer(_param); } } } <commit_msg>PostEffect: 特定のUniform値が宣言されていない場合でも警告を出さない<commit_after>#include "../sys_uniform_value.hpp" #include "screen.hpp" #include "../glx_if.hpp" #include "../systeminfo.hpp" #include "../sys_uniform.hpp" namespace rs { namespace util { const IdValue PostEffect::U_RectScale = IEffect::GlxId::GenUnifId("u_rectScale"); // --------------------- PostEffect --------------------- PostEffect::PostEffect(IdValue idTech, rs::Priority dprio): _idTech(idTech) { _dtag.priority = dprio; setRect({-1,1,-1,1}); } void PostEffect::setTechPassId(IdValue idTech) { _idTech = idTech; } void PostEffect::_applyParam(IEffect& e) const { for(auto& p : _param) p.second(e); } void PostEffect::setParamFunc(IdValue id, const ParamF& f) { auto itr = std::find_if(_param.begin(), _param.end(), [id](auto& p){ return p.first == id; }); if(itr == _param.end()) _param.emplace_back(id, f); else *itr = std::make_pair(id, f); } void PostEffect::clearParam() { _param.clear(); } void PostEffect::setRect(const spn::RectF& r) { _drawRect = r; } void PostEffect::onDraw(IEffect& e) const { e.setTechPassId(_idTech); _applyParam(e); e.setVDecl(DrawDecl<vdecl::screen>::GetVDecl()); e.setVStream(_rect11.getVertex(), 0); auto ib = _rect11.getIndex(); e.setIStream(ib); e.setUniform<false>(U_RectScale, spn::Vec4{ (_drawRect.x0+_drawRect.x1)/2, (_drawRect.y0+_drawRect.y1)/2, _drawRect.width()/2, _drawRect.height()/2}); // 重ねて描画 e.drawIndexed(GL_TRIANGLES, ib->get()->getNElem(), 0); } // --------------------- Viewport --------------------- Viewport::Viewport(Priority dprio) { _dtag.priority = dprio; setByRatio({0,1,0,1}); } void Viewport::setByRatio(const spn::RectF& r) { _bPixel = false; _rect = r; } void Viewport::setByPixel(const spn::RectF& r) { _bPixel = true; _rect = r; } void Viewport::onDraw(IEffect& e) const { e.setViewport(_bPixel, _rect); } // --------------------- FBSwitch --------------------- FBSwitch::FBSwitch(rs::Priority dprio, rs::HFb hFb, const ClearParam_OP& cp): _hlFb(hFb), _cparam(cp) { _dtag.priority = dprio; } void FBSwitch::setClearParam(const ClearParam_OP& p) { _cparam = p; } // これ自体の描画はしない void FBSwitch::onDraw(IEffect& e) const { if(_hlFb) e.setFramebuffer(_hlFb); else e.resetFramebuffer(); if(_cparam) e.clearFramebuffer(*_cparam); // ビューポートはフルスクリーンで初期化 Viewport(0x0000).onDraw(e); } // --------------------- FBClear --------------------- FBClear::FBClear(rs::Priority dprio, const rs::draw::ClearParam& p): _param(p) { _dtag.priority = dprio; } void FBClear::onDraw(IEffect& e) const { e.clearFramebuffer(_param); } } } <|endoftext|>
<commit_before>#include "../bitmap_content.hpp" namespace sani { namespace resource { inline const uint32 BitmapContent::getWidth() const { return width; } inline const uint32 BitmapContent::getHeight() const { return height; } template <class PixelType> PixelBitmapContent<PixelType>::PixelBitmapContent(uint32 width, uint32 height) : BitmapContent(width, height), pixels(new PixelType[width * height]) { tryGetFormat(format); } template <class PixelType> PixelBitmapContent<PixelType>::~PixelBitmapContent() { delete[] pixels; } template <class PixelType> void PixelBitmapContent<PixelType>::tryGetFormat(graphics::SurfaceFormat* out) const { using namespace sani::math; out = nullptr; if (typeid(PixelType) == typeid(Vec4f)) { *out = SurfaceFormat::ColorRGBA; } } } }<commit_msg>Set all pixels transparent as default<commit_after>#include "../bitmap_content.hpp" namespace sani { namespace resource { inline const uint32 BitmapContent::getWidth() const { return width; } inline const uint32 BitmapContent::getHeight() const { return height; } template <class PixelType> PixelBitmapContent<PixelType>::PixelBitmapContent(uint32 width, uint32 height) : BitmapContent(width, height), pixels(new PixelType[width * height]) { // transparent memset(pixels, 0, sizeof(PixelType) * width * height); tryGetFormat(format); } template <class PixelType> PixelBitmapContent<PixelType>::~PixelBitmapContent() { delete[] pixels; } template <class PixelType> void PixelBitmapContent<PixelType>::tryGetFormat(graphics::SurfaceFormat* out) const { using namespace sani::math; out = nullptr; if (typeid(PixelType) == typeid(Vec4f)) { *out = SurfaceFormat::ColorRGBA; } } } }<|endoftext|>
<commit_before>#pragma once #include "util.hpp" #include <utility> #include <algorithm> #include <cereal/access.hpp> namespace spi { namespace test { //! non-copyableな値 template <class T> class MoveOnly { public: using value_t = T; private: value_t _value; // MoveOnlyがネストされていた場合にget()で一括除去 template <class T2> static const T2& _getValue(const T2& t, ...) { return t; } template <class T3> static decltype(auto) _getValue(const MoveOnly<T3>& t, ...) { return t.getValue(); } public: MoveOnly() = default; MoveOnly(const value_t& v): _value(v) {} MoveOnly(value_t&& v) noexcept: _value(std::move(v)) {} MoveOnly(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; void operator = (const MoveOnly&) = delete; MoveOnly& operator = (MoveOnly&&) = default; decltype(auto) getValue() const { return _getValue(_value, nullptr); } bool operator == (const MoveOnly& m) const noexcept { return getValue() == m.getValue(); } bool operator != (const MoveOnly& m) const noexcept { return !(this->operator == (m)); } bool operator < (const MoveOnly& m) const noexcept { return getValue() < m.getValue(); } bool operator > (const MoveOnly& m) const noexcept { return getValue() > m.getValue(); } bool operator <= (const MoveOnly& m) const noexcept { return getValue() <= m.getValue(); } bool operator >= (const MoveOnly& m) const noexcept { return getValue() >= m.getValue(); } value_t& get() noexcept { return _value; } const value_t& get() const noexcept { return _value; } template <class Ar> void serialize(Ar& ar) { ar(_value); } template <class Ar> static void load_and_construct(Ar& ar, cereal::construct<MoveOnly>& cs) { value_t val; ar(val); cs(val); } }; template <class T> std::ostream& operator << (std::ostream& os, const MoveOnly<T>& m) { return os << m.get(); } template <class T> void ModifyValue(MoveOnly<T>& t) { ModifyValue(t.get()); } } } namespace std { template <class T> struct hash<spi::test::MoveOnly<T>> { std::size_t operator()(const spi::test::MoveOnly<T>& m) const noexcept { return std::hash<T>()(m.get()); } }; } <commit_msg>Test: MoveOnly: 値のデリファレンス<commit_after>#pragma once #include "util.hpp" #include <utility> #include <algorithm> #include <cereal/access.hpp> namespace spi { namespace test { //! non-copyableな値 template <class T> class MoveOnly { public: using value_t = T; private: value_t _value; // MoveOnlyがネストされていた場合にget()で一括除去 template <class T2> static const T2& _getValue(const T2& t, ...) { return t; } template <class T3> static decltype(auto) _getValue(const MoveOnly<T3>& t, ...) { return t.getValue(); } public: MoveOnly() = default; MoveOnly(const value_t& v): _value(v) {} MoveOnly(value_t&& v) noexcept: _value(std::move(v)) {} MoveOnly(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; void operator = (const MoveOnly&) = delete; MoveOnly& operator = (MoveOnly&&) = default; decltype(auto) getValue() const { return _getValue(_value, nullptr); } bool operator == (const MoveOnly& m) const noexcept { return getValue() == m.getValue(); } bool operator != (const MoveOnly& m) const noexcept { return !(this->operator == (m)); } bool operator < (const MoveOnly& m) const noexcept { return getValue() < m.getValue(); } bool operator > (const MoveOnly& m) const noexcept { return getValue() > m.getValue(); } bool operator <= (const MoveOnly& m) const noexcept { return getValue() <= m.getValue(); } bool operator >= (const MoveOnly& m) const noexcept { return getValue() >= m.getValue(); } value_t& get() noexcept { return _value; } const value_t& get() const noexcept { return _value; } template <class Ar> void serialize(Ar& ar) { ar(_value); } template <class Ar> static void load_and_construct(Ar& ar, cereal::construct<MoveOnly>& cs) { value_t val; ar(val); cs(val); } }; template <class T> std::ostream& operator << (std::ostream& os, const MoveOnly<T>& m) { return os << m.get(); } template <class T> decltype(auto) Deref_MoveOnly(const MoveOnly<T>& m) { return m.get(); } template <class T> decltype(auto) Deref_MoveOnly(const T& t) { return t; } template <class T> void ModifyValue(MoveOnly<T>& t) { ModifyValue(t.get()); } } } namespace std { template <class T> struct hash<spi::test::MoveOnly<T>> { std::size_t operator()(const spi::test::MoveOnly<T>& m) const noexcept { return std::hash<T>()(m.get()); } }; } <|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$ */ #if !defined(XERCESC_INCLUDE_GUARD_XMLBUFFER_HPP) #define XERCESC_INCLUDE_GUARD_XMLBUFFER_HPP #include <xercesc/util/XMemory.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/MemoryManager.hpp> #include <string.h> XERCES_CPP_NAMESPACE_BEGIN class XMLBufferFullHandler; /** * XMLBuffer is a lightweight, expandable Unicode text buffer. Since XML is * inherently theoretically unbounded in terms of the sizes of things, we * very often need to have expandable buffers. The primary concern here is * that appends of characters and other buffers or strings be very fast, so * it always maintains the current buffer size. * * The buffer is not null terminated until some asks to see the raw buffer * contents. This also avoids overhead during append operations. */ class XMLPARSER_EXPORT XMLBuffer : public XMemory { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- /** @name Constructor */ //@{ XMLBuffer(const XMLSize_t capacity = 1023 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) : fIndex(0) , fCapacity(capacity) , fFullSize(0) , fUsed(false) , fMemoryManager(manager) , fFullHandler(0) , fBuffer(0) { // Buffer is one larger than capacity, to allow for zero term fBuffer = (XMLCh*) manager->allocate((capacity+1) * sizeof(XMLCh)); //new XMLCh[fCapacity+1]; // Keep it null terminated fBuffer[0] = XMLCh(0); } //@} /** @name Destructor */ //@{ ~XMLBuffer() { fMemoryManager->deallocate(fBuffer); //delete [] fBuffer; } //@} // ----------------------------------------------------------------------- // Buffer Full Handler Management // ----------------------------------------------------------------------- void setFullHandler(XMLBufferFullHandler* handler, const XMLSize_t fullSize) { if (handler && fullSize) { fFullHandler = handler; fFullSize = fullSize; // Need to consider the case that the fullsize is less than the current capacity. // For example, say fullSize = 100 and fCapacity is 1023 (the default). // If the fIndex is less than the fullSize, then no problem. We can just carry // on by resetting fCapacity to fullsize and proceed business as usual. // If the fIndex is already bigger than the fullSize then we call insureCapacity // to see if it can handle emptying the current buffer (it will throw an // exception if it can't). if (fullSize < fCapacity) { fCapacity = fullSize; if (fIndex >= fullSize) { insureCapacity(0); } } } else { // reset fFullHandler to zero because setFullHandler had bad input fFullHandler = 0; } } // ----------------------------------------------------------------------- // Buffer Management // ----------------------------------------------------------------------- void append(const XMLCh toAppend) { // Put in char and bump the index if (fIndex == fCapacity) insureCapacity(1); fBuffer[fIndex++] = toAppend; } void append (const XMLCh* const chars, const XMLSize_t count) { if (count) { if (fIndex + count >= fCapacity) { insureCapacity(count); } memcpy(&fBuffer[fIndex], chars, count * sizeof(XMLCh)); fIndex += count; } else { append(chars); } } void append (const XMLCh* const chars) { if (chars != 0 && *chars != 0) { // get length of chars XMLSize_t count = 0; for (; *(chars+count); count++ ); if (fIndex + count >= fCapacity) { insureCapacity(count); } memcpy(&fBuffer[fIndex], chars, count * sizeof(XMLCh)); fIndex += count; } } void set (const XMLCh* const chars, const XMLSize_t count) { fIndex = 0; append(chars, count); } void set (const XMLCh* const chars) { fIndex = 0; if (chars != 0 && *chars != 0) append(chars); } const XMLCh* getRawBuffer() const { fBuffer[fIndex] = 0; return fBuffer; } XMLCh* getRawBuffer() { fBuffer[fIndex] = 0; return fBuffer; } void reset() { fIndex = 0; } // ----------------------------------------------------------------------- // Getters // ----------------------------------------------------------------------- bool getInUse() const { return fUsed; } XMLSize_t getLen() const { return fIndex; } bool isEmpty() const { return (fIndex == 0); } // ----------------------------------------------------------------------- // Setters // ----------------------------------------------------------------------- void setInUse(const bool newValue) { fUsed = newValue; } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XMLBuffer(const XMLBuffer&); XMLBuffer& operator=(const XMLBuffer&); // ----------------------------------------------------------------------- // Declare our friends // ----------------------------------------------------------------------- friend class XMLBufBid; // ----------------------------------------------------------------------- // Private helpers // ----------------------------------------------------------------------- void insureCapacity(const XMLSize_t extraNeeded); // ----------------------------------------------------------------------- // Private data members // // fBuffer // The pointer to the buffer data. Its grown as needed. Its always // one larger than fCapacity, to leave room for the null terminator. // // fIndex // The current index into the buffer, as characters are appended // to it. If its zero, then the buffer is empty. // // fCapacity // The current capacity of the buffer. Its actually always one // larger, to leave room for the null terminator. // // fUsed // Indicates whether this buffer is in use or not. // // fFullHandler, fFullSize // If fFullHandler is non-null, the buffer has a maximum size // indicated by fFullSize. If writing to the buffer would exceed the // buffer's maximum size, fFullHandler's bufferFull callback is // invoked, to empty the buffer. // ----------------------------------------------------------------------- XMLSize_t fIndex; XMLSize_t fCapacity; XMLSize_t fFullSize; bool fUsed; MemoryManager* const fMemoryManager; XMLBufferFullHandler* fFullHandler; XMLCh* fBuffer; }; /** * XMLBufferFullHandler is a callback interface for clients of * XMLBuffers that impose a size restriction (e.g. XMLScanner). * Note that this is intended solely as a mix-in for internal * use, and therefore does not derive from XMemory (to avoid * the ambiguous base class problem). */ class XMLPARSER_EXPORT XMLBufferFullHandler { public : virtual ~XMLBufferFullHandler() {} /** * Callback method, intended to allow clients of an XMLBuffer which has * become full to empty it appropriately. * @return true if the handler was able to empty the buffer (either * partially or completely), otherwise false to indicate an error. */ virtual bool bufferFull(XMLBuffer&) = 0; }; XERCES_CPP_NAMESPACE_END #endif <commit_msg>Suppress new warnings introduced in g++ 4.3.<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$ */ #if !defined(XERCESC_INCLUDE_GUARD_XMLBUFFER_HPP) #define XERCESC_INCLUDE_GUARD_XMLBUFFER_HPP #include <xercesc/util/XMemory.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/MemoryManager.hpp> #include <string.h> XERCES_CPP_NAMESPACE_BEGIN class XMLBufferFullHandler; /** * XMLBuffer is a lightweight, expandable Unicode text buffer. Since XML is * inherently theoretically unbounded in terms of the sizes of things, we * very often need to have expandable buffers. The primary concern here is * that appends of characters and other buffers or strings be very fast, so * it always maintains the current buffer size. * * The buffer is not null terminated until some asks to see the raw buffer * contents. This also avoids overhead during append operations. */ class XMLPARSER_EXPORT XMLBuffer : public XMemory { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- /** @name Constructor */ //@{ XMLBuffer(const XMLSize_t capacity = 1023 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) : fIndex(0) , fCapacity(capacity) , fFullSize(0) , fUsed(false) , fMemoryManager(manager) , fFullHandler(0) , fBuffer(0) { // Buffer is one larger than capacity, to allow for zero term fBuffer = (XMLCh*) manager->allocate((capacity+1) * sizeof(XMLCh)); //new XMLCh[fCapacity+1]; // Keep it null terminated fBuffer[0] = XMLCh(0); } //@} /** @name Destructor */ //@{ ~XMLBuffer() { fMemoryManager->deallocate(fBuffer); //delete [] fBuffer; } //@} // ----------------------------------------------------------------------- // Buffer Full Handler Management // ----------------------------------------------------------------------- void setFullHandler(XMLBufferFullHandler* handler, const XMLSize_t fullSize) { if (handler && fullSize) { fFullHandler = handler; fFullSize = fullSize; // Need to consider the case that the fullsize is less than the current capacity. // For example, say fullSize = 100 and fCapacity is 1023 (the default). // If the fIndex is less than the fullSize, then no problem. We can just carry // on by resetting fCapacity to fullsize and proceed business as usual. // If the fIndex is already bigger than the fullSize then we call insureCapacity // to see if it can handle emptying the current buffer (it will throw an // exception if it can't). if (fullSize < fCapacity) { fCapacity = fullSize; if (fIndex >= fullSize) { insureCapacity(0); } } } else { // reset fFullHandler to zero because setFullHandler had bad input fFullHandler = 0; } } // ----------------------------------------------------------------------- // Buffer Management // ----------------------------------------------------------------------- void append(const XMLCh toAppend) { // Put in char and bump the index if (fIndex == fCapacity) insureCapacity(1); fBuffer[fIndex++] = toAppend; } void append (const XMLCh* const chars, const XMLSize_t count) { if (count) { if (fIndex + count >= fCapacity) { insureCapacity(count); } memcpy(&fBuffer[fIndex], chars, count * sizeof(XMLCh)); fIndex += count; } else { append(chars); } } void append (const XMLCh* const chars) { if (chars != 0 && *chars != 0) { // get length of chars XMLSize_t count = 0; for (; *(chars+count); count++ ) /*noop*/; if (fIndex + count >= fCapacity) { insureCapacity(count); } memcpy(&fBuffer[fIndex], chars, count * sizeof(XMLCh)); fIndex += count; } } void set (const XMLCh* const chars, const XMLSize_t count) { fIndex = 0; append(chars, count); } void set (const XMLCh* const chars) { fIndex = 0; if (chars != 0 && *chars != 0) append(chars); } const XMLCh* getRawBuffer() const { fBuffer[fIndex] = 0; return fBuffer; } XMLCh* getRawBuffer() { fBuffer[fIndex] = 0; return fBuffer; } void reset() { fIndex = 0; } // ----------------------------------------------------------------------- // Getters // ----------------------------------------------------------------------- bool getInUse() const { return fUsed; } XMLSize_t getLen() const { return fIndex; } bool isEmpty() const { return (fIndex == 0); } // ----------------------------------------------------------------------- // Setters // ----------------------------------------------------------------------- void setInUse(const bool newValue) { fUsed = newValue; } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XMLBuffer(const XMLBuffer&); XMLBuffer& operator=(const XMLBuffer&); // ----------------------------------------------------------------------- // Declare our friends // ----------------------------------------------------------------------- friend class XMLBufBid; // ----------------------------------------------------------------------- // Private helpers // ----------------------------------------------------------------------- void insureCapacity(const XMLSize_t extraNeeded); // ----------------------------------------------------------------------- // Private data members // // fBuffer // The pointer to the buffer data. Its grown as needed. Its always // one larger than fCapacity, to leave room for the null terminator. // // fIndex // The current index into the buffer, as characters are appended // to it. If its zero, then the buffer is empty. // // fCapacity // The current capacity of the buffer. Its actually always one // larger, to leave room for the null terminator. // // fUsed // Indicates whether this buffer is in use or not. // // fFullHandler, fFullSize // If fFullHandler is non-null, the buffer has a maximum size // indicated by fFullSize. If writing to the buffer would exceed the // buffer's maximum size, fFullHandler's bufferFull callback is // invoked, to empty the buffer. // ----------------------------------------------------------------------- XMLSize_t fIndex; XMLSize_t fCapacity; XMLSize_t fFullSize; bool fUsed; MemoryManager* const fMemoryManager; XMLBufferFullHandler* fFullHandler; XMLCh* fBuffer; }; /** * XMLBufferFullHandler is a callback interface for clients of * XMLBuffers that impose a size restriction (e.g. XMLScanner). * Note that this is intended solely as a mix-in for internal * use, and therefore does not derive from XMemory (to avoid * the ambiguous base class problem). */ class XMLPARSER_EXPORT XMLBufferFullHandler { public : virtual ~XMLBufferFullHandler() {} /** * Callback method, intended to allow clients of an XMLBuffer which has * become full to empty it appropriately. * @return true if the handler was able to empty the buffer (either * partially or completely), otherwise false to indicate an error. */ virtual bool bufferFull(XMLBuffer&) = 0; }; XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/* ******************************************************* Parallel PLUQ quad recurisve with OpenMP ******************************************************* g++ -D__FFLASFFPACK_HAVE_CBLAS -Wall -g -fopenmp -O3 -march=native -mavx -I/home/sultan/soft/fflas-ffpack/ -I/usr/local/soft/givaro-3.7.1/include test-ppluq.C -L/home/pernet/Logiciels/ATLAS_1TH/lib -lcblas -latlas -L/usr/local/soft/givaro-3.7.1/lib -lgivaro -lm -lrt -Wl,-rpath -Wl,/usr/local/soft/givaro-3.7.1/lib -o test-ppluq */ #include <iostream> #include <fstream> #include <stdlib.h> #include <iomanip> //#include "omp.h" #define __FFLASFFPACK_USE_OPENMP #define __FFLAS__TRSM_READONLY #define __PFTRSM_FOR_PLUQ #include "fflas-ffpack/utils/Matio.h" //#include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/field/modular-balanced.h" #include "fflas-ffpack/field/modular-balanced.h" #include "fflas-ffpack/ffpack/ffpack.h" #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/fflas/fflas.h" #include "sys/time.h" //#define BASECASE_K 256 //#include "fflas-ffpack/ffpack/parallel.h" using namespace std; using namespace FFLAS; using namespace FFPACK; #ifndef MODULO #define MODULO 1 #endif #if(MODULO==1) typedef FFPACK::Modular<double> Field; #else typedef FFPACK::UnparametricField<double> Field; #endif #ifndef DEBUG #define DEBUG 1 #endif #ifndef SEQ #define SEQ 1 #endif void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A, size_t * P, size_t * Q, size_t m, size_t n, size_t R) { Field::Element * X = FFLAS::fflas_new<Field::Element>(m*n); Field::Element * L, *U; L = FFLAS::fflas_new<Field::Element>(m*R); U = FFLAS::fflas_new<Field::Element>(R*n); for (size_t i=0; i<m*R; ++i) F.init(L[i], 0.0); for (size_t i=0; i<m*R; ++i) F.init(U[i], 0.0); for (size_t i=0; i<m*n; ++i) F.init(X[i], 0.0); Field::Element zero,one; F.init(zero,0.0); F.init(one,1.0); for (size_t i=0; i<R; ++i){ for (size_t j=0; j<i; ++j) F.assign ( *(U + i*n + j), zero); for (size_t j=i; j<n; ++j) F.assign (*(U + i*n + j), *(A+ i*n+j)); } for ( size_t j=0; j<R; ++j ){ for (size_t i=0; i<=j; ++i ) F.assign( *(L+i*R+j), zero); F.assign(*(L+j*R+j), one); for (size_t i=j+1; i<m; i++) F.assign( *(L + i*R+j), *(A+i*n+j)); } FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P); FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q); FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R, 1.0, L,R, U,n, 0.0, X,n); bool fail = false; for (size_t i=0; i<m; ++i) for (size_t j=0; j<n; ++j) if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){ std::cerr << " B["<<i<<","<<j<<"] = " << (*(B+i*n+j)) << " X["<<i<<","<<j<<"] = " << (*(X+i*n+j)) << std::endl; fail=true; } if (fail) std::cerr<<"FAIL"<<std::endl; else std::cerr<<"PASS"<<std::endl; FFLAS::fflas_delete( U); FFLAS::fflas_delete( L); FFLAS::fflas_delete( X); } int main(int argc, char** argv) { int p, n, m, nbf; if (argc > 6){ std::cerr<<"usage : PLUQ-rec-omp <p> <m> <n> <i> <file>"<<std::endl // std::cerr<<"usage : PLUQ-rec-omp <m> <n> <p> <r> <i>"<<std::endl <<std::endl; exit(-1); } p = (argc>1 ? atoi( argv[1] ) : 1009); m = (argc>2 ? atoi( argv[2] ) : 1024); n = (argc>3 ? atoi( argv[3] ) : 1024); // r = atoi( argv[4] ); nbf = (argc>4 ? atoi( argv[4] ) : 1); // size_t lda = n; // random seed // ifstream f("/dev/urandom"); // size_t seed1, seed2, seed3,seed4; // f.read(reinterpret_cast<char*>(&seed1), sizeof(seed1)); // f.read(reinterpret_cast<char*>(&seed2), sizeof(seed2)); // f.read(reinterpret_cast<char*>(&seed3), sizeof(seed3)); // f.read(reinterpret_cast<char*>(&seed4), sizeof(seed4)); // seed1=10;seed2=12; // seed3=13;seed4=14; enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit; size_t R; const Field F((double)p); // Field::RandIter G(F, seed1); Field::Element alpha, beta; F.init(alpha,1.0); F.init(beta,0.0); // Field::Element * U = FFLAS::fflas_new<Field::Element>(n*n); typename Field::Element* Acop; if (argc > 5) { Acop = read_field(F,argv[5],&m,&n); } else { Field::RandIter G(F); Acop = FFLAS::fflas_new<Field::Element>(m*n); PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) G.random (*(Acop+i*n+j)); } // FFLAS::fflas_new<Field::Element>(n*m); Field::Element* A = FFLAS::fflas_new<Field::Element>(n*m); #if(DEBUG==1) Field::Element* Adebug = FFLAS::fflas_new<Field::Element>(n*m); #endif // std::vector<size_t> Index_P(r); // U = construct_U(F,G, n, r, Index_P, seed4, seed3); // A = construct_L(F,G, m, r, Index_P, seed2); // M_randgen(F, A, U, r, m, n); // size_t taille=m*n; // for(size_t i=0; i<taille;++i) U[i]=A[i]; struct timespec t0, t1;// tt0, tt1; double delay, avrg;//, avrgg; double t_total=0; size_t maxP, maxQ; maxP = m; maxQ = n; size_t *P = FFLAS::fflas_new<size_t>(maxP); size_t *Q = FFLAS::fflas_new<size_t>(maxQ); PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) { *(A+i*n+j) = *(Acop+i*n+j) ; #if(DEBUG==1) *(Adebug+i*n+j) = *(Acop+i*n+j) ; #endif } for ( int i=0;i<nbf+1;i++){ for (size_t j=0;j<maxP;j++) P[j]=0; for (size_t j=0;j<maxQ;j++) Q[j]=0; PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) *(A+i*n+j) = *(Acop+i*n+j) ; clock_gettime(CLOCK_REALTIME, &t0); PAR_REGION{ R = pPLUQ(F, diag, m, n, A, n, P, Q);// Parallel PLUQ } clock_gettime(CLOCK_REALTIME, &t1); delay = (double)(t1.tv_sec-t0.tv_sec)+(double)(t1.tv_nsec-t0.tv_nsec)/1000000000; if(i) t_total +=delay; } avrg = t_total/nbf; std::cerr << "MODULO: " << (MODULO?p:0) << std::endl; PAR_REGION{ std::cerr<<"Parallel --- m: "<<m<<" , n: " << n << " , r: " <<R<<" " <<avrg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrg))<<" " //#ifdef __FFLASFFPACK_USE_OPENMP <<NUM_THREADS<<endl; //#else } //<<endl; //#endi // std::cout<<typeid(A).name()<<endl; #if(DEBUG==1) cout<<"check equality A == PLUQ ?"<<endl; verification_PLUQ(F,Adebug,A,P,Q,m,n,R); FFLAS::fflas_delete( Adebug); #endif #if(SEQ==1) struct timespec tt0, tt1; double avrgg; //call sequential PLUQ size_t * PP = FFLAS::fflas_new<size_t>(maxP); size_t * QQ = FFLAS::fflas_new<size_t>(maxQ); for (size_t j=0;j<maxP;j++) PP[j]=0; for (size_t j=0;j<maxQ;j++) QQ[j]=0; clock_gettime(CLOCK_REALTIME, &tt0); size_t R2 = PLUQ(F, diag, m, n, Acop, n, PP, QQ); clock_gettime(CLOCK_REALTIME, &tt1); FFLAS::fflas_delete( Acop); avrgg = (double)(tt1.tv_sec-tt0.tv_sec)+(double)(tt1.tv_nsec-tt0.tv_nsec)/1000000000; //verification std::cerr<<"Sequential : "<<m<<" "<<R2<<" " <<avrgg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrgg))<<endl; #endif FFLAS::fflas_delete( A); return 0; } <commit_msg>PAR_FIOR test<commit_after>/* ******************************************************* Parallel PLUQ quad recurisve with OpenMP ******************************************************* g++ -D__FFLASFFPACK_HAVE_CBLAS -Wall -g -fopenmp -O3 -march=native -mavx -I/home/sultan/soft/fflas-ffpack/ -I/usr/local/soft/givaro-3.7.1/include test-ppluq.C -L/home/pernet/Logiciels/ATLAS_1TH/lib -lcblas -latlas -L/usr/local/soft/givaro-3.7.1/lib -lgivaro -lm -lrt -Wl,-rpath -Wl,/usr/local/soft/givaro-3.7.1/lib -o test-ppluq */ #include <iostream> #include <fstream> #include <stdlib.h> #include <iomanip> //#include "omp.h" #define __FFLASFFPACK_USE_OPENMP #define __FFLAS__TRSM_READONLY #define __PFTRSM_FOR_PLUQ #include "fflas-ffpack/utils/Matio.h" //#include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/field/modular-balanced.h" #include "fflas-ffpack/field/modular-balanced.h" #include "fflas-ffpack/ffpack/ffpack.h" #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/fflas/fflas.h" #include "sys/time.h" //#define BASECASE_K 256 //#include "fflas-ffpack/ffpack/parallel.h" using namespace std; using namespace FFLAS; using namespace FFPACK; #ifndef MODULO #define MODULO 1 #endif #if(MODULO==1) typedef FFPACK::Modular<double> Field; #else typedef FFPACK::UnparametricField<double> Field; #endif #ifndef DEBUG #define DEBUG 1 #endif #ifndef SEQ #define SEQ 1 #endif void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A, size_t * P, size_t * Q, size_t m, size_t n, size_t R) { Field::Element * X = FFLAS::fflas_new<Field::Element>(m*n); Field::Element * L, *U; L = FFLAS::fflas_new<Field::Element>(m*R); U = FFLAS::fflas_new<Field::Element>(R*n); PAR_FOR (size_t i=0; i<m*R; ++i) F.init(L[i], 0.0); PAR_FOR (size_t i=0; i<m*R; ++i) F.init(U[i], 0.0); PAR_FOR (size_t i=0; i<m*n; ++i) F.init(X[i], 0.0); Field::Element zero,one; F.init(zero,0.0); F.init(one,1.0); PAR_FOR (size_t i=0; i<R; ++i){ for (size_t j=0; j<i; ++j) F.assign ( *(U + i*n + j), zero); for (size_t j=i; j<n; ++j) F.assign (*(U + i*n + j), *(A+ i*n+j)); } PAR_FOR ( size_t j=0; j<R; ++j ){ for (size_t i=0; i<=j; ++i ) F.assign( *(L+i*R+j), zero); F.assign(*(L+j*R+j), one); for (size_t i=j+1; i<m; i++) F.assign( *(L + i*R+j), *(A+i*n+j)); } FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P); FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q); FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R, 1.0, L,R, U,n, 0.0, X,n); bool fail = false; PAR_FOR (size_t i=0; i<m; ++i) for (size_t j=0; j<n; ++j) if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){ std::stringstream errs; errs << " B["<<i<<","<<j<<"] = " << (*(B+i*n+j)) << " X["<<i<<","<<j<<"] = " << (*(X+i*n+j)) << std::endl; std::cerr << errs; fail=true; } if (fail) std::cerr<<"FAIL"<<std::endl; else std::cerr<<"PASS"<<std::endl; FFLAS::fflas_delete( U); FFLAS::fflas_delete( L); FFLAS::fflas_delete( X); } int main(int argc, char** argv) { int p, n, m, nbf; if (argc > 6){ std::cerr<<"usage : PLUQ-rec-omp <p> <m> <n> <i> <file>"<<std::endl // std::cerr<<"usage : PLUQ-rec-omp <m> <n> <p> <r> <i>"<<std::endl <<std::endl; exit(-1); } p = (argc>1 ? atoi( argv[1] ) : 1009); m = (argc>2 ? atoi( argv[2] ) : 1024); n = (argc>3 ? atoi( argv[3] ) : 1024); // r = atoi( argv[4] ); nbf = (argc>4 ? atoi( argv[4] ) : 1); // size_t lda = n; // random seed // ifstream f("/dev/urandom"); // size_t seed1, seed2, seed3,seed4; // f.read(reinterpret_cast<char*>(&seed1), sizeof(seed1)); // f.read(reinterpret_cast<char*>(&seed2), sizeof(seed2)); // f.read(reinterpret_cast<char*>(&seed3), sizeof(seed3)); // f.read(reinterpret_cast<char*>(&seed4), sizeof(seed4)); // seed1=10;seed2=12; // seed3=13;seed4=14; enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit; size_t R; const Field F((double)p); // Field::RandIter G(F, seed1); Field::Element alpha, beta; F.init(alpha,1.0); F.init(beta,0.0); // Field::Element * U = FFLAS::fflas_new<Field::Element>(n*n); typename Field::Element* Acop; if (argc > 5) { Acop = read_field(F,argv[5],&m,&n); } else { Field::RandIter G(F); Acop = FFLAS::fflas_new<Field::Element>(m*n); PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) G.random (*(Acop+i*n+j)); } // FFLAS::fflas_new<Field::Element>(n*m); Field::Element* A = FFLAS::fflas_new<Field::Element>(n*m); #if(DEBUG==1) Field::Element* Adebug = FFLAS::fflas_new<Field::Element>(n*m); #endif // std::vector<size_t> Index_P(r); // U = construct_U(F,G, n, r, Index_P, seed4, seed3); // A = construct_L(F,G, m, r, Index_P, seed2); // M_randgen(F, A, U, r, m, n); // size_t taille=m*n; // for(size_t i=0; i<taille;++i) U[i]=A[i]; struct timespec t0, t1;// tt0, tt1; double delay, avrg;//, avrgg; double t_total=0; size_t maxP, maxQ; maxP = m; maxQ = n; size_t *P = FFLAS::fflas_new<size_t>(maxP); size_t *Q = FFLAS::fflas_new<size_t>(maxQ); PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) { *(A+i*n+j) = *(Acop+i*n+j) ; #if(DEBUG==1) *(Adebug+i*n+j) = *(Acop+i*n+j) ; #endif } for ( int i=0;i<nbf+1;i++){ for (size_t j=0;j<maxP;j++) P[j]=0; for (size_t j=0;j<maxQ;j++) Q[j]=0; PAR_FOR(size_t i=0; i<(size_t)m; ++i) for (size_t j=0; j<(size_t)n; ++j) *(A+i*n+j) = *(Acop+i*n+j) ; clock_gettime(CLOCK_REALTIME, &t0); PAR_REGION{ R = pPLUQ(F, diag, m, n, A, n, P, Q);// Parallel PLUQ } clock_gettime(CLOCK_REALTIME, &t1); delay = (double)(t1.tv_sec-t0.tv_sec)+(double)(t1.tv_nsec-t0.tv_nsec)/1000000000; if(i) t_total +=delay; } avrg = t_total/nbf; std::cerr << "MODULO: " << (MODULO?p:0) << std::endl; PAR_REGION{ std::cerr<<"Parallel --- m: "<<m<<" , n: " << n << " , r: " <<R<<" " <<avrg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrg))<<" " //#ifdef __FFLASFFPACK_USE_OPENMP <<NUM_THREADS<<endl; //#else } //<<endl; //#endi // std::cout<<typeid(A).name()<<endl; #if(DEBUG==1) cout<<"check equality A == PLUQ ?"<<endl; verification_PLUQ(F,Adebug,A,P,Q,m,n,R); FFLAS::fflas_delete( Adebug); #endif #if(SEQ==1) struct timespec tt0, tt1; double avrgg; //call sequential PLUQ size_t * PP = FFLAS::fflas_new<size_t>(maxP); size_t * QQ = FFLAS::fflas_new<size_t>(maxQ); for (size_t j=0;j<maxP;j++) PP[j]=0; for (size_t j=0;j<maxQ;j++) QQ[j]=0; clock_gettime(CLOCK_REALTIME, &tt0); size_t R2 = PLUQ(F, diag, m, n, Acop, n, PP, QQ); clock_gettime(CLOCK_REALTIME, &tt1); FFLAS::fflas_delete( Acop); avrgg = (double)(tt1.tv_sec-tt0.tv_sec)+(double)(tt1.tv_nsec-tt0.tv_nsec)/1000000000; //verification std::cerr<<"Sequential : "<<m<<" "<<R2<<" " <<avrgg<<" "<<(2.0*n*n*n)/(double(3.0*(1000000000)*avrgg))<<endl; #endif FFLAS::fflas_delete( A); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL. // // This file is part of the hpp-corbaserver. // // This software is provided "as is" without warranty of any kind, // either expressed or implied, including but not limited to the // implied warranties of fitness for a particular purpose. // // See the COPYING file for more information. #include <errno.h> #include <pthread.h> #include <iostream> #include <kwsPlus/directPath/kwsPlusSteeringMethodFactory.h> #include <kwsPlus/directPath/kwsPlusDistanceFactory.h> #include <kwsPlus/roadmap/kwsPlusDiffusionNodePickerFactory.h> #include <kwsPlus/roadmap/kwsPlusDiffusionShooterFactory.h> #include <hpp/util/debug.hh> #include "hpp/corbaserver/server.hh" #include "server-private.hh" //FIXME: remove me. #define HPPCI_CATCH(msg, ret) \ catch(CORBA::SystemException&) { \ hppDout (error, "hppCorbaChppciServer: CORBA::SystemException: " << msg); \ return ret; \ } \ catch(CORBA::Exception&) { \ hppDout (error, "hppCorbaChppciServer: CORBA::Exception: " << msg); \ return ret; \ } \ catch(omniORB::fatalException& fe) { \ hppDout (error, "hppCorbaChppciServer: CORBA::fatalException: " << msg); \ return ret; \ } \ catch(...) { \ hppDout (error, "hppCorbaChppciServer: unknown exception: " << msg); \ return ret; \ } namespace hpp { namespace corbaChppciServer { using CORBA::Exception; using CORBA::Object_var; using CORBA::SystemException; using CORBA::ORB_init; using CORBA::PolicyList; using omniORB::fatalException; namespace { /// \brief Forward logging messages to hpp logging mechanism. /// If debug is disabled, CORBA logging will be disabled too. /// /// Tracing has to be enabled in your ``omniORB.cfg'' to use this /// feature. /// See ``omniORB configuration and API'' > ``Tracing options'' /// section of omniORB manual for more information. void logFunction (const char* msg); void logFunction (const char* msg) { hppDout (info, "omniORB: " << msg); } } // end of anonymous namespace. ChppciServer::ChppciServer(core::Planner *inHppPlanner, int argc, const char *argv[], bool inMultiThread) : hppPlanner(inHppPlanner) { // Register log function. omniORB::setLogFunction (&logFunction); attPrivate = new impl::ChppciServer; initORBandChppciServers (argc, argv, inMultiThread); initMapSteeringMethodFactory(); initMapDistanceFunctionFactory(); initMapDiffusionNodePickerFactory(); initMapDiffusionShooterFactory(); } /// \brief Shutdown CORBA server ChppciServer::~ChppciServer() { attPrivate->deactivateAndDestroyChppciServers(); attPrivate->orb_->shutdown(0); delete attPrivate; attPrivate = NULL; destroySteeringMethodFactory(); destroyDistanceFunctionFactory(); destroyDiffusionNodePickerFactory(); destroyDiffusionShooterFactory(); } /* STEERING METHOD FACTORIES */ void ChppciServer::initMapSteeringMethodFactory() { attMapSteeringMethodFactory["linear"] = new CkwsPlusLinearSteeringMethodFactory; attMapSteeringMethodFactory["rs"] = new CkwsPlusRSSteeringMethodFactory(1.0); attMapSteeringMethodFactory["flic"] = new CkwsPlusFlicSteeringMethodFactory(); } void ChppciServer::destroySteeringMethodFactory() { std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator start = attMapSteeringMethodFactory.begin(); std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator end = attMapSteeringMethodFactory.end(); for (std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator it=start; it != end; it++) { CkwsPlusSteeringMethodFactory* factory = it->second; hppDout (info, "deleting steering method factory" << it->first); delete factory; } } bool ChppciServer::steeringMethodFactoryAlreadySet(std::string inName) { if (attMapSteeringMethodFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addSteeringMethodFactory(std::string inName, CkwsPlusSteeringMethodFactory* inSteeringMethodFactory) { if(steeringMethodFactoryAlreadySet(inName)) { return false; } attMapSteeringMethodFactory[inName] = inSteeringMethodFactory; return true; } CkwsSteeringMethodShPtr ChppciServer::createSteeringMethod(std::string inName, bool inOriented) { CkwsSteeringMethodShPtr result; if (steeringMethodFactoryAlreadySet(inName)) { result = attMapSteeringMethodFactory[inName]->makeSteeringMethod(inOriented); } return result; } /* DISTANCE FUNCTION FACTORIES */ void ChppciServer::initMapDistanceFunctionFactory() { attMapDistanceFunctionFactory["linear"] = new CkwsPlusLinearDistanceFactory; attMapDistanceFunctionFactory["rs"] = new CkwsPlusRSDistanceFactory(1.0); attMapDistanceFunctionFactory["flic"] = new CkwsPlusApproxFlicDistanceFactory; } void ChppciServer::destroyDistanceFunctionFactory() { std::map<std::string, CkwsPlusDistanceFactory*>::iterator start = attMapDistanceFunctionFactory.begin(); std::map<std::string, CkwsPlusDistanceFactory*>::iterator end = attMapDistanceFunctionFactory.end(); for (std::map<std::string, CkwsPlusDistanceFactory*>::iterator it=start; it != end; it++) { CkwsPlusDistanceFactory* factory = it->second; hppDout (info, " deleting distance function factory" << it->first); delete factory; } } bool ChppciServer::distanceFactoryAlreadySet(std::string inName) { if (attMapDistanceFunctionFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDistanceFactory(std::string inName, CkwsPlusDistanceFactory* inDistanceFunctionFactory) { if(distanceFactoryAlreadySet(inName)) { return false; } attMapDistanceFunctionFactory[inName] = inDistanceFunctionFactory; return true; } CkwsDistanceShPtr ChppciServer::createDistanceFunction(std::string inName, bool inOriented) { CkwsDistanceShPtr result; if (distanceFactoryAlreadySet(inName)) { result = attMapDistanceFunctionFactory[inName]->makeDistance(inOriented); } return result; } /* DIFFUSION NODE PICKER FACTORIES */ void ChppciServer::initMapDiffusionNodePickerFactory() { attMapDiffusionNodePickerFactory["basic"] = new CkwsPlusBasicDiffusionNodePickerFactory; attMapDiffusionNodePickerFactory["smallestTree"] = new CkwsPlusSmallestTreeDiffusionNodePickerFactory; } void ChppciServer::destroyDiffusionNodePickerFactory() { std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator start = attMapDiffusionNodePickerFactory.begin(); std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator end = attMapDiffusionNodePickerFactory.end(); for (std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator it=start; it != end; it++) { CkwsPlusDiffusionNodePickerFactory* factory = it->second; hppDout (info, " deleting diffusion node picker factory" << it->first); delete factory; } } bool ChppciServer::diffusionNodePickerFactoryAlreadySet(std::string inName) { if (attMapDiffusionNodePickerFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDiffusionNodePickerFactory(std::string inName, CkwsPlusDiffusionNodePickerFactory* inDiffusionNodePickerFactory) { if(diffusionNodePickerFactoryAlreadySet(inName)) { return false; } attMapDiffusionNodePickerFactory[inName] = inDiffusionNodePickerFactory; return true; } CkwsDiffusionNodePickerShPtr ChppciServer::createDiffusionNodePicker(std::string inName) { CkwsDiffusionNodePickerShPtr result; if (diffusionNodePickerFactoryAlreadySet(inName)) { result = attMapDiffusionNodePickerFactory[inName]->makeDiffusionNodePicker(); } return result; } /* DIFFUSION SHOOTER FACTORIES */ void ChppciServer::initMapDiffusionShooterFactory() { attMapDiffusionShooterFactory["config space"] = new CkwsPlusShooterConfigSpaceFactory; attMapDiffusionShooterFactory["roadmap box"] = new CkwsPlusShooterRoadmapBoxFactory; attMapDiffusionShooterFactory["roadmap node"] = new CkwsPlusShooterRoadmapNodesFactory; } void ChppciServer::destroyDiffusionShooterFactory() { std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator start = attMapDiffusionShooterFactory.begin(); std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator end = attMapDiffusionShooterFactory.end(); for (std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator it=start; it != end; it++) { CkwsPlusDiffusionShooterFactory* factory = it->second; hppDout (info, " deleting diffusion shooter factory" << it->first); delete factory; } } bool ChppciServer::diffusionShooterFactoryAlreadySet(std::string inName) { if (attMapDiffusionShooterFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDiffusionShooterFactory(std::string inName, CkwsPlusDiffusionShooterFactory* inDiffusionShooterFactory) { if(diffusionShooterFactoryAlreadySet(inName)) { return false; } attMapDiffusionShooterFactory[inName] = inDiffusionShooterFactory; return true; } CkwsDiffusionShooterShPtr ChppciServer::createDiffusionShooter(std::string inName, double inStandardDeviation) { CkwsDiffusionShooterShPtr result; if (diffusionShooterFactoryAlreadySet(inName)) { result = attMapDiffusionShooterFactory[inName]->makeDiffusionShooter(inStandardDeviation); } return result; } /* CORBA SERVER INITIALIZATION */ ktStatus ChppciServer::initORBandChppciServers(int argc, const char* argv[], bool inMultiThread) { Object_var obj; PortableChppciServer::ThreadPolicy_var threadPolicy; PortableChppciServer::POA_var rootPoa; /* Fine granularity in exception handling */ /* ORB init */ try { attPrivate->orb_ = ORB_init (argc, const_cast<char **> (argv)); //FIXME: handle this properly. if (is_nil(attPrivate->orb_)) { hppDout (error, "failed to initialize ORB"); return KD_ERROR; } } HPPCI_CATCH("failed to initialize ORB", KD_ERROR) /* ORB init */ try { obj = attPrivate->orb_->resolve_initial_references("RootPOA"); } HPPCI_CATCH("failed to resolve initial references", KD_ERROR) /* Create thread policy */ try { // // Make the CORBA object single-threaded to avoid GUI krash // // Create a sigle threaded policy object rootPoa = PortableChppciServer::POA::_narrow(obj); if (inMultiThread) { threadPolicy = rootPoa->create_thread_policy(PortableChppciServer::ORB_CTRL_MODEL); } else { threadPolicy = rootPoa->create_thread_policy(PortableChppciServer::MAIN_THREAD_MODEL); } } HPPCI_CATCH("failed to create thread policy", KD_ERROR) /* Duplicate thread policy */ try { PolicyList policyList; policyList.length(1); policyList[0] = PortableChppciServer::ThreadPolicy::_duplicate(threadPolicy); attPrivate->poa_ = rootPoa->create_POA("child", PortableChppciServer::POAManager::_nil(), policyList); } HPPCI_CATCH("failed to duplicate thread policy", KD_ERROR) /* Destroy thread policy */ try { // Destroy policy object threadPolicy->destroy(); } HPPCI_CATCH("failed to destroy thread policy", KD_ERROR); return attPrivate->createAndActivateChppciServers(this); } int ChppciServer::startCorbaChppciServer() { try { // Obtain a reference to objects, and register them in // the naming service. Object_var robotObj = attPrivate->robotServant_->_this(); Object_var obstacleObj = attPrivate->obstacleServant_->_this(); Object_var problemObj = attPrivate->problemServant_->_this(); if (!attPrivate->createHppContext()) { return KD_ERROR; } // Bind robotObj with name Robot to the hppContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "robots"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(robotObj, objectName)) { return KD_ERROR; } attPrivate->robotServant_->_remove_ref(); // Bind obstacleObj with name Obstacle to the hppContext: objectName.length(1); objectName[0].id = (const char*) "obstacles"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(obstacleObj, objectName)) { return KD_ERROR; } attPrivate->obstacleServant_->_remove_ref(); // Bind problemObj with name Problem to the hppContext: objectName.length(1); objectName[0].id = (const char*) "problems"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(problemObj, objectName)) { return KD_ERROR; } attPrivate->problemServant_->_remove_ref(); PortableChppciServer::POAManager_var pman = attPrivate->poa_->the_POAManager(); pman->activate(); } HPPCI_CATCH("failed to start CORBA server", KD_ERROR); return KD_OK; } const core::Planner* ChppciServer::planner() const { return hppPlanner; } core::Planner* ChppciServer::planner() { return hppPlanner; } /// \brief If CORBA requests are pending, process them int ChppciServer::processRequest (bool loop) { if (loop) { hppDout (info, "start processing CORBA requests for ever."); attPrivate->orb_->run(); } else { if (attPrivate->orb_->work_pending()) attPrivate->orb_->perform_work(); } return 0; } } // end of namespace corbaChppciServer. } // end of namespace hpp. <commit_msg>Remove flic steering method to comply with kwsPlus.<commit_after>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL. // // This file is part of the hpp-corbaserver. // // This software is provided "as is" without warranty of any kind, // either expressed or implied, including but not limited to the // implied warranties of fitness for a particular purpose. // // See the COPYING file for more information. #include <errno.h> #include <pthread.h> #include <iostream> #include <kwsPlus/directPath/kwsPlusSteeringMethodFactory.h> #include <kwsPlus/directPath/kwsPlusDistanceFactory.h> #include <kwsPlus/roadmap/kwsPlusDiffusionNodePickerFactory.h> #include <kwsPlus/roadmap/kwsPlusDiffusionShooterFactory.h> #include <hpp/util/debug.hh> #include "hpp/corbaserver/server.hh" #include "server-private.hh" //FIXME: remove me. #define HPPCI_CATCH(msg, ret) \ catch(CORBA::SystemException&) { \ hppDout (error, "hppCorbaChppciServer: CORBA::SystemException: " << msg); \ return ret; \ } \ catch(CORBA::Exception&) { \ hppDout (error, "hppCorbaChppciServer: CORBA::Exception: " << msg); \ return ret; \ } \ catch(omniORB::fatalException& fe) { \ hppDout (error, "hppCorbaChppciServer: CORBA::fatalException: " << msg); \ return ret; \ } \ catch(...) { \ hppDout (error, "hppCorbaChppciServer: unknown exception: " << msg); \ return ret; \ } namespace hpp { namespace corbaChppciServer { using CORBA::Exception; using CORBA::Object_var; using CORBA::SystemException; using CORBA::ORB_init; using CORBA::PolicyList; using omniORB::fatalException; namespace { /// \brief Forward logging messages to hpp logging mechanism. /// If debug is disabled, CORBA logging will be disabled too. /// /// Tracing has to be enabled in your ``omniORB.cfg'' to use this /// feature. /// See ``omniORB configuration and API'' > ``Tracing options'' /// section of omniORB manual for more information. void logFunction (const char* msg); void logFunction (const char* msg) { hppDout (info, "omniORB: " << msg); } } // end of anonymous namespace. ChppciServer::ChppciServer(core::Planner *inHppPlanner, int argc, const char *argv[], bool inMultiThread) : hppPlanner(inHppPlanner) { // Register log function. omniORB::setLogFunction (&logFunction); attPrivate = new impl::ChppciServer; initORBandChppciServers (argc, argv, inMultiThread); initMapSteeringMethodFactory(); initMapDistanceFunctionFactory(); initMapDiffusionNodePickerFactory(); initMapDiffusionShooterFactory(); } /// \brief Shutdown CORBA server ChppciServer::~ChppciServer() { attPrivate->deactivateAndDestroyChppciServers(); attPrivate->orb_->shutdown(0); delete attPrivate; attPrivate = NULL; destroySteeringMethodFactory(); destroyDistanceFunctionFactory(); destroyDiffusionNodePickerFactory(); destroyDiffusionShooterFactory(); } /* STEERING METHOD FACTORIES */ void ChppciServer::initMapSteeringMethodFactory() { attMapSteeringMethodFactory["linear"] = new CkwsPlusLinearSteeringMethodFactory; attMapSteeringMethodFactory["rs"] = new CkwsPlusRSSteeringMethodFactory(1.0); } void ChppciServer::destroySteeringMethodFactory() { std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator start = attMapSteeringMethodFactory.begin(); std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator end = attMapSteeringMethodFactory.end(); for (std::map<std::string, CkwsPlusSteeringMethodFactory*>::iterator it=start; it != end; it++) { CkwsPlusSteeringMethodFactory* factory = it->second; hppDout (info, "deleting steering method factory" << it->first); delete factory; } } bool ChppciServer::steeringMethodFactoryAlreadySet(std::string inName) { if (attMapSteeringMethodFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addSteeringMethodFactory(std::string inName, CkwsPlusSteeringMethodFactory* inSteeringMethodFactory) { if(steeringMethodFactoryAlreadySet(inName)) { return false; } attMapSteeringMethodFactory[inName] = inSteeringMethodFactory; return true; } CkwsSteeringMethodShPtr ChppciServer::createSteeringMethod(std::string inName, bool inOriented) { CkwsSteeringMethodShPtr result; if (steeringMethodFactoryAlreadySet(inName)) { result = attMapSteeringMethodFactory[inName]->makeSteeringMethod(inOriented); } return result; } /* DISTANCE FUNCTION FACTORIES */ void ChppciServer::initMapDistanceFunctionFactory() { attMapDistanceFunctionFactory["linear"] = new CkwsPlusLinearDistanceFactory; attMapDistanceFunctionFactory["rs"] = new CkwsPlusRSDistanceFactory(1.0); } void ChppciServer::destroyDistanceFunctionFactory() { std::map<std::string, CkwsPlusDistanceFactory*>::iterator start = attMapDistanceFunctionFactory.begin(); std::map<std::string, CkwsPlusDistanceFactory*>::iterator end = attMapDistanceFunctionFactory.end(); for (std::map<std::string, CkwsPlusDistanceFactory*>::iterator it=start; it != end; it++) { CkwsPlusDistanceFactory* factory = it->second; hppDout (info, " deleting distance function factory" << it->first); delete factory; } } bool ChppciServer::distanceFactoryAlreadySet(std::string inName) { if (attMapDistanceFunctionFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDistanceFactory(std::string inName, CkwsPlusDistanceFactory* inDistanceFunctionFactory) { if(distanceFactoryAlreadySet(inName)) { return false; } attMapDistanceFunctionFactory[inName] = inDistanceFunctionFactory; return true; } CkwsDistanceShPtr ChppciServer::createDistanceFunction(std::string inName, bool inOriented) { CkwsDistanceShPtr result; if (distanceFactoryAlreadySet(inName)) { result = attMapDistanceFunctionFactory[inName]->makeDistance(inOriented); } return result; } /* DIFFUSION NODE PICKER FACTORIES */ void ChppciServer::initMapDiffusionNodePickerFactory() { attMapDiffusionNodePickerFactory["basic"] = new CkwsPlusBasicDiffusionNodePickerFactory; attMapDiffusionNodePickerFactory["smallestTree"] = new CkwsPlusSmallestTreeDiffusionNodePickerFactory; } void ChppciServer::destroyDiffusionNodePickerFactory() { std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator start = attMapDiffusionNodePickerFactory.begin(); std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator end = attMapDiffusionNodePickerFactory.end(); for (std::map<std::string, CkwsPlusDiffusionNodePickerFactory*>::iterator it=start; it != end; it++) { CkwsPlusDiffusionNodePickerFactory* factory = it->second; hppDout (info, " deleting diffusion node picker factory" << it->first); delete factory; } } bool ChppciServer::diffusionNodePickerFactoryAlreadySet(std::string inName) { if (attMapDiffusionNodePickerFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDiffusionNodePickerFactory(std::string inName, CkwsPlusDiffusionNodePickerFactory* inDiffusionNodePickerFactory) { if(diffusionNodePickerFactoryAlreadySet(inName)) { return false; } attMapDiffusionNodePickerFactory[inName] = inDiffusionNodePickerFactory; return true; } CkwsDiffusionNodePickerShPtr ChppciServer::createDiffusionNodePicker(std::string inName) { CkwsDiffusionNodePickerShPtr result; if (diffusionNodePickerFactoryAlreadySet(inName)) { result = attMapDiffusionNodePickerFactory[inName]->makeDiffusionNodePicker(); } return result; } /* DIFFUSION SHOOTER FACTORIES */ void ChppciServer::initMapDiffusionShooterFactory() { attMapDiffusionShooterFactory["config space"] = new CkwsPlusShooterConfigSpaceFactory; attMapDiffusionShooterFactory["roadmap box"] = new CkwsPlusShooterRoadmapBoxFactory; attMapDiffusionShooterFactory["roadmap node"] = new CkwsPlusShooterRoadmapNodesFactory; } void ChppciServer::destroyDiffusionShooterFactory() { std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator start = attMapDiffusionShooterFactory.begin(); std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator end = attMapDiffusionShooterFactory.end(); for (std::map<std::string, CkwsPlusDiffusionShooterFactory*>::iterator it=start; it != end; it++) { CkwsPlusDiffusionShooterFactory* factory = it->second; hppDout (info, " deleting diffusion shooter factory" << it->first); delete factory; } } bool ChppciServer::diffusionShooterFactoryAlreadySet(std::string inName) { if (attMapDiffusionShooterFactory.count(inName) == 1) { return true; } return false; } bool ChppciServer::addDiffusionShooterFactory(std::string inName, CkwsPlusDiffusionShooterFactory* inDiffusionShooterFactory) { if(diffusionShooterFactoryAlreadySet(inName)) { return false; } attMapDiffusionShooterFactory[inName] = inDiffusionShooterFactory; return true; } CkwsDiffusionShooterShPtr ChppciServer::createDiffusionShooter(std::string inName, double inStandardDeviation) { CkwsDiffusionShooterShPtr result; if (diffusionShooterFactoryAlreadySet(inName)) { result = attMapDiffusionShooterFactory[inName]->makeDiffusionShooter(inStandardDeviation); } return result; } /* CORBA SERVER INITIALIZATION */ ktStatus ChppciServer::initORBandChppciServers(int argc, const char* argv[], bool inMultiThread) { Object_var obj; PortableChppciServer::ThreadPolicy_var threadPolicy; PortableChppciServer::POA_var rootPoa; /* Fine granularity in exception handling */ /* ORB init */ try { attPrivate->orb_ = ORB_init (argc, const_cast<char **> (argv)); //FIXME: handle this properly. if (is_nil(attPrivate->orb_)) { hppDout (error, "failed to initialize ORB"); return KD_ERROR; } } HPPCI_CATCH("failed to initialize ORB", KD_ERROR) /* ORB init */ try { obj = attPrivate->orb_->resolve_initial_references("RootPOA"); } HPPCI_CATCH("failed to resolve initial references", KD_ERROR) /* Create thread policy */ try { // // Make the CORBA object single-threaded to avoid GUI krash // // Create a sigle threaded policy object rootPoa = PortableChppciServer::POA::_narrow(obj); if (inMultiThread) { threadPolicy = rootPoa->create_thread_policy(PortableChppciServer::ORB_CTRL_MODEL); } else { threadPolicy = rootPoa->create_thread_policy(PortableChppciServer::MAIN_THREAD_MODEL); } } HPPCI_CATCH("failed to create thread policy", KD_ERROR) /* Duplicate thread policy */ try { PolicyList policyList; policyList.length(1); policyList[0] = PortableChppciServer::ThreadPolicy::_duplicate(threadPolicy); attPrivate->poa_ = rootPoa->create_POA("child", PortableChppciServer::POAManager::_nil(), policyList); } HPPCI_CATCH("failed to duplicate thread policy", KD_ERROR) /* Destroy thread policy */ try { // Destroy policy object threadPolicy->destroy(); } HPPCI_CATCH("failed to destroy thread policy", KD_ERROR); return attPrivate->createAndActivateChppciServers(this); } int ChppciServer::startCorbaChppciServer() { try { // Obtain a reference to objects, and register them in // the naming service. Object_var robotObj = attPrivate->robotServant_->_this(); Object_var obstacleObj = attPrivate->obstacleServant_->_this(); Object_var problemObj = attPrivate->problemServant_->_this(); if (!attPrivate->createHppContext()) { return KD_ERROR; } // Bind robotObj with name Robot to the hppContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "robots"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(robotObj, objectName)) { return KD_ERROR; } attPrivate->robotServant_->_remove_ref(); // Bind obstacleObj with name Obstacle to the hppContext: objectName.length(1); objectName[0].id = (const char*) "obstacles"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(obstacleObj, objectName)) { return KD_ERROR; } attPrivate->obstacleServant_->_remove_ref(); // Bind problemObj with name Problem to the hppContext: objectName.length(1); objectName[0].id = (const char*) "problems"; // string copied objectName[0].kind = (const char*) "servant"; // string copied if(!attPrivate->bindObjectToName(problemObj, objectName)) { return KD_ERROR; } attPrivate->problemServant_->_remove_ref(); PortableChppciServer::POAManager_var pman = attPrivate->poa_->the_POAManager(); pman->activate(); } HPPCI_CATCH("failed to start CORBA server", KD_ERROR); return KD_OK; } const core::Planner* ChppciServer::planner() const { return hppPlanner; } core::Planner* ChppciServer::planner() { return hppPlanner; } /// \brief If CORBA requests are pending, process them int ChppciServer::processRequest (bool loop) { if (loop) { hppDout (info, "start processing CORBA requests for ever."); attPrivate->orb_->run(); } else { if (attPrivate->orb_->work_pending()) attPrivate->orb_->perform_work(); } return 0; } } // end of namespace corbaChppciServer. } // end of namespace hpp. <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <ten/json.hh> #include <array> #include "ten/logging.hh" #include "ten/jsonstream.hh" #include <map> using namespace std; using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; TEST(Json, Path1) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1{o.path("/store/book/author")}; EXPECT_EQ(json::load(a1), r1); json r2{o.path("//author")}; EXPECT_EQ(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3{o.path("/store/*")}; json t3{json::load(a3)}; EXPECT_EQ(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4{o.path("/store//price")}; EXPECT_EQ(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5{o.path("//book[3]")}; EXPECT_EQ(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6{o.path("/store/book[3]/author")}; EXPECT_EQ(json::load(a6), r6); EXPECT_TRUE(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7{o.path("/store/book[category=\"fiction\"]")}; EXPECT_EQ(json::load(a7), r7); } TEST(Json, Path2) { json o{json::load("[{\"type\": 0}, {\"type\": 1}]")}; EXPECT_EQ(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } TEST(Json, FilterKeyExists) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r{o.path("//book[isbn]")}; EXPECT_EQ(json::load(a), r); json r1{o.path("//book[doesnotexist]")}; ASSERT_TRUE(r1.is_array()); EXPECT_EQ(0, r1.asize()); } TEST(Json, Truth) { json o{{}}; // empty init list EXPECT_TRUE(o.get("nothing").is_true() == false); EXPECT_TRUE(o.get("nothing").is_false() == false); EXPECT_TRUE(o.get("nothing").is_null() == false); EXPECT_TRUE(!o.get("nothing")); } TEST(Json, Path3) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); EXPECT_EQ(o, o.path("/")); EXPECT_EQ("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; EXPECT_EQ(json(1), json::load(text).path("/[type=\"b\"]/value")); } TEST(Json, InitList) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; ASSERT_TRUE(meta); ASSERT_TRUE(meta.is_object()); EXPECT_EQ(meta.osize(), 5); EXPECT_EQ(meta["foo"].integer(), 17); EXPECT_EQ(meta["corge"][0].integer(), 1); EXPECT_EQ(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); EXPECT_EQ((json_type)j2.type(), t); EXPECT_EQ(j, j2); T val2 = json_cast<T>(j2); EXPECT_EQ(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } TEST(Json, Conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); EXPECT_EQ(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } TEST(Json, Create) { json obj1{{}}; EXPECT_TRUE(obj1); obj1.set("test", "set"); EXPECT_TRUE(obj1.get("test")); json root{ {"obj1", obj1} }; EXPECT_EQ(root.get("obj1"), obj1); obj1.set("this", "that"); EXPECT_EQ(root.get("obj1").get("this").str(), "that"); json obj2{ {"answer", 42} }; obj1.set("obj2", obj2); EXPECT_EQ(root.get("obj1").get("obj2"), obj2); } TEST(Json, Stream) { // TODO: improve these tests or don't. this is a hack anyway using namespace jsonstream_manip; std::stringstream ss; jsonstream s(ss); int8_t c = 'C'; // printable float fval = -1.28; double dval = -1.28; s << jsobject << "key1" << 1234 << "key2" << "value" << "list" << jsarray << "1" << 2.0f << 3.14e-20 << 4 << 5 << jsend << "list2" << jsarray << jsobject << jsend << jsend << "max_dbl" << std::numeric_limits<double>::max() << "inf" << std::numeric_limits<float>::infinity() << "nan" << (1.0 / 0.0) << "vec" << std::vector<int>({0, 1, 2, 3}) << "char" << c << "bool" << false << jsescape << "escape" << "\n\t\"" << "noescape" << "blahblah" << "raw" << jsraw << "[]" << jsnoraw << "lahalha" << 666 << "fval" << fval << "dval" << dval //<< "map" << std::map<const char *, int>({{"key", 1}}) << jsend; VLOG(1) << ss.str(); auto js = json::load(ss.str()); EXPECT_TRUE((bool)js); EXPECT_EQ(js.get("fval"), js.get("dval")); } <commit_msg>fix json test to handle explicit bool<commit_after>#include "gtest/gtest.h" #include <ten/json.hh> #include <array> #include "ten/logging.hh" #include "ten/jsonstream.hh" #include <map> using namespace std; using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; TEST(Json, Path1) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1{o.path("/store/book/author")}; EXPECT_EQ(json::load(a1), r1); json r2{o.path("//author")}; EXPECT_EQ(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3{o.path("/store/*")}; json t3{json::load(a3)}; EXPECT_EQ(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4{o.path("/store//price")}; EXPECT_EQ(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5{o.path("//book[3]")}; EXPECT_EQ(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6{o.path("/store/book[3]/author")}; EXPECT_EQ(json::load(a6), r6); EXPECT_TRUE(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7{o.path("/store/book[category=\"fiction\"]")}; EXPECT_EQ(json::load(a7), r7); } TEST(Json, Path2) { json o{json::load("[{\"type\": 0}, {\"type\": 1}]")}; EXPECT_EQ(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } TEST(Json, FilterKeyExists) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r{o.path("//book[isbn]")}; EXPECT_EQ(json::load(a), r); json r1{o.path("//book[doesnotexist]")}; ASSERT_TRUE(r1.is_array()); EXPECT_EQ(0, r1.asize()); } TEST(Json, Truth) { json o{{}}; // empty init list EXPECT_TRUE(o.get("nothing").is_true() == false); EXPECT_TRUE(o.get("nothing").is_false() == false); EXPECT_TRUE(o.get("nothing").is_null() == false); EXPECT_TRUE(!o.get("nothing")); } TEST(Json, Path3) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); EXPECT_EQ(o, o.path("/")); EXPECT_EQ("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; EXPECT_EQ(json(1), json::load(text).path("/[type=\"b\"]/value")); } TEST(Json, InitList) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; ASSERT_TRUE((bool)meta); ASSERT_TRUE(meta.is_object()); EXPECT_EQ(meta.osize(), 5); EXPECT_EQ(meta["foo"].integer(), 17); EXPECT_EQ(meta["corge"][0].integer(), 1); EXPECT_EQ(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); EXPECT_EQ((json_type)j2.type(), t); EXPECT_EQ(j, j2); T val2 = json_cast<T>(j2); EXPECT_EQ(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } TEST(Json, Conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); EXPECT_EQ(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } TEST(Json, Create) { json obj1{{}}; EXPECT_TRUE((bool)obj1); obj1.set("test", "set"); EXPECT_TRUE((bool)obj1.get("test")); json root{ {"obj1", obj1} }; EXPECT_EQ(root.get("obj1"), obj1); obj1.set("this", "that"); EXPECT_EQ(root.get("obj1").get("this").str(), "that"); json obj2{ {"answer", 42} }; obj1.set("obj2", obj2); EXPECT_EQ(root.get("obj1").get("obj2"), obj2); } TEST(Json, Stream) { // TODO: improve these tests or don't. this is a hack anyway using namespace jsonstream_manip; std::stringstream ss; jsonstream s(ss); int8_t c = 'C'; // printable float fval = -1.28; double dval = -1.28; s << jsobject << "key1" << 1234 << "key2" << "value" << "list" << jsarray << "1" << 2.0f << 3.14e-20 << 4 << 5 << jsend << "list2" << jsarray << jsobject << jsend << jsend << "max_dbl" << std::numeric_limits<double>::max() << "inf" << std::numeric_limits<float>::infinity() << "nan" << (1.0 / 0.0) << "vec" << std::vector<int>({0, 1, 2, 3}) << "char" << c << "bool" << false << jsescape << "escape" << "\n\t\"" << "noescape" << "blahblah" << "raw" << jsraw << "[]" << jsnoraw << "lahalha" << 666 << "fval" << fval << "dval" << dval //<< "map" << std::map<const char *, int>({{"key", 1}}) << jsend; VLOG(1) << ss.str(); auto js = json::load(ss.str()); EXPECT_TRUE((bool)js); EXPECT_EQ(js.get("fval"), js.get("dval")); } <|endoftext|>
<commit_before>#include <string> #include <stdio.h> #include <id3v2tag.h> #include <infotag.h> #include <tbytevectorlist.h> #include <tpropertymap.h> #include <wavfile.h> #include <cppunit/extensions/HelperMacros.h> #include "utils.h" using namespace std; using namespace TagLib; class TestWAV : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestWAV); CPPUNIT_TEST(testPCMProperties); CPPUNIT_TEST(testALAWProperties); CPPUNIT_TEST(testFloatProperties); CPPUNIT_TEST(testZeroSizeDataChunk); CPPUNIT_TEST(testID3v2Tag); CPPUNIT_TEST(testInfoTag); CPPUNIT_TEST(testStripTags); CPPUNIT_TEST(testDuplicateTags); CPPUNIT_TEST(testFuzzedFile1); CPPUNIT_TEST(testFuzzedFile2); CPPUNIT_TEST(testStripAndProperties); CPPUNIT_TEST_SUITE_END(); public: void testPCMProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("empty.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(3675, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(32, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(1000, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(3675U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->format()); } void testALAWProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("alaw.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(3550, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(128, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(8000, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(8, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(8, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(28400U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(6, f.audioProperties()->format()); } void testFloatProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("float64.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(97, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(5645, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(64, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(64, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(4281U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->format()); } void testZeroSizeDataChunk() { RIFF::WAV::File f(TEST_FILE_PATH_C("zero-size-chunk.wav")); CPPUNIT_ASSERT(!f.isValid()); } void testID3v2Tag() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); f.ID3v2Tag()->setTitle(L"Title"); f.ID3v2Tag()->setArtist(L"Artist"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT_EQUAL(String(L"Title"), f.ID3v2Tag()->title()); CPPUNIT_ASSERT_EQUAL(String(L"Artist"), f.ID3v2Tag()->artist()); f.ID3v2Tag()->setTitle(L""); f.ID3v2Tag()->setArtist(L""); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT_EQUAL(String(L""), f.ID3v2Tag()->title()); CPPUNIT_ASSERT_EQUAL(String(L""), f.ID3v2Tag()->artist()); } } void testInfoTag() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); f.InfoTag()->setTitle(L"Title"); f.InfoTag()->setArtist(L"Artist"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT_EQUAL(String(L"Title"), f.InfoTag()->title()); CPPUNIT_ASSERT_EQUAL(String(L"Artist"), f.InfoTag()->artist()); f.InfoTag()->setTitle(L""); f.InfoTag()->setArtist(L""); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT_EQUAL(String(L""), f.InfoTag()->title()); CPPUNIT_ASSERT_EQUAL(String(L""), f.InfoTag()->artist()); } } void testStripTags() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); f.ID3v2Tag()->setTitle("test title"); f.InfoTag()->setTitle("test title"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); f.save(RIFF::WAV::File::ID3v2, true); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(!f.hasInfoTag()); f.ID3v2Tag()->setTitle("test title"); f.InfoTag()->setTitle("test title"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); f.save(RIFF::WAV::File::Info, true); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); } } void testDuplicateTags() { ScopedFileCopy copy("duplicate_tags", ".wav"); RIFF::WAV::File f(copy.fileName().c_str()); CPPUNIT_ASSERT_EQUAL(17052L, f.length()); // duplicate_tags.wav has duplicate ID3v2/INFO tags. // title() returns "Title2" if can't skip the second tag. CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String("Title1"), f.ID3v2Tag()->title()); CPPUNIT_ASSERT(f.hasInfoTag()); CPPUNIT_ASSERT_EQUAL(String("Title1"), f.InfoTag()->title()); f.save(); CPPUNIT_ASSERT_EQUAL(15898L, f.length()); CPPUNIT_ASSERT_EQUAL(-1L, f.find("Title2")); } void testFuzzedFile1() { RIFF::WAV::File f1(TEST_FILE_PATH_C("infloop.wav")); CPPUNIT_ASSERT(!f1.isValid()); } void testFuzzedFile2() { RIFF::WAV::File f2(TEST_FILE_PATH_C("segfault.wav")); CPPUNIT_ASSERT(f2.isValid()); } void testStripAndProperties() { ScopedFileCopy copy("empty", ".wav"); { RIFF::WAV::File f(copy.fileName().c_str()); f.ID3v2Tag()->setTitle("ID3v2"); f.InfoTag()->setTitle("INFO"); f.save(); } { RIFF::WAV::File f(copy.fileName().c_str()); CPPUNIT_ASSERT_EQUAL(String("ID3v2"), f.properties()["TITLE"].front()); f.strip(RIFF::WAV::File::ID3v2); CPPUNIT_ASSERT_EQUAL(String("INFO"), f.properties()["TITLE"].front()); f.strip(RIFF::WAV::File::Info); CPPUNIT_ASSERT(f.properties().isEmpty()); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestWAV); <commit_msg>Add some tests to check if the internal flags are updated when writing WAV files.<commit_after>#include <string> #include <stdio.h> #include <id3v2tag.h> #include <infotag.h> #include <tbytevectorlist.h> #include <tpropertymap.h> #include <wavfile.h> #include <cppunit/extensions/HelperMacros.h> #include "utils.h" using namespace std; using namespace TagLib; class TestWAV : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestWAV); CPPUNIT_TEST(testPCMProperties); CPPUNIT_TEST(testALAWProperties); CPPUNIT_TEST(testFloatProperties); CPPUNIT_TEST(testZeroSizeDataChunk); CPPUNIT_TEST(testID3v2Tag); CPPUNIT_TEST(testInfoTag); CPPUNIT_TEST(testStripTags); CPPUNIT_TEST(testDuplicateTags); CPPUNIT_TEST(testFuzzedFile1); CPPUNIT_TEST(testFuzzedFile2); CPPUNIT_TEST(testStripAndProperties); CPPUNIT_TEST_SUITE_END(); public: void testPCMProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("empty.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(3675, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(32, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(1000, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(3675U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->format()); } void testALAWProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("alaw.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(3550, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(128, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(8000, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(8, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(8, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(28400U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(6, f.audioProperties()->format()); } void testFloatProperties() { RIFF::WAV::File f(TEST_FILE_PATH_C("float64.wav")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->length()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(97, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(5645, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(2, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(64, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(64, f.audioProperties()->sampleWidth()); CPPUNIT_ASSERT_EQUAL(4281U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(3, f.audioProperties()->format()); } void testZeroSizeDataChunk() { RIFF::WAV::File f(TEST_FILE_PATH_C("zero-size-chunk.wav")); CPPUNIT_ASSERT(!f.isValid()); } void testID3v2Tag() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); f.ID3v2Tag()->setTitle(L"Title"); f.ID3v2Tag()->setArtist(L"Artist"); f.save(); CPPUNIT_ASSERT(f.hasID3v2Tag()); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String(L"Title"), f.ID3v2Tag()->title()); CPPUNIT_ASSERT_EQUAL(String(L"Artist"), f.ID3v2Tag()->artist()); f.ID3v2Tag()->setTitle(L""); f.ID3v2Tag()->setArtist(L""); f.save(); CPPUNIT_ASSERT(!f.hasID3v2Tag()); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String(L""), f.ID3v2Tag()->title()); CPPUNIT_ASSERT_EQUAL(String(L""), f.ID3v2Tag()->artist()); } } void testInfoTag() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(!f.hasInfoTag()); f.InfoTag()->setTitle(L"Title"); f.InfoTag()->setArtist(L"Artist"); f.save(); CPPUNIT_ASSERT(f.hasInfoTag()); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(f.hasInfoTag()); CPPUNIT_ASSERT_EQUAL(String(L"Title"), f.InfoTag()->title()); CPPUNIT_ASSERT_EQUAL(String(L"Artist"), f.InfoTag()->artist()); f.InfoTag()->setTitle(L""); f.InfoTag()->setArtist(L""); f.save(); CPPUNIT_ASSERT(!f.hasInfoTag()); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.isValid()); CPPUNIT_ASSERT(!f.hasInfoTag()); CPPUNIT_ASSERT_EQUAL(String(L""), f.InfoTag()->title()); CPPUNIT_ASSERT_EQUAL(String(L""), f.InfoTag()->artist()); } } void testStripTags() { ScopedFileCopy copy("empty", ".wav"); string filename = copy.fileName(); { RIFF::WAV::File f(filename.c_str()); f.ID3v2Tag()->setTitle("test title"); f.InfoTag()->setTitle("test title"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); f.save(RIFF::WAV::File::ID3v2, true); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(!f.hasInfoTag()); f.ID3v2Tag()->setTitle("test title"); f.InfoTag()->setTitle("test title"); f.save(); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); f.save(RIFF::WAV::File::Info, true); } { RIFF::WAV::File f(filename.c_str()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); CPPUNIT_ASSERT(f.hasInfoTag()); } } void testDuplicateTags() { ScopedFileCopy copy("duplicate_tags", ".wav"); RIFF::WAV::File f(copy.fileName().c_str()); CPPUNIT_ASSERT_EQUAL(17052L, f.length()); // duplicate_tags.wav has duplicate ID3v2/INFO tags. // title() returns "Title2" if can't skip the second tag. CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String("Title1"), f.ID3v2Tag()->title()); CPPUNIT_ASSERT(f.hasInfoTag()); CPPUNIT_ASSERT_EQUAL(String("Title1"), f.InfoTag()->title()); f.save(); CPPUNIT_ASSERT_EQUAL(15898L, f.length()); CPPUNIT_ASSERT_EQUAL(-1L, f.find("Title2")); } void testFuzzedFile1() { RIFF::WAV::File f1(TEST_FILE_PATH_C("infloop.wav")); CPPUNIT_ASSERT(!f1.isValid()); } void testFuzzedFile2() { RIFF::WAV::File f2(TEST_FILE_PATH_C("segfault.wav")); CPPUNIT_ASSERT(f2.isValid()); } void testStripAndProperties() { ScopedFileCopy copy("empty", ".wav"); { RIFF::WAV::File f(copy.fileName().c_str()); f.ID3v2Tag()->setTitle("ID3v2"); f.InfoTag()->setTitle("INFO"); f.save(); } { RIFF::WAV::File f(copy.fileName().c_str()); CPPUNIT_ASSERT_EQUAL(String("ID3v2"), f.properties()["TITLE"].front()); f.strip(RIFF::WAV::File::ID3v2); CPPUNIT_ASSERT_EQUAL(String("INFO"), f.properties()["TITLE"].front()); f.strip(RIFF::WAV::File::Info); CPPUNIT_ASSERT(f.properties().isEmpty()); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestWAV); <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "Resources.h" #include "SkBitmap.h" #include "SkData.h" #include "SkImageEncoder.h" #include "sk_tool_utils.h" class EncodeBench : public Benchmark { public: EncodeBench(const char* filename, SkEncodedImageFormat type, int quality) : fFilename(filename) , fType(type) , fQuality(quality) { // Set the name of the bench SkString name("Encode_"); name.append(filename); name.append("_"); switch (type) { case SkEncodedImageFormat::kJPEG: name.append("JPEG"); break; case SkEncodedImageFormat::kPNG: name.append("PNG"); break; case SkEncodedImageFormat::kWEBP: name.append("WEBP"); break; default: name.append("Unknown"); break; } fName = name; } bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } const char* onGetName() override { return fName.c_str(); } void onPreDraw(SkCanvas*) override { #ifdef SK_DEBUG bool result = #endif GetResourceAsBitmap(fFilename, &fBitmap); SkASSERT(result); } void onDraw(int loops, SkCanvas*) override { for (int i = 0; i < loops; i++) { sk_sp<SkData> data(sk_tool_utils::EncodeImageToData(fBitmap, fType, fQuality)); SkASSERT(data); } } private: const char* fFilename; const SkEncodedImageFormat fType; const int fQuality; SkString fName; SkBitmap fBitmap; }; // The Android Photos app uses a quality of 90 on JPEG encodes DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kJPEG, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kJPEG, 90)); // PNG encodes are lossless so quality should be ignored DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kPNG, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kPNG, 90)); // TODO: What is the appropriate quality to use to benchmark WEBP encodes? DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kWEBP, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kWEBP, 90)); <commit_msg>Roll external/skia 1b0126b01..05784d9b1 (1 commits)<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "Resources.h" #include "SkBitmap.h" #include "SkJpegEncoder.h" #include "SkPngEncoder.h" #include "SkWebpEncoder.h" #include "SkStream.h" class EncodeBench : public Benchmark { public: using Encoder = bool (*)(SkWStream*, const SkPixmap&); EncodeBench(const char* filename, Encoder encoder, const char* encoderName) : fSourceFilename(filename) , fEncoder(encoder) , fName(SkStringPrintf("Encode_%s_%s", filename, encoderName)) {} bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } const char* onGetName() override { return fName.c_str(); } void onPreDraw(SkCanvas*) override { SkAssertResult(GetResourceAsBitmap(fSourceFilename, &fBitmap)); } void onDraw(int loops, SkCanvas*) override { while (loops-- > 0) { SkPixmap pixmap; SkAssertResult(fBitmap.peekPixels(&pixmap)); SkNullWStream dst; SkAssertResult(fEncoder(&dst, pixmap)); SkASSERT(dst.bytesWritten() > 0); } } private: const char* fSourceFilename; Encoder fEncoder; SkString fName; SkBitmap fBitmap; }; static bool encode_jpeg(SkWStream* dst, const SkPixmap& src) { SkJpegEncoder::Options opts; opts.fQuality = 90; return SkJpegEncoder::Encode(dst, src, opts); } static bool encode_webp_lossy(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossy; opts.fQuality = 90; opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_webp_lossless(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossless; opts.fQuality = 90; opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_png(SkWStream* dst, const SkPixmap& src, SkPngEncoder::FilterFlag filters, int zlibLevel) { SkPngEncoder::Options opts; opts.fFilterFlags = filters; opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore; opts.fZLibLevel = zlibLevel; return SkPngEncoder::Encode(dst, src, opts); } #define PNG(FLAG, ZLIBLEVEL) [](SkWStream* d, const SkPixmap& s) { \ return encode_png(d, s, SkPngEncoder::FilterFlag::FLAG, ZLIBLEVEL); } static const char* srcs[2] = {"mandrill_512.png", "color_wheel.jpg"}; // The Android Photos app uses a quality of 90 on JPEG encodes DEF_BENCH(return new EncodeBench(srcs[0], &encode_jpeg, "JPEG")); DEF_BENCH(return new EncodeBench(srcs[1], &encode_jpeg, "JPEG")); // TODO: What is the appropriate quality to use to benchmark WEBP encodes? DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 1), "PNG_1n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 1), "PNG_1n")); #undef PNG <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ /** * Print nicely formatted sheet content to stdout. Indispensable when * debugging the unit test code involving testing of sheet contents. */ #include <rtl/strbuf.hxx> #include <rtl/ustring.hxx> #include "document.hxx" #ifdef WNT #define NOMINMAX #include <prewin.h> #include <postwin.h> #undef NOMINMAX #endif #define MDDS_HASH_CONTAINER_BOOST 1 #include <mdds/mixed_type_matrix.hpp> #include <iostream> using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; using ::std::cout; using ::std::cerr; using ::std::endl; using ::std::vector; namespace { ::std::ostream& operator<< (::std::ostream& os, const rtl::OUString& str) { return os << ::rtl::OUStringToOString(str, RTL_TEXTENCODING_UTF8).getStr(); } } class SheetPrinter { typedef ::mdds::mixed_type_matrix<OUString, bool> MatrixType; public: SheetPrinter(size_t rows, size_t cols) : maMatrix(rows, cols, ::mdds::matrix_density_sparse_empty) {} void set(size_t row, size_t col, const OUString& aStr) { maMatrix.set_string(row, col, new OUString(aStr)); } #if CALC_DEBUG_OUTPUT void print(const char* header) const { if (header) cout << header << endl; MatrixType::size_pair_type ns = maMatrix.size(); vector<sal_Int32> aColWidths(ns.second, 0); // Calculate column widths first. for (size_t row = 0; row < ns.first; ++row) { for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); if (aColWidths[col] < p->getLength()) aColWidths[col] = p->getLength(); } } // Make the row separator string. OUStringBuffer aBuf; aBuf.appendAscii("+"); for (size_t col = 0; col < ns.second; ++col) { aBuf.appendAscii("-"); for (sal_Int32 i = 0; i < aColWidths[col]; ++i) aBuf.append(sal_Unicode('-')); aBuf.appendAscii("-+"); } OUString aSep = aBuf.makeStringAndClear(); // Now print to stdout. cout << aSep << endl; for (size_t row = 0; row < ns.first; ++row) { cout << "| "; for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); size_t nPadding = aColWidths[col] - p->getLength(); aBuf.append(*p); for (size_t i = 0; i < nPadding; ++i) aBuf.append(sal_Unicode(' ')); cout << aBuf.makeStringAndClear() << " | "; } cout << endl; cout << aSep << endl; } } #else void print(const char*) const {} #endif /** * Print nested string array which can be copy-n-pasted into the test code * for content verification. */ void printArray() const { #if CALC_DEBUG_OUTPUT MatrixType::size_pair_type ns = maMatrix.size(); for (size_t row = 0; row < ns.first; ++row) { cout << " { "; for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); if (p->getLength()) cout << "\"" << *p << "\""; else cout << "0"; if (col < ns.second - 1) cout << ", "; } cout << " }"; if (row < ns.first - 1) cout << ","; cout << endl; } #endif } void clear() { maMatrix.clear(); } void resize(size_t rows, size_t cols) { maMatrix.resize(rows, cols); } private: MatrixType maMatrix; }; /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: unused function<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ /** * Print nicely formatted sheet content to stdout. Indispensable when * debugging the unit test code involving testing of sheet contents. */ #include <rtl/strbuf.hxx> #include <rtl/ustring.hxx> #include "document.hxx" #ifdef WNT #define NOMINMAX #include <prewin.h> #include <postwin.h> #undef NOMINMAX #endif #define MDDS_HASH_CONTAINER_BOOST 1 #include <mdds/mixed_type_matrix.hpp> #include <iostream> using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; using ::std::cout; using ::std::cerr; using ::std::endl; using ::std::vector; namespace { #ifdef __GNUC__ __attribute__((used)) #endif ::std::ostream& operator<< (::std::ostream& os, const rtl::OUString& str) { return os << ::rtl::OUStringToOString(str, RTL_TEXTENCODING_UTF8).getStr(); } } class SheetPrinter { typedef ::mdds::mixed_type_matrix<OUString, bool> MatrixType; public: SheetPrinter(size_t rows, size_t cols) : maMatrix(rows, cols, ::mdds::matrix_density_sparse_empty) {} void set(size_t row, size_t col, const OUString& aStr) { maMatrix.set_string(row, col, new OUString(aStr)); } #if CALC_DEBUG_OUTPUT void print(const char* header) const { if (header) cout << header << endl; MatrixType::size_pair_type ns = maMatrix.size(); vector<sal_Int32> aColWidths(ns.second, 0); // Calculate column widths first. for (size_t row = 0; row < ns.first; ++row) { for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); if (aColWidths[col] < p->getLength()) aColWidths[col] = p->getLength(); } } // Make the row separator string. OUStringBuffer aBuf; aBuf.appendAscii("+"); for (size_t col = 0; col < ns.second; ++col) { aBuf.appendAscii("-"); for (sal_Int32 i = 0; i < aColWidths[col]; ++i) aBuf.append(sal_Unicode('-')); aBuf.appendAscii("-+"); } OUString aSep = aBuf.makeStringAndClear(); // Now print to stdout. cout << aSep << endl; for (size_t row = 0; row < ns.first; ++row) { cout << "| "; for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); size_t nPadding = aColWidths[col] - p->getLength(); aBuf.append(*p); for (size_t i = 0; i < nPadding; ++i) aBuf.append(sal_Unicode(' ')); cout << aBuf.makeStringAndClear() << " | "; } cout << endl; cout << aSep << endl; } } #else void print(const char*) const {} #endif /** * Print nested string array which can be copy-n-pasted into the test code * for content verification. */ void printArray() const { #if CALC_DEBUG_OUTPUT MatrixType::size_pair_type ns = maMatrix.size(); for (size_t row = 0; row < ns.first; ++row) { cout << " { "; for (size_t col = 0; col < ns.second; ++col) { const OUString* p = maMatrix.get_string(row, col); if (p->getLength()) cout << "\"" << *p << "\""; else cout << "0"; if (col < ns.second - 1) cout << ", "; } cout << " }"; if (row < ns.first - 1) cout << ","; cout << endl; } #endif } void clear() { maMatrix.clear(); } void resize(size_t rows, size_t cols) { maMatrix.resize(rows, cols); } private: MatrixType maMatrix; }; /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <sys/time.h> #include <sys/types.h> #include <sys/syscall.h> #define gettid() syscall(__NR_gettid) #include "thread_private.h" #include "parameters.h" #define NUM_PAGES (40960 * nthreads) extern bool verify_read_content; void check_read_content(char *buf, int size, off_t off) { // I assume the space in the buffer is larger than 8 bytes. off_t aligned_off = off & (~(sizeof(off_t) - 1)); long data[2]; data[0] = aligned_off / sizeof(off_t); data[1] = aligned_off / sizeof(off_t) + 1; long expected = 0; int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t); memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size); long read_value = 0; memcpy(&read_value, buf, copy_size); if(read_value != expected) printf("%ld %ld\n", read_value, expected); assert(read_value == expected); } void create_write_data(char *buf, int size, off_t off) { off_t aligned_start = off & (~(sizeof(off_t) - 1)); off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1)); long start_data = aligned_start / sizeof(off_t); long end_data = aligned_end / sizeof(off_t); int first_size = (int)(sizeof(off_t) - (off - aligned_start)); if (first_size == sizeof(off_t)) first_size = 0; if (first_size) memcpy(buf, ((char *) &start_data) + (off - aligned_start), first_size); for (int i = first_size; i < size; i += sizeof(off_t)) { *((long *) (buf + i)) = (off + i) / sizeof(off_t); } if (aligned_end > aligned_start) { int last_size = (int) (off + size - aligned_end); if (last_size) memcpy(buf + (aligned_end - off), (char *) &end_data, last_size); } check_read_content(buf, size, off); } class cleanup_callback: public callback { rand_buf *buf; ssize_t read_bytes; int thread_id; public: cleanup_callback(rand_buf *buf, int idx) { this->buf = buf; read_bytes = 0; this->thread_id = idx; } int invoke(io_request *rq) { extern bool verify_read_content; if (rq->get_access_method() == READ && verify_read_content) { off_t off = rq->get_offset(); for (int i = 0; i < rq->get_num_bufs(); i++) { check_read_content(rq->get_buf(i), rq->get_buf_size(i), off); off += rq->get_buf_size(i); } } for (int i = 0; i < rq->get_num_bufs(); i++) buf->free_entry(rq->get_buf(i)); read_bytes += rq->get_size(); return 0; } ssize_t get_size() { return read_bytes; } }; ssize_t thread_private::get_read_bytes() { if (cb) return cb->get_size(); else return read_bytes; } int thread_private::thread_init() { attach2cpu(); io->init(); extern int buf_size; rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads // TODO maybe I should set the right entry size for a buffer. // If each access size is irregular, I'll break each access // into pages so each access is no larger than a page, so it // should workl fine. / NUM_NODES) * PAGE_SIZE, buf_size); this->buf = buf; if (io->support_aio()) { cb = new cleanup_callback(buf, idx); io->set_callback(cb); } return 0; } int thread_private::run() { ssize_t ret = -1; gettimeofday(&start_time, NULL); io_request reqs[NUM_REQS_BY_USER]; char *entry = NULL; if (!io->support_aio()) { extern int buf_size; entry = (char *) valloc(buf_size); } while (gen->has_next()) { if (io->support_aio()) { int i; for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) { workload_t workload = gen->next(); int access_method = workload.read ? READ : WRITE; off_t off = workload.off; int size = workload.size; /* * If the size of the request is larger than a page size, * and the user explicitly wants to use multibuf requests. */ if (buf_type == MULTI_BUF) { assert(off % PAGE_SIZE == 0); int num_vecs = size / PAGE_SIZE; reqs[i].init(off, io, access_method); assert(buf->get_entry_size() >= PAGE_SIZE); for (int k = 0; k < num_vecs; k++) { reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE); } i++; } else if (buf_type == SINGLE_SMALL_BUF) { again: while (size > 0 && i < NUM_REQS_BY_USER) { off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + size) next_off = off + size; char *p = buf->next_entry(next_off - off); if (access_method == WRITE) create_write_data(p, next_off - off, off); reqs[i].init(p, off, next_off - off, access_method, io); size -= next_off - off; off = next_off; i++; } if (size > 0) { ret = io->access(reqs, i); i = 0; goto again; } } else { assert(buf->get_entry_size() >= size); char *p = buf->next_entry(size); if (access_method == WRITE) create_write_data(p, size, off); reqs[i++].init(p, off, size, access_method, io); } } ret = io->access(reqs, i); if (ret < 0) { perror("access_vector"); exit(1); } } else { workload_t workload = gen->next(); off_t off = workload.off; // TODO let's just read data first. int access_method = workload.read ? READ : WRITE; int entry_size = workload.size; if (buf_type == SINGLE_SMALL_BUF) { while (entry_size > 0) { /* * generate the data for writing the file, * so the data in the file isn't changed. */ if (access_method == WRITE) { create_write_data(entry, entry_size, off); } // There is at least one byte we need to access in the page. // By adding 1 and rounding up the offset, we'll get the next page // behind the current offset. off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + entry_size) next_off = off + entry_size; ret = io->access(entry, off, next_off - off, access_method); if (ret > 0) { if (access_method == READ && verify_read_content) { check_read_content(entry, next_off - off, off); } read_bytes += ret; } if (ret < 0) { perror("access"); exit(1); } entry_size -= next_off - off; off = next_off; } } else { if (access_method == WRITE) { create_write_data(entry, entry_size, off); } ret = io->access(entry, off, entry_size, access_method); if (ret > 0) { if (access_method == READ && verify_read_content) { check_read_content(entry, entry_size, off); } read_bytes += ret; } if (ret < 0) { perror("access"); exit(1); } } } } io->cleanup(); printf("thread %d exits\n", idx); gettimeofday(&end_time, NULL); return 0; } int thread_private::attach2cpu() { #if NCPUS > 0 cpu_set_t cpuset; pthread_t thread = pthread_self(); CPU_ZERO(&cpuset); int cpu_num = idx % NCPUS; CPU_SET(cpu_num, &cpuset); int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (ret != 0) { perror("pthread_setaffinity_np"); exit(1); } printf("attach thread %d to CPU %d\n", idx, cpu_num); return ret; #else return -1; #endif } static void *rand_read(void *arg) { thread_private *priv = (thread_private *) arg; printf("rand_read: pid: %d, tid: %ld\n", getpid(), gettid()); priv->thread_init(); priv->run(); return NULL; } #ifdef USE_PROCESS static int process_create(pid_t *pid, void (*func)(void *), void *priv) { pid_t id = fork(); if (id < 0) return -1; if (id == 0) { // child func(priv); exit(0); } if (id > 0) *pid = id; return 0; } static int process_join(pid_t pid) { int status; pid_t ret = waitpid(pid, &status, 0); return ret < 0 ? ret : 0; } #endif int thread_private::start_thread() { int ret; #ifdef USE_PROCESS ret = process_create(&id, rand_read, (void *) this); #else ret = pthread_create(&id, NULL, rand_read, (void *) this); #endif return ret; } int thread_private::wait_thread_end() { int ret; #ifdef USE_PROCESS ret = process_join(id); #else ret = pthread_join(id, NULL); #endif return ret; } <commit_msg>fix bugs in creating data for writing.<commit_after>#include <sys/time.h> #include <sys/types.h> #include <sys/syscall.h> #define gettid() syscall(__NR_gettid) #include "thread_private.h" #include "parameters.h" #define NUM_PAGES (40960 * nthreads) extern bool verify_read_content; void check_read_content(char *buf, int size, off_t off) { // I assume the space in the buffer is larger than 8 bytes. off_t aligned_off = off & (~(sizeof(off_t) - 1)); long data[2]; data[0] = aligned_off / sizeof(off_t); data[1] = aligned_off / sizeof(off_t) + 1; long expected = 0; int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t); memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size); long read_value = 0; memcpy(&read_value, buf, copy_size); if(read_value != expected) printf("%ld %ld\n", read_value, expected); assert(read_value == expected); } void create_write_data(char *buf, int size, off_t off) { off_t aligned_start = off & (~(sizeof(off_t) - 1)); off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1)); long start_data = aligned_start / sizeof(off_t); long end_data = aligned_end / sizeof(off_t); /* If all data is in one 8-byte word. */ if (aligned_start == aligned_end) { memcpy(buf, ((char *) &start_data) + (off - aligned_start), size); return; } int first_size = (int)(sizeof(off_t) - (off - aligned_start)); int last_size = (int) (off + size - aligned_end); if (first_size == sizeof(off_t)) first_size = 0; if (first_size) memcpy(buf, ((char *) &start_data) + (off - aligned_start), first_size); for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) { *((long *) (buf + i)) = (off + i) / sizeof(off_t); } if (aligned_end > aligned_start || (aligned_end == aligned_start && first_size == 0)) { if (last_size) memcpy(buf + (aligned_end - off), (char *) &end_data, last_size); } check_read_content(buf, size, off); } class cleanup_callback: public callback { rand_buf *buf; ssize_t read_bytes; int thread_id; public: cleanup_callback(rand_buf *buf, int idx) { this->buf = buf; read_bytes = 0; this->thread_id = idx; } int invoke(io_request *rq) { extern bool verify_read_content; if (rq->get_access_method() == READ && verify_read_content) { off_t off = rq->get_offset(); for (int i = 0; i < rq->get_num_bufs(); i++) { check_read_content(rq->get_buf(i), rq->get_buf_size(i), off); off += rq->get_buf_size(i); } } for (int i = 0; i < rq->get_num_bufs(); i++) buf->free_entry(rq->get_buf(i)); read_bytes += rq->get_size(); return 0; } ssize_t get_size() { return read_bytes; } }; ssize_t thread_private::get_read_bytes() { if (cb) return cb->get_size(); else return read_bytes; } int thread_private::thread_init() { attach2cpu(); io->init(); extern int buf_size; rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads // TODO maybe I should set the right entry size for a buffer. // If each access size is irregular, I'll break each access // into pages so each access is no larger than a page, so it // should workl fine. / NUM_NODES) * PAGE_SIZE, buf_size); this->buf = buf; if (io->support_aio()) { cb = new cleanup_callback(buf, idx); io->set_callback(cb); } return 0; } int thread_private::run() { ssize_t ret = -1; gettimeofday(&start_time, NULL); io_request reqs[NUM_REQS_BY_USER]; char *entry = NULL; if (!io->support_aio()) { extern int buf_size; entry = (char *) valloc(buf_size); } while (gen->has_next()) { if (io->support_aio()) { int i; for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) { workload_t workload = gen->next(); int access_method = workload.read ? READ : WRITE; off_t off = workload.off; int size = workload.size; /* * If the size of the request is larger than a page size, * and the user explicitly wants to use multibuf requests. */ if (buf_type == MULTI_BUF) { assert(off % PAGE_SIZE == 0); int num_vecs = size / PAGE_SIZE; reqs[i].init(off, io, access_method); assert(buf->get_entry_size() >= PAGE_SIZE); for (int k = 0; k < num_vecs; k++) { reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE); } i++; } else if (buf_type == SINGLE_SMALL_BUF) { again: while (size > 0 && i < NUM_REQS_BY_USER) { off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + size) next_off = off + size; char *p = buf->next_entry(next_off - off); if (access_method == WRITE) create_write_data(p, next_off - off, off); reqs[i].init(p, off, next_off - off, access_method, io); size -= next_off - off; off = next_off; i++; } if (size > 0) { ret = io->access(reqs, i); i = 0; goto again; } } else { assert(buf->get_entry_size() >= size); char *p = buf->next_entry(size); if (access_method == WRITE) create_write_data(p, size, off); reqs[i++].init(p, off, size, access_method, io); } } ret = io->access(reqs, i); if (ret < 0) { perror("access_vector"); exit(1); } } else { workload_t workload = gen->next(); off_t off = workload.off; // TODO let's just read data first. int access_method = workload.read ? READ : WRITE; int entry_size = workload.size; if (buf_type == SINGLE_SMALL_BUF) { while (entry_size > 0) { /* * generate the data for writing the file, * so the data in the file isn't changed. */ if (access_method == WRITE) { create_write_data(entry, entry_size, off); } // There is at least one byte we need to access in the page. // By adding 1 and rounding up the offset, we'll get the next page // behind the current offset. off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + entry_size) next_off = off + entry_size; ret = io->access(entry, off, next_off - off, access_method); if (ret > 0) { if (access_method == READ && verify_read_content) { check_read_content(entry, next_off - off, off); } read_bytes += ret; } if (ret < 0) { perror("access"); exit(1); } entry_size -= next_off - off; off = next_off; } } else { if (access_method == WRITE) { create_write_data(entry, entry_size, off); } ret = io->access(entry, off, entry_size, access_method); if (ret > 0) { if (access_method == READ && verify_read_content) { check_read_content(entry, entry_size, off); } read_bytes += ret; } if (ret < 0) { perror("access"); exit(1); } } } } io->cleanup(); printf("thread %d exits\n", idx); gettimeofday(&end_time, NULL); return 0; } int thread_private::attach2cpu() { #if NCPUS > 0 cpu_set_t cpuset; pthread_t thread = pthread_self(); CPU_ZERO(&cpuset); int cpu_num = idx % NCPUS; CPU_SET(cpu_num, &cpuset); int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (ret != 0) { perror("pthread_setaffinity_np"); exit(1); } printf("attach thread %d to CPU %d\n", idx, cpu_num); return ret; #else return -1; #endif } static void *rand_read(void *arg) { thread_private *priv = (thread_private *) arg; printf("rand_read: pid: %d, tid: %ld\n", getpid(), gettid()); priv->thread_init(); priv->run(); return NULL; } #ifdef USE_PROCESS static int process_create(pid_t *pid, void (*func)(void *), void *priv) { pid_t id = fork(); if (id < 0) return -1; if (id == 0) { // child func(priv); exit(0); } if (id > 0) *pid = id; return 0; } static int process_join(pid_t pid) { int status; pid_t ret = waitpid(pid, &status, 0); return ret < 0 ? ret : 0; } #endif int thread_private::start_thread() { int ret; #ifdef USE_PROCESS ret = process_create(&id, rand_read, (void *) this); #else ret = pthread_create(&id, NULL, rand_read, (void *) this); #endif return ret; } int thread_private::wait_thread_end() { int ret; #ifdef USE_PROCESS ret = process_join(id); #else ret = pthread_join(id, NULL); #endif return ret; } <|endoftext|>
<commit_before>#include "otc/otcli.h" using namespace otc; // Note that the "taxonomy" data member here will be the first tree (the supertree) struct DistanceState : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits> { unsigned long totalRF; unsigned long totalNumNotDisplayed; unsigned long totalNumInternals; unsigned long totalNumDisplayed; bool showRF; bool showNumNotDisplayed; bool showNumInternals; bool showNumDisplayed; std::string prevTreeFilename; std::size_t numComparisons; std::size_t numTreesInThisTreefile; virtual ~DistanceState(){} DistanceState() :totalRF(0U), totalNumNotDisplayed(0U), totalNumInternals(0U), totalNumDisplayed(0U), showRF(false), showNumNotDisplayed(false), showNumInternals(false), showNumDisplayed(false), numComparisons(0U), numTreesInThisTreefile(0U) { } bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> tree) { numComparisons += 1; std::string nameToPrint = otCLI.currentFilename; if (nameToPrint == prevTreeFilename) { numTreesInThisTreefile += 1; nameToPrint += "-tree#" + std::to_string(numTreesInThisTreefile); } else { prevTreeFilename = nameToPrint; numTreesInThisTreefile = 1; } assert(tree != nullptr); assert(taxonomy != nullptr); std::set<std::set<long> > inducedSplits; std::set<std::set<long> > tree2Splits; inducedCladeSets(*taxonomy, *tree, inducedSplits, tree2Splits, true); unsigned long rf = 0; unsigned long numNotDisplayed = 0; const unsigned long numInternals = tree2Splits.size(); unsigned long numDisplayed = 0; totalNumInternals += numInternals; if (showRF) { rf = sizeOfSymmetricDifference(tree2Splits, inducedSplits); totalRF += rf; } if (showNumDisplayed || showNumNotDisplayed) { for (auto ics : tree2Splits) { if (contains(inducedSplits, ics)) { numDisplayed += 1; } else { numNotDisplayed += 1; } } totalNumNotDisplayed += numNotDisplayed; } // display // header if first comparison if (numComparisons == 1) { otCLI.out << "treename"; if (showRF) { otCLI.out << "\tRF"; } if (showNumNotDisplayed) { otCLI.out << "\tNumNotDisplayed"; } if (showNumDisplayed) { otCLI.out << "\tNumDisplayed"; } if (showNumNotDisplayed) { otCLI.out << "\tNumInternals"; } otCLI.out << '\n'; } otCLI.out << nameToPrint; if (showRF) { otCLI.out << '\t' << rf; } if (showNumNotDisplayed) { otCLI.out << '\t' << numNotDisplayed; } if (showNumDisplayed) { otCLI.out << '\t' << numDisplayed; } if (showNumNotDisplayed) { otCLI.out << '\t' << numInternals; } otCLI.out << '\n'; return true; } bool summarize(OTCLI & otCLI) override { otCLI.out << "TOTALS"; if (showRF) { otCLI.out << '\t' << totalRF; } if (showNumNotDisplayed) { otCLI.out << '\t' << totalNumNotDisplayed; } if (showNumDisplayed) { otCLI.out << '\t' << totalNumDisplayed; } if (showNumNotDisplayed) { otCLI.out << '\t' << totalNumInternals; } otCLI.out << '\n'; return true; } }; int main(int argc, char *argv[]) { OTCLI otCLI("otc-distance", "takes at least 2 newick file paths: a supertree and some number of input trees. Writes one line for each input tree with the statistics requested for the comparison of the supertree to each input tree.", "synth.tre inp1.tre inp2.tre"); DistanceState proc; auto rc = taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true); return rc; } <commit_msg>flags for otc-distance<commit_after>#include "otc/otcli.h" using namespace otc; // Note that the "taxonomy" data member here will be the first tree (the supertree) struct DistanceState : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits> { unsigned long totalRF; unsigned long totalNumNotDisplayed; unsigned long totalNumInternals; unsigned long totalNumDisplayed; bool showRF; bool showNumNotDisplayed; bool showNumInternals; bool showNumDisplayed; std::string prevTreeFilename; std::size_t numComparisons; std::size_t numTreesInThisTreefile; virtual ~DistanceState(){} DistanceState() :totalRF(0U), totalNumNotDisplayed(0U), totalNumInternals(0U), totalNumDisplayed(0U), showRF(false), showNumNotDisplayed(false), showNumInternals(false), showNumDisplayed(false), numComparisons(0U), numTreesInThisTreefile(0U) { } bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> tree) { numComparisons += 1; std::string nameToPrint = otCLI.currentFilename; if (nameToPrint == prevTreeFilename) { numTreesInThisTreefile += 1; nameToPrint += "-tree#" + std::to_string(numTreesInThisTreefile); } else { prevTreeFilename = nameToPrint; numTreesInThisTreefile = 1; } assert(tree != nullptr); assert(taxonomy != nullptr); std::set<std::set<long> > inducedSplits; std::set<std::set<long> > tree2Splits; inducedCladeSets(*taxonomy, *tree, inducedSplits, tree2Splits, true); unsigned long rf = 0; unsigned long numNotDisplayed = 0; const unsigned long numInternals = tree2Splits.size(); unsigned long numDisplayed = 0; totalNumInternals += numInternals; if (showRF) { rf = sizeOfSymmetricDifference(tree2Splits, inducedSplits); totalRF += rf; } if (showNumDisplayed || showNumNotDisplayed) { for (auto ics : tree2Splits) { if (contains(inducedSplits, ics)) { numDisplayed += 1; } else { numNotDisplayed += 1; } } totalNumNotDisplayed += numNotDisplayed; totalNumDisplayed += numDisplayed; } // display // header if first comparison if (numComparisons == 1) { otCLI.out << "treename"; if (showRF) { otCLI.out << "\tRF"; } if (showNumNotDisplayed) { otCLI.out << "\tNumNotDisplayed"; } if (showNumDisplayed) { otCLI.out << "\tNumDisplayed"; } if (showNumNotDisplayed) { otCLI.out << "\tNumInternals"; } otCLI.out << '\n'; } otCLI.out << nameToPrint; if (showRF) { otCLI.out << '\t' << rf; } if (showNumNotDisplayed) { otCLI.out << '\t' << numNotDisplayed; } if (showNumDisplayed) { otCLI.out << '\t' << numDisplayed; } if (showNumNotDisplayed) { otCLI.out << '\t' << numInternals; } otCLI.out << '\n'; return true; } bool summarize(OTCLI & otCLI) override { otCLI.out << "TOTALS"; if (showRF) { otCLI.out << '\t' << totalRF; } if (showNumNotDisplayed) { otCLI.out << '\t' << totalNumNotDisplayed; } if (showNumDisplayed) { otCLI.out << '\t' << totalNumDisplayed; } if (showNumNotDisplayed) { otCLI.out << '\t' << totalNumInternals; } otCLI.out << '\n'; return true; } }; bool handleShowRF(OTCLI & otCLI, const std::string &); bool handleShowNumDisplayed(OTCLI & otCLI, const std::string &); bool handleShowShowNumNotDisplayed(OTCLI & otCLI, const std::string &); bool handleShowInternals(OTCLI & otCLI, const std::string &); bool handleShowRF(OTCLI & otCLI, const std::string &) { DistanceState * proc = static_cast<DistanceState *>(otCLI.blob); assert(proc != nullptr); proc->showRF = true; return true; } bool handleShowNumDisplayed(OTCLI & otCLI, const std::string &) { DistanceState * proc = static_cast<DistanceState *>(otCLI.blob); assert(proc != nullptr); proc->showNumDisplayed = true; return true; } bool handleShowShowNumNotDisplayed(OTCLI & otCLI, const std::string &) { DistanceState * proc = static_cast<DistanceState *>(otCLI.blob); assert(proc != nullptr); proc->showNumNotDisplayed = true; return true; } bool handleShowInternals(OTCLI & otCLI, const std::string &) { DistanceState * proc = static_cast<DistanceState *>(otCLI.blob); assert(proc != nullptr); proc->showNumInternals = true; return true; } int main(int argc, char *argv[]) { OTCLI otCLI("otc-distance", "takes at least 2 newick file paths: a supertree and some number of input trees. Writes one line for each input tree with the statistics requested for the comparison of the supertree to each input tree.", "synth.tre inp1.tre inp2.tre"); DistanceState proc; otCLI.addFlag('r', "Show RF symmetric distance", handleShowRF, false); otCLI.addFlag('d', "Show number of grouping in each input displayed on full tree", handleShowNumDisplayed, false); otCLI.addFlag('n', "Show number of grouping in each input NOT displayed on full tree", handleShowShowNumNotDisplayed, false); otCLI.addFlag('i', "Show the number of internal groupings in each input tree", handleShowInternals, false); auto rc = taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true); return rc; } <|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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "gms/inet_address.hh" #include <seastar/core/sstring.hh> #include <seastar/net/api.hh> #include <experimental/optional> namespace transport { class event { public: enum class event_type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE }; const event_type type; private: event(const event_type& type_) : type{type_} { } public: #if 0 public static Event deserialize(ByteBuf cb, int version) { switch (CBUtil.readEnumValue(Type.class, cb)) { case TOPOLOGY_CHANGE: return TopologyChange.deserializeEvent(cb, version); case STATUS_CHANGE: return StatusChange.deserializeEvent(cb, version); case SCHEMA_CHANGE: return SchemaChange.deserializeEvent(cb, version); } throw new AssertionError(); } public void serialize(ByteBuf dest, int version) { CBUtil.writeEnumValue(type, dest); serializeEvent(dest, version); } public int serializedSize(int version) { return CBUtil.sizeOfEnumValue(type) + eventSerializedSize(version); } protected abstract void serializeEvent(ByteBuf dest, int version); protected abstract int eventSerializedSize(int version); #endif class topology_change; class status_change; class schema_change; }; class event::topology_change : public event { public: enum class change_type { NEW_NODE, REMOVED_NODE, MOVED_NODE }; const change_type change; const ipv4_addr node; topology_change(change_type change, const ipv4_addr& node) : event{event_type::TOPOLOGY_CHANGE} , change{change} , node{node} { } static topology_change new_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::NEW_NODE, ipv4_addr{host.raw_addr(), port}}; } static topology_change removed_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::REMOVED_NODE, ipv4_addr{host.raw_addr(), port}}; } static topology_change moved_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::MOVED_NODE, ipv4_addr{host.raw_addr(), port}}; } #if 0 // Assumes the type has already been deserialized private static TopologyChange deserializeEvent(ByteBuf cb, int version) { Change change = CBUtil.readEnumValue(Change.class, cb); InetSocketAddress node = CBUtil.readInet(cb); return new TopologyChange(change, node); } protected void serializeEvent(ByteBuf dest, int version) { CBUtil.writeEnumValue(change, dest); CBUtil.writeInet(node, dest); } protected int eventSerializedSize(int version) { return CBUtil.sizeOfEnumValue(change) + CBUtil.sizeOfInet(node); } @Override public String toString() { return change + " " + node; } @Override public int hashCode() { return Objects.hashCode(change, node); } @Override public boolean equals(Object other) { if (!(other instanceof TopologyChange)) return false; TopologyChange tpc = (TopologyChange)other; return Objects.equal(change, tpc.change) && Objects.equal(node, tpc.node); } #endif }; class event::status_change : public event { public: enum class status_type { UP, DOWN }; const status_type status; const ipv4_addr node; status_change(status_type status, const ipv4_addr& node) : event{event_type::STATUS_CHANGE} , status{status} , node{node} { } static status_change node_up(const gms::inet_address& host, uint16_t port) { return status_change{status_type::UP, ipv4_addr{host.raw_addr(), port}}; } static status_change node_down(const gms::inet_address& host, uint16_t port) { return status_change{status_type::DOWN, ipv4_addr{host.raw_addr(), port}}; } #if 0 // Assumes the type has already been deserialized private static StatusChange deserializeEvent(ByteBuf cb, int version) { Status status = CBUtil.readEnumValue(Status.class, cb); InetSocketAddress node = CBUtil.readInet(cb); return new StatusChange(status, node); } protected void serializeEvent(ByteBuf dest, int version) { CBUtil.writeEnumValue(status, dest); CBUtil.writeInet(node, dest); } protected int eventSerializedSize(int version) { return CBUtil.sizeOfEnumValue(status) + CBUtil.sizeOfInet(node); } @Override public String toString() { return status + " " + node; } @Override public int hashCode() { return Objects.hashCode(status, node); } @Override public boolean equals(Object other) { if (!(other instanceof StatusChange)) return false; StatusChange stc = (StatusChange)other; return Objects.equal(status, stc.status) && Objects.equal(node, stc.node); } #endif }; class event::schema_change : public event { public: enum class change_type { CREATED, UPDATED, DROPPED }; enum class target_type { KEYSPACE, TABLE, TYPE }; const change_type change; const target_type target; const sstring keyspace; const std::experimental::optional<sstring> table_or_type_or_function; schema_change(const change_type change_, const target_type target_, const sstring& keyspace_, const std::experimental::optional<sstring>& table_or_type_or_function_) : event{event_type::SCHEMA_CHANGE} , change{change_} , target{target_} , keyspace{keyspace_} , table_or_type_or_function{table_or_type_or_function_} { #if 0 if (target != Target.KEYSPACE) assert this.tableOrTypeOrFunction != null : "Table or type should be set for non-keyspace schema change events"; #endif } schema_change(const change_type change_, const sstring keyspace_) : schema_change{change_, target_type::KEYSPACE, keyspace_, std::experimental::optional<sstring>{}} { } #if 0 // Assumes the type has already been deserialized public static SchemaChange deserializeEvent(ByteBuf cb, int version) { Change change = CBUtil.readEnumValue(Change.class, cb); if (version >= 3) { Target target = CBUtil.readEnumValue(Target.class, cb); String keyspace = CBUtil.readString(cb); String tableOrType = target == Target.KEYSPACE ? null : CBUtil.readString(cb); return new SchemaChange(change, target, keyspace, tableOrType); } else { String keyspace = CBUtil.readString(cb); String table = CBUtil.readString(cb); return new SchemaChange(change, table.isEmpty() ? Target.KEYSPACE : Target.TABLE, keyspace, table.isEmpty() ? null : table); } } public void serializeEvent(ByteBuf dest, int version) { if (version >= 3) { CBUtil.writeEnumValue(change, dest); CBUtil.writeEnumValue(target, dest); CBUtil.writeString(keyspace, dest); if (target != Target.KEYSPACE) CBUtil.writeString(tableOrTypeOrFunction, dest); } else { if (target == Target.TYPE) { // For the v1/v2 protocol, we have no way to represent type changes, so we simply say the keyspace // was updated. See CASSANDRA-7617. CBUtil.writeEnumValue(Change.UPDATED, dest); CBUtil.writeString(keyspace, dest); CBUtil.writeString("", dest); } else { CBUtil.writeEnumValue(change, dest); CBUtil.writeString(keyspace, dest); CBUtil.writeString(target == Target.KEYSPACE ? "" : tableOrTypeOrFunction, dest); } } } public int eventSerializedSize(int version) { if (version >= 3) { int size = CBUtil.sizeOfEnumValue(change) + CBUtil.sizeOfEnumValue(target) + CBUtil.sizeOfString(keyspace); if (target != Target.KEYSPACE) size += CBUtil.sizeOfString(tableOrTypeOrFunction); return size; } else { if (target == Target.TYPE) { return CBUtil.sizeOfEnumValue(Change.UPDATED) + CBUtil.sizeOfString(keyspace) + CBUtil.sizeOfString(""); } return CBUtil.sizeOfEnumValue(change) + CBUtil.sizeOfString(keyspace) + CBUtil.sizeOfString(target == Target.KEYSPACE ? "" : tableOrTypeOrFunction); } } @Override public String toString() { return change + " " + target + " " + keyspace + (tableOrTypeOrFunction == null ? "" : "." + tableOrTypeOrFunction); } @Override public int hashCode() { return Objects.hashCode(change, target, keyspace, tableOrTypeOrFunction); } @Override public boolean equals(Object other) { if (!(other instanceof SchemaChange)) return false; SchemaChange scc = (SchemaChange)other; return Objects.equal(change, scc.change) && Objects.equal(target, scc.target) && Objects.equal(keyspace, scc.keyspace) && Objects.equal(tableOrTypeOrFunction, scc.tableOrTypeOrFunction); } #endif }; } <commit_msg>transport/event: Eliminate ifdef'd code<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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "gms/inet_address.hh" #include <seastar/core/sstring.hh> #include <seastar/net/api.hh> #include <experimental/optional> namespace transport { class event { public: enum class event_type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE }; const event_type type; private: event(const event_type& type_) : type{type_} { } public: class topology_change; class status_change; class schema_change; }; class event::topology_change : public event { public: enum class change_type { NEW_NODE, REMOVED_NODE, MOVED_NODE }; const change_type change; const ipv4_addr node; topology_change(change_type change, const ipv4_addr& node) : event{event_type::TOPOLOGY_CHANGE} , change{change} , node{node} { } static topology_change new_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::NEW_NODE, ipv4_addr{host.raw_addr(), port}}; } static topology_change removed_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::REMOVED_NODE, ipv4_addr{host.raw_addr(), port}}; } static topology_change moved_node(const gms::inet_address& host, uint16_t port) { return topology_change{change_type::MOVED_NODE, ipv4_addr{host.raw_addr(), port}}; } }; class event::status_change : public event { public: enum class status_type { UP, DOWN }; const status_type status; const ipv4_addr node; status_change(status_type status, const ipv4_addr& node) : event{event_type::STATUS_CHANGE} , status{status} , node{node} { } static status_change node_up(const gms::inet_address& host, uint16_t port) { return status_change{status_type::UP, ipv4_addr{host.raw_addr(), port}}; } static status_change node_down(const gms::inet_address& host, uint16_t port) { return status_change{status_type::DOWN, ipv4_addr{host.raw_addr(), port}}; } }; class event::schema_change : public event { public: enum class change_type { CREATED, UPDATED, DROPPED }; enum class target_type { KEYSPACE, TABLE, TYPE }; const change_type change; const target_type target; const sstring keyspace; const std::experimental::optional<sstring> table_or_type_or_function; schema_change(const change_type change_, const target_type target_, const sstring& keyspace_, const std::experimental::optional<sstring>& table_or_type_or_function_) : event{event_type::SCHEMA_CHANGE} , change{change_} , target{target_} , keyspace{keyspace_} , table_or_type_or_function{table_or_type_or_function_} { #if 0 if (target != Target.KEYSPACE) assert this.tableOrTypeOrFunction != null : "Table or type should be set for non-keyspace schema change events"; #endif } schema_change(const change_type change_, const sstring keyspace_) : schema_change{change_, target_type::KEYSPACE, keyspace_, std::experimental::optional<sstring>{}} { } }; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _PROPREAD_HXX_ #define _PROPREAD_HXX_ #include <map> #include <boost/ptr_container/ptr_vector.hpp> #include <tools/solar.h> #include <sot/storage.hxx> #include <tools/gen.hxx> #include <tools/list.hxx> #include <tools/stream.hxx> #include <tools/datetime.hxx> #include <tools/string.hxx> // SummaryInformation #define PID_TITLE 0x02 #define PID_SUBJECT 0x03 #define PID_AUTHOR 0x04 #define PID_KEYWORDS 0x05 #define PID_COMMENTS 0x06 #define PID_TEMPLATE 0x07 #define PID_LASTAUTHOR 0x08 #define PID_REVNUMBER 0x09 #define PID_EDITTIME 0x0a #define PID_LASTPRINTED_DTM 0x0b #define PID_CREATE_DTM 0x0c #define PID_LASTSAVED_DTM 0x0d // DocumentSummaryInformation #define PID_CATEGORY 0x02 #define PID_PRESFORMAT 0x03 #define PID_BYTECOUNT 0x04 #define PID_LINECOUNT 0x05 #define PID_PARACOUNT 0x06 #define PID_SLIDECOUNT 0x07 #define PID_NOTECOUNT 0x08 #define PID_HIDDENCOUNT 0x09 #define PID_MMCLIPCOUNT 0x0a #define PID_SCALE 0x0b #define PID_HEADINGPAIR 0x0c #define PID_DOCPARTS 0x0d #define PID_MANAGER 0x0e #define PID_COMPANY 0x0f #define PID_LINKSDIRTY 0x10 #define VT_EMPTY 0 #define VT_NULL 1 #define VT_I2 2 #define VT_I4 3 #define VT_R4 4 #define VT_R8 5 #define VT_CY 6 #define VT_DATE 7 #define VT_BSTR 8 #define VT_UI4 9 #define VT_ERROR 10 #define VT_BOOL 11 #define VT_VARIANT 12 #define VT_DECIMAL 14 #define VT_I1 16 #define VT_UI1 17 #define VT_UI2 18 #define VT_I8 20 #define VT_UI8 21 #define VT_INT 22 #define VT_UINT 23 #define VT_LPSTR 30 #define VT_LPWSTR 31 #define VT_FILETIME 64 #define VT_BLOB 65 #define VT_STREAM 66 #define VT_STORAGE 67 #define VT_STREAMED_OBJECT 68 #define VT_STORED_OBJECT 69 #define VT_BLOB_OBJECT 70 #define VT_CF 71 #define VT_CLSID 72 #define VT_VECTOR 0x1000 #define VT_ARRAY 0x2000 #define VT_BYREF 0x4000 #define VT_TYPEMASK 0xFFF // ------------------------------------------------------------------------ typedef std::map<String,sal_uInt32> Dictionary; struct PropEntry { sal_uInt32 mnId; sal_uInt32 mnSize; sal_uInt16 mnTextEnc; sal_uInt8* mpBuf; PropEntry( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize, sal_uInt16 nTextEnc ); PropEntry( const PropEntry& rProp ); ~PropEntry() { delete[] mpBuf; } ; const PropEntry& operator=(const PropEntry& rPropEntry); }; class PropItem : public SvMemoryStream { sal_uInt16 mnTextEnc; public : PropItem(){}; void Clear(); void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; }; sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True ); PropItem& operator=( PropItem& rPropItem ); using SvStream::Read; }; // ------------------------------------------------------------------------ class Section { sal_uInt16 mnTextEnc; boost::ptr_vector<PropEntry> maEntries; protected: sal_uInt8 aFMTID[ 16 ]; void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize ); public: Section( const sal_uInt8* pFMTID ); Section( const Section& rSection ); Section& operator=( const Section& rSection ); sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem ); sal_Bool GetDictionary( Dictionary& rDict ); const sal_uInt8* GetFMTID() const { return aFMTID; }; void Read( SvStorageStream* pStrm ); }; // ------------------------------------------------------------------------ class PropRead { sal_Bool mbStatus; SvStorageStreamRef mpSvStream; sal_uInt16 mnByteOrder; sal_uInt16 mnFormat; sal_uInt16 mnVersionLo; sal_uInt16 mnVersionHi; sal_uInt8 mApplicationCLSID[ 16 ]; boost::ptr_vector<Section> maSections; void AddSection( Section& rSection ); public: PropRead( SvStorage& rSvStorage, const String& rName ); PropRead& operator=( const PropRead& rPropRead ); const Section* GetSection( const sal_uInt8* pFMTID ); sal_Bool IsValid() const { return mbStatus; }; void Read(); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove tools/list.hxx include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _PROPREAD_HXX_ #define _PROPREAD_HXX_ #include <map> #include <boost/ptr_container/ptr_vector.hpp> #include <tools/solar.h> #include <sot/storage.hxx> #include <tools/gen.hxx> #include <tools/stream.hxx> #include <tools/datetime.hxx> #include <tools/string.hxx> // SummaryInformation #define PID_TITLE 0x02 #define PID_SUBJECT 0x03 #define PID_AUTHOR 0x04 #define PID_KEYWORDS 0x05 #define PID_COMMENTS 0x06 #define PID_TEMPLATE 0x07 #define PID_LASTAUTHOR 0x08 #define PID_REVNUMBER 0x09 #define PID_EDITTIME 0x0a #define PID_LASTPRINTED_DTM 0x0b #define PID_CREATE_DTM 0x0c #define PID_LASTSAVED_DTM 0x0d // DocumentSummaryInformation #define PID_CATEGORY 0x02 #define PID_PRESFORMAT 0x03 #define PID_BYTECOUNT 0x04 #define PID_LINECOUNT 0x05 #define PID_PARACOUNT 0x06 #define PID_SLIDECOUNT 0x07 #define PID_NOTECOUNT 0x08 #define PID_HIDDENCOUNT 0x09 #define PID_MMCLIPCOUNT 0x0a #define PID_SCALE 0x0b #define PID_HEADINGPAIR 0x0c #define PID_DOCPARTS 0x0d #define PID_MANAGER 0x0e #define PID_COMPANY 0x0f #define PID_LINKSDIRTY 0x10 #define VT_EMPTY 0 #define VT_NULL 1 #define VT_I2 2 #define VT_I4 3 #define VT_R4 4 #define VT_R8 5 #define VT_CY 6 #define VT_DATE 7 #define VT_BSTR 8 #define VT_UI4 9 #define VT_ERROR 10 #define VT_BOOL 11 #define VT_VARIANT 12 #define VT_DECIMAL 14 #define VT_I1 16 #define VT_UI1 17 #define VT_UI2 18 #define VT_I8 20 #define VT_UI8 21 #define VT_INT 22 #define VT_UINT 23 #define VT_LPSTR 30 #define VT_LPWSTR 31 #define VT_FILETIME 64 #define VT_BLOB 65 #define VT_STREAM 66 #define VT_STORAGE 67 #define VT_STREAMED_OBJECT 68 #define VT_STORED_OBJECT 69 #define VT_BLOB_OBJECT 70 #define VT_CF 71 #define VT_CLSID 72 #define VT_VECTOR 0x1000 #define VT_ARRAY 0x2000 #define VT_BYREF 0x4000 #define VT_TYPEMASK 0xFFF // ------------------------------------------------------------------------ typedef std::map<String,sal_uInt32> Dictionary; struct PropEntry { sal_uInt32 mnId; sal_uInt32 mnSize; sal_uInt16 mnTextEnc; sal_uInt8* mpBuf; PropEntry( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize, sal_uInt16 nTextEnc ); PropEntry( const PropEntry& rProp ); ~PropEntry() { delete[] mpBuf; } ; const PropEntry& operator=(const PropEntry& rPropEntry); }; class PropItem : public SvMemoryStream { sal_uInt16 mnTextEnc; public : PropItem(){}; void Clear(); void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; }; sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True ); PropItem& operator=( PropItem& rPropItem ); using SvStream::Read; }; // ------------------------------------------------------------------------ class Section { sal_uInt16 mnTextEnc; boost::ptr_vector<PropEntry> maEntries; protected: sal_uInt8 aFMTID[ 16 ]; void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize ); public: Section( const sal_uInt8* pFMTID ); Section( const Section& rSection ); Section& operator=( const Section& rSection ); sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem ); sal_Bool GetDictionary( Dictionary& rDict ); const sal_uInt8* GetFMTID() const { return aFMTID; }; void Read( SvStorageStream* pStrm ); }; // ------------------------------------------------------------------------ class PropRead { sal_Bool mbStatus; SvStorageStreamRef mpSvStream; sal_uInt16 mnByteOrder; sal_uInt16 mnFormat; sal_uInt16 mnVersionLo; sal_uInt16 mnVersionHi; sal_uInt8 mApplicationCLSID[ 16 ]; boost::ptr_vector<Section> maSections; void AddSection( Section& rSection ); public: PropRead( SvStorage& rSvStorage, const String& rName ); PropRead& operator=( const PropRead& rPropRead ); const Section* GetSection( const sal_uInt8* pFMTID ); sal_Bool IsValid() const { return mbStatus; }; void Read(); }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#define _REENTRANT #include <cstdio> #include "sync_objs.h" #include "loom.h" #include <pthread.h> #include <semaphore.h> using namespace std; static pthread_mutex_t mutexes[MAX_N_FIXES]; static sem_t sems[MAX_N_FIXES]; void init_sync_objs() { for (int i = 0; i < MAX_N_FIXES; ++i) { pthread_mutex_init(&mutexes[i], NULL); sem_init(&sems[i], 0, 0); } } int enter_critical_region(argument_t arg) { long fix_id = (long)arg; pthread_mutex_lock(&mutexes[fix_id]); fprintf(stderr, "enter_critical_region %p\n", &mutexes[fix_id]); return 0; } int exit_critical_region(argument_t arg) { long fix_id = (long)arg; fprintf(stderr, "exit_critical_region %p\n", &mutexes[fix_id]); pthread_mutex_unlock(&mutexes[fix_id]); return 0; } int enter_atomic_region(argument_t arg) { return __enter_atomic_region(); } int exit_atomic_region(argument_t arg) { return __exit_atomic_region(); } int semaphore_up(argument_t arg) { fprintf(stderr, "semaphore_up\n"); long fix_id = (long)arg; sem_post(&sems[fix_id]); return 0; } int semaphore_down(argument_t arg) { fprintf(stderr, "semaphore_down\n"); long fix_id = (long)arg; sem_wait(&sems[fix_id]); return 0; } <commit_msg>printing enter/exit inside the critical region<commit_after>#define _REENTRANT #include <cstdio> #include "sync_objs.h" #include "loom.h" #include <pthread.h> #include <semaphore.h> using namespace std; static pthread_mutex_t mutexes[MAX_N_FIXES]; static sem_t sems[MAX_N_FIXES]; void init_sync_objs() { for (int i = 0; i < MAX_N_FIXES; ++i) { pthread_mutex_init(&mutexes[i], NULL); sem_init(&sems[i], 0, 0); } } int enter_critical_region(argument_t arg) { long fix_id = (long)arg; pthread_mutex_lock(&mutexes[fix_id]); // fprintf(stderr, "enter_critical_region %p\n", &mutexes[fix_id]); return 0; } int exit_critical_region(argument_t arg) { long fix_id = (long)arg; // fprintf(stderr, "exit_critical_region %p\n", &mutexes[fix_id]); pthread_mutex_unlock(&mutexes[fix_id]); return 0; } int enter_atomic_region(argument_t arg) { return __enter_atomic_region(); } int exit_atomic_region(argument_t arg) { return __exit_atomic_region(); } int semaphore_up(argument_t arg) { fprintf(stderr, "semaphore_up\n"); long fix_id = (long)arg; sem_post(&sems[fix_id]); return 0; } int semaphore_down(argument_t arg) { fprintf(stderr, "semaphore_down\n"); long fix_id = (long)arg; sem_wait(&sems[fix_id]); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: patattr.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:25:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SCPATATR_HXX #define SC_SCPATATR_HXX #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SV_FONTCVT_HXX #include <vcl/fontcvt.hxx> #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif #ifndef INCLUDED_SCDLLAPI_H #include "scdllapi.h" #endif class Font; class OutputDevice; class Fraction; class ScStyleSheet; class SvNumberFormatter; class ScDocument; // how to treat COL_AUTO in GetFont: enum ScAutoFontColorMode { SC_AUTOCOL_RAW, // COL_AUTO is returned SC_AUTOCOL_BLACK, // always use black SC_AUTOCOL_PRINT, // black or white, depending on background SC_AUTOCOL_DISPLAY, // from style settings, or black/white if needed SC_AUTOCOL_IGNOREFONT, // like DISPLAY, but ignore stored font color (assume COL_AUTO) SC_AUTOCOL_IGNOREBACK, // like DISPLAY, but ignore stored background color (use configured color) SC_AUTOCOL_IGNOREALL // like DISPLAY, but ignore stored font and background colors }; class SC_DLLPUBLIC ScPatternAttr: public SfxSetItem { String* pName; ScStyleSheet* pStyle; public: static ScDocument* pDoc; ScPatternAttr(SfxItemSet* pItemSet, const String& rStyleName); ScPatternAttr(SfxItemSet* pItemSet, ScStyleSheet* pStyleSheet = NULL); ScPatternAttr(SfxItemPool* pItemPool); ScPatternAttr(const ScPatternAttr& rPatternAttr); ~ScPatternAttr(); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream& rStream, USHORT nVersion) const; virtual SvStream& Store(SvStream& rStream, USHORT nItemVersion) const; virtual int operator==(const SfxPoolItem& rCmp) const; const SfxPoolItem& GetItem( USHORT nWhich ) const { return GetItemSet().Get(nWhich); } static const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet& rItemSet, const SfxItemSet* pCondSet ); const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet* pCondSet ) const; // pWhich sind keine Ranges, sondern einzelne IDs, 0-terminiert BOOL HasItemsSet( const USHORT* pWhich ) const; void ClearItems( const USHORT* pWhich ); void DeleteUnchanged( const ScPatternAttr* pOldAttrs ); static SvxCellOrientation GetCellOrientation( const SfxItemSet& rItemSet, const SfxItemSet* pCondSet = 0 ); SvxCellOrientation GetCellOrientation( const SfxItemSet* pCondSet = 0 ) const; /** Static helper function to fill a font object from the passed item set. */ static void GetFont( Font& rFont, const SfxItemSet& rItemSet, ScAutoFontColorMode eAutoMode, OutputDevice* pOutDev = NULL, const Fraction* pScale = NULL, const SfxItemSet* pCondSet = NULL, BYTE nScript = 0, const Color* pBackConfigColor = NULL, const Color* pTextConfigColor = NULL ); /** Fills a font object from the own item set. */ void GetFont( Font& rFont, ScAutoFontColorMode eAutoMode, OutputDevice* pOutDev = NULL, const Fraction* pScale = NULL, const SfxItemSet* pCondSet = NULL, BYTE nScript = 0, const Color* pBackConfigColor = NULL, const Color* pTextConfigColor = NULL ) const; /** Converts all Calc items contained in rSrcSet to edit engine items and puts them into rEditSet. */ static void FillToEditItemSet( SfxItemSet& rEditSet, const SfxItemSet& rSrcSet, const SfxItemSet* pCondSet = NULL ); /** Converts all Calc items contained in the own item set to edit engine items and puts them into pEditSet. */ void FillEditItemSet( SfxItemSet* pEditSet, const SfxItemSet* pCondSet = NULL ) const; /** Converts all edit engine items contained in rEditSet to Calc items and puts them into rDestSet. */ static void GetFromEditItemSet( SfxItemSet& rDestSet, const SfxItemSet& rEditSet ); /** Converts all edit engine items contained in pEditSet to Calc items and puts them into the own item set. */ void GetFromEditItemSet( const SfxItemSet* pEditSet ); void FillEditParaItems( SfxItemSet* pSet ) const; ScPatternAttr* PutInPool( ScDocument* pDestDoc, ScDocument* pSrcDoc ) const; void SetStyleSheet(ScStyleSheet* pNewStyle); const ScStyleSheet* GetStyleSheet() const { return pStyle; } const String* GetStyleName() const; void UpdateStyleSheet(); void StyleToName(); BOOL IsVisible() const; BOOL IsVisibleEqual( const ScPatternAttr& rOther ) const; /** If font is an old symbol font StarBats/StarMath with text encoding RTL_TEXTENC_SYMBOL */ BOOL IsSymbolFont() const; /** Create a FontToSubsFontConverter if needed for this pattern, else return 0. @param nFlags is the bit mask which shall be used for CreateFontToSubsFontConverter(). The converter must be destroyed by the caller using DestroyFontToSubsFontConverter() which should be accomplished using the ScFontToSubsFontConverter_AutoPtr */ FontToSubsFontConverter GetSubsFontConverter( ULONG nFlags ) const; ULONG GetNumberFormat( SvNumberFormatter* ) const; ULONG GetNumberFormat( SvNumberFormatter* pFormatter, const SfxItemSet* pCondSet ) const; long GetRotateVal( const SfxItemSet* pCondSet ) const; BYTE GetRotateDir( const SfxItemSet* pCondSet ) const; }; class ScFontToSubsFontConverter_AutoPtr { FontToSubsFontConverter h; void release() { if ( h ) DestroyFontToSubsFontConverter( h ); } // prevent usage ScFontToSubsFontConverter_AutoPtr( const ScFontToSubsFontConverter_AutoPtr& ); ScFontToSubsFontConverter_AutoPtr& operator=( const ScFontToSubsFontConverter_AutoPtr& ); public: ScFontToSubsFontConverter_AutoPtr() : h(0) {} ~ScFontToSubsFontConverter_AutoPtr() { release(); } ScFontToSubsFontConverter_AutoPtr& operator=( FontToSubsFontConverter hN ) { release(); h = hN; return *this; } operator FontToSubsFontConverter() const { return h; } }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.11.346); FILE MERGED 2005/09/05 15:00:53 rt 1.11.346.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: patattr.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:48:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_SCPATATR_HXX #define SC_SCPATATR_HXX #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SV_FONTCVT_HXX #include <vcl/fontcvt.hxx> #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif #ifndef INCLUDED_SCDLLAPI_H #include "scdllapi.h" #endif class Font; class OutputDevice; class Fraction; class ScStyleSheet; class SvNumberFormatter; class ScDocument; // how to treat COL_AUTO in GetFont: enum ScAutoFontColorMode { SC_AUTOCOL_RAW, // COL_AUTO is returned SC_AUTOCOL_BLACK, // always use black SC_AUTOCOL_PRINT, // black or white, depending on background SC_AUTOCOL_DISPLAY, // from style settings, or black/white if needed SC_AUTOCOL_IGNOREFONT, // like DISPLAY, but ignore stored font color (assume COL_AUTO) SC_AUTOCOL_IGNOREBACK, // like DISPLAY, but ignore stored background color (use configured color) SC_AUTOCOL_IGNOREALL // like DISPLAY, but ignore stored font and background colors }; class SC_DLLPUBLIC ScPatternAttr: public SfxSetItem { String* pName; ScStyleSheet* pStyle; public: static ScDocument* pDoc; ScPatternAttr(SfxItemSet* pItemSet, const String& rStyleName); ScPatternAttr(SfxItemSet* pItemSet, ScStyleSheet* pStyleSheet = NULL); ScPatternAttr(SfxItemPool* pItemPool); ScPatternAttr(const ScPatternAttr& rPatternAttr); ~ScPatternAttr(); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create(SvStream& rStream, USHORT nVersion) const; virtual SvStream& Store(SvStream& rStream, USHORT nItemVersion) const; virtual int operator==(const SfxPoolItem& rCmp) const; const SfxPoolItem& GetItem( USHORT nWhich ) const { return GetItemSet().Get(nWhich); } static const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet& rItemSet, const SfxItemSet* pCondSet ); const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet* pCondSet ) const; // pWhich sind keine Ranges, sondern einzelne IDs, 0-terminiert BOOL HasItemsSet( const USHORT* pWhich ) const; void ClearItems( const USHORT* pWhich ); void DeleteUnchanged( const ScPatternAttr* pOldAttrs ); static SvxCellOrientation GetCellOrientation( const SfxItemSet& rItemSet, const SfxItemSet* pCondSet = 0 ); SvxCellOrientation GetCellOrientation( const SfxItemSet* pCondSet = 0 ) const; /** Static helper function to fill a font object from the passed item set. */ static void GetFont( Font& rFont, const SfxItemSet& rItemSet, ScAutoFontColorMode eAutoMode, OutputDevice* pOutDev = NULL, const Fraction* pScale = NULL, const SfxItemSet* pCondSet = NULL, BYTE nScript = 0, const Color* pBackConfigColor = NULL, const Color* pTextConfigColor = NULL ); /** Fills a font object from the own item set. */ void GetFont( Font& rFont, ScAutoFontColorMode eAutoMode, OutputDevice* pOutDev = NULL, const Fraction* pScale = NULL, const SfxItemSet* pCondSet = NULL, BYTE nScript = 0, const Color* pBackConfigColor = NULL, const Color* pTextConfigColor = NULL ) const; /** Converts all Calc items contained in rSrcSet to edit engine items and puts them into rEditSet. */ static void FillToEditItemSet( SfxItemSet& rEditSet, const SfxItemSet& rSrcSet, const SfxItemSet* pCondSet = NULL ); /** Converts all Calc items contained in the own item set to edit engine items and puts them into pEditSet. */ void FillEditItemSet( SfxItemSet* pEditSet, const SfxItemSet* pCondSet = NULL ) const; /** Converts all edit engine items contained in rEditSet to Calc items and puts them into rDestSet. */ static void GetFromEditItemSet( SfxItemSet& rDestSet, const SfxItemSet& rEditSet ); /** Converts all edit engine items contained in pEditSet to Calc items and puts them into the own item set. */ void GetFromEditItemSet( const SfxItemSet* pEditSet ); void FillEditParaItems( SfxItemSet* pSet ) const; ScPatternAttr* PutInPool( ScDocument* pDestDoc, ScDocument* pSrcDoc ) const; void SetStyleSheet(ScStyleSheet* pNewStyle); const ScStyleSheet* GetStyleSheet() const { return pStyle; } const String* GetStyleName() const; void UpdateStyleSheet(); void StyleToName(); BOOL IsVisible() const; BOOL IsVisibleEqual( const ScPatternAttr& rOther ) const; /** If font is an old symbol font StarBats/StarMath with text encoding RTL_TEXTENC_SYMBOL */ BOOL IsSymbolFont() const; /** Create a FontToSubsFontConverter if needed for this pattern, else return 0. @param nFlags is the bit mask which shall be used for CreateFontToSubsFontConverter(). The converter must be destroyed by the caller using DestroyFontToSubsFontConverter() which should be accomplished using the ScFontToSubsFontConverter_AutoPtr */ FontToSubsFontConverter GetSubsFontConverter( ULONG nFlags ) const; ULONG GetNumberFormat( SvNumberFormatter* ) const; ULONG GetNumberFormat( SvNumberFormatter* pFormatter, const SfxItemSet* pCondSet ) const; long GetRotateVal( const SfxItemSet* pCondSet ) const; BYTE GetRotateDir( const SfxItemSet* pCondSet ) const; }; class ScFontToSubsFontConverter_AutoPtr { FontToSubsFontConverter h; void release() { if ( h ) DestroyFontToSubsFontConverter( h ); } // prevent usage ScFontToSubsFontConverter_AutoPtr( const ScFontToSubsFontConverter_AutoPtr& ); ScFontToSubsFontConverter_AutoPtr& operator=( const ScFontToSubsFontConverter_AutoPtr& ); public: ScFontToSubsFontConverter_AutoPtr() : h(0) {} ~ScFontToSubsFontConverter_AutoPtr() { release(); } ScFontToSubsFontConverter_AutoPtr& operator=( FontToSubsFontConverter hN ) { release(); h = hN; return *this; } operator FontToSubsFontConverter() const { return h; } }; #endif <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> #include <stdio.h> #include <stdlib.h> #include <vector> using namespace cv; using std::vector; int main(int argc, char** argv) { // Display usage if (argc < 5) { printf("Usage: %s <rows> <cols> <size> [cameras...]\n", argv[0]); return -1; } // Parse arguments int rows = atoi(argv[1]); int cols = atoi(argv[2]); float size = atof(argv[3]); // Open video capture devices vector<VideoCapture> devices; for (int i = 4; i < argc; i++) { int id = atoi(argv[i]); VideoCapture device(id); if (device.isOpened()) { devices.push_back(device); device.set(CV_CAP_PROP_FRAME_WIDTH, 1280); device.set(CV_CAP_PROP_FRAME_HEIGHT, 720); } else { std::cerr << "Failed to open video capture device " << id << std::endl; } } Mat frame, gray; while (true) { for (size_t i = 0; i < devices.size(); i++) { devices[i] >> frame; imshow(std::to_string(i), frame); } // Quit on escape keypress if (waitKey(16) >= 27) { break; } } } <commit_msg>Detect checkerboard corners<commit_after>#include <opencv2/opencv.hpp> #include <stdio.h> #include <stdlib.h> #include <vector> using namespace cv; using std::vector; int main(int argc, char** argv) { // Display usage if (argc < 5) { printf("Usage: %s <rows> <cols> <size> [cameras...]\n", argv[0]); return -1; } // Parse arguments int rows = atoi(argv[1]); int cols = atoi(argv[2]); float size = atof(argv[3]); // Open video capture devices vector<VideoCapture> devices; vector<vector<Point2f>> img_points; for (int i = 4; i < argc; i++) { int id = atoi(argv[i]); VideoCapture device(id); if (device.isOpened()) { devices.push_back(device); device.set(CV_CAP_PROP_FRAME_WIDTH, 1280); device.set(CV_CAP_PROP_FRAME_HEIGHT, 720); device.set(CV_CAP_PROP_FPS, 30); img_points.push_back(vector<Point2f>()); } else { std::cerr << "Failed to open video capture device " << id << std::endl; } } // Calibration variables Size checkerboard_size(cols, rows); int key = 0; Mat frame, gray; vector<Point2f> corners; while (key != 27) { // Quit on escape keypress for (size_t i = 0; i < devices.size(); i++) { devices[i] >> frame; // Detect checkerboards on spacebar if (waitKey(1) == 32) { cvtColor(frame, gray, COLOR_BGR2GRAY); bool found = findChessboardCorners(gray, checkerboard_size, corners); if (found) { std::cout << "Found checkerboard on " << i << std::endl; img_points[i].insert( std::end(img_points[i]), std::begin(corners), std::end(corners)); cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); } drawChessboardCorners(frame, checkerboard_size, Mat(corners), found); } imshow(std::to_string(i), frame); } key = waitKey(16); if (key == 'W') { // Write calibration to text files std::cout << "TODO Write to output" << std:: endl; } } } <|endoftext|>
<commit_before>#include <cassert> #include <algorithm> #include "jsobject.h" #include "property.h" #include "jsfunction.h" #include "jsval.h" #include "jsenv.h" #include "context.h" #include "class.h" namespace iv { namespace lv5 { JSObject::JSObject() : prototype_(NULL), class_name_(), extensible_(true), table_() { } JSObject::JSObject(JSObject* proto, Symbol class_name, bool extensible) : prototype_(proto), class_name_(class_name), extensible_(extensible), table_() { } #define TRY(context, sym, arg, error)\ do {\ const JSVal method = Get(context, sym, error);\ if (*error) {\ return JSUndefined;\ }\ if (method.IsCallable()) {\ const JSVal val = method.object()->AsCallable()->Call(arg, error);\ if (*error) {\ return JSUndefined;\ }\ if (val.IsPrimitive() || val.IsNull() || val.IsUndefined()) {\ return val;\ }\ }\ } while (0) JSVal JSObject::DefaultValue(Context* ctx, Hint::Object hint, Error* res) { const Arguments args(ctx, this); if (hint == Hint::STRING) { // hint is STRING TRY(ctx, ctx->toString_symbol(), args, res); TRY(ctx, ctx->valueOf_symbol(), args, res); } else { // section 8.12.8 // hint is NUMBER or NONE TRY(ctx, ctx->valueOf_symbol(), args, res); TRY(ctx, ctx->toString_symbol(), args, res); } res->Report(Error::Type, "invalid default value"); return JSUndefined; } #undef TRY JSVal JSObject::Get(Context* ctx, Symbol name, Error* res) { const PropertyDescriptor desc = GetProperty(ctx, name); if (desc.IsEmpty()) { return JSUndefined; } if (desc.IsDataDescriptor()) { return desc.AsDataDescriptor()->value(); } else { assert(desc.IsAccessorDescriptor()); JSObject* const getter = desc.AsAccessorDescriptor()->get(); if (getter) { return getter->AsCallable()->Call(Arguments(ctx, this), res); } else { return JSUndefined; } } } JSVal JSObject::GetWithIndex(Context* ctx, uint32_t index, Error* res) { return Get(ctx, ctx->InternIndex(index), res); } // not recursion PropertyDescriptor JSObject::GetProperty(Context* ctx, Symbol name) const { const JSObject* obj = this; do { const PropertyDescriptor prop = obj->GetOwnProperty(ctx, name); if (!prop.IsEmpty()) { return prop; } obj = obj->prototype(); } while (obj); return JSUndefined; } PropertyDescriptor JSObject::GetPropertyWithIndex(Context* ctx, uint32_t index) const { return GetProperty(ctx, ctx->InternIndex(index)); } PropertyDescriptor JSObject::GetOwnProperty(Context* ctx, Symbol name) const { const Properties::const_iterator it = table_.find(name); if (it == table_.end()) { return JSUndefined; } else { return it->second; } } PropertyDescriptor JSObject::GetOwnPropertyWithIndex(Context* ctx, uint32_t index) const { return GetOwnProperty(ctx, ctx->InternIndex(index)); } bool JSObject::CanPut(Context* ctx, Symbol name) const { const PropertyDescriptor desc = GetOwnProperty(ctx, name); if (!desc.IsEmpty()) { if (desc.IsAccessorDescriptor()) { return desc.AsAccessorDescriptor()->set(); } else { assert(desc.IsDataDescriptor()); return desc.AsDataDescriptor()->IsWritable(); } } if (!prototype_) { return extensible_; } const PropertyDescriptor inherited = prototype_->GetProperty(ctx, name); if (inherited.IsEmpty()) { return extensible_; } else { if (inherited.IsAccessorDescriptor()) { return inherited.AsAccessorDescriptor()->set(); } else { assert(inherited.IsDataDescriptor()); return inherited.AsDataDescriptor()->IsWritable(); } } } bool JSObject::CanPutWithIndex(Context* ctx, uint32_t index) const { return CanPut(ctx, ctx->InternIndex(index)); } #define REJECT(str)\ do {\ if (th) {\ res->Report(Error::Type, str);\ }\ return false;\ } while (0) bool JSObject::DefineOwnProperty(Context* ctx, Symbol name, const PropertyDescriptor& desc, bool th, Error* res) { // section 8.12.9 [[DefineOwnProperty]] const PropertyDescriptor current = GetOwnProperty(ctx, name); if (current.IsEmpty()) { if (!extensible_) { REJECT("object not extensible"); } else { if (!desc.IsAccessorDescriptor()) { assert(desc.IsDataDescriptor() || desc.IsGenericDescriptor()); table_[name] = PropertyDescriptor::SetDefault(desc); } else { assert(desc.IsAccessorDescriptor()); table_[name] = PropertyDescriptor::SetDefault(desc); } return true; } } // step 5 if (PropertyDescriptor::IsAbsent(desc)) { return true; } // step 6 if (PropertyDescriptor::Equals(desc, current)) { return true; } // step 7 if (!current.IsConfigurable()) { if (desc.IsConfigurable()) { REJECT( "changing [[Configurable]] of unconfigurable property not allowed"); } if (!desc.IsEnumerableAbsent() && current.IsEnumerable() != desc.IsEnumerable()) { REJECT("changing [[Enumerable]] of unconfigurable property not allowed"); } } // step 9 if (desc.IsGenericDescriptor()) { // no further validation } else if (current.type() != desc.type()) { if (!current.IsConfigurable()) { REJECT("changing descriptor type of unconfigurable property not allowed"); } if (current.IsDataDescriptor()) { assert(desc.IsAccessorDescriptor()); } else { assert(desc.IsDataDescriptor()); } } else { // step 10 if (current.IsDataDescriptor()) { assert(desc.IsDataDescriptor()); if (!current.IsConfigurable()) { if (!current.AsDataDescriptor()->IsWritable()) { const DataDescriptor* const data = desc.AsDataDescriptor(); if (data->IsWritable()) { REJECT( "changing [[Writable]] of unconfigurable property not allowed"); } if (SameValue(current.AsDataDescriptor()->value(), data->value())) { REJECT("changing [[Value]] of readonly property not allowed"); } } } } else { // step 11 assert(desc.IsAccessorDescriptor()); if (!current.IsConfigurableAbsent() && !current.IsConfigurable()) { const AccessorDescriptor* const lhs = current.AsAccessorDescriptor(); const AccessorDescriptor* const rhs = desc.AsAccessorDescriptor(); if ((lhs->set() && (lhs->set() != rhs->set())) || (lhs->get() && (lhs->get() != rhs->get()))) { REJECT("changing [[Set]] or [[Get]] " "of unconfigurable property not allowed"); } } } } table_[name] = PropertyDescriptor::Merge(desc, current); return true; } bool JSObject::DefineOwnPropertyWithIndex(Context* ctx, uint32_t index, const PropertyDescriptor& desc, bool th, Error* res) { return DefineOwnProperty(ctx, ctx->InternIndex(index), desc, th, res); } #undef REJECT void JSObject::Put(Context* ctx, Symbol name, const JSVal& val, bool th, Error* res) { if (!CanPut(ctx, name)) { if (th) { res->Report(Error::Type, "put failed"); } return; } const PropertyDescriptor own_desc = GetOwnProperty(ctx, name); if (!own_desc.IsEmpty() && own_desc.IsDataDescriptor()) { DefineOwnProperty(ctx, name, DataDescriptor( val, PropertyDescriptor::UNDEF_ENUMERABLE | PropertyDescriptor::UNDEF_CONFIGURABLE | PropertyDescriptor::UNDEF_WRITABLE), th, res); return; } const PropertyDescriptor desc = GetProperty(ctx, name); if (!desc.IsEmpty() && desc.IsAccessorDescriptor()) { const AccessorDescriptor* const accs = desc.AsAccessorDescriptor(); assert(accs->set()); Arguments args(ctx, 1); args.set_this_binding(this); args[0] = val; accs->set()->AsCallable()->Call(args, res); } else { DefineOwnProperty(ctx, name, DataDescriptor(val, PropertyDescriptor::WRITABLE | PropertyDescriptor::ENUMERABLE | PropertyDescriptor::CONFIGURABLE), th, res); } } void JSObject::PutWithIndex(Context* ctx, uint32_t index, const JSVal& val, bool th, Error* res) { Put(ctx, ctx->InternIndex(index), val, th, res); } bool JSObject::HasProperty(Context* ctx, Symbol name) const { return !GetProperty(ctx, name).IsEmpty(); } bool JSObject::HasPropertyWithIndex(Context* ctx, uint32_t index) const { return HasProperty(ctx, ctx->InternIndex(index)); } bool JSObject::Delete(Context* ctx, Symbol name, bool th, Error* res) { const PropertyDescriptor desc = GetOwnProperty(ctx, name); if (desc.IsEmpty()) { return true; } if (desc.IsConfigurable()) { table_.erase(name); return true; } else { if (th) { res->Report(Error::Type, "delete failed"); } return false; } } bool JSObject::DeleteWithIndex(Context* ctx, uint32_t index, bool th, Error* res) { return Delete(ctx, ctx->InternIndex(index), th, res); } void JSObject::GetPropertyNames(Context* ctx, std::vector<Symbol>* vec, EnumerationMode mode) const { using std::find; GetOwnPropertyNames(ctx, vec, mode); const JSObject* obj = prototype_; while (obj) { obj->GetOwnPropertyNames(ctx, vec, mode); obj = obj->prototype(); } } void JSObject::GetOwnPropertyNames(Context* ctx, std::vector<Symbol>* vec, EnumerationMode mode) const { using std::find; if (vec->empty()) { for (JSObject::Properties::const_iterator it = table_.begin(), last = table_.end(); it != last; ++it) { if (it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) { vec->push_back(it->first); } } } else { for (JSObject::Properties::const_iterator it = table_.begin(), last = table_.end(); it != last; ++it) { if ((it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) && (find(vec->begin(), vec->end(), it->first) == vec->end())) { vec->push_back(it->first); } } } } JSObject* JSObject::New(Context* ctx) { JSObject* const obj = NewPlain(ctx); const Symbol name = ctx->Intern("Object"); const Class& cls = ctx->Cls(name); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSObject* JSObject::NewPlain(Context* ctx) { return new JSObject(); } JSStringObject::JSStringObject(Context* ctx, JSString* value) : value_(value) { DefineOwnProperty(ctx, ctx->length_symbol(), DataDescriptor(value->size(), PropertyDescriptor::NONE), false, ctx->error()); } JSStringObject* JSStringObject::New(Context* ctx, JSString* str) { JSStringObject* const obj = new JSStringObject(ctx, str); const Symbol name = ctx->Intern("String"); const Class& cls = ctx->Cls(name); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSStringObject* JSStringObject::NewPlain(Context* ctx) { return new JSStringObject(ctx, JSString::NewEmptyString(ctx)); } JSNumberObject* JSNumberObject::New(Context* ctx, const double& value) { JSNumberObject* const obj = new JSNumberObject(value); const Class& cls = ctx->Cls("Number"); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSNumberObject* JSNumberObject::NewPlain(Context* ctx, const double& value) { return new JSNumberObject(value); } JSBooleanObject* JSBooleanObject::NewPlain(Context* ctx, bool value) { return new JSBooleanObject(value); } JSBooleanObject* JSBooleanObject::New(Context* ctx, bool value) { JSBooleanObject* const obj = new JSBooleanObject(value); const Class& cls = ctx->Cls(ctx->Intern("Boolean")); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } } } // namespace iv::lv5 <commit_msg>fix 2<commit_after>#include <cassert> #include <algorithm> #include "jsobject.h" #include "property.h" #include "jsfunction.h" #include "jsval.h" #include "jsenv.h" #include "context.h" #include "class.h" namespace iv { namespace lv5 { JSObject::JSObject() : prototype_(NULL), class_name_(), extensible_(true), table_() { } JSObject::JSObject(JSObject* proto, Symbol class_name, bool extensible) : prototype_(proto), class_name_(class_name), extensible_(extensible), table_() { } #define TRY(context, sym, arg, error)\ do {\ const JSVal method = Get(context, sym, error);\ if (*error) {\ return JSUndefined;\ }\ if (method.IsCallable()) {\ const JSVal val = method.object()->AsCallable()->Call(arg, error);\ if (*error) {\ return JSUndefined;\ }\ if (val.IsPrimitive() || val.IsNull() || val.IsUndefined()) {\ return val;\ }\ }\ } while (0) JSVal JSObject::DefaultValue(Context* ctx, Hint::Object hint, Error* res) { const Arguments args(ctx, this); if (hint == Hint::STRING) { // hint is STRING TRY(ctx, ctx->toString_symbol(), args, res); TRY(ctx, ctx->valueOf_symbol(), args, res); } else { // section 8.12.8 // hint is NUMBER or NONE TRY(ctx, ctx->valueOf_symbol(), args, res); TRY(ctx, ctx->toString_symbol(), args, res); } res->Report(Error::Type, "invalid default value"); return JSUndefined; } #undef TRY JSVal JSObject::Get(Context* ctx, Symbol name, Error* res) { const PropertyDescriptor desc = GetProperty(ctx, name); if (desc.IsEmpty()) { return JSUndefined; } if (desc.IsDataDescriptor()) { return desc.AsDataDescriptor()->value(); } else { assert(desc.IsAccessorDescriptor()); JSObject* const getter = desc.AsAccessorDescriptor()->get(); if (getter) { return getter->AsCallable()->Call(Arguments(ctx, this), res); } else { return JSUndefined; } } } JSVal JSObject::GetWithIndex(Context* ctx, uint32_t index, Error* res) { return Get(ctx, ctx->InternIndex(index), res); } // not recursion PropertyDescriptor JSObject::GetProperty(Context* ctx, Symbol name) const { const JSObject* obj = this; do { const PropertyDescriptor prop = obj->GetOwnProperty(ctx, name); if (!prop.IsEmpty()) { return prop; } obj = obj->prototype(); } while (obj); return JSUndefined; } PropertyDescriptor JSObject::GetPropertyWithIndex(Context* ctx, uint32_t index) const { return GetProperty(ctx, ctx->InternIndex(index)); } PropertyDescriptor JSObject::GetOwnProperty(Context* ctx, Symbol name) const { const Properties::const_iterator it = table_.find(name); if (it == table_.end()) { return JSUndefined; } else { return it->second; } } PropertyDescriptor JSObject::GetOwnPropertyWithIndex(Context* ctx, uint32_t index) const { return GetOwnProperty(ctx, ctx->InternIndex(index)); } bool JSObject::CanPut(Context* ctx, Symbol name) const { const PropertyDescriptor desc = GetOwnProperty(ctx, name); if (!desc.IsEmpty()) { if (desc.IsAccessorDescriptor()) { return desc.AsAccessorDescriptor()->set(); } else { assert(desc.IsDataDescriptor()); return desc.AsDataDescriptor()->IsWritable(); } } if (!prototype_) { return extensible_; } const PropertyDescriptor inherited = prototype_->GetProperty(ctx, name); if (inherited.IsEmpty()) { return extensible_; } else { if (inherited.IsAccessorDescriptor()) { return inherited.AsAccessorDescriptor()->set(); } else { assert(inherited.IsDataDescriptor()); return inherited.AsDataDescriptor()->IsWritable(); } } } bool JSObject::CanPutWithIndex(Context* ctx, uint32_t index) const { return CanPut(ctx, ctx->InternIndex(index)); } #define REJECT(str)\ do {\ if (th) {\ res->Report(Error::Type, str);\ }\ return false;\ } while (0) bool JSObject::DefineOwnProperty(Context* ctx, Symbol name, const PropertyDescriptor& desc, bool th, Error* res) { // section 8.12.9 [[DefineOwnProperty]] const PropertyDescriptor current = GetOwnProperty(ctx, name); if (current.IsEmpty()) { if (!extensible_) { REJECT("object not extensible"); } else { if (!desc.IsAccessorDescriptor()) { assert(desc.IsDataDescriptor() || desc.IsGenericDescriptor()); table_[name] = PropertyDescriptor::SetDefault(desc); } else { assert(desc.IsAccessorDescriptor()); table_[name] = PropertyDescriptor::SetDefault(desc); } return true; } } // step 5 if (PropertyDescriptor::IsAbsent(desc)) { return true; } // step 6 if (PropertyDescriptor::Equals(desc, current)) { return true; } // step 7 if (!current.IsConfigurable()) { if (desc.IsConfigurable()) { REJECT( "changing [[Configurable]] of unconfigurable property not allowed"); } if (!desc.IsEnumerableAbsent() && current.IsEnumerable() != desc.IsEnumerable()) { REJECT("changing [[Enumerable]] of unconfigurable property not allowed"); } } // step 9 if (desc.IsGenericDescriptor()) { // no further validation } else if (current.type() != desc.type()) { if (!current.IsConfigurable()) { REJECT("changing descriptor type of unconfigurable property not allowed"); } if (current.IsDataDescriptor()) { assert(desc.IsAccessorDescriptor()); } else { assert(desc.IsDataDescriptor()); } } else { // step 10 if (current.IsDataDescriptor()) { assert(desc.IsDataDescriptor()); if (!current.IsConfigurable()) { if (!current.AsDataDescriptor()->IsWritable()) { const DataDescriptor* const data = desc.AsDataDescriptor(); if (data->IsWritable()) { REJECT( "changing [[Writable]] of unconfigurable property not allowed"); } if (SameValue(current.AsDataDescriptor()->value(), data->value())) { REJECT("changing [[Value]] of readonly property not allowed"); } } } } else { // step 11 assert(desc.IsAccessorDescriptor()); if (!current.IsConfigurableAbsent() && !current.IsConfigurable()) { const AccessorDescriptor* const lhs = current.AsAccessorDescriptor(); const AccessorDescriptor* const rhs = desc.AsAccessorDescriptor(); if ((rhs->set() && (lhs->set() != rhs->set())) || (rhs->get() && (lhs->get() != rhs->get()))) { REJECT("changing [[Set]] or [[Get]] " "of unconfigurable property not allowed"); } } } } table_[name] = PropertyDescriptor::Merge(desc, current); return true; } bool JSObject::DefineOwnPropertyWithIndex(Context* ctx, uint32_t index, const PropertyDescriptor& desc, bool th, Error* res) { return DefineOwnProperty(ctx, ctx->InternIndex(index), desc, th, res); } #undef REJECT void JSObject::Put(Context* ctx, Symbol name, const JSVal& val, bool th, Error* res) { if (!CanPut(ctx, name)) { if (th) { res->Report(Error::Type, "put failed"); } return; } const PropertyDescriptor own_desc = GetOwnProperty(ctx, name); if (!own_desc.IsEmpty() && own_desc.IsDataDescriptor()) { DefineOwnProperty(ctx, name, DataDescriptor( val, PropertyDescriptor::UNDEF_ENUMERABLE | PropertyDescriptor::UNDEF_CONFIGURABLE | PropertyDescriptor::UNDEF_WRITABLE), th, res); return; } const PropertyDescriptor desc = GetProperty(ctx, name); if (!desc.IsEmpty() && desc.IsAccessorDescriptor()) { const AccessorDescriptor* const accs = desc.AsAccessorDescriptor(); assert(accs->set()); Arguments args(ctx, 1); args.set_this_binding(this); args[0] = val; accs->set()->AsCallable()->Call(args, res); } else { DefineOwnProperty(ctx, name, DataDescriptor(val, PropertyDescriptor::WRITABLE | PropertyDescriptor::ENUMERABLE | PropertyDescriptor::CONFIGURABLE), th, res); } } void JSObject::PutWithIndex(Context* ctx, uint32_t index, const JSVal& val, bool th, Error* res) { Put(ctx, ctx->InternIndex(index), val, th, res); } bool JSObject::HasProperty(Context* ctx, Symbol name) const { return !GetProperty(ctx, name).IsEmpty(); } bool JSObject::HasPropertyWithIndex(Context* ctx, uint32_t index) const { return HasProperty(ctx, ctx->InternIndex(index)); } bool JSObject::Delete(Context* ctx, Symbol name, bool th, Error* res) { const PropertyDescriptor desc = GetOwnProperty(ctx, name); if (desc.IsEmpty()) { return true; } if (desc.IsConfigurable()) { table_.erase(name); return true; } else { if (th) { res->Report(Error::Type, "delete failed"); } return false; } } bool JSObject::DeleteWithIndex(Context* ctx, uint32_t index, bool th, Error* res) { return Delete(ctx, ctx->InternIndex(index), th, res); } void JSObject::GetPropertyNames(Context* ctx, std::vector<Symbol>* vec, EnumerationMode mode) const { using std::find; GetOwnPropertyNames(ctx, vec, mode); const JSObject* obj = prototype_; while (obj) { obj->GetOwnPropertyNames(ctx, vec, mode); obj = obj->prototype(); } } void JSObject::GetOwnPropertyNames(Context* ctx, std::vector<Symbol>* vec, EnumerationMode mode) const { using std::find; if (vec->empty()) { for (JSObject::Properties::const_iterator it = table_.begin(), last = table_.end(); it != last; ++it) { if (it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) { vec->push_back(it->first); } } } else { for (JSObject::Properties::const_iterator it = table_.begin(), last = table_.end(); it != last; ++it) { if ((it->second.IsEnumerable() || (mode == kIncludeNotEnumerable)) && (find(vec->begin(), vec->end(), it->first) == vec->end())) { vec->push_back(it->first); } } } } JSObject* JSObject::New(Context* ctx) { JSObject* const obj = NewPlain(ctx); const Symbol name = ctx->Intern("Object"); const Class& cls = ctx->Cls(name); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSObject* JSObject::NewPlain(Context* ctx) { return new JSObject(); } JSStringObject::JSStringObject(Context* ctx, JSString* value) : value_(value) { DefineOwnProperty(ctx, ctx->length_symbol(), DataDescriptor(value->size(), PropertyDescriptor::NONE), false, ctx->error()); } JSStringObject* JSStringObject::New(Context* ctx, JSString* str) { JSStringObject* const obj = new JSStringObject(ctx, str); const Symbol name = ctx->Intern("String"); const Class& cls = ctx->Cls(name); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSStringObject* JSStringObject::NewPlain(Context* ctx) { return new JSStringObject(ctx, JSString::NewEmptyString(ctx)); } JSNumberObject* JSNumberObject::New(Context* ctx, const double& value) { JSNumberObject* const obj = new JSNumberObject(value); const Class& cls = ctx->Cls("Number"); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } JSNumberObject* JSNumberObject::NewPlain(Context* ctx, const double& value) { return new JSNumberObject(value); } JSBooleanObject* JSBooleanObject::NewPlain(Context* ctx, bool value) { return new JSBooleanObject(value); } JSBooleanObject* JSBooleanObject::New(Context* ctx, bool value) { JSBooleanObject* const obj = new JSBooleanObject(value); const Class& cls = ctx->Cls(ctx->Intern("Boolean")); obj->set_class_name(cls.name); obj->set_prototype(cls.prototype); return obj; } } } // namespace iv::lv5 <|endoftext|>
<commit_before>/* Copyright 2014 Google Inc. 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 <cstdlib> #include <iostream> #include <fstream> #include <vector> extern "C" { #include "libjsonnet.h" } std::string next_arg(unsigned &i, const std::vector<std::string> &args) { i++; if (i >= args.size()) { std::cerr << "Expected another commandline argument." << std::endl; exit(EXIT_FAILURE); } return args[i]; } /** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */ std::vector<std::string> simplify_args (int argc, const char **argv) { std::vector<std::string> r; for (int i=1 ; i<argc ; ++i) { std::string arg = argv[i]; if (arg == "--") { // Add this arg and all remaining ones without simplification. r.push_back(arg); while ((++i) < argc) r.push_back(argv[i]); break; } // Check if it is of the form -abc and convert to -a -b -c if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') { for (unsigned j=1 ; j<arg.length() ; ++j) { r.push_back("-" + arg.substr(j,1)); } } else { r.push_back(arg); } } return r; } void usage(std::ostream &o) { o << "Usage:\n"; o << "jsonnet {<option>} [<filename>]\n"; o << "where <filename> defaults to - (stdin)\n"; o << "and <option> can be:\n"; o << " -h / --help This message\n"; o << " -e / --exec Treat filename as code (requires explicit filename)\n"; o << " -E --env Add an environment variable\n\n"; o << " -s / --max-stack <n> Number of allowed stack frames\n"; o << " -t / --max-trace <n> Max length of stack trace before cropping\n"; o << " --gc-min-objects Do not run garbage collector until this many\n"; o << " --gc-growth-trigger Run garbage collector after this amount of object growth\n"; o << " --debug-ast Unparse the parsed AST without executing it\n\n"; o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n"; o << "The -- option suppresses option processing. Note that since jsonnet programs can\n"; o << "begin with -, it is advised to use -- with -e if the program is unknown."; o << std::endl; } long strtol_check(const std::string &str) { const char *arg = str.c_str(); char *ep; long r = std::strtol(arg, &ep, 10); if (*ep != '\0' || *arg == '\0') { std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } return r; } int main(int argc, const char **argv) { JsonnetVM *vm = jsonnet_make(); std::string filename = "-"; bool filename_is_code = false; auto args = simplify_args(argc, argv); std::vector<std::string> remaining_args; for (unsigned i=0 ; i<args.size() ; ++i) { const std::string &arg = args[i]; if (arg == "-h" || arg == "--help") { usage(std::cout); exit(EXIT_SUCCESS); } else if (arg == "-s" || arg == "--max-stack") { long l = strtol_check(next_arg(i, args)); if (l < 1) { std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_max_stack(vm, l); } else if (arg == "-E" || arg == "--env") { const std::string &var = next_arg(i, args); const char *val = ::getenv(var.c_str()); if (val == nullptr) { std::cerr << "ERROR: Environment variable " << var << " was undefined." << std::endl; exit(EXIT_FAILURE); } jsonnet_env(vm, var.c_str(), val); } else if (arg == "--gc-min-objects") { long l = strtol_check(next_arg(i, args)); if (l < 0) { std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_gc_min_objects(vm, l); } else if (arg == "-t" || arg == "--max-trace") { long l = strtol_check(next_arg(i, args)); if (l < 0) { std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_max_trace(vm, l); } else if (arg == "--gc-growth-trigger") { const char *arg = next_arg(i,args).c_str(); char *ep; double v = std::strtod(arg, &ep); if (*ep != '\0' || *arg == '\0') { std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } if (v < 0) { std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_gc_growth_trigger(vm, v); } else if (arg == "-e" || arg == "--exec") { filename_is_code = true; } else if (arg == "--debug-ast") { jsonnet_debug_ast(vm, true); } else if (arg == "--") { // All subsequent args are not options. while ((++i) < args.size()) remaining_args.push_back(args[i]); break; } else { remaining_args.push_back(args[i]); } } if (remaining_args.size() > 0) filename = remaining_args[0]; if (remaining_args.size() > 1) { std::cerr << "ERROR: Filename already specified as \"" << filename << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } if (filename_is_code && remaining_args.size() == 0) { std::cerr << "ERROR: Must give filename when using -e, --exec\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } std::string input; if (filename_is_code) { input = filename; filename = "<cmdline>"; } else { if (filename == "-") { filename = "<stdin>"; input.assign(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()); } else { std::ifstream f; f.open(filename.c_str()); if (!f.good()) { std::string msg = "Opening input file: " + filename; perror(msg.c_str()); return EXIT_FAILURE; } input.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()); if (!f.good()) { std::string msg = "Reading input file: " + filename; perror(msg.c_str()); return EXIT_FAILURE; } } } int error; const char *output = jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error); if (error) { std::cerr << output; std::cerr.flush(); jsonnet_cleanup_string(vm, output); jsonnet_destroy(vm); return EXIT_FAILURE; } std::cout << output; std::cout.flush(); jsonnet_cleanup_string(vm, output); jsonnet_destroy(vm); return EXIT_SUCCESS; } <commit_msg>Fix --help output<commit_after>/* Copyright 2014 Google Inc. 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 <cstdlib> #include <iostream> #include <fstream> #include <vector> extern "C" { #include "libjsonnet.h" } std::string next_arg(unsigned &i, const std::vector<std::string> &args) { i++; if (i >= args.size()) { std::cerr << "Expected another commandline argument." << std::endl; exit(EXIT_FAILURE); } return args[i]; } /** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */ std::vector<std::string> simplify_args (int argc, const char **argv) { std::vector<std::string> r; for (int i=1 ; i<argc ; ++i) { std::string arg = argv[i]; if (arg == "--") { // Add this arg and all remaining ones without simplification. r.push_back(arg); while ((++i) < argc) r.push_back(argv[i]); break; } // Check if it is of the form -abc and convert to -a -b -c if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') { for (unsigned j=1 ; j<arg.length() ; ++j) { r.push_back("-" + arg.substr(j,1)); } } else { r.push_back(arg); } } return r; } void usage(std::ostream &o) { o << "Usage:\n"; o << "jsonnet {<option>} [<filename>]\n"; o << "where <filename> defaults to - (stdin)\n"; o << "and <option> can be:\n"; o << " -h / --help This message\n"; o << " -e / --exec Treat filename as code (requires explicit filename)\n"; o << " -E / --env Add an environment variable\n\n"; o << " -s / --max-stack <n> Number of allowed stack frames\n"; o << " -t / --max-trace <n> Max length of stack trace before cropping\n"; o << " --gc-min-objects <n> Do not run garbage collector until this many\n"; o << " --gc-growth-trigger <n> Run garbage collector after this amount of object growth\n"; o << " --debug-ast Unparse the parsed AST without executing it\n\n"; o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n"; o << "The -- option suppresses option processing. Note that since jsonnet programs can\n"; o << "begin with -, it is advised to use -- with -e if the program is unknown."; o << std::endl; } long strtol_check(const std::string &str) { const char *arg = str.c_str(); char *ep; long r = std::strtol(arg, &ep, 10); if (*ep != '\0' || *arg == '\0') { std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } return r; } int main(int argc, const char **argv) { JsonnetVM *vm = jsonnet_make(); std::string filename = "-"; bool filename_is_code = false; auto args = simplify_args(argc, argv); std::vector<std::string> remaining_args; for (unsigned i=0 ; i<args.size() ; ++i) { const std::string &arg = args[i]; if (arg == "-h" || arg == "--help") { usage(std::cout); exit(EXIT_SUCCESS); } else if (arg == "-s" || arg == "--max-stack") { long l = strtol_check(next_arg(i, args)); if (l < 1) { std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_max_stack(vm, l); } else if (arg == "-E" || arg == "--env") { const std::string &var = next_arg(i, args); const char *val = ::getenv(var.c_str()); if (val == nullptr) { std::cerr << "ERROR: Environment variable " << var << " was undefined." << std::endl; exit(EXIT_FAILURE); } jsonnet_env(vm, var.c_str(), val); } else if (arg == "--gc-min-objects") { long l = strtol_check(next_arg(i, args)); if (l < 0) { std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_gc_min_objects(vm, l); } else if (arg == "-t" || arg == "--max-trace") { long l = strtol_check(next_arg(i, args)); if (l < 0) { std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_max_trace(vm, l); } else if (arg == "--gc-growth-trigger") { const char *arg = next_arg(i,args).c_str(); char *ep; double v = std::strtod(arg, &ep); if (*ep != '\0' || *arg == '\0') { std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } if (v < 0) { std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } jsonnet_gc_growth_trigger(vm, v); } else if (arg == "-e" || arg == "--exec") { filename_is_code = true; } else if (arg == "--debug-ast") { jsonnet_debug_ast(vm, true); } else if (arg == "--") { // All subsequent args are not options. while ((++i) < args.size()) remaining_args.push_back(args[i]); break; } else { remaining_args.push_back(args[i]); } } if (remaining_args.size() > 0) filename = remaining_args[0]; if (remaining_args.size() > 1) { std::cerr << "ERROR: Filename already specified as \"" << filename << "\"\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } if (filename_is_code && remaining_args.size() == 0) { std::cerr << "ERROR: Must give filename when using -e, --exec\n" << std::endl; usage(std::cerr); exit(EXIT_FAILURE); } std::string input; if (filename_is_code) { input = filename; filename = "<cmdline>"; } else { if (filename == "-") { filename = "<stdin>"; input.assign(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()); } else { std::ifstream f; f.open(filename.c_str()); if (!f.good()) { std::string msg = "Opening input file: " + filename; perror(msg.c_str()); return EXIT_FAILURE; } input.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()); if (!f.good()) { std::string msg = "Reading input file: " + filename; perror(msg.c_str()); return EXIT_FAILURE; } } } int error; const char *output = jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error); if (error) { std::cerr << output; std::cerr.flush(); jsonnet_cleanup_string(vm, output); jsonnet_destroy(vm); return EXIT_FAILURE; } std::cout << output; std::cout.flush(); jsonnet_cleanup_string(vm, output); jsonnet_destroy(vm); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <iostream> #include <math.h> #include <stdio.h> using namespace cv; using namespace std; int main() { //char dir[100]={"/home/sedrica/Desktop/images.jpg"}; Mat img; img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct Mat img_bw; cvtColor(img, img_bw,COLOR_RGB2GRAY); // conversion to greayscale /* note: we may have to either pre process the image or not work with the custom bgr to greyscale or both as they might not be able to detect edge very well */ Mat grad_x, grad_y; // derivative along x and y direction respectively Mat square_grad_x, square_grad_y; // absoute value of derivative /// Gradient along X direction Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT ); /// Gradient along y direction Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT ); square_grad_y=grad_y.mul(grad_y); square_grad_x=grad_x.mul(grad_x); Mat img_edge; addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge); // more weight is provided in the horizontal direction for more importance to lane detection Mat img_edge_dilated; Point anchor=Point(-1,-1); Size str_elem_dim_11; str_elem_dim_11=Size(11,11); Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor); dilate(img_edge,img_edge_dilated,rect_str_elem); /* Mat img_eroded; Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor); erode( img_edge_dilated,img_eroded,circ_str_elem); */ Mat img_flood_fill; Point origin=Point(0,0); // is this have to be origin or (-1,-1) ? floodFill(img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4); /// got an issue with arguments SCALAR Mat img_openloops_removed; morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem); // <------ confirm it Mat img_small_closedloops_removed; morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_OPENCLOSED,rect_str_elem); // comfirm it Mat img_erode_post_fill1;img_erode_post_erode; erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem); erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem); Mat img_final_filled; floodFill(img_final_filled,origin,Scalar(255),); /// got an issue with arguments SCALAR //////////////////////////////////////////////////////////////////////////// int connected_components_count; Mat img_label; connected_components_count=onnectedComponents(img_final_filled,img_label,8,int ltype=cv_32s); Mat label; label = // add matlab labelmatrix function equivalent of opencv Mat final_color_segmented; applyColorMap(label,final_color_segmented, COLORMAP_JET); return 0; } <commit_msg>flood fill 2<commit_after>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <iostream> #include <math.h> #include <stdio.h> using namespace cv; using namespace std; int main() { //char dir[100]={"/home/sedrica/Desktop/images.jpg"}; Mat img; img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct Mat img_bw; cvtColor(img, img_bw,COLOR_RGB2GRAY); // conversion to greayscale /* note: we may have to either pre process the image or not work with the custom bgr to greyscale or both as they might not be able to detect edge very well */ Mat grad_x, grad_y; // derivative along x and y direction respectively Mat square_grad_x, square_grad_y; // absoute value of derivative /// Gradient along X direction Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT ); /// Gradient along y direction Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT ); square_grad_y=grad_y.mul(grad_y); square_grad_x=grad_x.mul(grad_x); Mat img_edge; addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge); // more weight is provided in the horizontal direction for more importance to lane detection Mat img_edge_dilated; Point anchor=Point(-1,-1); Size str_elem_dim_11; str_elem_dim_11=Size(11,11); Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor); dilate(img_edge,img_edge_dilated,rect_str_elem); /* Mat img_eroded; Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor); erode( img_edge_dilated,img_eroded,circ_str_elem); */ Mat img_flood_fill; Point origin=Point(0,0); // is this have to be origin or (-1,-1) ? floodFill(img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4); /// got an issue with arguments SCALAR Mat img_openloops_removed; morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem); // <------ confirm it Mat img_small_closedloops_removed; morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_OPENCLOSED,rect_str_elem); // comfirm it Mat img_erode_post_fill1;img_erode_post_erode; erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem); erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem); Mat img_final_filled; floodFill(img_final_filled,origin,Scalar(255),0,Scalar(),Scalar(),4); /// got an issue with arguments SCALAR //////////////////////////////////////////////////////////////////////////// int connected_components_count; Mat img_label; connected_components_count=onnectedComponents(img_final_filled,img_label,8,int ltype=cv_32s); Mat label; label = // add matlab labelmatrix function equivalent of opencv Mat final_color_segmented; applyColorMap(label,final_color_segmented, COLORMAP_JET); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRawImageReadWrite.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImage.h" // Include generic Input Source #include "itkImageFileReader.h" // Incluide generic Output Sink #include "itkImageFileWriter.h" // Include file-format specific readers/writers #include "itkRawImageIO.h" int main(int argc, char **argv) { // Taking parameters from the command line if( argc < 6 ) { std::cerr << std::endl; std::cerr << "Usage: RawImageReadWrite inputImageFile.raw sizeX sizeY sizeZ outputImageFile.raw" << std::endl; std::cerr << std::endl; return -1; } const char * inputFileName = argv[1]; const char * outputFileName = argv[5]; const unsigned int nx = atoi( argv[2] ); const unsigned int ny = atoi( argv[3] ); const unsigned int nz = atoi( argv[4] ); typedef unsigned char PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; // Read a Raw File typedef itk::ImageFileReader< ImageType > FileSourceType; typedef itk::RawImageIO<PixelType,Dimension> RawReaderType; FileSourceType::Pointer fileSource = FileSourceType::New(); fileSource->SetFileName( inputFileName ); RawReaderType::Pointer rawReader = RawReaderType::New(); rawReader->SetDimensions( 0, nx ); rawReader->SetDimensions( 1, ny ); rawReader->SetDimensions( 2, nz ); fileSource->SetImageIO( rawReader ); try { fileSource->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during Raw file reading " << std::endl; std::cerr << e << std::endl; return -1; } std::cout << "File succesfully read ! " << std::endl; // Print information about the image ImageType::Pointer image = fileSource->GetOutput(); image->Print( std::cout ); // Write a Raw File typedef itk::ImageFileWriter< ImageType > FileSinkType; typedef itk::RawImageIO<PixelType,Dimension> RawWriterType; FileSinkType::Pointer fileSink = FileSinkType::New(); RawWriterType::Pointer rawWriter = RawWriterType::New(); fileSink->SetImageIO( rawWriter ); fileSink->SetFileName( outputFileName ); fileSink->SetInput( image ); try { fileSink->Write(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during Raw file writing " << std::endl; std::cerr << e << std::endl; return -1; } std::cout << "File succesfully writen ! " << std::endl; return 0; } <commit_msg>FIX: FileDimensionality( 3 ) was missing. Print's removed.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRawImageReadWrite.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImage.h" // Include generic Input Source #include "itkImageFileReader.h" // Incluide generic Output Sink #include "itkImageFileWriter.h" // Include file-format specific readers/writers #include "itkRawImageIO.h" int main(int argc, char **argv) { // Taking parameters from the command line if( argc < 6 ) { std::cerr << std::endl; std::cerr << "Usage: RawImageReadWrite inputImageFile.raw sizeX sizeY sizeZ outputImageFile.raw" << std::endl; std::cerr << std::endl; return -1; } const char * inputFileName = argv[1]; const char * outputFileName = argv[5]; const unsigned int nx = atoi( argv[2] ); const unsigned int ny = atoi( argv[3] ); const unsigned int nz = atoi( argv[4] ); typedef unsigned char PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; // Read a Raw File typedef itk::ImageFileReader< ImageType > FileSourceType; typedef itk::RawImageIO<PixelType,Dimension> RawReaderType; FileSourceType::Pointer fileSource = FileSourceType::New(); fileSource->SetFileName( inputFileName ); RawReaderType::Pointer rawReader = RawReaderType::New(); rawReader->SetFileDimensionality( 3 ); rawReader->SetDimensions( 0, nx ); rawReader->SetDimensions( 1, ny ); rawReader->SetDimensions( 2, nz ); fileSource->SetImageIO( rawReader ); try { fileSource->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during Raw file reading " << std::endl; std::cerr << e << std::endl; return -1; } std::cout << "File succesfully read ! " << std::endl; // Write a Raw File typedef itk::ImageFileWriter< ImageType > FileSinkType; typedef itk::RawImageIO<PixelType,Dimension> RawWriterType; FileSinkType::Pointer fileSink = FileSinkType::New(); RawWriterType::Pointer rawWriter = RawWriterType::New(); fileSink->SetImageIO( rawWriter ); fileSink->SetFileName( outputFileName ); fileSink->SetInput( fileSource->GetOutput() ); try { fileSink->Write(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during Raw file writing " << std::endl; std::cerr << e << std::endl; return -1; } std::cout << "File succesfully writen ! " << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (2015) Gustav #include "ride/builtinthemes.h" #include <string> typedef google::protobuf::RepeatedPtrField<ride::Theme> ThemeList; ride::Theme* GetOrCreateTheme(ThemeList* themes, const std::string& name) { for (ride::Theme& t : *themes) { if (t.name() == name) return &t; } ride::Theme* temp = themes->Add(); temp->set_name(name); temp->set_can_remove(false); return temp; } ride::Color Color(google::protobuf::int32 r, google::protobuf::int32 g, google::protobuf::int32 b) { ride::Color c; c.set_r(r); c.set_g(g); c.set_b(b); return c; } ride::Color Color(google::protobuf::int32 c) { return Color(c, c, c); } ride::Style Style(ride::Color* front, ride::Color* back = NULL, bool bold = false) { ride::Style style; if (front) { style.set_use_foreground(true); style.set_allocated_foreground(front); } if (back) { style.set_use_background(true); style.set_allocated_background(back); } if (bold) { style.set_use_bold(true); style.set_bold(true); } return style; } template <typename T> T* New(const T& t) { return new T(t); } ride::Indicator Indicator(const ride::Color& c) { ride::Indicator ind; ind.set_allocated_foreground(New(c)); return ind; } ////////////////////////////////////////////////////////////////////////// class BasicThemeBuilder { public: BasicThemeBuilder& set_selection_foreground(const ride::Color& c) { selection_foreground_ = c; return *this; } BasicThemeBuilder& set_selection_background(const ride::Color& c) { selection_background_ = c; return *this; } BasicThemeBuilder& set_front(const ride::Color& c) { front_ = c; return *this; } BasicThemeBuilder& set_bkg(const ride::Color& c) { bkg_ = c; return *this; } BasicThemeBuilder& set_fold_hi(const ride::Color& c) { fold_hi_ = c; return *this; } BasicThemeBuilder& set_fold_lo(const ride::Color& c) { fold_lo_ = c; return *this; } BasicThemeBuilder& set_selected_line(const ride::Color& c) { selected_line_ = c; return *this; } BasicThemeBuilder& set_comment(const ride::Color& c) { comment_ = c; return *this; } BasicThemeBuilder& set_keyword(const ride::Color& c) { keyword_ = c; return *this; } BasicThemeBuilder& set_error(const ride::Color& c) { error_ = c; return *this; } BasicThemeBuilder& set_error_front(const ride::Color& c) { error_front_ = c; return *this; } BasicThemeBuilder& set_warning(const ride::Color& c) { warning_ = c; return *this; } BasicThemeBuilder& set_warning_front(const ride::Color& c) { warning_front_ = c; return *this; } BasicThemeBuilder& set_search_hi(const ride::Color& c) { search_hi_ = c; return *this; } BasicThemeBuilder& set_select_hi(const ride::Color& c) { select_hi_ = c; return *this; } const ride::Color& selection_foreground() { return selection_foreground_; } const ride::Color& selection_background() { return selection_background_; } const ride::Color& front() { return front_; } const ride::Color& bkg() { return bkg_; } const ride::Color& fold_hi() { return fold_hi_; } const ride::Color& fold_lo() { return fold_lo_; } const ride::Color& selected_line() { return selected_line_; } const ride::Color& comment() { return comment_; } const ride::Color& keyword() { return keyword_; } const ride::Color& error() { return error_; } const ride::Color& error_front() { return error_front_; } const ride::Color& warning() { return warning_; } const ride::Color& warning_front() { return warning_front_; } const ride::Color& search_hi() { return search_hi_; } const ride::Color& select_hi() { return select_hi_; } void Setup(ride::FontsAndColors* colors) { colors->set_use_selection_background(true); colors->set_use_selection_foreground(true); colors->set_allocated_selection_foreground(New(selection_foreground_)); colors->set_allocated_selection_background(New(selection_background_)); colors->set_allocated_default_style(New(Style(New(front_), New(bkg_)))); colors->set_allocated_line_number_style(New(Style(NULL, New(bkg_)))); colors->set_allocated_fold_margin_hi(New(fold_hi_)); colors->set_allocated_fold_margin_low(New(fold_lo_)); colors->set_allocated_selected_line(New(selected_line_)); // yellow colors->set_allocated_style_comment(New(Style(New(comment_)))); colors->set_allocated_style_commentline(New(Style(New(comment_)))); colors->set_allocated_style_commentdoc(New(Style(New(comment_)))); colors->set_allocated_style_commentlinedoc(New(Style(New(comment_)))); colors->set_allocated_style_keyword(New(Style(New(keyword_), NULL, true))); colors->set_allocated_folderend_foreground(New(front_)); colors->set_allocated_folderopenmid_foreground(New(front_)); colors->set_allocated_foldermidtail_foreground(New(front_)); colors->set_allocated_foldertail_foreground(New(front_)); colors->set_allocated_foldersub_foreground(New(front_)); colors->set_allocated_folder_foreground(New(front_)); colors->set_allocated_folderopen_foreground(New(front_)); colors->set_allocated_folderend_background(New(bkg_)); colors->set_allocated_folderopenmid_background(New(bkg_)); colors->set_allocated_foldermidtail_background(New(bkg_)); colors->set_allocated_foldertail_background(New(bkg_)); colors->set_allocated_foldersub_background(New(bkg_)); colors->set_allocated_folder_background(New(bkg_)); colors->set_allocated_folderopen_background(New(bkg_)); colors->set_allocated_props_key(New(Style(New(keyword_)))); colors->set_allocated_props_section(New(Style(NULL, NULL, true))); colors->set_allocated_indicator_error(New(Indicator(error_))); colors->set_allocated_indicator_warning(New(Indicator(warning_))); colors->set_allocated_indicator_search_highlight( New(Indicator(search_hi_))); colors->set_allocated_indicator_select_highlight( New(Indicator(select_hi_))); colors->set_allocated_annotation_error_style( New(Style(New(error_front_), New(error_)))); colors->set_allocated_annotation_warning_style( New(Style(New(warning_front_), New(warning_)))); } private: ride::Color selection_foreground_; ride::Color selection_background_; ride::Color front_; ride::Color bkg_; ride::Color fold_hi_; ride::Color fold_lo_; ride::Color selected_line_; ride::Color comment_; ride::Color keyword_; ride::Color error_; ride::Color error_front_; ride::Color warning_; ride::Color warning_front_; ride::Color search_hi_; ride::Color select_hi_; }; ////////////////////////////////////////////////////////////////////////// void SetupDefaultTheme(ride::FontsAndColors* colors) { BasicThemeBuilder() .set_selection_foreground(Color(255)) .set_selection_background(Color(0)) .set_front(Color(0)) .set_bkg(Color(224)) .set_fold_hi(Color(192)) .set_fold_lo(Color(224)) .set_selected_line(Color(255, 255, 0)) // yellow .set_comment(Color(128, 64, 0)) .set_keyword(Color(0, 0, 255)) .set_error(Color(255, 60, 60)) .set_error_front(Color(0)) .set_warning(Color(0, 255, 0)) .set_warning_front(Color(0)) .set_search_hi(Color(200)) .set_select_hi(Color(180)) .Setup(colors); } ////////////////////////////////////////////////////////////////////////// // solarized colors from http://ethanschoonover.com/solarized const ride::Color solarized_base03 = Color(0, 43, 54); const ride::Color solarized_base02 = Color(7, 54, 66); const ride::Color solarized_base01 = Color(88, 110, 117); const ride::Color solarized_base00 = Color(101, 123, 131); const ride::Color solarized_base0 = Color(131, 148, 150); const ride::Color solarized_base1 = Color(147, 161, 161); const ride::Color solarized_base2 = Color(238, 232, 213); const ride::Color solarized_base3 = Color(253, 246, 227); const ride::Color solarized_yellow = Color(181, 137, 0); const ride::Color solarized_orange = Color(203, 75, 22); const ride::Color solarized_red = Color(220, 50, 47); const ride::Color solarized_magenta = Color(211, 54, 130); const ride::Color solarized_violet = Color(108, 113, 196); const ride::Color solarized_blue = Color(38, 139, 210); const ride::Color solarized_cyan = Color(42, 161, 152); const ride::Color solarized_green = Color(133, 153, 0); void SetupSolarizedDarkTheme(ride::FontsAndColors* colors) { BasicThemeBuilder() .set_selection_foreground(solarized_base1) .set_selection_background(solarized_base00) .set_front(solarized_base0) .set_bkg(solarized_base03) .set_fold_hi(solarized_base02) .set_fold_lo(solarized_base02) .set_selected_line(solarized_base02) .set_comment(solarized_base01) .set_keyword(solarized_base1) .set_error(solarized_red) .set_error_front(solarized_base03) .set_warning(solarized_base00) .set_warning_front(solarized_base03) .set_search_hi(solarized_base01) .set_select_hi(solarized_base02) .Setup(colors); } ////////////////////////////////////////////////////////////////////////// void AddBuiltInThemes(::ride::Settings* settings) { ThemeList* themes = settings->mutable_themes(); ride::Theme* default_theme = GetOrCreateTheme(themes, "Ride (default)"); SetupDefaultTheme(default_theme->mutable_data()); ride::Theme* solarized_dark_theme = GetOrCreateTheme(themes, "Solarized (dark)"); SetupSolarizedDarkTheme(solarized_dark_theme->mutable_data()); if (false == settings->has_fonts_and_colors()) { // if the current settings is missing the fonts and colors // apply the default theme settings->set_allocated_fonts_and_colors( new ride::FontsAndColors(default_theme->data())); } } <commit_msg>edge color fix for solarized #64<commit_after>// Copyright (2015) Gustav #include "ride/builtinthemes.h" #include <string> typedef google::protobuf::RepeatedPtrField<ride::Theme> ThemeList; ride::Theme* GetOrCreateTheme(ThemeList* themes, const std::string& name) { for (ride::Theme& t : *themes) { if (t.name() == name) return &t; } ride::Theme* temp = themes->Add(); temp->set_name(name); temp->set_can_remove(false); return temp; } ride::Color Color(google::protobuf::int32 r, google::protobuf::int32 g, google::protobuf::int32 b) { ride::Color c; c.set_r(r); c.set_g(g); c.set_b(b); return c; } ride::Color Color(google::protobuf::int32 c) { return Color(c, c, c); } ride::Style Style(ride::Color* front, ride::Color* back = NULL, bool bold = false) { ride::Style style; if (front) { style.set_use_foreground(true); style.set_allocated_foreground(front); } if (back) { style.set_use_background(true); style.set_allocated_background(back); } if (bold) { style.set_use_bold(true); style.set_bold(true); } return style; } template <typename T> T* New(const T& t) { return new T(t); } ride::Indicator Indicator(const ride::Color& c) { ride::Indicator ind; ind.set_allocated_foreground(New(c)); return ind; } ////////////////////////////////////////////////////////////////////////// class BasicThemeBuilder { public: BasicThemeBuilder& set_selection_foreground(const ride::Color& c) { selection_foreground_ = c; return *this; } BasicThemeBuilder& set_selection_background(const ride::Color& c) { selection_background_ = c; return *this; } BasicThemeBuilder& set_front(const ride::Color& c) { front_ = c; return *this; } BasicThemeBuilder& set_bkg(const ride::Color& c) { bkg_ = c; return *this; } BasicThemeBuilder& set_fold_hi(const ride::Color& c) { fold_hi_ = c; return *this; } BasicThemeBuilder& set_fold_lo(const ride::Color& c) { fold_lo_ = c; return *this; } BasicThemeBuilder& set_selected_line(const ride::Color& c) { selected_line_ = c; return *this; } BasicThemeBuilder& set_comment(const ride::Color& c) { comment_ = c; return *this; } BasicThemeBuilder& set_keyword(const ride::Color& c) { keyword_ = c; return *this; } BasicThemeBuilder& set_error(const ride::Color& c) { error_ = c; return *this; } BasicThemeBuilder& set_error_front(const ride::Color& c) { error_front_ = c; return *this; } BasicThemeBuilder& set_warning(const ride::Color& c) { warning_ = c; return *this; } BasicThemeBuilder& set_warning_front(const ride::Color& c) { warning_front_ = c; return *this; } BasicThemeBuilder& set_search_hi(const ride::Color& c) { search_hi_ = c; return *this; } BasicThemeBuilder& set_select_hi(const ride::Color& c) { select_hi_ = c; return *this; } BasicThemeBuilder& set_edge_color(const ride::Color& c) { edge_color_ = c; return *this; } const ride::Color& selection_foreground() { return selection_foreground_; } const ride::Color& selection_background() { return selection_background_; } const ride::Color& front() { return front_; } const ride::Color& bkg() { return bkg_; } const ride::Color& fold_hi() { return fold_hi_; } const ride::Color& fold_lo() { return fold_lo_; } const ride::Color& selected_line() { return selected_line_; } const ride::Color& comment() { return comment_; } const ride::Color& keyword() { return keyword_; } const ride::Color& error() { return error_; } const ride::Color& error_front() { return error_front_; } const ride::Color& warning() { return warning_; } const ride::Color& warning_front() { return warning_front_; } const ride::Color& search_hi() { return search_hi_; } const ride::Color& select_hi() { return select_hi_; } const ride::Color& edge_color() { return edge_color_; } void Setup(ride::FontsAndColors* colors) { colors->set_use_selection_background(true); colors->set_use_selection_foreground(true); colors->set_allocated_selection_foreground(New(selection_foreground_)); colors->set_allocated_selection_background(New(selection_background_)); colors->set_allocated_default_style(New(Style(New(front_), New(bkg_)))); colors->set_allocated_line_number_style(New(Style(NULL, New(bkg_)))); colors->set_allocated_fold_margin_hi(New(fold_hi_)); colors->set_allocated_fold_margin_low(New(fold_lo_)); colors->set_allocated_selected_line(New(selected_line_)); // yellow colors->set_allocated_style_comment(New(Style(New(comment_)))); colors->set_allocated_style_commentline(New(Style(New(comment_)))); colors->set_allocated_style_commentdoc(New(Style(New(comment_)))); colors->set_allocated_style_commentlinedoc(New(Style(New(comment_)))); colors->set_allocated_style_keyword(New(Style(New(keyword_), NULL, true))); colors->set_allocated_folderend_foreground(New(front_)); colors->set_allocated_folderopenmid_foreground(New(front_)); colors->set_allocated_foldermidtail_foreground(New(front_)); colors->set_allocated_foldertail_foreground(New(front_)); colors->set_allocated_foldersub_foreground(New(front_)); colors->set_allocated_folder_foreground(New(front_)); colors->set_allocated_folderopen_foreground(New(front_)); colors->set_allocated_folderend_background(New(bkg_)); colors->set_allocated_folderopenmid_background(New(bkg_)); colors->set_allocated_foldermidtail_background(New(bkg_)); colors->set_allocated_foldertail_background(New(bkg_)); colors->set_allocated_foldersub_background(New(bkg_)); colors->set_allocated_folder_background(New(bkg_)); colors->set_allocated_folderopen_background(New(bkg_)); colors->set_allocated_props_key(New(Style(New(keyword_)))); colors->set_allocated_props_section(New(Style(NULL, NULL, true))); colors->set_allocated_indicator_error(New(Indicator(error_))); colors->set_allocated_indicator_warning(New(Indicator(warning_))); colors->set_allocated_indicator_search_highlight( New(Indicator(search_hi_))); colors->set_allocated_indicator_select_highlight( New(Indicator(select_hi_))); colors->set_allocated_annotation_error_style( New(Style(New(error_front_), New(error_)))); colors->set_allocated_annotation_warning_style( New(Style(New(warning_front_), New(warning_)))); colors->set_allocated_edgecolor(New(edge_color_)); } private: ride::Color selection_foreground_; ride::Color selection_background_; ride::Color front_; ride::Color bkg_; ride::Color fold_hi_; ride::Color fold_lo_; ride::Color selected_line_; ride::Color comment_; ride::Color keyword_; ride::Color error_; ride::Color error_front_; ride::Color warning_; ride::Color warning_front_; ride::Color search_hi_; ride::Color select_hi_; ride::Color edge_color_; }; ////////////////////////////////////////////////////////////////////////// void SetupDefaultTheme(ride::FontsAndColors* colors) { BasicThemeBuilder() .set_selection_foreground(Color(255)) .set_selection_background(Color(0)) .set_front(Color(0)) .set_bkg(Color(224)) .set_fold_hi(Color(192)) .set_fold_lo(Color(224)) .set_selected_line(Color(255, 255, 0)) // yellow .set_comment(Color(128, 64, 0)) .set_keyword(Color(0, 0, 255)) .set_error(Color(255, 60, 60)) .set_error_front(Color(0)) .set_warning(Color(0, 255, 0)) .set_warning_front(Color(0)) .set_search_hi(Color(200)) .set_select_hi(Color(180)) .set_edge_color(Color(0)) .Setup(colors); } ////////////////////////////////////////////////////////////////////////// // solarized colors from http://ethanschoonover.com/solarized const ride::Color solarized_base03 = Color(0, 43, 54); const ride::Color solarized_base02 = Color(7, 54, 66); const ride::Color solarized_base01 = Color(88, 110, 117); const ride::Color solarized_base00 = Color(101, 123, 131); const ride::Color solarized_base0 = Color(131, 148, 150); const ride::Color solarized_base1 = Color(147, 161, 161); const ride::Color solarized_base2 = Color(238, 232, 213); const ride::Color solarized_base3 = Color(253, 246, 227); const ride::Color solarized_yellow = Color(181, 137, 0); const ride::Color solarized_orange = Color(203, 75, 22); const ride::Color solarized_red = Color(220, 50, 47); const ride::Color solarized_magenta = Color(211, 54, 130); const ride::Color solarized_violet = Color(108, 113, 196); const ride::Color solarized_blue = Color(38, 139, 210); const ride::Color solarized_cyan = Color(42, 161, 152); const ride::Color solarized_green = Color(133, 153, 0); void SetupSolarizedDarkTheme(ride::FontsAndColors* colors) { BasicThemeBuilder() .set_selection_foreground(solarized_base1) .set_selection_background(solarized_base00) .set_front(solarized_base0) .set_bkg(solarized_base03) .set_fold_hi(solarized_base02) .set_fold_lo(solarized_base02) .set_selected_line(solarized_base02) .set_comment(solarized_base01) .set_keyword(solarized_base1) .set_error(solarized_red) .set_error_front(solarized_base03) .set_warning(solarized_base00) .set_warning_front(solarized_base03) .set_search_hi(solarized_base01) .set_select_hi(solarized_base02) .set_edge_color(solarized_base01) .Setup(colors); } ////////////////////////////////////////////////////////////////////////// void AddBuiltInThemes(::ride::Settings* settings) { ThemeList* themes = settings->mutable_themes(); ride::Theme* default_theme = GetOrCreateTheme(themes, "Ride (default)"); SetupDefaultTheme(default_theme->mutable_data()); ride::Theme* solarized_dark_theme = GetOrCreateTheme(themes, "Solarized (dark)"); SetupSolarizedDarkTheme(solarized_dark_theme->mutable_data()); if (false == settings->has_fonts_and_colors()) { // if the current settings is missing the fonts and colors // apply the default theme settings->set_allocated_fonts_and_colors( new ride::FontsAndColors(default_theme->data())); } } <|endoftext|>
<commit_before>#include "catch.hpp" // mapnik #include <mapnik/vertex_cache.hpp> // stl #include <iostream> #include <vector> #include <tuple> struct fake_path { using coord_type = std::tuple<double, double, unsigned>; using cont_type = std::vector<coord_type>; cont_type vertices_; cont_type::iterator itr_; fake_path(std::initializer_list<double> l) : fake_path(l.begin(), l.size()) { } fake_path(std::vector<double> const &v) : fake_path(v.begin(), v.size()) { } template <typename Itr> fake_path(Itr itr, size_t sz) { size_t num_coords = sz >> 1; vertices_.reserve(num_coords); for (size_t i = 0; i < num_coords; ++i) { double x = *itr++; double y = *itr++; unsigned cmd = (i == 0) ? agg::path_cmd_move_to : agg::path_cmd_line_to; vertices_.push_back(std::make_tuple(x, y, cmd)); } itr_ = vertices_.begin(); } unsigned vertex(double *x, double *y) { if (itr_ == vertices_.end()) { return agg::path_cmd_stop; } *x = std::get<0>(*itr_); *y = std::get<1>(*itr_); unsigned cmd = std::get<2>(*itr_); ++itr_; return cmd; } void rewind(unsigned) { itr_ = vertices_.begin(); } }; double dist(mapnik::pixel_position const &a, mapnik::pixel_position const &b) { mapnik::pixel_position d = a - b; return std::sqrt(d.x*d.x + d.y*d.y); } void test_simple_segment(double const &offset) { const double dx = 0.01; fake_path path = {0, 0, 1, 0}, off_path = {0, offset, 1, offset}; mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double pos = vc.linear_position(); double off_pos = off_vc.position_closest_to(vc.current_position()); REQUIRE(std::abs(pos - off_pos) < 1.0e-6); } } void test_straight_line(double const &offset) { const double dx = 0.01; fake_path path = {0, 0, 0.1, 0, 0.9, 0, 1, 0}, off_path = {0, offset, 0.4, offset, 0.6, offset, 1, offset}; mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double pos = vc.linear_position(); double off_pos = off_vc.position_closest_to(vc.current_position()); REQUIRE(std::abs(pos - off_pos) < 1.0e-6); } } void test_offset_curve(double const &offset) { const double dx = 0.01; const double r = (1.0 + offset); std::vector<double> pos, off_pos; const size_t max_i = 1000; for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x)); pos.push_back(std::sin(x)); off_pos.push_back(-r * std::cos(x)); off_pos.push_back(r * std::sin(x)); } fake_path path(pos), off_path(off_pos); mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double mpos = vc.linear_position(); double moff_pos = off_vc.position_closest_to(vc.current_position()); { mapnik::vertex_cache::scoped_state s(off_vc); off_vc.move(moff_pos); auto eps = (1.001 * offset); auto actual = dist(vc.current_position(), off_vc.current_position()); REQUIRE(actual < eps); } REQUIRE(std::abs((mpos / vc.length()) - (moff_pos / off_vc.length())) < 1.0e-3); } } void test_s_shaped_curve(double const &offset) { const double dx = 0.01; const double r = (1.0 + offset); const double r2 = (1.0 - offset); std::vector<double> pos, off_pos; const size_t max_i = 1000; for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x) - 1); pos.push_back(std::sin(x)); off_pos.push_back(-r * std::cos(x) - 1); off_pos.push_back(r * std::sin(x)); } for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x) + 1); pos.push_back(-std::sin(x)); off_pos.push_back(-r2 * std::cos(x) + 1); off_pos.push_back(-r2 * std::sin(x)); } fake_path path(pos), off_path(off_pos); mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double moff_pos = off_vc.position_closest_to(vc.current_position()); { mapnik::vertex_cache::scoped_state s(off_vc); off_vc.move(moff_pos); REQUIRE(dist(vc.current_position(), off_vc.current_position()) < (1.002 * offset)); } } } TEST_CASE("offsets") { SECTION("line") { try { std::vector<double> offsets = { 0.01, 0.02, 0.1, 0.2 }; for (double offset : offsets) { // test simple straight line segment - should be easy to // find the correspondance here. test_simple_segment(offset); // test straight line consisting of more than one segment. test_straight_line(offset); // test an offset outer curve test_offset_curve(offset); // test an offset along an S-shaped curve, which is harder // because the positions along the offset are no longer // linearly related to the positions along the original // curve. test_s_shaped_curve(offset); } } catch (std::exception const& ex) { std::cerr << ex.what() << "\n"; REQUIRE(false); } } } <commit_msg>Windows tests: fix missing "M_PI"<commit_after>#include "catch.hpp" // mapnik #include <mapnik/vertex_cache.hpp> #include <mapnik/global.hpp> // stl #include <iostream> #include <vector> #include <tuple> struct fake_path { using coord_type = std::tuple<double, double, unsigned>; using cont_type = std::vector<coord_type>; cont_type vertices_; cont_type::iterator itr_; fake_path(std::initializer_list<double> l) : fake_path(l.begin(), l.size()) { } fake_path(std::vector<double> const &v) : fake_path(v.begin(), v.size()) { } template <typename Itr> fake_path(Itr itr, size_t sz) { size_t num_coords = sz >> 1; vertices_.reserve(num_coords); for (size_t i = 0; i < num_coords; ++i) { double x = *itr++; double y = *itr++; unsigned cmd = (i == 0) ? agg::path_cmd_move_to : agg::path_cmd_line_to; vertices_.push_back(std::make_tuple(x, y, cmd)); } itr_ = vertices_.begin(); } unsigned vertex(double *x, double *y) { if (itr_ == vertices_.end()) { return agg::path_cmd_stop; } *x = std::get<0>(*itr_); *y = std::get<1>(*itr_); unsigned cmd = std::get<2>(*itr_); ++itr_; return cmd; } void rewind(unsigned) { itr_ = vertices_.begin(); } }; double dist(mapnik::pixel_position const &a, mapnik::pixel_position const &b) { mapnik::pixel_position d = a - b; return std::sqrt(d.x*d.x + d.y*d.y); } void test_simple_segment(double const &offset) { const double dx = 0.01; fake_path path = {0, 0, 1, 0}, off_path = {0, offset, 1, offset}; mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double pos = vc.linear_position(); double off_pos = off_vc.position_closest_to(vc.current_position()); REQUIRE(std::abs(pos - off_pos) < 1.0e-6); } } void test_straight_line(double const &offset) { const double dx = 0.01; fake_path path = {0, 0, 0.1, 0, 0.9, 0, 1, 0}, off_path = {0, offset, 0.4, offset, 0.6, offset, 1, offset}; mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double pos = vc.linear_position(); double off_pos = off_vc.position_closest_to(vc.current_position()); REQUIRE(std::abs(pos - off_pos) < 1.0e-6); } } void test_offset_curve(double const &offset) { const double dx = 0.01; const double r = (1.0 + offset); std::vector<double> pos, off_pos; const size_t max_i = 1000; for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x)); pos.push_back(std::sin(x)); off_pos.push_back(-r * std::cos(x)); off_pos.push_back(r * std::sin(x)); } fake_path path(pos), off_path(off_pos); mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double mpos = vc.linear_position(); double moff_pos = off_vc.position_closest_to(vc.current_position()); { mapnik::vertex_cache::scoped_state s(off_vc); off_vc.move(moff_pos); auto eps = (1.001 * offset); auto actual = dist(vc.current_position(), off_vc.current_position()); REQUIRE(actual < eps); } REQUIRE(std::abs((mpos / vc.length()) - (moff_pos / off_vc.length())) < 1.0e-3); } } void test_s_shaped_curve(double const &offset) { const double dx = 0.01; const double r = (1.0 + offset); const double r2 = (1.0 - offset); std::vector<double> pos, off_pos; const size_t max_i = 1000; for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x) - 1); pos.push_back(std::sin(x)); off_pos.push_back(-r * std::cos(x) - 1); off_pos.push_back(r * std::sin(x)); } for (size_t i = 0; i <= max_i; ++i) { double x = M_PI * double(i) / max_i; pos.push_back(-std::cos(x) + 1); pos.push_back(-std::sin(x)); off_pos.push_back(-r2 * std::cos(x) + 1); off_pos.push_back(-r2 * std::sin(x)); } fake_path path(pos), off_path(off_pos); mapnik::vertex_cache vc(path), off_vc(off_path); vc.reset(); vc.next_subpath(); off_vc.reset(); off_vc.next_subpath(); while (vc.move(dx)) { double moff_pos = off_vc.position_closest_to(vc.current_position()); { mapnik::vertex_cache::scoped_state s(off_vc); off_vc.move(moff_pos); REQUIRE(dist(vc.current_position(), off_vc.current_position()) < (1.002 * offset)); } } } TEST_CASE("offsets") { SECTION("line") { try { std::vector<double> offsets = { 0.01, 0.02, 0.1, 0.2 }; for (double offset : offsets) { // test simple straight line segment - should be easy to // find the correspondance here. test_simple_segment(offset); // test straight line consisting of more than one segment. test_straight_line(offset); // test an offset outer curve test_offset_curve(offset); // test an offset along an S-shaped curve, which is harder // because the positions along the offset are no longer // linearly related to the positions along the original // curve. test_s_shaped_curve(offset); } } catch (std::exception const& ex) { std::cerr << ex.what() << "\n"; REQUIRE(false); } } } <|endoftext|>
<commit_before>/* * RudeMesh.cpp * * Bork3D Game Engine * Copyright (c) 2009 Bork 3D LLC. All rights reserved. * */ #include "RudeMesh.h" #include "RudeGL.h" #include "RudeTextureManager.h" #include "RudeFile.h" #include "RudeDebug.h" RudeMesh::RudeMesh(RudeObject *owner) : m_owner(owner) , m_scale(1.0f, 1.0f, 1.0f) , m_textureOverride(false) { for(int i = 0; i < kMaxNodes; i++) m_colorOverrides[i] = 0; for(int i = 0; i < kMaxTextures; i++) m_textureOverrides[i] = -1; } RudeMesh::~RudeMesh() { } int RudeMesh::Load(const char *name) { RUDE_ASSERT(name, "Loading mesh with no name"); RUDE_REPORT("RudeMesh::Load %s\n", name); char filename[64]; sprintf(filename, "%s.POD", name); char modelfile[512]; RudeFileGetFile(filename, modelfile, 512); int result = m_model.ReadFromFile(modelfile, 0, 0); RUDE_ASSERT(result == 1, "Could not load model"); if(result == 0) return -1; RUDE_ASSERT(m_model.nNumTexture < kMaxTextures, "Too many textures in model"); for(unsigned int i = 0; i < m_model.nNumTexture; i++) { SPODTexture *texture = &m_model.pTexture[i]; RUDE_ASSERT(texture, "Invalid texture in model"); char texturename[64]; sprintf(texturename, "%s", texture->pszName); int texturenamelen = strlen(texturename); // cut off the last 4 chars texturename[texturenamelen-4] = '\0'; m_textures[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(texturename); RUDE_ASSERT(m_textures[i] >= 0, "Could not load texture"); } // make sure we have at least one renderable node bool foundRenderable = false; for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; foundRenderable = true; RUDE_REPORT(" Node %s: mesh %d\n", node->pszName, node->nIdx); } RUDE_ASSERT(foundRenderable, "Didn't find any renderable meshes in %s", name); // flip endianess of colors stored in meshes for(unsigned int i = 0; i < m_model.nNumMesh; i++) { SPODMesh *mesh = &m_model.pMesh[i]; RUDE_ASSERT(mesh->pInterleaved, "Mesh data must be interleaved"); if((mesh->sVtxColours.n > 0)) { RUDE_ASSERT(mesh->sVtxColours.eType == EPODDataRGBA, "Vertex colors must be in RGBA format"); if(mesh->sVtxColours.eType == EPODDataRGBA) { unsigned char *c = (mesh->pInterleaved + (long)mesh->sVtxColours.pData); for(unsigned int j = 0; j < mesh->nNumVertex; j++) { unsigned int *cc = (unsigned int *) c; unsigned int b = *cc & 0x000000FF; unsigned int g = (*cc & 0x0000FF00) >> 8; unsigned int r = (*cc & 0x00FF0000) >> 16; //unsigned int a = (*cc & 0xFF000000) >> 24; b = g = r; *cc = 0xFF000000 | (b << 16) | (g << 8) | r; c += mesh->sVtxColours.nStride; } } } } return 0; } void RudeMesh::AddTextureOverride(const char *oldTexture, const char *newTexture) { bool found = false; for(unsigned int i = 0; i < m_model.nNumTexture; i++) { SPODTexture *texture = &m_model.pTexture[i]; RUDE_ASSERT(texture, "Invalid texture in model"); char texturename[64]; sprintf(texturename, "%s", texture->pszName); int texturenamelen = strlen(texturename); // cut off the last 4 chars texturename[texturenamelen-4] = '\0'; if(strcmp(oldTexture, texturename) == 0) { m_textureOverrides[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(newTexture); RUDE_ASSERT(m_textureOverrides[i] >= 0, "Could not load texture %s", newTexture); found = true; } } RUDE_ASSERT(found, "Texture %s not found", oldTexture); } void RudeMesh::SetColorOverride(int node, const char *colordata) { RUDE_ASSERT(node < kMaxNodes, "Invalid node"); m_colorOverrides[node] = colordata; } void RudeMesh::EnableModel(int n, bool enable) { bool found = false; for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] == 'M' || node->pszName[0] == 'm') { if(node->pszName[1] == ('0' + n)) { found = true; if(enable) node->pszName[0] = 'M'; else node->pszName[0] = 'm'; } } } RUDE_ASSERT(found, "Could not find model number %d", n); } void RudeMesh::Render() { //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); RGL.EnableClient(kVertexArray, true); RGL.EnableClient(kTextureCoordArray, true); //glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); //glScalef(m_scale.x(), m_scale.y(), m_scale.z()); for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; int textureid = material->nIdxTexDiffuse; if(textureid >= 0) { if(m_textureOverride && m_textureOverrides[textureid] >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]); else RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); } unsigned short *indices = (unsigned short*) mesh->sFaces.pData; if(mesh->sVertex.eType == EPODDataShortNorm) { float s = 1.0f / 1000.0f; glMatrixMode(GL_MODELVIEW); glScalef(s, s, s); glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); } else glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if(m_colorOverrides[i]) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, 4, m_colorOverrides[i]); } else { if(mesh->sVtxColours.n > 0) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else RGL.EnableClient(kColorArray, false); } glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices); } #if 0 glAlphaFunc ( GL_GREATER, 0.5 ) ; glEnable ( GL_ALPHA_TEST ) ; for(int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'D') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; int textureid = material->nIdxTexDiffuse; if(textureid >= 0) { if(m_textureOverride && m_textureOverrides[textureid] >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]); else RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); } unsigned short *indices = (unsigned short*) mesh->sFaces.pData; if(mesh->sVertex.eType == EPODDataFixed16_16) glVertexPointer(3, GL_FIXED, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); else if(mesh->sVertex.eType == EPODDataShortNorm) { float s = 1.0f / 1000.0f; glMatrixMode(GL_MODELVIEW); glScalef(s, s, s); glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); } else glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if(mesh->sVtxColours.n > 0) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else RGL.EnableClient(kColorArray, false); glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices); } glDisable ( GL_ALPHA_TEST ) ; #endif } <commit_msg>Fix for no-color mesh rendering on win32<commit_after>/* * RudeMesh.cpp * * Bork3D Game Engine * Copyright (c) 2009 Bork 3D LLC. All rights reserved. * */ #include "RudeMesh.h" #include "RudeGL.h" #include "RudeTextureManager.h" #include "RudeFile.h" #include "RudeDebug.h" RudeMesh::RudeMesh(RudeObject *owner) : m_owner(owner) , m_scale(1.0f, 1.0f, 1.0f) , m_textureOverride(false) { for(int i = 0; i < kMaxNodes; i++) m_colorOverrides[i] = 0; for(int i = 0; i < kMaxTextures; i++) m_textureOverrides[i] = -1; } RudeMesh::~RudeMesh() { } int RudeMesh::Load(const char *name) { RUDE_ASSERT(name, "Loading mesh with no name"); RUDE_REPORT("RudeMesh::Load %s\n", name); char filename[64]; sprintf(filename, "%s.POD", name); char modelfile[512]; RudeFileGetFile(filename, modelfile, 512); int result = m_model.ReadFromFile(modelfile, 0, 0); RUDE_ASSERT(result == 1, "Could not load model"); if(result == 0) return -1; RUDE_ASSERT(m_model.nNumTexture < kMaxTextures, "Too many textures in model"); for(unsigned int i = 0; i < m_model.nNumTexture; i++) { SPODTexture *texture = &m_model.pTexture[i]; RUDE_ASSERT(texture, "Invalid texture in model"); char texturename[64]; sprintf(texturename, "%s", texture->pszName); int texturenamelen = strlen(texturename); // cut off the last 4 chars texturename[texturenamelen-4] = '\0'; m_textures[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(texturename); RUDE_ASSERT(m_textures[i] >= 0, "Could not load texture"); } // make sure we have at least one renderable node bool foundRenderable = false; for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; foundRenderable = true; RUDE_REPORT(" Node %s: mesh %d\n", node->pszName, node->nIdx); } RUDE_ASSERT(foundRenderable, "Didn't find any renderable meshes in %s", name); // flip endianess of colors stored in meshes for(unsigned int i = 0; i < m_model.nNumMesh; i++) { SPODMesh *mesh = &m_model.pMesh[i]; RUDE_ASSERT(mesh->pInterleaved, "Mesh data must be interleaved"); if((mesh->sVtxColours.n > 0)) { RUDE_ASSERT(mesh->sVtxColours.eType == EPODDataRGBA, "Vertex colors must be in RGBA format"); if(mesh->sVtxColours.eType == EPODDataRGBA) { unsigned char *c = (mesh->pInterleaved + (long)mesh->sVtxColours.pData); for(unsigned int j = 0; j < mesh->nNumVertex; j++) { unsigned int *cc = (unsigned int *) c; unsigned int b = *cc & 0x000000FF; unsigned int g = (*cc & 0x0000FF00) >> 8; unsigned int r = (*cc & 0x00FF0000) >> 16; //unsigned int a = (*cc & 0xFF000000) >> 24; b = g = r; *cc = 0xFF000000 | (b << 16) | (g << 8) | r; c += mesh->sVtxColours.nStride; } } } } return 0; } void RudeMesh::AddTextureOverride(const char *oldTexture, const char *newTexture) { bool found = false; for(unsigned int i = 0; i < m_model.nNumTexture; i++) { SPODTexture *texture = &m_model.pTexture[i]; RUDE_ASSERT(texture, "Invalid texture in model"); char texturename[64]; sprintf(texturename, "%s", texture->pszName); int texturenamelen = strlen(texturename); // cut off the last 4 chars texturename[texturenamelen-4] = '\0'; if(strcmp(oldTexture, texturename) == 0) { m_textureOverrides[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(newTexture); RUDE_ASSERT(m_textureOverrides[i] >= 0, "Could not load texture %s", newTexture); found = true; } } RUDE_ASSERT(found, "Texture %s not found", oldTexture); } void RudeMesh::SetColorOverride(int node, const char *colordata) { RUDE_ASSERT(node < kMaxNodes, "Invalid node"); m_colorOverrides[node] = colordata; } void RudeMesh::EnableModel(int n, bool enable) { bool found = false; for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] == 'M' || node->pszName[0] == 'm') { if(node->pszName[1] == ('0' + n)) { found = true; if(enable) node->pszName[0] = 'M'; else node->pszName[0] = 'm'; } } } RUDE_ASSERT(found, "Could not find model number %d", n); } void RudeMesh::Render() { //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); RGL.EnableClient(kVertexArray, true); RGL.EnableClient(kTextureCoordArray, true); //glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); //glScalef(m_scale.x(), m_scale.y(), m_scale.z()); for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; int textureid = material->nIdxTexDiffuse; if(textureid >= 0) { if(m_textureOverride && m_textureOverrides[textureid] >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]); else RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); } unsigned short *indices = (unsigned short*) mesh->sFaces.pData; if(mesh->sVertex.eType == EPODDataShortNorm) { float s = 1.0f / 1000.0f; glMatrixMode(GL_MODELVIEW); glScalef(s, s, s); glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); } else glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if(m_colorOverrides[i]) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, 4, m_colorOverrides[i]); } else { if(mesh->sVtxColours.n > 0) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else { RGL.EnableClient(kColorArray, false); glColor4f(1.0, 1.0, 1.0, 1.0); } } glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices); } #if 0 glAlphaFunc ( GL_GREATER, 0.5 ) ; glEnable ( GL_ALPHA_TEST ) ; for(int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'D') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; int textureid = material->nIdxTexDiffuse; if(textureid >= 0) { if(m_textureOverride && m_textureOverrides[textureid] >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]); else RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); } unsigned short *indices = (unsigned short*) mesh->sFaces.pData; if(mesh->sVertex.eType == EPODDataFixed16_16) glVertexPointer(3, GL_FIXED, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); else if(mesh->sVertex.eType == EPODDataShortNorm) { float s = 1.0f / 1000.0f; glMatrixMode(GL_MODELVIEW); glScalef(s, s, s); glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); } else glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if(mesh->sVtxColours.n > 0) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else RGL.EnableClient(kColorArray, false); glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices); } glDisable ( GL_ALPHA_TEST ) ; #endif } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <vcl/toolbox.hxx> #include <sfx2/app.hxx> #include "appdata.hxx" #include "arrdecl.hxx" #include "sfx2/sfxhelp.hxx" #include <sfx2/templdlg.hxx> #include "inettbc.hxx" #include "sfx2/stbitem.hxx" #include <sfx2/navigat.hxx> #include <sfx2/taskpane.hxx> #include <sfx2/module.hxx> #include <sfx2/viewfrm.hxx> #include "partwnd.hxx" #include <sfx2/sfxsids.hrc> #include "recfloat.hxx" #include <sfx2/objsh.hxx> #include <sfx2/viewsh.hxx> #include <sfx2/objface.hxx> //=================================================================== void SfxApplication::Registrations_Impl() { // Interfaces SfxApplication::RegisterInterface(); SfxModule::RegisterInterface(); SfxViewFrame::RegisterInterface(); SfxObjectShell::RegisterInterface(); SfxViewShell::RegisterInterface(); // ChildWindows SfxRecordingFloatWrapper_Impl::RegisterChildWindow(); SfxNavigatorWrapper::RegisterChildWindow( sal_False, NULL, SFX_CHILDWIN_NEVERHIDE ); SfxPartChildWnd_Impl::RegisterChildWindow(); SfxTemplateDialogWrapper::RegisterChildWindow(sal_True); SfxDockingWrapper::RegisterChildWindow(); // Controller SfxToolBoxControl::RegisterControl(SID_REPEAT); SfxURLToolBoxControl_Impl::RegisterControl(SID_OPENURL); SfxAppToolBoxControl_Impl::RegisterControl( SID_NEWDOCDIRECT ); SfxAppToolBoxControl_Impl::RegisterControl( SID_AUTOPILOTMENU ); }; //-------------------------------------------------------------------- void SfxApplication::RegisterToolBoxControl_Impl( SfxModule *pMod, SfxTbxCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterToolBoxControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pTbxCtrlFac->Count(); n++ ) { SfxTbxCtrlFactory *pF = (*pAppData_Impl->pTbxCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("TbxController registration is not clearly defined!"); } } #endif pAppData_Impl->pTbxCtrlFac->C40_INSERT( SfxTbxCtrlFactory, pFact, pAppData_Impl->pTbxCtrlFac->Count() ); } //-------------------------------------------------------------------- void SfxApplication::RegisterStatusBarControl_Impl( SfxModule *pMod, SfxStbCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterStatusBarControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pStbCtrlFac->Count(); n++ ) { SfxStbCtrlFactory *pF = (*pAppData_Impl->pStbCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("StbController registration is not clearly defined!"); } } #endif pAppData_Impl->pStbCtrlFac->C40_INSERT( SfxStbCtrlFactory, pFact, pAppData_Impl->pStbCtrlFac->Count() ); } //-------------------------------------------------------------------- void SfxApplication::RegisterMenuControl_Impl( SfxModule *pMod, SfxMenuCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterMenuControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pMenuCtrlFac->Count(); n++ ) { SfxMenuCtrlFactory *pF = (*pAppData_Impl->pMenuCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("MenuController register is not clearly defined!"); } } #endif pAppData_Impl->pMenuCtrlFac->C40_INSERT( SfxMenuCtrlFactory, pFact, pAppData_Impl->pMenuCtrlFac->Count() ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>include mnuitem.hxx to build with --enable-dbgutil<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <vcl/toolbox.hxx> #include <sfx2/app.hxx> #include "appdata.hxx" #include "arrdecl.hxx" #include "sfx2/sfxhelp.hxx" #include <sfx2/templdlg.hxx> #include "inettbc.hxx" #include "sfx2/stbitem.hxx" #include <sfx2/navigat.hxx> #include <sfx2/taskpane.hxx> #include <sfx2/module.hxx> #include <sfx2/viewfrm.hxx> #include "partwnd.hxx" #include <sfx2/sfxsids.hrc> #include "recfloat.hxx" #include <sfx2/objsh.hxx> #include <sfx2/viewsh.hxx> #include <sfx2/objface.hxx> #include <sfx2/mnuitem.hxx> //=================================================================== void SfxApplication::Registrations_Impl() { // Interfaces SfxApplication::RegisterInterface(); SfxModule::RegisterInterface(); SfxViewFrame::RegisterInterface(); SfxObjectShell::RegisterInterface(); SfxViewShell::RegisterInterface(); // ChildWindows SfxRecordingFloatWrapper_Impl::RegisterChildWindow(); SfxNavigatorWrapper::RegisterChildWindow( sal_False, NULL, SFX_CHILDWIN_NEVERHIDE ); SfxPartChildWnd_Impl::RegisterChildWindow(); SfxTemplateDialogWrapper::RegisterChildWindow(sal_True); SfxDockingWrapper::RegisterChildWindow(); // Controller SfxToolBoxControl::RegisterControl(SID_REPEAT); SfxURLToolBoxControl_Impl::RegisterControl(SID_OPENURL); SfxAppToolBoxControl_Impl::RegisterControl( SID_NEWDOCDIRECT ); SfxAppToolBoxControl_Impl::RegisterControl( SID_AUTOPILOTMENU ); }; //-------------------------------------------------------------------- void SfxApplication::RegisterToolBoxControl_Impl( SfxModule *pMod, SfxTbxCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterToolBoxControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pTbxCtrlFac->Count(); n++ ) { SfxTbxCtrlFactory *pF = (*pAppData_Impl->pTbxCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("TbxController registration is not clearly defined!"); } } #endif pAppData_Impl->pTbxCtrlFac->C40_INSERT( SfxTbxCtrlFactory, pFact, pAppData_Impl->pTbxCtrlFac->Count() ); } //-------------------------------------------------------------------- void SfxApplication::RegisterStatusBarControl_Impl( SfxModule *pMod, SfxStbCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterStatusBarControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pStbCtrlFac->Count(); n++ ) { SfxStbCtrlFactory *pF = (*pAppData_Impl->pStbCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("StbController registration is not clearly defined!"); } } #endif pAppData_Impl->pStbCtrlFac->C40_INSERT( SfxStbCtrlFactory, pFact, pAppData_Impl->pStbCtrlFac->Count() ); } //-------------------------------------------------------------------- void SfxApplication::RegisterMenuControl_Impl( SfxModule *pMod, SfxMenuCtrlFactory *pFact ) { if ( pMod ) { pMod->RegisterMenuControl( pFact ); return; } #ifdef DBG_UTIL for ( sal_uInt16 n=0; n<pAppData_Impl->pMenuCtrlFac->Count(); n++ ) { SfxMenuCtrlFactory *pF = (*pAppData_Impl->pMenuCtrlFac)[n]; if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId && (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) ) { DBG_WARNING("MenuController register is not clearly defined!"); } } #endif pAppData_Impl->pMenuCtrlFac->C40_INSERT( SfxMenuCtrlFactory, pFact, pAppData_Impl->pMenuCtrlFac->Count() ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <boost/regex.hpp> #include <boost/filesystem.hpp> #include "Reseed.h" #include "Log.h" #include "util.h" namespace i2p { namespace data { static std::vector<std::string> httpReseedHostList = { "http://193.150.121.66/netDb/", "http://netdb.i2p2.no/", "http://reseed.i2p-projekt.de/", "http://cowpuncher.drollette.com/netdb/", "http://i2p.mooo.com/netDb/", "http://reseed.info/", "http://reseed.pkol.de/", "http://uk.reseed.i2p2.no/", "http://i2p-netdb.innovatio.no/", "http://ieb9oopo.mooo.com" }; //TODO: Implement v2 reseeding. Lightweight zip library is needed. //TODO: Implement SU3, utils. Reseeder::Reseeder() { } Reseeder::~Reseeder() { } bool Reseeder::reseedNow() { try { std::string reseedHost = httpReseedHostList[(rand() % httpReseedHostList.size())]; LogPrint("Reseeding from ", reseedHost); std::string content = i2p::util::http::httpRequest(reseedHost); if (content == "") { LogPrint("Reseed failed"); return false; } boost::regex e("<\\s*A\\s+[^>]*href\\s*=\\s*\"([^\"]*)\"", boost::regex::normal | boost::regbase::icase); boost::sregex_token_iterator i(content.begin(), content.end(), e, 1); boost::sregex_token_iterator j; //TODO: Ugly code, try to clean up. //TODO: Try to reduce N number of variables std::string name; std::string routerInfo; std::string tmpUrl; std::string filename; std::string ignoreFileSuffix = ".zip"; boost::filesystem::path root = i2p::util::filesystem::GetDataDir(); while (i != j) { name = *i++; if (name.find(ignoreFileSuffix)!=std::string::npos) continue; LogPrint("Downloading ", name); tmpUrl = reseedHost; tmpUrl.append(name); routerInfo = i2p::util::http::httpRequest(tmpUrl); if (routerInfo.size()==0) continue; filename = root.string(); #ifndef _WIN32 filename += "/netDb/r"; #else filename += "\\netDb\\r"; #endif filename += name.at(11); // first char in id #ifndef _WIN32 filename.append("/"); #else filename.append("\\"); #endif filename.append(name.c_str()); std::ofstream outfile (filename, std::ios::binary); outfile << routerInfo; outfile.close(); } return true; } catch (std::exception& ex) { //TODO: error reporting return false; } return false; } } } <commit_msg>Ignore su3 files for now, support is comming.<commit_after>#include <iostream> #include <fstream> #include <boost/regex.hpp> #include <boost/filesystem.hpp> #include "Reseed.h" #include "Log.h" #include "util.h" namespace i2p { namespace data { static std::vector<std::string> httpReseedHostList = { "http://193.150.121.66/netDb/", "http://netdb.i2p2.no/", "http://reseed.i2p-projekt.de/", "http://cowpuncher.drollette.com/netdb/", "http://i2p.mooo.com/netDb/", "http://reseed.info/", "http://reseed.pkol.de/", "http://uk.reseed.i2p2.no/", "http://i2p-netdb.innovatio.no/", "http://ieb9oopo.mooo.com" }; //TODO: Implement v2 reseeding. Lightweight zip library is needed. //TODO: Implement SU3, utils. Reseeder::Reseeder() { } Reseeder::~Reseeder() { } bool Reseeder::reseedNow() { try { std::string reseedHost = httpReseedHostList[(rand() % httpReseedHostList.size())]; LogPrint("Reseeding from ", reseedHost); std::string content = i2p::util::http::httpRequest(reseedHost); if (content == "") { LogPrint("Reseed failed"); return false; } boost::regex e("<\\s*A\\s+[^>]*href\\s*=\\s*\"([^\"]*)\"", boost::regex::normal | boost::regbase::icase); boost::sregex_token_iterator i(content.begin(), content.end(), e, 1); boost::sregex_token_iterator j; //TODO: Ugly code, try to clean up. //TODO: Try to reduce N number of variables std::string name; std::string routerInfo; std::string tmpUrl; std::string filename; std::string ignoreFileSuffix = ".su3"; boost::filesystem::path root = i2p::util::filesystem::GetDataDir(); while (i != j) { name = *i++; if (name.find(ignoreFileSuffix)!=std::string::npos) continue; LogPrint("Downloading ", name); tmpUrl = reseedHost; tmpUrl.append(name); routerInfo = i2p::util::http::httpRequest(tmpUrl); if (routerInfo.size()==0) continue; filename = root.string(); #ifndef _WIN32 filename += "/netDb/r"; #else filename += "\\netDb\\r"; #endif filename += name.at(11); // first char in id #ifndef _WIN32 filename.append("/"); #else filename.append("\\"); #endif filename.append(name.c_str()); std::ofstream outfile (filename, std::ios::binary); outfile << routerInfo; outfile.close(); } return true; } catch (std::exception& ex) { //TODO: error reporting return false; } return false; } } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX #define INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX #include <vector> #include <deque> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/ui/XUIElement.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/frame/XLayoutManagerListener.hpp> #include <cppuhelper/implbase2.hxx> #include <cppuhelper/propshlp.hxx> #include <rtl/ustring.hxx> #include <osl/mutex.hxx> #include <o3tl/typed_flags_set.hxx> #include <sfx2/sfx.hrc> #include <sfx2/childwin.hxx> #include <sfx2/shell.hxx> #include <sfx2/ctrlitem.hxx> #include <sfx2/viewfrm.hxx> class SfxSplitWindow; class SfxWorkWindow; // This struct makes all relevant Informationen available of Toolboxes struct SfxObjectBar_Impl { sal_uInt16 nId; // Resource - and ConfigId of Toolbox sal_uInt16 nMode; // special visibility flags sal_uInt16 nPos; sal_uInt16 nIndex; bool bDestroy; SfxInterface* pIFace; SfxObjectBar_Impl() : nId(0), nMode(0), nPos(0), nIndex(0), bDestroy(false), pIFace(0) {} }; // This struct makes all relevant Informationen available of the status bar struct SfxStatBar_Impl { sal_uInt16 nId; bool bOn; bool bTemp; SfxStatBar_Impl() : nId(0), bOn(true), bTemp(false) {} }; enum class SfxChildVisibility { NOT_VISIBLE = 0, ACTIVE = 1, // not disabled through HidePopups NOT_HIDDEN = 2, // not disabled through HideChildWindow FITS_IN = 4, // not too large for output size of the parent VISIBLE = 7, // NOT_HIDDEN | ACTIVE | FITS_IN) }; namespace o3tl { template<> struct typed_flags<SfxChildVisibility> : is_typed_flags<SfxChildVisibility, 0x07> {}; } struct SfxChild_Impl { vcl::Window* pWin; Size aSize; SfxChildAlignment eAlign; SfxChildVisibility nVisible; bool bResize; bool bCanGetFocus; bool bSetFocus; SfxChild_Impl( vcl::Window& rChild, const Size& rSize, SfxChildAlignment eAlignment, bool bIsVisible ): pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(false), bCanGetFocus( false ), bSetFocus( false ) { nVisible = bIsVisible ? SfxChildVisibility::VISIBLE : SfxChildVisibility::NOT_VISIBLE; } }; struct SfxChildWin_Impl { sal_uInt16 nSaveId; // the ChildWindow-Id sal_uInt16 nInterfaceId; // the current context sal_uInt16 nId; // current Id SfxChildWindow* pWin; bool bCreate; SfxChildWinInfo aInfo; SfxChild_Impl* pCli; // != 0 at direct Children sal_uInt16 nVisibility; bool bEnable; bool bDisabled; SfxChildWin_Impl( sal_uInt32 nID ) : nSaveId((sal_uInt16) (nID & 0xFFFF) ), nInterfaceId((sal_uInt16) (nID >> 16)), nId(nSaveId), pWin(0), bCreate(false), pCli(0), nVisibility( sal_False ), bEnable( true ), bDisabled( false ) {} }; enum class SfxChildIdentifier { STATBAR, OBJECTBAR, DOCKINGWINDOW, SPLITWINDOW }; enum class SfxDockingConfig { SETDOCKINGRECTS, ALIGNDOCKINGWINDOW, TOGGLEFLOATMODE, MOVEDOCKINGWINDOW }; typedef std::vector<SfxChild_Impl*> SfxChildList_Impl; typedef std::vector<SfxChildWin_Impl*> SfxChildWindows_Impl; struct SfxObjectBarList_Impl { std::deque<SfxObjectBar_Impl> aArr; sal_uInt16 nAct; SfxObjectBar_Impl operator[] ( sal_uInt16 n ) { return aArr[n]; } SfxObjectBar_Impl Actual() { return aArr[nAct]; } }; #define SFX_SPLITWINDOWS_LEFT 0 #define SFX_SPLITWINDOWS_TOP 2 #define SFX_SPLITWINDOWS_RIGHT 1 #define SFX_SPLITWINDOWS_MAX 4 class LayoutManagerListener : public ::cppu::WeakImplHelper2< css::frame::XLayoutManagerListener, css::lang::XComponent > { public: LayoutManagerListener( SfxWorkWindow* pWrkWin ); virtual ~LayoutManagerListener(); void setFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); // XComponent virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XLayoutManagerEventListener virtual void SAL_CALL layoutEvent( const ::com::sun::star::lang::EventObject& aSource, ::sal_Int16 eLayoutEvent, const ::com::sun::star::uno::Any& aInfo ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; private: bool m_bHasFrame; SfxWorkWindow* m_pWrkWin; ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > m_xFrame; OUString m_aLayoutManagerPropName; }; class SfxWorkWindow { friend class LayoutManagerListener; protected: std::vector<sal_uInt16> aSortedList; SfxStatBar_Impl aStatBar; std::vector< SfxObjectBar_Impl > aObjBarList; Rectangle aClientArea; Rectangle aUpperClientArea; SfxWorkWindow* pParent; SfxSplitWindow* pSplit[SFX_SPLITWINDOWS_MAX]; SfxChildList_Impl aChildren; SfxChildWindows_Impl aChildWins; SfxBindings* pBindings; vcl::Window* pWorkWin; SfxShell* pConfigShell; vcl::Window* pActiveChild; sal_uInt16 nUpdateMode; sal_uInt16 nChildren; sal_uInt16 nOrigMode; bool bSorted : 1; bool bDockingAllowed : 1; bool bInternalDockingAllowed : 1; bool bAllChildrenVisible : 1; bool bIsFullScreen : 1; bool bShowStatusBar : 1; sal_Int32 m_nLock; OUString m_aStatusBarResName; OUString m_aLayoutManagerPropName; OUString m_aTbxTypeName; OUString m_aProgressBarResName; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xLayoutManagerListener; protected: void CreateChildWin_Impl(SfxChildWin_Impl*,bool); void RemoveChildWin_Impl(SfxChildWin_Impl*); void Sort_Impl(); SfxChild_Impl* FindChild_Impl( const vcl::Window& rWindow ) const; bool RequestTopToolSpacePixel_Impl( SvBorder aBorder ); virtual Rectangle GetTopRect_Impl(); SvBorder Arrange_Impl(); void SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&); static bool IsPluginMode( SfxObjectShell* pObjShell ); public: SfxWorkWindow( vcl::Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL); virtual ~SfxWorkWindow(); SfxBindings& GetBindings() { return *pBindings; } vcl::Window* GetWindow() const { return pWorkWin; } Rectangle GetFreeArea( bool bAutoHide ) const; void SetDockingAllowed(bool bSet) { bDockingAllowed = bSet; } void SetInternalDockingAllowed(bool bSet) { bInternalDockingAllowed = bSet; } bool IsDockingAllowed() const { return bDockingAllowed; } bool IsInternalDockingAllowed() const { return bInternalDockingAllowed; } SfxWorkWindow* GetParent_Impl() const { return pParent; } // Methods for all Child windows void DataChanged_Impl( const DataChangedEvent& rDCEvt ); void ReleaseChild_Impl( vcl::Window& rWindow ); SfxChild_Impl* RegisterChild_Impl( vcl::Window& rWindow, SfxChildAlignment eAlign, bool bCanGetFocus=false ); void ShowChildren_Impl(); void HideChildren_Impl(); bool PrepareClose_Impl(); virtual void ArrangeChildren_Impl( bool bForce = true ); void DeleteControllers_Impl(); void HidePopups_Impl(bool bHide, bool bParent=false, sal_uInt16 nId=0); void ConfigChild_Impl(SfxChildIdentifier, SfxDockingConfig, sal_uInt16); void MakeChildrenVisible_Impl( bool bVis ); void ArrangeAutoHideWindows( SfxSplitWindow *pSplit ); bool IsAutoHideMode( const SfxSplitWindow *pSplit ); void EndAutoShow_Impl( Point aPos ); void SetFullScreen_Impl( bool bSet ) { bIsFullScreen = bSet; } bool IsFullScreen_Impl() const { return bIsFullScreen; } // Methods for Objectbars virtual void UpdateObjectBars_Impl(); void ResetObjectBars_Impl(); void SetObjectBar_Impl(sal_uInt16 nPos, sal_uInt32 nResId, SfxInterface *pIFace); bool KnowsObjectBar_Impl( sal_uInt16 nPos ) const; bool IsVisible_Impl(); void MakeVisible_Impl( bool ); void SetObjectBarVisibility_Impl( sal_uInt16 nVis ); bool IsContainer_Impl() const; void Lock_Impl( bool ); // Methods for ChildWindows void UpdateChildWindows_Impl(); void ResetChildWindows_Impl(); void SetChildWindowVisible_Impl( sal_uInt32, bool, sal_uInt16 ); void ToggleChildWindow_Impl(sal_uInt16,bool); bool HasChildWindow_Impl(sal_uInt16); bool KnowsChildWindow_Impl(sal_uInt16); void ShowChildWindow_Impl(sal_uInt16, bool bVisible, bool bSetFocus); void SetChildWindow_Impl(sal_uInt16, bool bOn, bool bSetFocus); SfxChildWindow* GetChildWindow_Impl(sal_uInt16); void InitializeChild_Impl(SfxChildWin_Impl*); SfxSplitWindow* GetSplitWindow_Impl(SfxChildAlignment); bool IsVisible_Impl( sal_uInt16 nMode ) const; bool IsFloating( sal_uInt16 nId ); void SetActiveChild_Impl( vcl::Window *pChild ); bool ActivateNextChild_Impl( bool bForward = true ); bool AllowChildWindowCreation_Impl( const SfxChildWin_Impl& i_rCW ) const; // Methods for StatusBar void ResetStatusBar_Impl(); void SetStatusBar_Impl(sal_uInt32 nResId, SfxShell *pShell, SfxBindings& ); void UpdateStatusBar_Impl(); ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > GetStatusIndicator(); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > GetFrameInterface(); }; class SfxFrameWorkWin_Impl : public SfxWorkWindow { SfxFrame* pMasterFrame; SfxFrame* pFrame; public: SfxFrameWorkWin_Impl( vcl::Window* pWin, SfxFrame* pFrm, SfxFrame* pMaster ); virtual void ArrangeChildren_Impl( bool bForce = true ) SAL_OVERRIDE; virtual void UpdateObjectBars_Impl() SAL_OVERRIDE; virtual Rectangle GetTopRect_Impl() SAL_OVERRIDE; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>SfxChildWin_Impl::nVisibility is of type sal_uInt16/SVX_VISIBILITY_*<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX #define INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX #include <vector> #include <deque> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/ui/XUIElement.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/frame/XLayoutManagerListener.hpp> #include <cppuhelper/implbase2.hxx> #include <cppuhelper/propshlp.hxx> #include <rtl/ustring.hxx> #include <osl/mutex.hxx> #include <o3tl/typed_flags_set.hxx> #include <sfx2/sfx.hrc> #include <sfx2/childwin.hxx> #include <sfx2/shell.hxx> #include <sfx2/ctrlitem.hxx> #include <sfx2/viewfrm.hxx> class SfxSplitWindow; class SfxWorkWindow; // This struct makes all relevant Informationen available of Toolboxes struct SfxObjectBar_Impl { sal_uInt16 nId; // Resource - and ConfigId of Toolbox sal_uInt16 nMode; // special visibility flags sal_uInt16 nPos; sal_uInt16 nIndex; bool bDestroy; SfxInterface* pIFace; SfxObjectBar_Impl() : nId(0), nMode(0), nPos(0), nIndex(0), bDestroy(false), pIFace(0) {} }; // This struct makes all relevant Informationen available of the status bar struct SfxStatBar_Impl { sal_uInt16 nId; bool bOn; bool bTemp; SfxStatBar_Impl() : nId(0), bOn(true), bTemp(false) {} }; enum class SfxChildVisibility { NOT_VISIBLE = 0, ACTIVE = 1, // not disabled through HidePopups NOT_HIDDEN = 2, // not disabled through HideChildWindow FITS_IN = 4, // not too large for output size of the parent VISIBLE = 7, // NOT_HIDDEN | ACTIVE | FITS_IN) }; namespace o3tl { template<> struct typed_flags<SfxChildVisibility> : is_typed_flags<SfxChildVisibility, 0x07> {}; } struct SfxChild_Impl { vcl::Window* pWin; Size aSize; SfxChildAlignment eAlign; SfxChildVisibility nVisible; bool bResize; bool bCanGetFocus; bool bSetFocus; SfxChild_Impl( vcl::Window& rChild, const Size& rSize, SfxChildAlignment eAlignment, bool bIsVisible ): pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(false), bCanGetFocus( false ), bSetFocus( false ) { nVisible = bIsVisible ? SfxChildVisibility::VISIBLE : SfxChildVisibility::NOT_VISIBLE; } }; struct SfxChildWin_Impl { sal_uInt16 nSaveId; // the ChildWindow-Id sal_uInt16 nInterfaceId; // the current context sal_uInt16 nId; // current Id SfxChildWindow* pWin; bool bCreate; SfxChildWinInfo aInfo; SfxChild_Impl* pCli; // != 0 at direct Children sal_uInt16 nVisibility; bool bEnable; bool bDisabled; SfxChildWin_Impl( sal_uInt32 nID ) : nSaveId((sal_uInt16) (nID & 0xFFFF) ), nInterfaceId((sal_uInt16) (nID >> 16)), nId(nSaveId), pWin(0), bCreate(false), pCli(0), nVisibility( SFX_VISIBILITY_UNVISIBLE ), bEnable( true ), bDisabled( false ) {} }; enum class SfxChildIdentifier { STATBAR, OBJECTBAR, DOCKINGWINDOW, SPLITWINDOW }; enum class SfxDockingConfig { SETDOCKINGRECTS, ALIGNDOCKINGWINDOW, TOGGLEFLOATMODE, MOVEDOCKINGWINDOW }; typedef std::vector<SfxChild_Impl*> SfxChildList_Impl; typedef std::vector<SfxChildWin_Impl*> SfxChildWindows_Impl; struct SfxObjectBarList_Impl { std::deque<SfxObjectBar_Impl> aArr; sal_uInt16 nAct; SfxObjectBar_Impl operator[] ( sal_uInt16 n ) { return aArr[n]; } SfxObjectBar_Impl Actual() { return aArr[nAct]; } }; #define SFX_SPLITWINDOWS_LEFT 0 #define SFX_SPLITWINDOWS_TOP 2 #define SFX_SPLITWINDOWS_RIGHT 1 #define SFX_SPLITWINDOWS_MAX 4 class LayoutManagerListener : public ::cppu::WeakImplHelper2< css::frame::XLayoutManagerListener, css::lang::XComponent > { public: LayoutManagerListener( SfxWorkWindow* pWrkWin ); virtual ~LayoutManagerListener(); void setFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); // XComponent virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE; // XLayoutManagerEventListener virtual void SAL_CALL layoutEvent( const ::com::sun::star::lang::EventObject& aSource, ::sal_Int16 eLayoutEvent, const ::com::sun::star::uno::Any& aInfo ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; private: bool m_bHasFrame; SfxWorkWindow* m_pWrkWin; ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > m_xFrame; OUString m_aLayoutManagerPropName; }; class SfxWorkWindow { friend class LayoutManagerListener; protected: std::vector<sal_uInt16> aSortedList; SfxStatBar_Impl aStatBar; std::vector< SfxObjectBar_Impl > aObjBarList; Rectangle aClientArea; Rectangle aUpperClientArea; SfxWorkWindow* pParent; SfxSplitWindow* pSplit[SFX_SPLITWINDOWS_MAX]; SfxChildList_Impl aChildren; SfxChildWindows_Impl aChildWins; SfxBindings* pBindings; vcl::Window* pWorkWin; SfxShell* pConfigShell; vcl::Window* pActiveChild; sal_uInt16 nUpdateMode; sal_uInt16 nChildren; sal_uInt16 nOrigMode; bool bSorted : 1; bool bDockingAllowed : 1; bool bInternalDockingAllowed : 1; bool bAllChildrenVisible : 1; bool bIsFullScreen : 1; bool bShowStatusBar : 1; sal_Int32 m_nLock; OUString m_aStatusBarResName; OUString m_aLayoutManagerPropName; OUString m_aTbxTypeName; OUString m_aProgressBarResName; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xLayoutManagerListener; protected: void CreateChildWin_Impl(SfxChildWin_Impl*,bool); void RemoveChildWin_Impl(SfxChildWin_Impl*); void Sort_Impl(); SfxChild_Impl* FindChild_Impl( const vcl::Window& rWindow ) const; bool RequestTopToolSpacePixel_Impl( SvBorder aBorder ); virtual Rectangle GetTopRect_Impl(); SvBorder Arrange_Impl(); void SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&); static bool IsPluginMode( SfxObjectShell* pObjShell ); public: SfxWorkWindow( vcl::Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL); virtual ~SfxWorkWindow(); SfxBindings& GetBindings() { return *pBindings; } vcl::Window* GetWindow() const { return pWorkWin; } Rectangle GetFreeArea( bool bAutoHide ) const; void SetDockingAllowed(bool bSet) { bDockingAllowed = bSet; } void SetInternalDockingAllowed(bool bSet) { bInternalDockingAllowed = bSet; } bool IsDockingAllowed() const { return bDockingAllowed; } bool IsInternalDockingAllowed() const { return bInternalDockingAllowed; } SfxWorkWindow* GetParent_Impl() const { return pParent; } // Methods for all Child windows void DataChanged_Impl( const DataChangedEvent& rDCEvt ); void ReleaseChild_Impl( vcl::Window& rWindow ); SfxChild_Impl* RegisterChild_Impl( vcl::Window& rWindow, SfxChildAlignment eAlign, bool bCanGetFocus=false ); void ShowChildren_Impl(); void HideChildren_Impl(); bool PrepareClose_Impl(); virtual void ArrangeChildren_Impl( bool bForce = true ); void DeleteControllers_Impl(); void HidePopups_Impl(bool bHide, bool bParent=false, sal_uInt16 nId=0); void ConfigChild_Impl(SfxChildIdentifier, SfxDockingConfig, sal_uInt16); void MakeChildrenVisible_Impl( bool bVis ); void ArrangeAutoHideWindows( SfxSplitWindow *pSplit ); bool IsAutoHideMode( const SfxSplitWindow *pSplit ); void EndAutoShow_Impl( Point aPos ); void SetFullScreen_Impl( bool bSet ) { bIsFullScreen = bSet; } bool IsFullScreen_Impl() const { return bIsFullScreen; } // Methods for Objectbars virtual void UpdateObjectBars_Impl(); void ResetObjectBars_Impl(); void SetObjectBar_Impl(sal_uInt16 nPos, sal_uInt32 nResId, SfxInterface *pIFace); bool KnowsObjectBar_Impl( sal_uInt16 nPos ) const; bool IsVisible_Impl(); void MakeVisible_Impl( bool ); void SetObjectBarVisibility_Impl( sal_uInt16 nVis ); bool IsContainer_Impl() const; void Lock_Impl( bool ); // Methods for ChildWindows void UpdateChildWindows_Impl(); void ResetChildWindows_Impl(); void SetChildWindowVisible_Impl( sal_uInt32, bool, sal_uInt16 ); void ToggleChildWindow_Impl(sal_uInt16,bool); bool HasChildWindow_Impl(sal_uInt16); bool KnowsChildWindow_Impl(sal_uInt16); void ShowChildWindow_Impl(sal_uInt16, bool bVisible, bool bSetFocus); void SetChildWindow_Impl(sal_uInt16, bool bOn, bool bSetFocus); SfxChildWindow* GetChildWindow_Impl(sal_uInt16); void InitializeChild_Impl(SfxChildWin_Impl*); SfxSplitWindow* GetSplitWindow_Impl(SfxChildAlignment); bool IsVisible_Impl( sal_uInt16 nMode ) const; bool IsFloating( sal_uInt16 nId ); void SetActiveChild_Impl( vcl::Window *pChild ); bool ActivateNextChild_Impl( bool bForward = true ); bool AllowChildWindowCreation_Impl( const SfxChildWin_Impl& i_rCW ) const; // Methods for StatusBar void ResetStatusBar_Impl(); void SetStatusBar_Impl(sal_uInt32 nResId, SfxShell *pShell, SfxBindings& ); void UpdateStatusBar_Impl(); ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > GetStatusIndicator(); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > GetFrameInterface(); }; class SfxFrameWorkWin_Impl : public SfxWorkWindow { SfxFrame* pMasterFrame; SfxFrame* pFrame; public: SfxFrameWorkWin_Impl( vcl::Window* pWin, SfxFrame* pFrm, SfxFrame* pMaster ); virtual void ArrangeChildren_Impl( bool bForce = true ) SAL_OVERRIDE; virtual void UpdateObjectBars_Impl() SAL_OVERRIDE; virtual Rectangle GetTopRect_Impl() SAL_OVERRIDE; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include "CallGraph.h" #include "FindCalls.h" #include "IR.h" #include "Util.h" namespace Bish { void Module::set_main(Function *f) { add_function(f); main = f; } void Module::add_function(Function *f) { functions.push_back(f); } void Module::add_global(Assignment *a) { global_variables.push_back(a); } void Module::set_path(const std::string &p) { path = p; namespace_id = remove_suffix(basename(path), "."); assert(!namespace_id.empty() && "Unable to resolve namespace identifier."); } Function *Module::get_function(const Name &name) const { for (std::vector<Function *>::const_iterator I = functions.begin(), E = functions.end(); I != E; ++I) { if (name.name == (*I)->name.name) { return *I; } } return NULL; } void Module::import(Module *m) { FindCallsToModule find(m); accept(&find); CallGraphBuilder cgb; CallGraph cg = cgb.build(m); std::set<Name> to_link = find.functions(); for (std::set<Name>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) { const Name &name = *I; // FindCallsToModule only compares function names to allow the // standard library functions to be called without a // namespace. Therefore, to_link can contain functions with // the same name but belonging to a different namespace. Don't // process those here: if (!name.namespace_id.empty() && name.namespace_id != m->namespace_id) continue; Function *f = m->get_function(name); assert(f); assert(f->name.namespace_id.empty()); f->name.namespace_id = m->namespace_id; add_function(f); // Make sure to pull in functions that f calls as well. std::vector<Function *> calls = cg.transitive_calls(f); for (std::vector<Function *>::iterator CI = calls.begin(), CE = calls.end(); CI != CE; ++CI) { f = *CI; // Avoid dummy functions and duplicates. if (f->body == NULL || to_link.count(f->name)) continue; assert(f->name.namespace_id.empty()); f->name.namespace_id = m->namespace_id; add_function(f); } } // Special case for standard library functions: fix up the // function call namespaces. This is so that the user does not // have to write, for example, "Stdlib.assert()" in order to call // the standard library assert function. if (m->path == get_stdlib_path()) { std::vector<FunctionCall *> calls = find.function_calls(); for (std::vector<FunctionCall *>::iterator I = calls.begin(), E = calls.end(); I != E; ++I) { FunctionCall *call = *I; call->function->name.namespace_id = "StdLib"; } } } } <commit_msg>Update function pointers when importing.<commit_after>#include <cassert> #include <iostream> #include "CallGraph.h" #include "FindCalls.h" #include "IR.h" #include "Util.h" namespace Bish { void Module::set_main(Function *f) { add_function(f); main = f; } void Module::add_function(Function *f) { functions.push_back(f); } void Module::add_global(Assignment *a) { global_variables.push_back(a); } void Module::set_path(const std::string &p) { path = p; namespace_id = remove_suffix(basename(path), "."); assert(!namespace_id.empty() && "Unable to resolve namespace identifier."); } Function *Module::get_function(const Name &name) const { for (std::vector<Function *>::const_iterator I = functions.begin(), E = functions.end(); I != E; ++I) { if (name.name == (*I)->name.name) { return *I; } } return NULL; } void Module::import(Module *m) { FindCallsToModule find(m); accept(&find); CallGraphBuilder cgb; CallGraph cg = cgb.build(m); std::set<Name> to_link = find.functions(); std::map<Name, Function *> linked; for (std::set<Name>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) { const Name &name = *I; // FindCallsToModule only compares function names to allow the // standard library functions to be called without a // namespace. Therefore, to_link can contain functions with // the same name but belonging to a different namespace. Don't // process those here: if (!name.namespace_id.empty() && name.namespace_id != m->namespace_id) continue; Function *f = m->get_function(name); assert(f); assert(f->name.namespace_id.empty()); f->name.namespace_id = m->namespace_id; add_function(f); linked[f->name] = f; // Make sure to pull in functions that f calls as well. std::vector<Function *> calls = cg.transitive_calls(f); for (std::vector<Function *>::iterator CI = calls.begin(), CE = calls.end(); CI != CE; ++CI) { f = *CI; // Avoid dummy functions and duplicates. if (f->body == NULL || to_link.count(f->name)) continue; //assert(f->name.namespace_id.empty()); f->name.namespace_id = m->namespace_id; add_function(f); linked[f->name] = f; } } // Now patch up the function pointers, replacing the "dummy" // functions inserted at parse time with the real functions from // the imported module. std::vector<FunctionCall *> calls = find.function_calls(); std::set<Function *> to_erase; for (std::vector<FunctionCall *>::iterator I = calls.begin(), E = calls.end(); I != E; ++I) { FunctionCall *call = *I; Name name = call->function->name; // Special case for stdlib functions: they can be called // without a namespace, so add it here. if (m->path == get_stdlib_path()) { call->function->name.namespace_id = "StdLib"; } if (linked.find(name) != linked.end()) { assert(call->function->body == NULL); to_erase.insert(call->function); call->function = linked[name]; } } // Finally, erase the old dummy functions. for (std::vector<Function *>::iterator I = functions.begin(), E = functions.end(); I != E; ) { if (to_erase.find(*I) != to_erase.end()) { delete *I; I = functions.erase(I); } else { ++I; } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: admininvokationpage.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-08-02 17:36:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #include "admininvokationpage.hxx" #endif #ifndef EXTENSIONS_ABSPILOT_HXX #include "abspilot.hxx" #endif #ifndef EXTENSIONS_ABP_ADMININVOKATIONIMPL_HXX #include "admininvokationimpl.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AdminDialogInvokationPage //===================================================================== AdminDialogInvokationPage::AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent ) :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_ADMININVOKATION)) ,m_aExplanation (this, ResId(FT_ADMINEXPLANATION)) ,m_aInvokeAdminDialog (this, ResId(PB_INVOKE_ADMIN_DIALOG)) ,m_aErrorMessage (this, ResId(FT_ERROR)) ,m_bSuccessfullyExecutedDialog(sal_False) { FreeResource(); m_aInvokeAdminDialog.SetClickHdl( LINK(this, AdminDialogInvokationPage, OnInvokeAdminDialog) ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::ActivatePage() { AddressBookSourcePage::ActivatePage(); m_aInvokeAdminDialog.GrabFocus(); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::implUpdateErrorMessage() { const sal_Bool bIsConnected = getDialog()->getDataSource().isConnected(); m_aErrorMessage.Show( !bIsConnected ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::initializePage() { AddressBookSourcePage::initializePage(); m_aErrorMessage.Hide(); // if we're entering this page, we assume we had no connection trial with this data source } //--------------------------------------------------------------------- sal_Bool AdminDialogInvokationPage::commitPage( COMMIT_REASON _eReason ) { return AddressBookSourcePage::commitPage( _eReason ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::implTryConnect() { sal_Bool bConnected = getDialog()->connectToDataSource( sal_True ); // show our error message if and only if we could not connect implUpdateErrorMessage(); // the status of the next button may have changed implCheckNextButton(); // automatically go to the next page (if successfully connected) if ( determineNextButtonState() ) getDialog()->travelNext(); } //--------------------------------------------------------------------- sal_Bool AdminDialogInvokationPage::determineNextButtonState() { return AddressBookSourcePage::determineNextButtonState() && getDialog()->getDataSource().isConnected(); } //--------------------------------------------------------------------- IMPL_LINK( AdminDialogInvokationPage, OnInvokeAdminDialog, void*, NOTINTERESTEDIN ) { OAdminDialogInvokation aInvokation( getORB(), getDialog()->getDataSource().getDataSource(), getDialog() ); if ( aInvokation.invokeAdministration( AST_LDAP == getSettings().eType ) ) { // try to connect to this data source implTryConnect(); } return 0L; } //......................................................................... } // namespace abp //......................................................................... <commit_msg>INTEGRATION: CWS ooo19126 (1.4.222); FILE MERGED 2005/09/05 12:58:31 rt 1.4.222.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: admininvokationpage.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:05:47 $ * * 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 EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #include "admininvokationpage.hxx" #endif #ifndef EXTENSIONS_ABSPILOT_HXX #include "abspilot.hxx" #endif #ifndef EXTENSIONS_ABP_ADMININVOKATIONIMPL_HXX #include "admininvokationimpl.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AdminDialogInvokationPage //===================================================================== AdminDialogInvokationPage::AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent ) :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_ADMININVOKATION)) ,m_aExplanation (this, ResId(FT_ADMINEXPLANATION)) ,m_aInvokeAdminDialog (this, ResId(PB_INVOKE_ADMIN_DIALOG)) ,m_aErrorMessage (this, ResId(FT_ERROR)) ,m_bSuccessfullyExecutedDialog(sal_False) { FreeResource(); m_aInvokeAdminDialog.SetClickHdl( LINK(this, AdminDialogInvokationPage, OnInvokeAdminDialog) ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::ActivatePage() { AddressBookSourcePage::ActivatePage(); m_aInvokeAdminDialog.GrabFocus(); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::implUpdateErrorMessage() { const sal_Bool bIsConnected = getDialog()->getDataSource().isConnected(); m_aErrorMessage.Show( !bIsConnected ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::initializePage() { AddressBookSourcePage::initializePage(); m_aErrorMessage.Hide(); // if we're entering this page, we assume we had no connection trial with this data source } //--------------------------------------------------------------------- sal_Bool AdminDialogInvokationPage::commitPage( COMMIT_REASON _eReason ) { return AddressBookSourcePage::commitPage( _eReason ); } //--------------------------------------------------------------------- void AdminDialogInvokationPage::implTryConnect() { sal_Bool bConnected = getDialog()->connectToDataSource( sal_True ); // show our error message if and only if we could not connect implUpdateErrorMessage(); // the status of the next button may have changed implCheckNextButton(); // automatically go to the next page (if successfully connected) if ( determineNextButtonState() ) getDialog()->travelNext(); } //--------------------------------------------------------------------- sal_Bool AdminDialogInvokationPage::determineNextButtonState() { return AddressBookSourcePage::determineNextButtonState() && getDialog()->getDataSource().isConnected(); } //--------------------------------------------------------------------- IMPL_LINK( AdminDialogInvokationPage, OnInvokeAdminDialog, void*, NOTINTERESTEDIN ) { OAdminDialogInvokation aInvokation( getORB(), getDialog()->getDataSource().getDataSource(), getDialog() ); if ( aInvokation.invokeAdministration( AST_LDAP == getSettings().eType ) ) { // try to connect to this data source implTryConnect(); } return 0L; } //......................................................................... } // namespace abp //......................................................................... <|endoftext|>
<commit_before>#include "marketorderswidget.hpp" #include "ui_marketorderswidget.h" #include <QSqlQuery> #include <QListIterator> #include <QPushButton> #include <QTableWidget> #include <QtXmlPatterns> #include <QMovie> #include "network.hpp" #include "queries.hpp" #include "settings.hpp" #include "global.hpp" MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MarketOrdersWidget) { ui->setupUi(this); for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) { MarketOrdersTable* table = i.next(); table->setColumnCount(4); table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")}); table->verticalHeader()->hide(); table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); } refreshOrStopButton = new QPushButton(); setButtonState(RefreshState); ui->tabs->setCornerWidget(refreshOrStopButton); typeId = -1; connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)), this, SLOT(typeDropped(int))); connect(refreshOrStopButton, SIGNAL(clicked()), this, SLOT(refreshOrStop())); } MarketOrdersWidget::~MarketOrdersWidget() { delete ui; } void MarketOrdersWidget::typeDropped(int typeId) { this->typeId = typeId; QSqlQuery* typeNameQuery = Queries::getTypeNameQuery(); typeNameQuery->bindValue(":id", typeId); typeNameQuery->exec(); typeNameQuery->next(); QString typeName = typeNameQuery->value(0).toString(); ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(typeName)); ui->infoButton->init(typeId); reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting()); refreshOrStopButton->show(); setButtonState(StopState); connect(reply, SIGNAL(finished()), this, SLOT(replyFinished())); } void MarketOrdersWidget::replyFinished() { QString xmlString = reply->readAll(); reply->deleteLater(); clearTable(ui->sellOrdersTable); clearTable(ui->buyOrdersTable); parseReply(xmlString); setButtonState(RefreshState); } void MarketOrdersWidget::parseReply(const QString& xmlString) { parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders"); parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders"); } void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName) { QXmlQuery query; query.setFocus(xmlString); query.setQuery(QString("for $x in //%1/order \n" "return fn:concat($x/station/text(), \"/\"," " $x/price/text(), \"/\"," " $x/vol_remain/text(), \"/\"," " $x/reported_time/text())").arg(tagName)); QStringList strlist; query.evaluateTo(&strlist); for (int i = 0; i < strlist.size(); i++) { QStringList splitted = strlist[i].split("/"); addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(), splitted[2].toInt(), splitted[3]); } } void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price, int quantity, QString reportedTime) { QLocale locale(QLocale::English); int rowId = table->rowCount(); table->insertRow(rowId); QSqlQuery* stationNameQuery = Queries::getStationNameQuery(); stationNameQuery->bindValue(":id", stationId); stationNameQuery->exec(); stationNameQuery->next(); table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString())); table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2))); table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity))); table->setItem(rowId, 3, new QTableWidgetItem(reportedTime)); for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();) table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); } void MarketOrdersWidget::clearTable(QTableWidget* table) { while (table->rowCount()) table->removeRow(0); } void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state) { buttonState = state; switch (state) { case RefreshState: refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11"))); break; case StopState: refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45"))); break; } } void MarketOrdersWidget::refreshOrStop() { switch (buttonState) { case RefreshState: refresh(); break; case StopState: stop(); break; } } void MarketOrdersWidget::refresh() { typeDropped(typeId); } void MarketOrdersWidget::stop() { reply->deleteLater(); setButtonState(RefreshState); } <commit_msg>Fix a bug where the refreshOrStopButton will be shown on startup.<commit_after>#include "marketorderswidget.hpp" #include "ui_marketorderswidget.h" #include <QSqlQuery> #include <QListIterator> #include <QPushButton> #include <QTableWidget> #include <QtXmlPatterns> #include <QMovie> #include "network.hpp" #include "queries.hpp" #include "settings.hpp" #include "global.hpp" MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MarketOrdersWidget) { ui->setupUi(this); for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) { MarketOrdersTable* table = i.next(); table->setColumnCount(4); table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")}); table->verticalHeader()->hide(); table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); } refreshOrStopButton = new QPushButton(); setButtonState(RefreshState); ui->tabs->setCornerWidget(refreshOrStopButton); refreshOrStopButton->hide(); typeId = -1; connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)), this, SLOT(typeDropped(int))); connect(refreshOrStopButton, SIGNAL(clicked()), this, SLOT(refreshOrStop())); } MarketOrdersWidget::~MarketOrdersWidget() { delete ui; } void MarketOrdersWidget::typeDropped(int typeId) { this->typeId = typeId; QSqlQuery* typeNameQuery = Queries::getTypeNameQuery(); typeNameQuery->bindValue(":id", typeId); typeNameQuery->exec(); typeNameQuery->next(); QString typeName = typeNameQuery->value(0).toString(); ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(typeName)); ui->infoButton->init(typeId); reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting()); refreshOrStopButton->show(); setButtonState(StopState); connect(reply, SIGNAL(finished()), this, SLOT(replyFinished())); } void MarketOrdersWidget::replyFinished() { QString xmlString = reply->readAll(); reply->deleteLater(); clearTable(ui->sellOrdersTable); clearTable(ui->buyOrdersTable); parseReply(xmlString); setButtonState(RefreshState); } void MarketOrdersWidget::parseReply(const QString& xmlString) { parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders"); parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders"); } void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName) { QXmlQuery query; query.setFocus(xmlString); query.setQuery(QString("for $x in //%1/order \n" "return fn:concat($x/station/text(), \"/\"," " $x/price/text(), \"/\"," " $x/vol_remain/text(), \"/\"," " $x/reported_time/text())").arg(tagName)); QStringList strlist; query.evaluateTo(&strlist); for (int i = 0; i < strlist.size(); i++) { QStringList splitted = strlist[i].split("/"); addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(), splitted[2].toInt(), splitted[3]); } } void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price, int quantity, QString reportedTime) { QLocale locale(QLocale::English); int rowId = table->rowCount(); table->insertRow(rowId); QSqlQuery* stationNameQuery = Queries::getStationNameQuery(); stationNameQuery->bindValue(":id", stationId); stationNameQuery->exec(); stationNameQuery->next(); table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString())); table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2))); table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity))); table->setItem(rowId, 3, new QTableWidgetItem(reportedTime)); for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();) table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); } void MarketOrdersWidget::clearTable(QTableWidget* table) { while (table->rowCount()) table->removeRow(0); } void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state) { buttonState = state; switch (state) { case RefreshState: refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11"))); break; case StopState: refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45"))); break; } } void MarketOrdersWidget::refreshOrStop() { switch (buttonState) { case RefreshState: refresh(); break; case StopState: stop(); break; } } void MarketOrdersWidget::refresh() { typeDropped(typeId); } void MarketOrdersWidget::stop() { reply->deleteLater(); setButtonState(RefreshState); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "processcontrol.h" #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <signal.h> #endif using namespace Akonadi; ProcessControl::ProcessControl( QObject *parent ) : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ), mRestartOnceOnExit( false ) { connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ), this, SLOT( slotError( QProcess::ProcessError ) ) ); connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) ); connect( &mProcess, SIGNAL( readyReadStandardError() ), this, SLOT( slotErrorMessages() ) ); connect( &mProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( slotStdoutMessages() ) ); } ProcessControl::~ProcessControl() { stop(); } void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy ) { mFailedToStart = false; mApplication = application; mArguments = arguments; mPolicy = policy; start(); } void ProcessControl::setCrashPolicy( CrashPolicy policy ) { mPolicy = policy; } void ProcessControl::stop() { if ( mProcess.state() != QProcess::NotRunning ) { mProcess.waitForFinished( 10000 ); mProcess.terminate(); } } void ProcessControl::slotError( QProcess::ProcessError error ) { switch ( error ) { case QProcess::Crashed: // do nothing, we'll respawn in slotFinished break; case QProcess::FailedToStart: default: mFailedToStart = true; break; } qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); } void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus ) { if ( exitStatus == QProcess::CrashExit ) { if ( mPolicy == RestartOnCrash ) { if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( exitCode != 0 ) { qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)", qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) ); if ( mPolicy == RestartOnCrash ) { if ( mCrashCount > 2 ) { qWarning() << mApplication << "crashed too often and will not be restarted!"; mPolicy = StopOnCrash; emit unableToStart(); return; } ++mCrashCount; QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) ); if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( mRestartOnceOnExit ) { mRestartOnceOnExit = false; qDebug( "Restarting application '%s'.", qPrintable( mApplication ) ); start(); } else { qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) ); } } } } void ProcessControl::start() { #ifdef Q_OS_UNIX QString agentValgrind = QString::fromLocal8Bit( qgetenv("AKONADI_VALGRIND") ); if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Valgrinding process" << mApplication; qDebug() << "============================================================"; qDebug(); QString valgrindSkin = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) ); mArguments.prepend( mApplication ); mApplication = QString::fromLocal8Bit( "valgrind" ); if ( !valgrindSkin.isEmpty() ) mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin ); else mArguments.prepend (QLatin1String( "--tool=memcheck") ); } #endif mProcess.start( mApplication, mArguments ); if ( !mProcess.waitForStarted( ) ) { qDebug( "ProcessControl: Unable to start application '%s' (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); return; } #ifdef Q_OS_UNIX else { QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) ); pid_t pid = mProcess.pid(); if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Suspending process" << mApplication; qDebug() << "'gdb" << pid << "' to debug"; qDebug() << "'kill -SIGCONT" << pid << "' to continue"; qDebug() << "============================================================"; qDebug(); kill( pid, SIGSTOP ); } } #endif } void Akonadi::ProcessControl::slotStdoutMessages() { mProcess.setReadChannel( QProcess::StandardOutput ); while ( mProcess.canReadLine() ) { QString message = QString::fromUtf8( mProcess.readLine() ); qDebug() << mApplication << "[out]" << message; } } void ProcessControl::slotErrorMessages() { mProcess.setReadChannel( QProcess::StandardError ); while ( mProcess.canReadLine() ) { QString message = QString::fromUtf8( mProcess.readLine() ); emit processErrorMessages( message ); qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) ); } } void ProcessControl::resetCrashCount() { mCrashCount = 0; } #include "processcontrol.moc" <commit_msg>add AKONADI_VALGRIND_OPTIONS to specify additional options (besides the skin used) for valgrind<commit_after>/*************************************************************************** * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "processcontrol.h" #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <signal.h> #endif using namespace Akonadi; ProcessControl::ProcessControl( QObject *parent ) : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ), mRestartOnceOnExit( false ) { connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ), this, SLOT( slotError( QProcess::ProcessError ) ) ); connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) ); connect( &mProcess, SIGNAL( readyReadStandardError() ), this, SLOT( slotErrorMessages() ) ); connect( &mProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( slotStdoutMessages() ) ); } ProcessControl::~ProcessControl() { stop(); } void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy ) { mFailedToStart = false; mApplication = application; mArguments = arguments; mPolicy = policy; start(); } void ProcessControl::setCrashPolicy( CrashPolicy policy ) { mPolicy = policy; } void ProcessControl::stop() { if ( mProcess.state() != QProcess::NotRunning ) { mProcess.waitForFinished( 10000 ); mProcess.terminate(); } } void ProcessControl::slotError( QProcess::ProcessError error ) { switch ( error ) { case QProcess::Crashed: // do nothing, we'll respawn in slotFinished break; case QProcess::FailedToStart: default: mFailedToStart = true; break; } qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); } void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus ) { if ( exitStatus == QProcess::CrashExit ) { if ( mPolicy == RestartOnCrash ) { if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( exitCode != 0 ) { qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)", qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) ); if ( mPolicy == RestartOnCrash ) { if ( mCrashCount > 2 ) { qWarning() << mApplication << "crashed too often and will not be restarted!"; mPolicy = StopOnCrash; emit unableToStart(); return; } ++mCrashCount; QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) ); if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( mRestartOnceOnExit ) { mRestartOnceOnExit = false; qDebug( "Restarting application '%s'.", qPrintable( mApplication ) ); start(); } else { qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) ); } } } } namespace { static QString getEnv( const char* name, const QString& defaultValue=QString() ) { const QString v = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) ); return !v.isEmpty() ? v : defaultValue; } } void ProcessControl::start() { #ifdef Q_OS_UNIX QString agentValgrind = getEnv( "AKONADI_VALGRIND" ); if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) { mArguments.prepend( mApplication ); mApplication = QString::fromLocal8Bit( "valgrind" ); const QString valgrindSkin = getEnv( "AKONADI_VALGRIND_SKIN", QString::fromLocal8Bit( "memcheck" ) ); mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin ); const QString valgrindOptions = getEnv( "AKONADI_VALGRIND_OPTIONS" ); if ( !valgrindOptions.isEmpty() ) mArguments.prepend( valgrindOptions ); qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Valgrinding process" << mApplication; if ( !valgrindSkin.isEmpty() ) qDebug() << "ProcessControl: Valgrind skin:" << valgrindSkin; if ( !valgrindOptions.isEmpty() ) qDebug() << "ProcessControl: Additional Valgrind options:" << valgrindOptions; qDebug() << "============================================================"; qDebug(); } #endif mProcess.start( mApplication, mArguments ); if ( !mProcess.waitForStarted( ) ) { qDebug( "ProcessControl: Unable to start application '%s' (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); return; } #ifdef Q_OS_UNIX else { QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) ); pid_t pid = mProcess.pid(); if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Suspending process" << mApplication; qDebug() << "'gdb" << pid << "' to debug"; qDebug() << "'kill -SIGCONT" << pid << "' to continue"; qDebug() << "============================================================"; qDebug(); kill( pid, SIGSTOP ); } } #endif } void Akonadi::ProcessControl::slotStdoutMessages() { mProcess.setReadChannel( QProcess::StandardOutput ); while ( mProcess.canReadLine() ) { QString message = QString::fromUtf8( mProcess.readLine() ); qDebug() << mApplication << "[out]" << message; } } void ProcessControl::slotErrorMessages() { mProcess.setReadChannel( QProcess::StandardError ); while ( mProcess.canReadLine() ) { QString message = QString::fromUtf8( mProcess.readLine() ); emit processErrorMessages( message ); qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) ); } } void ProcessControl::resetCrashCount() { mCrashCount = 0; } #include "processcontrol.moc" <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfiltertabpagexslt.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:49:14 $ * * 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_filter.hxx" #ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_ #include <com/sun/star/frame/XConfigManager.hpp> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "xmlfiltertabpagexslt.hxx" #include "xmlfiltertabpagexslt.hrc" #include "xmlfiltersettingsdialog.hxx" #include "xmlfilterhelpids.hrc" using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) : TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, &rResMgr ) ), maFTDocType( this, ResId( FT_XML_DOCTYPE ) ), maEDDocType( this, ResId( ED_XML_DOCTYPE ) ), maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA ) ), maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA ), INET_PROT_FILE ), maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE ) ), maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT ) ), maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT ), INET_PROT_FILE ), maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE ) ), maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT ) ), maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT ), INET_PROT_FILE ), maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE ) ), maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE ) ), maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE ), INET_PROT_FILE ), maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE ) ), sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ), sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ), sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ), sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ), sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) ) { FreeResource(); try { Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY ); if( xCfgMgr.is() ) sInstPath = xCfgMgr->substituteVariables( sInstPath ); } catch(Exception&) { DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" ); } maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD ); maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT ); maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT ); maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE ); } XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT() { } bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo ) { if( pInfo ) { pInfo->maDocType = maEDDocType.GetText(); pInfo->maDTD = GetURL( maEDDTDSchema ); pInfo->maExportXSLT = GetURL( maEDExportXSLT ); pInfo->maImportXSLT = GetURL( maEDImportXSLT ); pInfo->maImportTemplate = GetURL( maEDImportTemplate ); } return true; } void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo) { if( pInfo ) { maEDDocType.SetText( pInfo->maDocType ); SetURL( maEDDTDSchema, pInfo->maDTD ); SetURL( maEDExportXSLT, pInfo->maExportXSLT ); SetURL( maEDImportXSLT, pInfo->maImportXSLT ); SetURL( maEDImportTemplate, pInfo->maImportTemplate ); } } void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL ) { OUString aPath; if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) ) { osl::FileBase::getSystemPathFromFileURL( rURL, aPath ); rURLBox.SetBaseURL( rURL ); rURLBox.SetText( aPath ); } else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) || rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) || rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) ) { rURLBox.SetBaseURL( rURL ); rURLBox.SetText( rURL ); } else if( rURL.getLength() ) { rtl::OUString aURL( rURL ); aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false ); osl::FileBase::getSystemPathFromFileURL( aURL, aPath ); rURLBox.SetBaseURL( aURL ); rURLBox.SetText( aPath ); } else { rURLBox.SetBaseURL( sInstPath ); String aEmpty; rURLBox.SetText( aEmpty ); } } OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox ) { OUString aURL; OUString aStrPath ( rURLBox.GetText() ); if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) || aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) || aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) ) { return aStrPath; } else { const String aBaseURL ( rURLBox.GetBaseURL() ); osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL ); } return aURL; } IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton ) { SvtURLBox* pURLBox; if( pButton == &maPBDTDSchemaBrowse ) { pURLBox = &maEDDTDSchema; } else if( pButton == &maPBExprotXSLT ) { pURLBox = &maEDExportXSLT; } else if( pButton == &maPBImportXSLT ) { pURLBox = &maEDImportXSLT; } else { pURLBox = &maEDImportTemplate; } // Open Fileopen-Dialog ::sfx2::FileDialogHelper aDlg( ::sfx2::FILEOPEN_SIMPLE, 0 ); aDlg.SetDisplayDirectory( GetURL( *pURLBox ) ); if ( aDlg.Execute() == ERRCODE_NONE ) { OUString aURL( aDlg.GetPath() ); SetURL( *pURLBox, aURL ); } return( 0L ); } <commit_msg>INTEGRATION: CWS sb59 (1.4.192); FILE MERGED 2006/08/22 12:58:29 sb 1.4.192.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlfiltertabpagexslt.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-10-12 13:45:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_ #include <com/sun/star/frame/XConfigManager.hpp> #endif #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "xmlfiltertabpagexslt.hxx" #include "xmlfiltertabpagexslt.hrc" #include "xmlfiltersettingsdialog.hxx" #include "xmlfilterhelpids.hrc" using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) : TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, &rResMgr ) ), maFTDocType( this, ResId( FT_XML_DOCTYPE ) ), maEDDocType( this, ResId( ED_XML_DOCTYPE ) ), maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA ) ), maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA ), INET_PROT_FILE ), maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE ) ), maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT ) ), maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT ), INET_PROT_FILE ), maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE ) ), maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT ) ), maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT ), INET_PROT_FILE ), maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE ) ), maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE ) ), maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE ), INET_PROT_FILE ), maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE ) ), sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ), sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ), sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ), sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ), sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) ) { FreeResource(); try { Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY ); if( xCfgMgr.is() ) sInstPath = xCfgMgr->substituteVariables( sInstPath ); } catch(Exception&) { DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" ); } maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) ); maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD ); maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT ); maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT ); maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE ); } XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT() { } bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo ) { if( pInfo ) { pInfo->maDocType = maEDDocType.GetText(); pInfo->maDTD = GetURL( maEDDTDSchema ); pInfo->maExportXSLT = GetURL( maEDExportXSLT ); pInfo->maImportXSLT = GetURL( maEDImportXSLT ); pInfo->maImportTemplate = GetURL( maEDImportTemplate ); } return true; } void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo) { if( pInfo ) { maEDDocType.SetText( pInfo->maDocType ); SetURL( maEDDTDSchema, pInfo->maDTD ); SetURL( maEDExportXSLT, pInfo->maExportXSLT ); SetURL( maEDImportXSLT, pInfo->maImportXSLT ); SetURL( maEDImportTemplate, pInfo->maImportTemplate ); } } void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL ) { OUString aPath; if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) ) { osl::FileBase::getSystemPathFromFileURL( rURL, aPath ); rURLBox.SetBaseURL( rURL ); rURLBox.SetText( aPath ); } else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) || rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) || rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) ) { rURLBox.SetBaseURL( rURL ); rURLBox.SetText( rURL ); } else if( rURL.getLength() ) { rtl::OUString aURL( rURL ); aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false ); osl::FileBase::getSystemPathFromFileURL( aURL, aPath ); rURLBox.SetBaseURL( aURL ); rURLBox.SetText( aPath ); } else { rURLBox.SetBaseURL( sInstPath ); String aEmpty; rURLBox.SetText( aEmpty ); } } OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox ) { OUString aURL; OUString aStrPath ( rURLBox.GetText() ); if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) || aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) || aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) ) { return aStrPath; } else { const String aBaseURL ( rURLBox.GetBaseURL() ); osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL ); } return aURL; } IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton ) { SvtURLBox* pURLBox; if( pButton == &maPBDTDSchemaBrowse ) { pURLBox = &maEDDTDSchema; } else if( pButton == &maPBExprotXSLT ) { pURLBox = &maEDExportXSLT; } else if( pButton == &maPBImportXSLT ) { pURLBox = &maEDImportXSLT; } else { pURLBox = &maEDImportTemplate; } // Open Fileopen-Dialog ::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 ); aDlg.SetDisplayDirectory( GetURL( *pURLBox ) ); if ( aDlg.Execute() == ERRCODE_NONE ) { OUString aURL( aDlg.GetPath() ); SetURL( *pURLBox, aURL ); } return( 0L ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: statusbarcontroller.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2008-03-07 14:34:07 $ * * 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 _SVTOOLS_STATUSBARCONTROLLER_HXX #define _SVTOOLS_STATUSBARCONTROLLER_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XUPDATABLE_HPP_ #include <com/sun/star/util/XUpdatable.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSBARCONTROLLER_HPP_ #include <com/sun/star/frame/XStatusbarController.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_ #include <com/sun/star/frame/XLayoutManager.hpp> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef INCLUDED_HASH_MAP #include <hash_map> #define INCLUDED_HASH_MAP #endif #include <tools/gen.hxx> namespace svt { class SVT_DLLPUBLIC StatusbarController : public ::com::sun::star::frame::XStatusListener, public ::com::sun::star::frame::XStatusbarController, public ::com::sun::star::lang::XInitialization, public ::com::sun::star::util::XUpdatable, public ::com::sun::star::lang::XComponent, public ::comphelper::OBaseMutex, public ::cppu::OWeakObject { public: StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& aCommandURL, unsigned short nID ); StatusbarController(); virtual ~StatusbarController(); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > getLayoutManager() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const; void updateStatus( const rtl::OUString aCommandURL ); void updateStatus(); ::Rectangle getControlRect() const; // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (); virtual void SAL_CALL release() throw (); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XUpdatable virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusbarController virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos, ::sal_Int32 nCommand, ::sal_Bool bMouseEvent, const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics, const ::com::sun::star::awt::Rectangle& rOutputRectangle, ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException); protected: struct Listener { Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) : aURL( rURL ), xDispatch( rDispatch ) {} ::com::sun::star::util::URL aURL; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch; }; typedef ::std::hash_map< ::rtl::OUString, com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > URLToDispatchMap; // methods to support status forwarder, known by the old sfx2 toolbox controller implementation void addStatusListener( const rtl::OUString& aCommandURL ); void removeStatusListener( const rtl::OUString& aCommandURL ); void bindListener(); void unbindListener(); sal_Bool isBound() const; // execute methods // execute bound status bar controller command/execute various commands void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ); void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ); sal_Bool m_bInitialized : 1, m_bDisposed : 1; unsigned short m_nID; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xParentWindow; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; rtl::OUString m_aCommandURL; URLToDispatchMap m_aListenerMap; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer; }; } #endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.26); FILE MERGED 2008/04/01 15:44:24 thb 1.6.26.3: #i85898# Stripping all external header guards 2008/04/01 12:43:09 thb 1.6.26.2: #i85898# Stripping all external header guards 2008/03/31 13:00:56 rt 1.6.26.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: statusbarcontroller.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX #define _SVTOOLS_STATUSBARCONTROLLER_HXX #include "svtools/svtdllapi.h" #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/util/XUpdatable.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XStatusListener.hpp> #include <com/sun/star/frame/XStatusbarController.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <com/sun/star/frame/XLayoutManager.hpp> #include <cppuhelper/weak.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <comphelper/broadcasthelper.hxx> #ifndef INCLUDED_HASH_MAP #include <hash_map> #define INCLUDED_HASH_MAP #endif #include <tools/gen.hxx> namespace svt { class SVT_DLLPUBLIC StatusbarController : public ::com::sun::star::frame::XStatusListener, public ::com::sun::star::frame::XStatusbarController, public ::com::sun::star::lang::XInitialization, public ::com::sun::star::util::XUpdatable, public ::com::sun::star::lang::XComponent, public ::comphelper::OBaseMutex, public ::cppu::OWeakObject { public: StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& aCommandURL, unsigned short nID ); StatusbarController(); virtual ~StatusbarController(); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > getLayoutManager() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const; void updateStatus( const rtl::OUString aCommandURL ); void updateStatus(); ::Rectangle getControlRect() const; // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (); virtual void SAL_CALL release() throw (); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XUpdatable virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusbarController virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos, ::sal_Int32 nCommand, ::sal_Bool bMouseEvent, const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics, const ::com::sun::star::awt::Rectangle& rOutputRectangle, ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException); protected: struct Listener { Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) : aURL( rURL ), xDispatch( rDispatch ) {} ::com::sun::star::util::URL aURL; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch; }; typedef ::std::hash_map< ::rtl::OUString, com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > URLToDispatchMap; // methods to support status forwarder, known by the old sfx2 toolbox controller implementation void addStatusListener( const rtl::OUString& aCommandURL ); void removeStatusListener( const rtl::OUString& aCommandURL ); void bindListener(); void unbindListener(); sal_Bool isBound() const; // execute methods // execute bound status bar controller command/execute various commands void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ); void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ); sal_Bool m_bInitialized : 1, m_bDisposed : 1; unsigned short m_nID; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xParentWindow; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; rtl::OUString m_aCommandURL; URLToDispatchMap m_aListenerMap; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer; }; } #endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX <|endoftext|>
<commit_before>// vasi.hxx -- a class to hold some critical vasi data // // Written by Curtis Olson, started December 2003. // // Copyright (C) 2003 Curtis L. Olson - curt@flightgear.org // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #ifndef _SG_VASI_HXX #define _SG_VASI_HXX #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include STL_STRING SG_USING_STD(string); #include <plib/ssg.h> // plib include #include <simgear/math/sg_geodesy.hxx> class SGVASIUserData : public ssgBase { private: sgdVec3 abs_pos; double alt_m; ssgLeaf *leaf; public: SGVASIUserData( sgdVec3 pos_cart, ssgLeaf *l ) { sgdCopyVec3( abs_pos, pos_cart ); double lat, lon; sgCartToGeod( abs_pos, &lat, &lon, &alt_m ); leaf = l; } ~SGVASIUserData() {} double get_alt_m() { return alt_m; } double *get_abs_pos() { return abs_pos; } int i; // color the vasi/papi correctly based on angle void set_color( float angle_deg ) { int count = leaf->getNumColours(); double trans = 0.05; double color = 1.0; double ref; float *entry; if ( count == 12 ) { // PAPI configuration // papi D ref = 3.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 0; i < 3; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi C ref = 3.167; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 3; i < 6; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi B ref = 2.833; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 6; i < 9; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi A ref = 2.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 9; i < 12; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } else if ( count == 36 ) { // probably vasi, first 18 are downwind bar (2.5 deg) ref = 2.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( int i = 0; i < 18; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // last 6 are upwind bar (3.0 deg) ref = 3.0; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( int i = 18; i < 36; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } else { // fail safe cout << "unknown vasi/papi configuration, count = " << count << endl; for ( int i = 0; i < count; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } } }; #endif // _SG_VASI_HXX <commit_msg>Oops, I originally had ramped the vasi/papi color transition the wrong way. So as you passed through the target glide slope from low to high it would be colored: red -> white -> small range of transition to red -> white. Now it goes the right way so you get: red -> smooth transition to -> white. You can tell you are getting high if you see the bottom vasi start to turn pink ... etc. etc. hopefully just like in real life.<commit_after>// vasi.hxx -- a class to hold some critical vasi data // // Written by Curtis Olson, started December 2003. // // Copyright (C) 2003 Curtis L. Olson - curt@flightgear.org // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #ifndef _SG_VASI_HXX #define _SG_VASI_HXX #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include STL_STRING SG_USING_STD(string); #include <plib/ssg.h> // plib include #include <simgear/math/sg_geodesy.hxx> class SGVASIUserData : public ssgBase { private: sgdVec3 abs_pos; double alt_m; ssgLeaf *leaf; public: SGVASIUserData( sgdVec3 pos_cart, ssgLeaf *l ) { sgdCopyVec3( abs_pos, pos_cart ); double lat, lon; sgCartToGeod( abs_pos, &lat, &lon, &alt_m ); leaf = l; } ~SGVASIUserData() {} double get_alt_m() { return alt_m; } double *get_abs_pos() { return abs_pos; } int i; // color the vasi/papi correctly based on angle void set_color( float angle_deg ) { int count = leaf->getNumColours(); double trans = 0.05; double color = 1.0; double ref; float *entry; if ( count == 12 ) { // PAPI configuration // papi D ref = 3.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 0; i < 3; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi C ref = 3.167; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 3; i < 6; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi B ref = 2.833; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 6; i < 9; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // papi A ref = 2.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( i = 9; i < 12; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } else if ( count == 36 ) { // probably vasi, first 18 are downwind bar (2.5 deg) ref = 2.5; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( int i = 0; i < 18; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } // last 6 are upwind bar (3.0 deg) ref = 3.0; if ( angle_deg < ref - trans ) { color = 0.0; } else if ( angle_deg < ref + trans ) { color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) ); } else { color = 1.0; } for ( int i = 18; i < 36; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } else { // fail safe cout << "unknown vasi/papi configuration, count = " << count << endl; for ( int i = 0; i < count; ++i ) { entry = leaf->getColour( i ); entry[1] = color; entry[2] = color; } } } }; #endif // _SG_VASI_HXX <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <cstdlib> #include <iomanip> #include <string> using namespace std; int main(){ int f[20] = {1,1}; for (int i=2;i<20;i++){ f[i] = f[i-1] + f[i-2]; } for (int i=0;i<20;i++){ if(i%4 == 0)cout<<endl; cout.width(5); cout<<f[i]; } cout<<endl; // int a[10], b[10]; // for(int i = 0; i < 10; i++) { // a[i] = i * 2 - 1; // b[10 - i - 1] = a[i]; // } // for(int i = 0; i < 10; i++) { // cout << "a[" << i << "] = " << a[i] << " "; // cout << "b[" << i << "] = " << b[i] << endl; // } return 0; }<commit_msg>New practice.<commit_after>#include <iostream> #include <cmath> #include <cstdlib> #include <iomanip> #include <string> using namespace std; void rowSum(int a[][4],int nRow){ for(int i=0;i<nRow;i++){ for(int j=0;j<4;j++){ a[i][0] = a[i][j]; } } } int main(){ int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) cout << table[i][j] << " "; cout << endl; } rowSum(table, 3); for(int i=0;i<3;i++){ cout << "Sum of row " << i << " is " << table[i][0] << endl; } // const char key[] = {'a','c','b','a','d'}; // const int ques_num = 5; // char usr_input; // int ques = 0, correct_num = 0; // cout<<"Enter the "<<ques_num<<" question tests:"<<endl; // while(cin.get(usr_input)){ // if(usr_input != '\n'){ // if(usr_input == key[ques]){ // correct_num++; // cout<<" "; // } // else{ // cout<<"*"; // } // ques++; // } // else{ // cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%"; // ques = 0; correct_num = 0;cout<<endl; // } // } // int f[20] = {1,1}; // for (int i=2;i<20;i++){ // f[i] = f[i-1] + f[i-2]; // } // for (int i=0;i<20;i++){ // if(i%4 == 0)cout<<endl; // cout.width(5); // cout<<f[i]; // } // cout<<endl; // int a[10], b[10]; // for(int i = 0; i < 10; i++) { // a[i] = i * 2 - 1; // b[10 - i - 1] = a[i]; // } // for(int i = 0; i < 10; i++) { // cout << "a[" << i << "] = " << a[i] << " "; // cout << "b[" << i << "] = " << b[i] << endl; // } return 0; }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _GRFCACHE_HXX #define _GRFCACHE_HXX #include <vcl/graph.hxx> #include <vcl/timer.hxx> #include <svtools/grfmgr.hxx> // ----------------------- // - GraphicManagerCache - // ----------------------- class GraphicCacheEntry; class GraphicCache { private: GraphicManager& mrMgr; Timer maReleaseTimer; List maGraphicCache; List maDisplayCache; sal_uLong mnReleaseTimeoutSeconds; sal_uLong mnMaxDisplaySize; sal_uLong mnMaxObjDisplaySize; sal_uLong mnUsedDisplaySize; sal_Bool ImplFreeDisplayCacheSpace( sal_uLong nSizeToFree ); GraphicCacheEntry* ImplGetCacheEntry( const GraphicObject& rObj ); DECL_LINK( ReleaseTimeoutHdl, Timer* pTimer ); public: GraphicCache( GraphicManager& rMgr, sal_uLong nDisplayCacheSize = 10000000UL, sal_uLong nMaxObjDisplayCacheSize = 2400000UL ); ~GraphicCache(); public: void AddGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute, const ByteString* pID, const GraphicObject* pCopyObj ); void ReleaseGraphicObject( const GraphicObject& rObj ); void GraphicObjectWasSwappedOut( const GraphicObject& rObj ); sal_Bool FillSwappedGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute ); void GraphicObjectWasSwappedIn( const GraphicObject& rObj ); ByteString GetUniqueID( const GraphicObject& rObj ) const; public: void SetMaxDisplayCacheSize( sal_uLong nNewCacheSize ); sal_uLong GetMaxDisplayCacheSize() const { return mnMaxDisplaySize; }; void SetMaxObjDisplayCacheSize( sal_uLong nNewMaxObjSize, sal_Bool bDestroyGreaterCached = sal_False ); sal_uLong GetMaxObjDisplayCacheSize() const { return mnMaxObjDisplaySize; } sal_uLong GetUsedDisplayCacheSize() const { return mnUsedDisplaySize; } sal_uLong GetFreeDisplayCacheSize() const { return( mnMaxDisplaySize - mnUsedDisplaySize ); } void SetCacheTimeout( sal_uLong nTimeoutSeconds ); sal_uLong GetCacheTimeout() const { return mnReleaseTimeoutSeconds; } sal_Bool IsDisplayCacheable( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ) const; sal_Bool IsInDisplayCache( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ) const; sal_Bool CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr, const BitmapEx& rBmpEx ); sal_Bool CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr, const GDIMetaFile& rMtf ); sal_Bool DrawDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ); }; #endif // _GRFCACHE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Whitespace cleanup<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _GRFCACHE_HXX #define _GRFCACHE_HXX #include <vcl/graph.hxx> #include <vcl/timer.hxx> #include <svtools/grfmgr.hxx> // ----------------------- // - GraphicManagerCache - // ----------------------- class GraphicCacheEntry; class GraphicCache { private: GraphicManager& mrMgr; Timer maReleaseTimer; List maGraphicCache; List maDisplayCache; sal_uLong mnReleaseTimeoutSeconds; sal_uLong mnMaxDisplaySize; sal_uLong mnMaxObjDisplaySize; sal_uLong mnUsedDisplaySize; sal_Bool ImplFreeDisplayCacheSpace( sal_uLong nSizeToFree ); GraphicCacheEntry* ImplGetCacheEntry( const GraphicObject& rObj ); DECL_LINK( ReleaseTimeoutHdl, Timer* pTimer ); public: GraphicCache( GraphicManager& rMgr, sal_uLong nDisplayCacheSize = 10000000UL, sal_uLong nMaxObjDisplayCacheSize = 2400000UL ); ~GraphicCache(); public: void AddGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute, const ByteString* pID, const GraphicObject* pCopyObj ); void ReleaseGraphicObject( const GraphicObject& rObj ); void GraphicObjectWasSwappedOut( const GraphicObject& rObj ); sal_Bool FillSwappedGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute ); void GraphicObjectWasSwappedIn( const GraphicObject& rObj ); ByteString GetUniqueID( const GraphicObject& rObj ) const; public: void SetMaxDisplayCacheSize( sal_uLong nNewCacheSize ); sal_uLong GetMaxDisplayCacheSize() const { return mnMaxDisplaySize; }; void SetMaxObjDisplayCacheSize( sal_uLong nNewMaxObjSize, sal_Bool bDestroyGreaterCached = sal_False ); sal_uLong GetMaxObjDisplayCacheSize() const { return mnMaxObjDisplaySize; } sal_uLong GetUsedDisplayCacheSize() const { return mnUsedDisplaySize; } sal_uLong GetFreeDisplayCacheSize() const { return( mnMaxDisplaySize - mnUsedDisplaySize ); } void SetCacheTimeout( sal_uLong nTimeoutSeconds ); sal_uLong GetCacheTimeout() const { return mnReleaseTimeoutSeconds; } sal_Bool IsDisplayCacheable( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ) const; sal_Bool IsInDisplayCache( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ) const; sal_Bool CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr, const BitmapEx& rBmpEx ); sal_Bool CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr, const GDIMetaFile& rMtf ); sal_Bool DrawDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz, const GraphicObject& rObj, const GraphicAttr& rAttr ); }; #endif // _GRFCACHE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <wdt/Throttler.h> #include <wdt/test/TestCommon.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <chrono> namespace facebook { namespace wdt { void testThrottling(std::shared_ptr<Throttler> throttler, int expectedRate) { int64_t numTransferred = 0; auto startTime = Clock::now(); while (durationSeconds(Clock::now() - startTime) < 2) { throttler->limit(1000); numTransferred += 1000; } auto endTime = Clock::now(); double durationSecs = durationSeconds(endTime - startTime); double throughputMBps = numTransferred / durationSecs / kMbToB; EXPECT_NEAR(throughputMBps, expectedRate, 3); } TEST(ThrottlerTest, RATE_CHANGE) { WdtOptions options; options.avg_mbytes_per_sec = 500; std::shared_ptr<Throttler> throttler = Throttler::makeThrottler(options); throttler->startTransfer(); testThrottling(throttler, 500); // test rate decrease options.avg_mbytes_per_sec = 300; throttler->setThrottlerRates(options); testThrottling(throttler, 300); // test rate increase options.avg_mbytes_per_sec = 700; throttler->setThrottlerRates(options); testThrottling(throttler, 700); throttler->endTransfer(); } } } <commit_msg>Reducing throttler rate in test so that it passes with asan<commit_after>#include <wdt/Throttler.h> #include <wdt/test/TestCommon.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <chrono> namespace facebook { namespace wdt { void testThrottling(std::shared_ptr<Throttler> throttler, int expectedRate) { int64_t numTransferred = 0; auto startTime = Clock::now(); while (durationSeconds(Clock::now() - startTime) <= 2) { throttler->limit(1000); numTransferred += 1000; } auto endTime = Clock::now(); double durationSecs = durationSeconds(endTime - startTime); double throughputMBps = numTransferred / durationSecs / kMbToB; EXPECT_NEAR(throughputMBps, expectedRate, 1); } TEST(ThrottlerTest, RATE_CHANGE) { WdtOptions options; options.avg_mbytes_per_sec = 50; std::shared_ptr<Throttler> throttler = Throttler::makeThrottler(options); throttler->startTransfer(); testThrottling(throttler, 50); // test rate decrease options.avg_mbytes_per_sec = 30; throttler->setThrottlerRates(options); testThrottling(throttler, 30); // test rate increase options.avg_mbytes_per_sec = 70; throttler->setThrottlerRates(options); testThrottling(throttler, 70); throttler->endTransfer(); } } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stylepool.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifdef _MSC_VER #pragma hdrstop #endif #include <vector> #include <map> #include "stylepool.hxx" #include <svtools/itemiter.hxx> #include <svtools/itempool.hxx> using namespace boost; namespace { // A "Node" represents a subset of inserted SfxItemSets // The root node represents the empty set // The other nodes contain a SfxPoolItem and represents an item set which contains their // pool item and the pool items of their parents. class Node { std::vector<Node*> mChildren; // child nodes, create by findChildNode(..) std::vector< StylePool::SfxItemSet_Pointer_t > aItemSet; // shared pointer an inserted item set or nul const SfxPoolItem *pItem; // my pool item Node *pUpper; // if I'm a child node that's my parent node public: Node() : pItem( 0 ), pUpper( 0 ) {} // root node Ctor Node( const SfxPoolItem& rItem, Node* pParent ) : // child node Ctor pItem( rItem.Clone() ), pUpper( pParent ){} ~Node(); const bool hasItemSet() const { return 0 < aItemSet.size(); } const StylePool::SfxItemSet_Pointer_t getItemSet() const { return aItemSet[aItemSet.size()-1]; } void setItemSet( const SfxItemSet& rSet ){ aItemSet.push_back( StylePool::SfxItemSet_Pointer_t( rSet.Clone() ) ); } Node* findChildNode( const SfxPoolItem& rItem ); Node* nextItemSet( Node* pLast ); const SfxPoolItem& getPoolItem() const { return *pItem; } }; Node* Node::findChildNode( const SfxPoolItem& rItem ) { Node* pNextNode = this; std::vector<Node*>::iterator aIter = mChildren.begin(); while( aIter != mChildren.end() ) { if( rItem.Which() == (*aIter)->getPoolItem().Which() && rItem == (*aIter)->getPoolItem() ) return *aIter; ++aIter; } pNextNode = new Node( rItem, pNextNode ); mChildren.push_back( pNextNode ); return pNextNode; } /* Find the next node which has a SfxItemSet. The input parameter pLast has a sophisticated meaning: downstairs only: pLast == 0 => scan your children and their children but neither your parents neither your siblings downstairs and upstairs: pLast == this => scan your children, their children, the children of your parent behind you, and so on partial downstairs and upstairs pLast != 0 && pLast != this => scan your children behind the given children, the children of your parent behind you and so on. */ Node* Node::nextItemSet( Node* pLast ) { // Searching downstairs std::vector<Node*>::iterator aIter = mChildren.begin(); // For pLast == 0 and pLast == this all children are of interest // for another pLast the search starts behind pLast... if( pLast && pLast != this ) { aIter = std::find( mChildren.begin(), mChildren.end(), pLast ); if( aIter != mChildren.end() ) ++aIter; } Node *pNext = 0; while( aIter != mChildren.end() ) { pNext = *aIter; if( pNext->hasItemSet() ) // any child with item set? return pNext; pNext = pNext->nextItemSet( 0 ); // 0 => downstairs only if( pNext ) return pNext; ++aIter; } // Searching upstairs if( pLast && pUpper ) pNext = pUpper->nextItemSet( this ); return pNext; } Node::~Node() { std::vector<Node*>::iterator aIter = mChildren.begin(); while( aIter != mChildren.end() ) { delete *aIter; ++aIter; } delete pItem; } class Iterator : public IStylePoolIteratorAccess { std::map< const SfxItemSet*, Node >& rRoot; std::map< const SfxItemSet*, Node >::iterator pCurrNode; Node* pNode; public: Iterator( std::map< const SfxItemSet*, Node >& rR ) : rRoot( rR ), pCurrNode( rR.begin() ), pNode(0) {} virtual StylePool::SfxItemSet_Pointer_t getNext(); virtual ::rtl::OUString getName(); }; StylePool::SfxItemSet_Pointer_t Iterator::getNext() { StylePool::SfxItemSet_Pointer_t pReturn; while( pNode || pCurrNode != rRoot.end() ) { if( !pNode ) { pNode = &pCurrNode->second; ++pCurrNode; if( pNode->hasItemSet() ) return pNode->getItemSet(); } pNode = pNode->nextItemSet( pNode ); if( pNode && pNode->hasItemSet() ) return pNode->getItemSet(); } return pReturn; } ::rtl::OUString Iterator::getName() { ::rtl::OUString aString; if( pNode && pNode->hasItemSet() ) aString = StylePool::nameOf( pNode->getItemSet() ); return aString; } } /* This static method creates a unique name from a shared pointer to a SfxItemSet The name is the memory address of the SfxItemSet itself. */ ::rtl::OUString StylePool::nameOf( SfxItemSet_Pointer_t pSet ) { return ::rtl::OUString::valueOf( reinterpret_cast<sal_IntPtr>( pSet.get() ), 16 ); } // class StylePoolImpl organized a tree-structure where every node represents a SfxItemSet. // The insertItemSet method adds a SfxItemSet into the tree if necessary and returns a shared_ptr // to a copy of the SfxItemSet. // The aRoot-Node represents an empty SfxItemSet. class StylePoolImpl { private: std::map< const SfxItemSet*, Node > aRoot; sal_Int32 nCount; public: StylePoolImpl() : nCount(0) {} StylePool::SfxItemSet_Pointer_t insertItemSet( const SfxItemSet& rSet ); IStylePoolIteratorAccess* createIterator(); sal_Int32 getCount() const { return nCount; } }; StylePool::SfxItemSet_Pointer_t StylePoolImpl::insertItemSet( const SfxItemSet& rSet ) { bool bNonPoolable = false; Node* pCurNode = &aRoot[ rSet.GetParent() ]; SfxItemIter aIter( rSet ); const SfxPoolItem* pItem = aIter.GetCurItem(); // Every SfxPoolItem in the SfxItemSet causes a step deeper into the tree, // a complete empty SfxItemSet would stay at the root node. while( pItem ) { if( !rSet.GetPool()->IsItemFlag(pItem->Which(), SFX_ITEM_POOLABLE ) ) bNonPoolable = true; pCurNode = pCurNode->findChildNode( *pItem ); pItem = aIter.NextItem(); } // Every leaf node represents an inserted item set, but "non-leaf" nodes represents subsets // of inserted itemsets. // These nodes could have but does not need to have a shared_ptr to a item set. if( !pCurNode->hasItemSet() ) { pCurNode->setItemSet( rSet ); bNonPoolable = false; // to avoid a double insertion ++nCount; } // If rSet contains at least one non poolable item, a new itemset has to be inserted if( bNonPoolable ) pCurNode->setItemSet( rSet ); #ifdef DEBUG { sal_Int32 nCheck = -1; sal_Int32 nNo = -1; IStylePoolIteratorAccess* pIter = createIterator(); StylePool::SfxItemSet_Pointer_t pTemp; do { ++nCheck; pTemp = pIter->getNext(); if( pCurNode->hasItemSet() && pTemp.get() == pCurNode->getItemSet().get() ) { ::rtl::OUString aStr = pIter->getName(); nNo = nCheck; } } while( pTemp.get() ); DBG_ASSERT( nCount == nCheck, "Wrong counting"); delete pIter; } #endif return pCurNode->getItemSet(); } IStylePoolIteratorAccess* StylePoolImpl::createIterator() { return new Iterator( aRoot ); } // Ctor, Dtor and redirected methods of class StylePool, nearly inline ;-) StylePool::StylePool() : pImpl( new StylePoolImpl() ) {} StylePool::SfxItemSet_Pointer_t StylePool::insertItemSet( const SfxItemSet& rSet ) { return pImpl->insertItemSet( rSet ); } IStylePoolIteratorAccess* StylePool::createIterator() { return pImpl->createIterator(); } sal_Int32 StylePool::getCount() const { return pImpl->getCount(); } StylePool::~StylePool() { delete pImpl; } // End of class StylePool <commit_msg>INTEGRATION: CWS sw241bf02_DEV300 (1.6.96.1.22); FILE MERGED 2008/04/30 09:18:44 od 1.6.96.1.22.1: #i87808# if the style access iterator is used to retrieve stored styles, try to provide used styles, if at a certain style pool node are stored more than one style due to non-poolable items<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stylepool.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifdef _MSC_VER #pragma hdrstop #endif #include <vector> #include <map> #include "stylepool.hxx" #include <svtools/itemiter.hxx> #include <svtools/itempool.hxx> using namespace boost; namespace { // A "Node" represents a subset of inserted SfxItemSets // The root node represents the empty set // The other nodes contain a SfxPoolItem and represents an item set which contains their // pool item and the pool items of their parents. class Node { std::vector<Node*> mChildren; // child nodes, create by findChildNode(..) std::vector< StylePool::SfxItemSet_Pointer_t > aItemSet; // shared pointer an inserted item set or nul const SfxPoolItem *pItem; // my pool item Node *pUpper; // if I'm a child node that's my parent node public: Node() : pItem( 0 ), pUpper( 0 ) {} // root node Ctor Node( const SfxPoolItem& rItem, Node* pParent ) : // child node Ctor pItem( rItem.Clone() ), pUpper( pParent ){} ~Node(); const bool hasItemSet() const { return 0 < aItemSet.size(); } // --> OD 2008-04-29 #i87808# // const StylePool::SfxItemSet_Pointer_t getItemSet() const { return aItemSet[aItemSet.size()-1]; } const StylePool::SfxItemSet_Pointer_t getItemSet() const { return aItemSet.back(); } const StylePool::SfxItemSet_Pointer_t getUsedOrLastAddedItemSet() const; // <-- void setItemSet( const SfxItemSet& rSet ){ aItemSet.push_back( StylePool::SfxItemSet_Pointer_t( rSet.Clone() ) ); } Node* findChildNode( const SfxPoolItem& rItem ); Node* nextItemSet( Node* pLast ); const SfxPoolItem& getPoolItem() const { return *pItem; } }; // --> OD 2008-04-29 #i87808# const StylePool::SfxItemSet_Pointer_t Node::getUsedOrLastAddedItemSet() const { std::vector< StylePool::SfxItemSet_Pointer_t >::const_reverse_iterator aIter; for ( aIter = aItemSet.rbegin(); aIter != aItemSet.rend(); ++aIter ) { if ( (*aIter).use_count() > 1 ) { return *aIter; } } return aItemSet.back(); } // <-- Node* Node::findChildNode( const SfxPoolItem& rItem ) { Node* pNextNode = this; std::vector<Node*>::iterator aIter = mChildren.begin(); while( aIter != mChildren.end() ) { if( rItem.Which() == (*aIter)->getPoolItem().Which() && rItem == (*aIter)->getPoolItem() ) return *aIter; ++aIter; } pNextNode = new Node( rItem, pNextNode ); mChildren.push_back( pNextNode ); return pNextNode; } /* Find the next node which has a SfxItemSet. The input parameter pLast has a sophisticated meaning: downstairs only: pLast == 0 => scan your children and their children but neither your parents neither your siblings downstairs and upstairs: pLast == this => scan your children, their children, the children of your parent behind you, and so on partial downstairs and upstairs pLast != 0 && pLast != this => scan your children behind the given children, the children of your parent behind you and so on. */ Node* Node::nextItemSet( Node* pLast ) { // Searching downstairs std::vector<Node*>::iterator aIter = mChildren.begin(); // For pLast == 0 and pLast == this all children are of interest // for another pLast the search starts behind pLast... if( pLast && pLast != this ) { aIter = std::find( mChildren.begin(), mChildren.end(), pLast ); if( aIter != mChildren.end() ) ++aIter; } Node *pNext = 0; while( aIter != mChildren.end() ) { pNext = *aIter; if( pNext->hasItemSet() ) // any child with item set? return pNext; pNext = pNext->nextItemSet( 0 ); // 0 => downstairs only if( pNext ) return pNext; ++aIter; } // Searching upstairs if( pLast && pUpper ) pNext = pUpper->nextItemSet( this ); return pNext; } Node::~Node() { std::vector<Node*>::iterator aIter = mChildren.begin(); while( aIter != mChildren.end() ) { delete *aIter; ++aIter; } delete pItem; } class Iterator : public IStylePoolIteratorAccess { std::map< const SfxItemSet*, Node >& rRoot; std::map< const SfxItemSet*, Node >::iterator pCurrNode; Node* pNode; public: Iterator( std::map< const SfxItemSet*, Node >& rR ) : rRoot( rR ), pCurrNode( rR.begin() ), pNode(0) {} virtual StylePool::SfxItemSet_Pointer_t getNext(); virtual ::rtl::OUString getName(); }; StylePool::SfxItemSet_Pointer_t Iterator::getNext() { StylePool::SfxItemSet_Pointer_t pReturn; while( pNode || pCurrNode != rRoot.end() ) { if( !pNode ) { pNode = &pCurrNode->second; ++pCurrNode; if( pNode->hasItemSet() ) { // --> OD 2008-04-30 #i87808# // return pNode->getItemSet(); return pNode->getUsedOrLastAddedItemSet(); // <-- } } pNode = pNode->nextItemSet( pNode ); if( pNode && pNode->hasItemSet() ) { // --> OD 2008-04-30 #i87808# // return pNode->getItemSet(); return pNode->getUsedOrLastAddedItemSet(); // <-- } } return pReturn; } ::rtl::OUString Iterator::getName() { ::rtl::OUString aString; if( pNode && pNode->hasItemSet() ) { // --> OD 2008-04-30 #i87808# // aString = StylePool::nameOf( pNode->getItemSet() ); aString = StylePool::nameOf( pNode->getUsedOrLastAddedItemSet() ); // <-- } return aString; } } /* This static method creates a unique name from a shared pointer to a SfxItemSet The name is the memory address of the SfxItemSet itself. */ ::rtl::OUString StylePool::nameOf( SfxItemSet_Pointer_t pSet ) { return ::rtl::OUString::valueOf( reinterpret_cast<sal_IntPtr>( pSet.get() ), 16 ); } // class StylePoolImpl organized a tree-structure where every node represents a SfxItemSet. // The insertItemSet method adds a SfxItemSet into the tree if necessary and returns a shared_ptr // to a copy of the SfxItemSet. // The aRoot-Node represents an empty SfxItemSet. class StylePoolImpl { private: std::map< const SfxItemSet*, Node > aRoot; sal_Int32 nCount; public: StylePoolImpl() : nCount(0) {} StylePool::SfxItemSet_Pointer_t insertItemSet( const SfxItemSet& rSet ); IStylePoolIteratorAccess* createIterator(); sal_Int32 getCount() const { return nCount; } }; StylePool::SfxItemSet_Pointer_t StylePoolImpl::insertItemSet( const SfxItemSet& rSet ) { bool bNonPoolable = false; Node* pCurNode = &aRoot[ rSet.GetParent() ]; SfxItemIter aIter( rSet ); const SfxPoolItem* pItem = aIter.GetCurItem(); // Every SfxPoolItem in the SfxItemSet causes a step deeper into the tree, // a complete empty SfxItemSet would stay at the root node. while( pItem ) { if( !rSet.GetPool()->IsItemFlag(pItem->Which(), SFX_ITEM_POOLABLE ) ) bNonPoolable = true; pCurNode = pCurNode->findChildNode( *pItem ); pItem = aIter.NextItem(); } // Every leaf node represents an inserted item set, but "non-leaf" nodes represents subsets // of inserted itemsets. // These nodes could have but does not need to have a shared_ptr to a item set. if( !pCurNode->hasItemSet() ) { pCurNode->setItemSet( rSet ); bNonPoolable = false; // to avoid a double insertion ++nCount; } // If rSet contains at least one non poolable item, a new itemset has to be inserted if( bNonPoolable ) pCurNode->setItemSet( rSet ); #ifdef DEBUG { sal_Int32 nCheck = -1; sal_Int32 nNo = -1; IStylePoolIteratorAccess* pIter = createIterator(); StylePool::SfxItemSet_Pointer_t pTemp; do { ++nCheck; pTemp = pIter->getNext(); if( pCurNode->hasItemSet() && pTemp.get() == pCurNode->getItemSet().get() ) { ::rtl::OUString aStr = pIter->getName(); nNo = nCheck; } } while( pTemp.get() ); DBG_ASSERT( nCount == nCheck, "Wrong counting"); delete pIter; } #endif return pCurNode->getItemSet(); } IStylePoolIteratorAccess* StylePoolImpl::createIterator() { return new Iterator( aRoot ); } // Ctor, Dtor and redirected methods of class StylePool, nearly inline ;-) StylePool::StylePool() : pImpl( new StylePoolImpl() ) {} StylePool::SfxItemSet_Pointer_t StylePool::insertItemSet( const SfxItemSet& rSet ) { return pImpl->insertItemSet( rSet ); } IStylePoolIteratorAccess* StylePool::createIterator() { return pImpl->createIterator(); } sal_Int32 StylePool::getCount() const { return pImpl->getCount(); } StylePool::~StylePool() { delete pImpl; } // End of class StylePool <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sqlparserclient.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 05:13:37 $ * * 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_svx.hxx" #ifndef SVX_SQLPARSERCLIENT_HXX #include "sqlparserclient.hxx" #endif #include "ParseContext.hxx" //........................................................................ namespace svxform { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //==================================================================== //= OSQLParserClient //==================================================================== //-------------------------------------------------------------------- OSQLParserClient::OSQLParserClient(const Reference< XMultiServiceFactory >& _rxORB) { m_xORB = _rxORB; } //-------------------------------------------------------------------- //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void OSQLParserClient::create() const { if (!getFactory().is()) ODbtoolsClient::create(); if (getFactory().is()) m_xParser = getFactory()->createSQLParser(m_xORB,getParseContext()); } //........................................................................ } // namespace svxform //........................................................................ <commit_msg>INTEGRATION: CWS dba24b (1.6.480); FILE MERGED 2007/09/04 21:44:21 fs 1.6.480.1: during #i73237#: slight refactoring<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sqlparserclient.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-11-01 14:59:17 $ * * 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_svx.hxx" #ifndef SVX_SQLPARSERCLIENT_HXX #include "sqlparserclient.hxx" #endif #include "ParseContext.hxx" //........................................................................ namespace svxform { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //==================================================================== //= OSQLParserClient //==================================================================== //-------------------------------------------------------------------- OSQLParserClient::OSQLParserClient(const Reference< XMultiServiceFactory >& _rxORB) { m_xORB = _rxORB; } //-------------------------------------------------------------------- bool OSQLParserClient::ensureLoaded() const { if ( !ODbtoolsClient::ensureLoaded() ) return false; m_xParser = getFactory()->createSQLParser(m_xORB,getParseContext()); return m_xParser.is(); } //........................................................................ } // namespace svxform //........................................................................ <|endoftext|>
<commit_before>/* Copyright 2013-2014 Daniele Di Sarli 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 <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <pthread.h> #include <syslog.h> #include <errno.h> #include "comsock.h" #include "client.h" #include <errno.h> #include <err.h> #include <bsd/libutil.h> using namespace std; void logServerExit(int __status, int __pri, const char *fmt...); void startDaemon(); void enableALS(bool enable); void *IPCHandler(void *arg); void *clientHandler(void *arg); char* acpi_call(string data); int getLidStatus(); volatile bool active = false; int g_socket = -1; const string SOCKET_PATH = "/var/run/als-controller.socket"; char* C_SOCKET_PATH = (char*)SOCKET_PATH.c_str(); pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t start = PTHREAD_COND_INITIALIZER; /** Signal mask */ static sigset_t g_sigset; /*void sigHandler(int sig) { if(sig == SIGUSR1) { .. } }*/ void *sigManager(void *arg) { int signum; while(1) { sigwait(&g_sigset, &signum); if(signum == SIGINT || signum == SIGTERM) { logServerExit(EXIT_SUCCESS, LOG_INFO, "Terminated."); } } return NULL; } void logServerExit(int __status, int __pri, const char *fmt...) { closeServerChannel(C_SOCKET_PATH, g_socket); enableALS(false); syslog(__pri, fmt); if(__status != EXIT_SUCCESS) syslog(LOG_INFO, "Terminated."); closelog(); exit(__status); } char* acpi_call(string data) { int fd = open("/proc/acpi/call", O_RDWR); if(fd == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error opening /proc/acpi/call"); } if(write(fd, data.c_str(), data.length() + 1) == -1) { syslog(LOG_ERR, "Error writing to /proc/acpi/call"); return NULL; } int buf_size = 100; char* buf = (char*)calloc(buf_size, sizeof(char)); int nread = read(fd, buf, buf_size-1); if(nread == -1) { syslog(LOG_ERR, "Error reading from /proc/acpi/call"); return NULL; } close(fd); //syslog(LOG_DEBUG, buf); return buf; } void enableALS(bool enable) { if(enable) { acpi_call("\\_SB.ATKD.ALSC 0x1"); acpi_call("\\_SB.PCI0.LPCB.EC0.TALS 0x1"); } else { acpi_call("\\_SB.PCI0.LPCB.EC0.TALS 0x0"); } if (enable) syslog(LOG_INFO, "ALS enabled"); else syslog(LOG_INFO, "ALS disabled"); } void setScreenBacklight(int percent) { int ret = 0; char cmd[100]; snprintf(cmd, 100, "xbacklight -set %d", percent); ret = system(cmd); if (ret < 0) { syslog(LOG_ERR, "Failed to set screen backlight."); } } void setKeyboardBacklight(int percent) { int value = 0; int ret = 0; if(percent <= 25) value = 0; else if(percent <= 50) value = 1; else if(percent <= 75) value = 2; else if(percent <= 100) value = 3; char cmd[150]; snprintf(cmd, 150, "echo %d | tee /sys/class/leds/asus::kbd_backlight/brightness", value); ret = system(cmd); if (ret < 0) { syslog(LOG_ERR, "Failed to set keyboard backlight."); } } /** * @brief getLidStatus * @return 1 if opened, 0 if closed, -1 on error, -2 if unknown */ int getLidStatus() { int fd = open("/proc/acpi/button/lid/LID/state", O_RDONLY); if(fd == -1) { syslog(LOG_ERR, "Error opening /sys/bus/acpi/devices/ACPI0008:00/ali"); return -1; } else { char str[100]; int count = read(fd, str, 100); str[count] = '\0'; close(fd); string s = string(str); if(s.find("open") != string::npos) { return 1; } else if(s.find("closed") != string::npos) { return 0; } else { return -2; } } } int getAmbientLightPercent() { int fd = open("/sys/bus/acpi/devices/ACPI0008:00/ali", O_RDONLY); if(fd == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error opening /sys/bus/acpi/devices/ACPI0008:00/ali"); } char strals[100]; int count = read(fd, strals, 100); strals[count] = '\0'; close(fd); // 0x32 (min illuminance), 0xC8, 0x190, 0x258, 0x320 (max illuminance). int als = atoi(strals); //printf("\"%s\"\n", strals); //printf("Illuminance detected: %d\n", als); float percent = 0; switch(als) { case 0x32: percent = 10; break; case 0xC8: percent = 25; break; case 0x190: percent = 50; break; case 0x258: percent = 75; break; case 0x320: percent = 100; break; } return percent; } int main(int argc, char *argv[]) { /*struct sigaction sa; sa.sa_handler = sigHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL);*/ if(argc > 1) { Client c = Client(argc, argv, SOCKET_PATH); c.Run(); exit(EXIT_SUCCESS); } struct pidfh *pfh; pid_t otherpid; pfh = pidfile_open("/var/run/als-controller.pid", 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid); } /* If we cannot create pidfile from other reasons, only warn. */ warn("Cannot open or create pidfile"); } if (daemon(0, 0) == -1) { warn("Cannot daemonize"); pidfile_remove(pfh); exit(EXIT_FAILURE); } pidfile_write(pfh); /* Change the file mode mask */ umask(0); /* Open the log file */ openlog("als-controller", LOG_PID, LOG_DAEMON); startDaemon(); pidfile_remove(pfh); return 0; } void startDaemon() { syslog(LOG_NOTICE, "Started."); /* Maschera i signal handler. La maschera viene ereditata dai thread successivi * (quindi questi segnali verranno bloccati in tutti i thread). * In particolare, il thread "sigthread" si occuperà di gestire tutti i segnali * che qui stiamo bloccando. */ sigemptyset(&g_sigset); sigaddset(&g_sigset, SIGINT); sigaddset(&g_sigset, SIGTERM); if(pthread_sigmask(SIG_SETMASK, &g_sigset, NULL) != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Sigmask error."); } pthread_t sigthread; if(pthread_create(&sigthread, NULL, sigManager, NULL) != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Creating thread."); } pthread_t thread_id; int err = pthread_create(&thread_id, NULL, IPCHandler, NULL); if(err != 0) { syslog(LOG_CRIT, "Cannot create thread"); exit(EXIT_FAILURE); } while(1) { pthread_mutex_lock(&mtx); while(!active) { pthread_cond_wait(&start, &mtx); } pthread_mutex_unlock(&mtx); if(getLidStatus() == 0) { setKeyboardBacklight(0); } else { float als = getAmbientLightPercent(); //printf("Illuminance percent: %f\n", als); if(als <= 10) { setScreenBacklight(40); setKeyboardBacklight(100); } else if(als <= 25) { setScreenBacklight(60); setKeyboardBacklight(0); } else if(als <= 50) { setScreenBacklight(75); setKeyboardBacklight(0); } else if(als <= 75) { setScreenBacklight(90); setKeyboardBacklight(0); } else if(als <= 100) { setScreenBacklight(100); setKeyboardBacklight(0); } } sleep(3); } logServerExit(EXIT_SUCCESS, LOG_NOTICE, "Terminated."); } void *IPCHandler(void *arg) { unlink(C_SOCKET_PATH); g_socket = createServerChannel(C_SOCKET_PATH); if(g_socket == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error creating socket"); } // Permessi 777 sulla socket if(chmod(C_SOCKET_PATH, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) != 0) { closeServerChannel(C_SOCKET_PATH, g_socket); return NULL; } while(1) { int client = acceptConnection(g_socket); if(client == -1) { syslog(LOG_ERR, "Error accepting client connection."); } else { pthread_t thread_id; int err = pthread_create(&thread_id, NULL, clientHandler, (void *)(size_t)client); if(err != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error creating client thread."); } } } } void *clientHandler(void *arg) { int client = (int)(size_t)arg; message_t msg; if(receiveMessage(client, &msg) == -1) { syslog(LOG_ERR, "Error receiving message from client."); return NULL; } if(msg.type == MSG_ENABLE) { enableALS(true); pthread_mutex_lock(&mtx); active = true; pthread_mutex_unlock(&mtx); pthread_cond_signal(&start); } else if(msg.type == MSG_DISABLE) { pthread_mutex_lock(&mtx); active = false; pthread_mutex_unlock(&mtx); enableALS(false); } else if(msg.type == MSG_STATUS) { bool status = false; pthread_mutex_lock(&mtx); status = active; pthread_mutex_unlock(&mtx); int sent; message_t msg; msg.type = status ? MSG_ENABLED : MSG_DISABLED; msg.buffer = NULL; msg.length = 0; sent = sendMessage(client, &msg); if(sent == -1) { syslog(LOG_ERR, "Error sending reply to client."); return NULL; } } return NULL; } <commit_msg>Fix error message<commit_after>/* Copyright 2013-2014 Daniele Di Sarli 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 <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <pthread.h> #include <syslog.h> #include <errno.h> #include "comsock.h" #include "client.h" #include <errno.h> #include <err.h> #include <bsd/libutil.h> using namespace std; void logServerExit(int __status, int __pri, const char *fmt...); void startDaemon(); void enableALS(bool enable); void *IPCHandler(void *arg); void *clientHandler(void *arg); char* acpi_call(string data); int getLidStatus(); volatile bool active = false; int g_socket = -1; const string SOCKET_PATH = "/var/run/als-controller.socket"; char* C_SOCKET_PATH = (char*)SOCKET_PATH.c_str(); pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t start = PTHREAD_COND_INITIALIZER; /** Signal mask */ static sigset_t g_sigset; /*void sigHandler(int sig) { if(sig == SIGUSR1) { .. } }*/ void *sigManager(void *arg) { int signum; while(1) { sigwait(&g_sigset, &signum); if(signum == SIGINT || signum == SIGTERM) { logServerExit(EXIT_SUCCESS, LOG_INFO, "Terminated."); } } return NULL; } void logServerExit(int __status, int __pri, const char *fmt...) { closeServerChannel(C_SOCKET_PATH, g_socket); enableALS(false); syslog(__pri, fmt); if(__status != EXIT_SUCCESS) syslog(LOG_INFO, "Terminated."); closelog(); exit(__status); } char* acpi_call(string data) { int fd = open("/proc/acpi/call", O_RDWR); if(fd == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error opening /proc/acpi/call"); } if(write(fd, data.c_str(), data.length() + 1) == -1) { syslog(LOG_ERR, "Error writing to /proc/acpi/call"); return NULL; } int buf_size = 100; char* buf = (char*)calloc(buf_size, sizeof(char)); int nread = read(fd, buf, buf_size-1); if(nread == -1) { syslog(LOG_ERR, "Error reading from /proc/acpi/call"); return NULL; } close(fd); //syslog(LOG_DEBUG, buf); return buf; } void enableALS(bool enable) { if(enable) { acpi_call("\\_SB.ATKD.ALSC 0x1"); acpi_call("\\_SB.PCI0.LPCB.EC0.TALS 0x1"); } else { acpi_call("\\_SB.PCI0.LPCB.EC0.TALS 0x0"); } if (enable) syslog(LOG_INFO, "ALS enabled"); else syslog(LOG_INFO, "ALS disabled"); } void setScreenBacklight(int percent) { int ret = 0; char cmd[100]; snprintf(cmd, 100, "xbacklight -set %d", percent); ret = system(cmd); if (ret < 0) { syslog(LOG_ERR, "Failed to set screen backlight."); } } void setKeyboardBacklight(int percent) { int value = 0; int ret = 0; if(percent <= 25) value = 0; else if(percent <= 50) value = 1; else if(percent <= 75) value = 2; else if(percent <= 100) value = 3; char cmd[150]; snprintf(cmd, 150, "echo %d | tee /sys/class/leds/asus::kbd_backlight/brightness", value); ret = system(cmd); if (ret < 0) { syslog(LOG_ERR, "Failed to set keyboard backlight."); } } /** * @brief getLidStatus * @return 1 if opened, 0 if closed, -1 on error, -2 if unknown */ int getLidStatus() { int fd = open("/proc/acpi/button/lid/LID/state", O_RDONLY); if(fd == -1) { syslog(LOG_ERR, "Error opening /proc/acpi/button/lid/LID/state"); return -1; } else { char str[100]; int count = read(fd, str, 100); str[count] = '\0'; close(fd); string s = string(str); if(s.find("open") != string::npos) { return 1; } else if(s.find("closed") != string::npos) { return 0; } else { return -2; } } } int getAmbientLightPercent() { int fd = open("/sys/bus/acpi/devices/ACPI0008:00/ali", O_RDONLY); if(fd == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error opening /sys/bus/acpi/devices/ACPI0008:00/ali"); } char strals[100]; int count = read(fd, strals, 100); strals[count] = '\0'; close(fd); // 0x32 (min illuminance), 0xC8, 0x190, 0x258, 0x320 (max illuminance). int als = atoi(strals); //printf("\"%s\"\n", strals); //printf("Illuminance detected: %d\n", als); float percent = 0; switch(als) { case 0x32: percent = 10; break; case 0xC8: percent = 25; break; case 0x190: percent = 50; break; case 0x258: percent = 75; break; case 0x320: percent = 100; break; } return percent; } int main(int argc, char *argv[]) { /*struct sigaction sa; sa.sa_handler = sigHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL);*/ if(argc > 1) { Client c = Client(argc, argv, SOCKET_PATH); c.Run(); exit(EXIT_SUCCESS); } struct pidfh *pfh; pid_t otherpid; pfh = pidfile_open("/var/run/als-controller.pid", 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid); } /* If we cannot create pidfile from other reasons, only warn. */ warn("Cannot open or create pidfile"); } if (daemon(0, 0) == -1) { warn("Cannot daemonize"); pidfile_remove(pfh); exit(EXIT_FAILURE); } pidfile_write(pfh); /* Change the file mode mask */ umask(0); /* Open the log file */ openlog("als-controller", LOG_PID, LOG_DAEMON); startDaemon(); pidfile_remove(pfh); return 0; } void startDaemon() { syslog(LOG_NOTICE, "Started."); /* Maschera i signal handler. La maschera viene ereditata dai thread successivi * (quindi questi segnali verranno bloccati in tutti i thread). * In particolare, il thread "sigthread" si occuperà di gestire tutti i segnali * che qui stiamo bloccando. */ sigemptyset(&g_sigset); sigaddset(&g_sigset, SIGINT); sigaddset(&g_sigset, SIGTERM); if(pthread_sigmask(SIG_SETMASK, &g_sigset, NULL) != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Sigmask error."); } pthread_t sigthread; if(pthread_create(&sigthread, NULL, sigManager, NULL) != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Creating thread."); } pthread_t thread_id; int err = pthread_create(&thread_id, NULL, IPCHandler, NULL); if(err != 0) { syslog(LOG_CRIT, "Cannot create thread"); exit(EXIT_FAILURE); } while(1) { pthread_mutex_lock(&mtx); while(!active) { pthread_cond_wait(&start, &mtx); } pthread_mutex_unlock(&mtx); if(getLidStatus() == 0) { setKeyboardBacklight(0); } else { float als = getAmbientLightPercent(); //printf("Illuminance percent: %f\n", als); if(als <= 10) { setScreenBacklight(40); setKeyboardBacklight(100); } else if(als <= 25) { setScreenBacklight(60); setKeyboardBacklight(0); } else if(als <= 50) { setScreenBacklight(75); setKeyboardBacklight(0); } else if(als <= 75) { setScreenBacklight(90); setKeyboardBacklight(0); } else if(als <= 100) { setScreenBacklight(100); setKeyboardBacklight(0); } } sleep(3); } logServerExit(EXIT_SUCCESS, LOG_NOTICE, "Terminated."); } void *IPCHandler(void *arg) { unlink(C_SOCKET_PATH); g_socket = createServerChannel(C_SOCKET_PATH); if(g_socket == -1) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error creating socket"); } // Permessi 777 sulla socket if(chmod(C_SOCKET_PATH, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) != 0) { closeServerChannel(C_SOCKET_PATH, g_socket); return NULL; } while(1) { int client = acceptConnection(g_socket); if(client == -1) { syslog(LOG_ERR, "Error accepting client connection."); } else { pthread_t thread_id; int err = pthread_create(&thread_id, NULL, clientHandler, (void *)(size_t)client); if(err != 0) { logServerExit(EXIT_FAILURE, LOG_CRIT, "Error creating client thread."); } } } } void *clientHandler(void *arg) { int client = (int)(size_t)arg; message_t msg; if(receiveMessage(client, &msg) == -1) { syslog(LOG_ERR, "Error receiving message from client."); return NULL; } if(msg.type == MSG_ENABLE) { enableALS(true); pthread_mutex_lock(&mtx); active = true; pthread_mutex_unlock(&mtx); pthread_cond_signal(&start); } else if(msg.type == MSG_DISABLE) { pthread_mutex_lock(&mtx); active = false; pthread_mutex_unlock(&mtx); enableALS(false); } else if(msg.type == MSG_STATUS) { bool status = false; pthread_mutex_lock(&mtx); status = active; pthread_mutex_unlock(&mtx); int sent; message_t msg; msg.type = status ? MSG_ENABLED : MSG_DISABLED; msg.buffer = NULL; msg.length = 0; sent = sendMessage(client, &msg); if(sent == -1) { syslog(LOG_ERR, "Error sending reply to client."); return NULL; } } return NULL; } <|endoftext|>
<commit_before> #include <string> #include <vector> #include <iostream> #include <algorithm> #include <sstream> #include "logstore.h" #include "regionAllocator.h" #include "diskTreeComponent.h" #include <assert.h> #include <limits.h> #include <math.h> #include <pthread.h> #include <sys/time.h> #include <time.h> #define LOG_NAME "check_logTree.log" #define NUM_ENTRIES_A 10000 #define NUM_ENTRIES_B 10 #define NUM_ENTRIES_C 0 #define OFFSET (NUM_ENTRIES * 10) #include <stasis/transactional.h> #undef begin #undef end #include "check_util.h" void insertProbeIter_str(int NUM_ENTRIES) { srand(1000); unlink("storefile.txt"); unlink("logfile.txt"); sync(); logtable<datatuple>::init_stasis(); int xid = Tbegin(); Tcommit(xid); xid = Tbegin(); diskTreeComponent::internalNodes *lt = new diskTreeComponent::internalNodes(xid, 1000, 10000, 40); long oldpagenum = -1; std::vector<std::string> arr; preprandstr(NUM_ENTRIES, arr, 50, false); std::sort(arr.begin(), arr.end(), &mycmp); //for(int i = 0; i < NUM_ENTRIES; i++) //{ // printf("%s\t", arr[i].c_str()); // int keylen = arr[i].length()+1; // printf("%d\n", keylen); //} printf("Stage 1: Writing %d keys\n", NUM_ENTRIES); for(int i = 0; i < NUM_ENTRIES; i++) { int keylen = arr[i].length()+1; byte *currkey = (byte*)malloc(keylen); for(int j=0; j<keylen-1; j++) currkey[j] = arr[i][j]; currkey[keylen-1]='\0'; //printf("\n#########\ni=%d\nkey:\t%s\nkeylen:%d\n",i,((char*)currkey),keylen); long pagenum = lt->findPage(xid, currkey, keylen); //printf("pagenum:%d\n", pagenum); assert(pagenum == -1 || pagenum == oldpagenum || oldpagenum == -1); //printf("TlsmAppendPage %d\n",i); lt->appendPage(xid, currkey, keylen, i + OFFSET); pagenum = lt->findPage(xid, currkey,keylen); oldpagenum = pagenum; //printf("pagenum:%d\n", pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Writes complete."); Tcommit(xid); xid = Tbegin(); printf("\nTREE STRUCTURE\n"); lt->print_tree(xid); printf("Stage 2: Looking up %d keys\n", NUM_ENTRIES); for(int i = 0; i < NUM_ENTRIES; i++) { int keylen = arr[i].length()+1; byte *currkey = (byte*)malloc(keylen); for(int j=0; j<keylen-1; j++) currkey[j] = arr[i][j]; currkey[keylen-1]='\0'; //printf("\n#########\ni=%d\nkey:\t%s\nkeylen:%d\n",i,((char*)currkey),keylen); long pagenum = lt->findPage(xid, currkey, keylen); //printf("pagenum:%d\n", pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Stage 3: Iterating over %d keys\n", NUM_ENTRIES); int64_t count = 0; RegionAllocator * ro_alloc = new RegionAllocator(); diskTreeComponent::internalNodes::iterator * it = new diskTreeComponent::internalNodes::iterator(xid, ro_alloc, lt->get_root_rec()); while(it->next()) { byte * key; byte **key_ptr = &key; size_t keysize = it->key((byte**)key_ptr); pageid_t *value; pageid_t **value_ptr = &value; size_t valsize = it->value((byte**)value_ptr); assert(valsize == sizeof(pageid_t)); assert(!mycmp(std::string((char*)key), arr[count]) && !mycmp(arr[count],std::string((char*)key))); assert(keysize == arr[count].length()+1); count++; } assert(count == NUM_ENTRIES); it->close(); delete it; delete ro_alloc; Tcommit(xid); logtable<datatuple>::deinit_stasis(); } void insertProbeIter_int(int NUM_ENTRIES) { unlink("storefile.txt"); unlink("logfile.txt"); sync(); bufferManagerNonBlockingSlowHandleType = IO_HANDLE_PFILE; Tinit(); int xid = Tbegin(); Tcommit(xid); xid = Tbegin(); diskTreeComponent::internalNodes *lt = new diskTreeComponent::internalNodes(xid, 1000, 10000, 40); long oldpagenum = -1; for(int32_t i = 0; i < NUM_ENTRIES; i++) { int keylen = sizeof(int32_t); byte *currkey = (byte*)malloc(keylen); memcpy(currkey, (byte*)(&i), keylen); //currkey[]='\0'; printf("\n#########\ni=%d\nkey:\t%d\nkeylen:%d\n",i,*((int32_t*)currkey),keylen); pageid_t pagenum = lt->findPage(xid, currkey, keylen); printf("pagenum:%lld\n", (long long)pagenum); assert(pagenum == -1 || pagenum == oldpagenum || oldpagenum == -1); printf("TlsmAppendPage %d\n",i); lt->appendPage(xid, currkey, keylen, i + OFFSET); pagenum = lt->findPage(xid, currkey,keylen); oldpagenum = pagenum; printf("pagenum:%lld\n", (long long)pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Writes complete."); Tcommit(xid); xid = Tbegin(); printf("\nTREE STRUCTURE\n"); lt->print_tree(xid); for(int32_t i = 1; i < NUM_ENTRIES; i++) { int keylen = sizeof(int32_t); byte *currkey = (byte*)malloc(keylen); memcpy(currkey, (byte*)(&i), keylen); printf("\n#########\ni=%d\nkey:\t%d\nkeylen:%d\n",i,*((int32_t*)currkey),keylen); pageid_t pagenum = lt->findPage(xid, currkey, keylen); printf("pagenum:%lld\n", (long long) pagenum); assert(pagenum == i + OFFSET); free(currkey); } /* int64_t count = 0; lladdIterator_t * it = lsmTreeIterator_open(xid, tree); while(lsmTreeIterator_next(xid, it)) { lsmkey_t * key; lsmkey_t **key_ptr = &key; int size = lsmTreeIterator_key(xid, it, (byte**)key_ptr); assert(size == sizeof(lsmkey_t)); long *value; long **value_ptr = &value; size = lsmTreeIterator_value(xid, it, (byte**)value_ptr); assert(size == sizeof(pageid_t)); assert(*key + OFFSET == *value); assert(*key == count); count++; } assert(count == NUM_ENTRIES); lsmTreeIterator_close(xid, it); */ Tcommit(xid); Tdeinit(); } /** @test */ int main() { insertProbeIter_str(NUM_ENTRIES_A); //insertProbeIter_int(NUM_ENTRIES_A); return 0; } <commit_msg>remove line from unit test that had no effect, but broke compilation<commit_after> #include <string> #include <vector> #include <iostream> #include <algorithm> #include <sstream> #include "logstore.h" #include "regionAllocator.h" #include "diskTreeComponent.h" #include <assert.h> #include <limits.h> #include <math.h> #include <pthread.h> #include <sys/time.h> #include <time.h> #define LOG_NAME "check_logTree.log" #define NUM_ENTRIES_A 10000 #define NUM_ENTRIES_B 10 #define NUM_ENTRIES_C 0 #define OFFSET (NUM_ENTRIES * 10) #include <stasis/transactional.h> #undef begin #undef end #include "check_util.h" void insertProbeIter_str(int NUM_ENTRIES) { srand(1000); unlink("storefile.txt"); unlink("logfile.txt"); sync(); logtable<datatuple>::init_stasis(); int xid = Tbegin(); Tcommit(xid); xid = Tbegin(); diskTreeComponent::internalNodes *lt = new diskTreeComponent::internalNodes(xid, 1000, 10000, 40); long oldpagenum = -1; std::vector<std::string> arr; preprandstr(NUM_ENTRIES, arr, 50, false); std::sort(arr.begin(), arr.end(), &mycmp); //for(int i = 0; i < NUM_ENTRIES; i++) //{ // printf("%s\t", arr[i].c_str()); // int keylen = arr[i].length()+1; // printf("%d\n", keylen); //} printf("Stage 1: Writing %d keys\n", NUM_ENTRIES); for(int i = 0; i < NUM_ENTRIES; i++) { int keylen = arr[i].length()+1; byte *currkey = (byte*)malloc(keylen); for(int j=0; j<keylen-1; j++) currkey[j] = arr[i][j]; currkey[keylen-1]='\0'; //printf("\n#########\ni=%d\nkey:\t%s\nkeylen:%d\n",i,((char*)currkey),keylen); long pagenum = lt->findPage(xid, currkey, keylen); //printf("pagenum:%d\n", pagenum); assert(pagenum == -1 || pagenum == oldpagenum || oldpagenum == -1); //printf("TlsmAppendPage %d\n",i); lt->appendPage(xid, currkey, keylen, i + OFFSET); pagenum = lt->findPage(xid, currkey,keylen); oldpagenum = pagenum; //printf("pagenum:%d\n", pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Writes complete."); Tcommit(xid); xid = Tbegin(); printf("\nTREE STRUCTURE\n"); lt->print_tree(xid); printf("Stage 2: Looking up %d keys\n", NUM_ENTRIES); for(int i = 0; i < NUM_ENTRIES; i++) { int keylen = arr[i].length()+1; byte *currkey = (byte*)malloc(keylen); for(int j=0; j<keylen-1; j++) currkey[j] = arr[i][j]; currkey[keylen-1]='\0'; //printf("\n#########\ni=%d\nkey:\t%s\nkeylen:%d\n",i,((char*)currkey),keylen); long pagenum = lt->findPage(xid, currkey, keylen); //printf("pagenum:%d\n", pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Stage 3: Iterating over %d keys\n", NUM_ENTRIES); int64_t count = 0; RegionAllocator * ro_alloc = new RegionAllocator(); diskTreeComponent::internalNodes::iterator * it = new diskTreeComponent::internalNodes::iterator(xid, ro_alloc, lt->get_root_rec()); while(it->next()) { byte * key; byte **key_ptr = &key; size_t keysize = it->key((byte**)key_ptr); pageid_t *value; pageid_t **value_ptr = &value; size_t valsize = it->value((byte**)value_ptr); assert(valsize == sizeof(pageid_t)); assert(!mycmp(std::string((char*)key), arr[count]) && !mycmp(arr[count],std::string((char*)key))); assert(keysize == arr[count].length()+1); count++; } assert(count == NUM_ENTRIES); it->close(); delete it; delete ro_alloc; Tcommit(xid); logtable<datatuple>::deinit_stasis(); } void insertProbeIter_int(int NUM_ENTRIES) { unlink("storefile.txt"); unlink("logfile.txt"); sync(); Tinit(); int xid = Tbegin(); Tcommit(xid); xid = Tbegin(); diskTreeComponent::internalNodes *lt = new diskTreeComponent::internalNodes(xid, 1000, 10000, 40); long oldpagenum = -1; for(int32_t i = 0; i < NUM_ENTRIES; i++) { int keylen = sizeof(int32_t); byte *currkey = (byte*)malloc(keylen); memcpy(currkey, (byte*)(&i), keylen); //currkey[]='\0'; printf("\n#########\ni=%d\nkey:\t%d\nkeylen:%d\n",i,*((int32_t*)currkey),keylen); pageid_t pagenum = lt->findPage(xid, currkey, keylen); printf("pagenum:%lld\n", (long long)pagenum); assert(pagenum == -1 || pagenum == oldpagenum || oldpagenum == -1); printf("TlsmAppendPage %d\n",i); lt->appendPage(xid, currkey, keylen, i + OFFSET); pagenum = lt->findPage(xid, currkey,keylen); oldpagenum = pagenum; printf("pagenum:%lld\n", (long long)pagenum); assert(pagenum == i + OFFSET); free(currkey); } printf("Writes complete."); Tcommit(xid); xid = Tbegin(); printf("\nTREE STRUCTURE\n"); lt->print_tree(xid); for(int32_t i = 1; i < NUM_ENTRIES; i++) { int keylen = sizeof(int32_t); byte *currkey = (byte*)malloc(keylen); memcpy(currkey, (byte*)(&i), keylen); printf("\n#########\ni=%d\nkey:\t%d\nkeylen:%d\n",i,*((int32_t*)currkey),keylen); pageid_t pagenum = lt->findPage(xid, currkey, keylen); printf("pagenum:%lld\n", (long long) pagenum); assert(pagenum == i + OFFSET); free(currkey); } /* int64_t count = 0; lladdIterator_t * it = lsmTreeIterator_open(xid, tree); while(lsmTreeIterator_next(xid, it)) { lsmkey_t * key; lsmkey_t **key_ptr = &key; int size = lsmTreeIterator_key(xid, it, (byte**)key_ptr); assert(size == sizeof(lsmkey_t)); long *value; long **value_ptr = &value; size = lsmTreeIterator_value(xid, it, (byte**)value_ptr); assert(size == sizeof(pageid_t)); assert(*key + OFFSET == *value); assert(*key == count); count++; } assert(count == NUM_ENTRIES); lsmTreeIterator_close(xid, it); */ Tcommit(xid); Tdeinit(); } /** @test */ int main() { insertProbeIter_str(NUM_ENTRIES_A); //insertProbeIter_int(NUM_ENTRIES_A); return 0; } <|endoftext|>
<commit_before>#pragma once // `krbn::device_observer` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "grabbable_state_manager.hpp" #include "grabber_client.hpp" #include "hid_observer.hpp" #include "logger.hpp" #include "time_utility.hpp" #include "types.hpp" #include <pqrs/dispatcher.hpp> #include <pqrs/osx/iokit_hid_manager.hpp> #include <pqrs/osx/iokit_types.hpp> namespace krbn { class device_observer final : public pqrs::dispatcher::extra::dispatcher_client { public: device_observer(const device_observer&) = delete; device_observer(std::weak_ptr<grabber_client> grabber_client) : dispatcher_client(), grabber_client_(grabber_client) { // grabbable_state_manager_ grabbable_state_manager_ = std::make_unique<grabbable_state_manager>(); grabbable_state_manager_->grabbable_state_changed.connect([this](auto&& grabbable_state) { if (auto client = grabber_client_.lock()) { client->async_grabbable_state_changed(grabbable_state); } }); // hid_manager_ std::vector<pqrs::cf_ptr<CFDictionaryRef>> matching_dictionaries{ pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_keyboard), pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_mouse), pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_pointer), }; hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_, matching_dictionaries); hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) { iokit_utility::log_matching_device(registry_entry_id, *device_ptr); auto hid = std::make_shared<krbn::human_interface_device>(*device_ptr, registry_entry_id); hids_[registry_entry_id] = hid; auto device_name = hid->get_name_for_log(); logger::get_logger().info("{0} is matched.", device_name); grabbable_state_manager_->update(grabbable_state(hid->get_registry_entry_id(), grabbable_state::state::device_error, grabbable_state::ungrabbable_temporarily_reason::none, time_utility::mach_absolute_time_point())); if (hid->is_karabiner_virtual_hid_device()) { // Handle caps_lock_state_changed event only if the hid is Karabiner-VirtualHIDDevice. hid->values_arrived.connect([this](auto&& shared_event_queue) { for (const auto& e : shared_event_queue->get_entries()) { if (e.get_event().get_type() == event_queue::event::type::caps_lock_state_changed) { if (auto client = grabber_client_.lock()) { if (auto state = e.get_event().get_integer_value()) { client->async_caps_lock_state_changed(*state); } } } } }); } else { hid->values_arrived.connect([this](auto&& shared_event_queue) { grabbable_state_manager_->update(*shared_event_queue); }); } auto observer = std::make_shared<hid_observer>(hid); hid_observers_[hid->get_registry_entry_id()] = observer; observer->device_observed.connect([this, registry_entry_id, device_name] { logger::get_logger().info("{0} is observed.", device_name); if (auto state = grabbable_state_manager_->get_grabbable_state(registry_entry_id)) { // Keep grabbable_state if the state is already changed by value_callback. if (state->get_state() == grabbable_state::state::device_error) { grabbable_state_manager_->update(grabbable_state(registry_entry_id, grabbable_state::state::grabbable, grabbable_state::ungrabbable_temporarily_reason::none, time_utility::mach_absolute_time_point())); } } }); observer->async_observe(); }); hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) { auto it = hids_.find(registry_entry_id); if (it != std::end(hids_)) { logger::get_logger().info("{0} is terminated.", it->second->get_name_for_log()); } hid_observers_.erase(registry_entry_id); hids_.erase(registry_entry_id); }); hid_manager_->error_occurred.connect([](auto&& message, auto&& iokit_return) { logger::get_logger().error("{0}: {1}", message, iokit_return.to_string()); }); hid_manager_->async_start(); logger::get_logger().info("device_observer is started."); } virtual ~device_observer(void) { detach_from_dispatcher([this] { hid_manager_ = nullptr; hid_observers_.clear(); hids_.clear(); grabbable_state_manager_ = nullptr; }); logger::get_logger().info("device_observer is stopped."); } private: std::weak_ptr<grabber_client> grabber_client_; std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_; std::unordered_map<pqrs::osx::iokit_registry_entry_id, std::shared_ptr<krbn::human_interface_device>> hids_; std::unordered_map<pqrs::osx::iokit_registry_entry_id, std::shared_ptr<hid_observer>> hid_observers_; std::unique_ptr<grabbable_state_manager> grabbable_state_manager_; }; } // namespace krbn <commit_msg>use hid_queue_value_monitor<commit_after>#pragma once // `krbn::device_observer` can be used safely in a multi-threaded environment. #include "event_queue.hpp" #include "grabbable_state_manager/manager.hpp" #include "grabber_client.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "time_utility.hpp" #include "types.hpp" #include <pqrs/dispatcher.hpp> #include <pqrs/osx/iokit_hid_manager.hpp> #include <pqrs/osx/iokit_hid_queue_value_monitor.hpp> #include <pqrs/osx/iokit_types.hpp> namespace krbn { class device_observer final : public pqrs::dispatcher::extra::dispatcher_client { public: device_observer(const device_observer&) = delete; device_observer(std::weak_ptr<grabber_client> grabber_client) : dispatcher_client(), grabber_client_(grabber_client) { // grabbable_state_manager_ grabbable_state_manager_ = std::make_unique<grabbable_state_manager::manager>(); grabbable_state_manager_->grabbable_state_changed.connect([this](auto&& grabbable_state) { if (auto client = grabber_client_.lock()) { client->async_grabbable_state_changed(grabbable_state); } }); // hid_manager_ std::vector<pqrs::cf_ptr<CFDictionaryRef>> matching_dictionaries{ pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_keyboard), pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_mouse), pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::osx::iokit_hid_usage_page_generic_desktop, pqrs::osx::iokit_hid_usage_generic_desktop_pointer), }; hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_, matching_dictionaries); hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) { if (device_ptr) { iokit_utility::log_matching_device(registry_entry_id, *device_ptr); auto device_id = make_device_id(registry_entry_id); auto device_name = iokit_utility::make_device_name_for_log(device_id, *device_ptr); grabbable_state_manager_->update(grabbable_state(device_id, grabbable_state::state::device_error, grabbable_state::ungrabbable_temporarily_reason::none, time_utility::mach_absolute_time_point())); auto hid_queue_value_monitor = std::make_shared<pqrs::osx::iokit_hid_queue_value_monitor>(weak_dispatcher_, *device_ptr); hid_queue_value_monitors_[device_id] = hid_queue_value_monitor; if (iokit_utility::is_karabiner_virtual_hid_device(*device_ptr)) { // Handle caps_lock_state_changed event only if the hid is Karabiner-VirtualHIDDevice. hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) { auto event_queue = krbn::event_queue::make_queue(device_id, values_ptr); for (const auto& e : event_queue->get_entries()) { if (e.get_event().get_type() == event_queue::event::type::caps_lock_state_changed) { if (auto client = grabber_client_.lock()) { if (auto state = e.get_event().get_integer_value()) { client->async_caps_lock_state_changed(*state); } } } } }); } else { hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) { auto event_queue = krbn::event_queue::make_queue(device_id, values_ptr); grabbable_state_manager_->update(*event_queue); }); } hid_queue_value_monitor->started.connect([this, device_id, device_name] { logger::get_logger().info("{0} is observed.", device_name); if (auto state = grabbable_state_manager_->get_grabbable_state(device_id)) { // Keep grabbable_state if the state is already changed by value_callback. if (state->get_state() == grabbable_state::state::device_error) { grabbable_state_manager_->update(grabbable_state(device_id, grabbable_state::state::grabbable, grabbable_state::ungrabbable_temporarily_reason::none, time_utility::mach_absolute_time_point())); } } }); hid_queue_value_monitor->async_start(kIOHIDOptionsTypeNone, std::chrono::milliseconds(3000)); } }); hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) { auto device_id = krbn::make_device_id(registry_entry_id); krbn::logger::get_logger().info("device_id:{0} is terminated.", type_safe::get(device_id)); hid_queue_value_monitors_.erase(device_id); }); hid_manager_->error_occurred.connect([](auto&& message, auto&& iokit_return) { logger::get_logger().error("{0}: {1}", message, iokit_return.to_string()); }); hid_manager_->async_start(); logger::get_logger().info("device_observer is started."); } virtual ~device_observer(void) { detach_from_dispatcher([this] { hid_manager_ = nullptr; hid_queue_value_monitors_.clear(); grabbable_state_manager_ = nullptr; }); logger::get_logger().info("device_observer is stopped."); } private: std::weak_ptr<grabber_client> grabber_client_; std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_; std::unordered_map<device_id, std::shared_ptr<pqrs::osx::iokit_hid_queue_value_monitor>> hid_queue_value_monitors_; std::unique_ptr<grabbable_state_manager::manager> grabbable_state_manager_; }; } // namespace krbn <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fieldmappingimpl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:07:28 $ * * 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 EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX #define EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef EXTENSIONS_ABP_ABPTYPES_HXX #include "abptypes.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } } class Window; //......................................................................... namespace abp { //......................................................................... //..................................................................... namespace fieldmapping { //..................................................................... //----------------------------------------------------------------- /** invokes the field mapping dialog @param _rxORB service factory to use for creating UNO services @param _pParent window to use as parent for the dialog and error messages @param _rDataSourceName name of the data source which should be used @param _rTableName name of the table which should be used @param _rFieldAssignment Upon returning from the function, this is field with the field mapping. If the user cancelled the dialog, this is cleared. */ sal_Bool invokeDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, class Window* _pParent, const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rTableName, MapString2String& /* [out] */ _rFieldAssignment ) SAL_THROW ( ( ) ); //----------------------------------------------------------------- /** creates a default field mapping for usage with the address book SDBC driver <p>The column names as used by the SDBC driver for address books is stored in the configuration, and this function creates a mapping which uses this configuration information.</p> */ void defaultMapping( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, MapString2String& /* [out] */ _rFieldAssignment ) SAL_THROW ( ( ) ); //----------------------------------------------------------------- /** writes a field mapping for the template document address source */ void writeTemplateAddressFieldMapping( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const MapString2String& _rFieldAssignment ) SAL_THROW ( ( ) ); //..................................................................... } // namespace fieldmapping //..................................................................... //..................................................................... namespace addressconfig { //..................................................................... //----------------------------------------------------------------- /** writes the data source / table name given into the configuration, to where the template documents expect it. */ void writeTemplateAddressSource( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rTableName ) SAL_THROW ( ( ) ); /** writes the configuration entry which states the the pilot has been completed successfully */ void markPilotSuccess( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ) SAL_THROW ( ( ) ); //..................................................................... } // namespace addressconfig //..................................................................... //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX <commit_msg>INTEGRATION: CWS dba201b (1.2.470); FILE MERGED 2005/09/21 06:41:37 oj 1.2.470.2: RESYNC: (1.2-1.3); FILE MERGED 2005/07/18 10:51:13 fs 1.2.470.1: #i51833# also pass the XDataSource object around - the field mapping dialog needs it, since the data source is not registered at the database context<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fieldmappingimpl.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2005-09-23 12:49:35 $ * * 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 EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX #define EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef EXTENSIONS_ABP_ABPTYPES_HXX #include "abptypes.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #include "addresssettings.hxx" #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } namespace beans { class XPropertySet; } } } } class Window; //......................................................................... namespace abp { //......................................................................... //..................................................................... namespace fieldmapping { //..................................................................... //----------------------------------------------------------------- /** invokes the field mapping dialog @param _rxORB service factory to use for creating UNO services @param _pParent window to use as parent for the dialog and error messages @param _rSettings current settings. Upon return, the field mapping member of this structure will be filled with the settings the user did in the field mapping dialog. */ sal_Bool invokeDialog( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, class Window* _pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDataSource, AddressSettings& _rSettings ) SAL_THROW ( ( ) ); //----------------------------------------------------------------- /** creates a default field mapping for usage with the address book SDBC driver <p>The column names as used by the SDBC driver for address books is stored in the configuration, and this function creates a mapping which uses this configuration information.</p> */ void defaultMapping( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, MapString2String& /* [out] */ _rFieldAssignment ) SAL_THROW ( ( ) ); //----------------------------------------------------------------- /** writes a field mapping for the template document address source */ void writeTemplateAddressFieldMapping( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const MapString2String& _rFieldAssignment ) SAL_THROW ( ( ) ); //..................................................................... } // namespace fieldmapping //..................................................................... //..................................................................... namespace addressconfig { //..................................................................... //----------------------------------------------------------------- /** writes the data source / table name given into the configuration, to where the template documents expect it. */ void writeTemplateAddressSource( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rTableName ) SAL_THROW ( ( ) ); /** writes the configuration entry which states the the pilot has been completed successfully */ void markPilotSuccess( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ) SAL_THROW ( ( ) ); //..................................................................... } // namespace addressconfig //..................................................................... //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX <|endoftext|>
<commit_before> #include <string> #include <sstream> #include "flame/base.h" #include "pyflame.h" #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL FLAME_PyArray_API #include <numpy/ndarrayobject.h> #if SIZE_MAX==NPY_MAX_UINT32 #define NPY_SIZE_T NPY_UINT32 #elif SIZE_MAX==NPY_MAX_UINT64 #define NPY_SIZE_T NPY_UINT64 #else #error logic error with SIZE_MAX #endif #define TRY PyState *state = (PyState*)raw; try namespace { struct PyState { PyObject_HEAD PyObject *dict, *weak; // __dict__ and __weakref__ PyObject *attrs; // lookup name to attribute index (for StateBase) StateBase *state; }; static int PyState_traverse(PyObject *raw, visitproc visit, void *arg) { PyState *state = (PyState*)raw; Py_VISIT(state->attrs); Py_VISIT(state->dict); return 0; } static int PyState_clear(PyObject *raw) { PyState *state = (PyState*)raw; Py_CLEAR(state->dict); Py_CLEAR(state->attrs); return 0; } static void PyState_free(PyObject *raw) { TRY { std::auto_ptr<StateBase> S(state->state); state->state = NULL; if(state->weak) PyObject_ClearWeakRefs(raw); PyState_clear(raw); Py_TYPE(raw)->tp_free(raw); } CATCH2V(std::exception, RuntimeError) } static PyObject *PyState_getattro(PyObject *raw, PyObject *attr) { TRY { PyObject *idx = PyDict_GetItem(state->attrs, attr); if(!idx) { return PyObject_GenericGetAttr(raw, attr); } int i = PyInt_AsLong(idx); StateBase::ArrayInfo info; if(!state->state->getArray(i, info)) return PyErr_Format(PyExc_RuntimeError, "invalid attribute name (sub-class forgot %d)", i); if(info.ndim==0) { // Scalar switch(info.type) { case StateBase::ArrayInfo::Double: return PyFloat_FromDouble(*(double*)info.ptr); case StateBase::ArrayInfo::Sizet: return PyLong_FromSize_t(*(size_t*)info.ptr); } return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } int pytype; switch(info.type) { case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break; case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break; default: return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } npy_intp dims[StateBase::ArrayInfo::maxdims]; std::copy(info.dim, info.dim+StateBase::ArrayInfo::maxdims, dims); // Alloc new array and copy in PyRef<PyArrayObject> obj(PyArray_SimpleNew(info.ndim, dims, pytype)); // pull parts from PyArray into ArrayInfo so we can use ArrayInfo::raw() to access StateBase::ArrayInfo pyinfo; pyinfo.ptr = PyArray_BYTES(obj.py()); pyinfo.ndim= PyArray_NDIM(obj.get()); std::copy(PyArray_DIMS(obj.get()), PyArray_DIMS(obj.get())+pyinfo.ndim, pyinfo.dim); std::copy(PyArray_STRIDES(obj.get()), PyArray_STRIDES(obj.get())+pyinfo.ndim, pyinfo.stride); ndindex_iterate<StateBase::ArrayInfo::maxdims> idxiter(info.ndim, info.dim); for(; !idxiter.done; idxiter.next()) { void *dest = pyinfo.raw(idxiter.index); const void *src = info .raw(idxiter.index); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } return obj.releasePy(); } CATCH() } static int PyState_setattro(PyObject *raw, PyObject *attr, PyObject *val) { TRY { PyObject *idx = PyDict_GetItem(state->attrs, attr); if(!idx) return PyObject_GenericSetAttr(raw, attr, val); int i = PyInt_AsLong(idx); StateBase::ArrayInfo info; if(!state->state->getArray(i, info)) { PyErr_Format(PyExc_RuntimeError, "invalid attribute name (sub-class forgot %d)", i); return -1; } if(info.ndim==0) { // Scalar (use python primative types) switch(info.type) { case StateBase::ArrayInfo::Double: { double *dest = (double*)info.ptr; if(PyFloat_Check(val)) *dest = PyFloat_AsDouble(val); else if(PyLong_Check(val)) *dest = PyLong_AsDouble(val); else if(PyInt_Check(val)) *dest = PyInt_AsLong(val); else PyErr_Format(PyExc_ValueError, "Can't assign to double field"); } break; case StateBase::ArrayInfo::Sizet: { size_t *dest = (size_t*)info.ptr; if(PyFloat_Check(val)) *dest = PyFloat_AsDouble(val); else if(PyLong_Check(val)) *dest = PyLong_AsUnsignedLongLong(val); else if(PyInt_Check(val)) *dest = PyInt_AsLong(val); else PyErr_Format(PyExc_ValueError, "Can't assign to double field"); } break; default: PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } return PyErr_Occurred() ? -1 : 0; } // array (use numpy) int pytype; switch(info.type) { case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break; case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break; default: PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); return -1; } PyRef<PyArrayObject> arr(PyArray_FromObject(val, pytype, 1, 2)); if(info.ndim!=(size_t)PyArray_NDIM(arr.py())) { PyErr_Format(PyExc_ValueError, "cardinality don't match"); return -1; } else if(!std::equal(info.dim, info.dim+info.ndim, PyArray_DIMS(arr.py()))) { PyErr_Format(PyExc_ValueError, "shape does not match don't match"); return -1; } // pull parts from PyArray into ArrayInfo so we can use ArrayInfo::raw() to access StateBase::ArrayInfo pyinfo; pyinfo.ptr = PyArray_BYTES(arr.py()); pyinfo.ndim= PyArray_NDIM(arr.get()); std::copy(PyArray_DIMS(arr.get()), PyArray_DIMS(arr.get())+pyinfo.ndim, pyinfo.dim); std::copy(PyArray_STRIDES(arr.get()), PyArray_STRIDES(arr.get())+pyinfo.ndim, pyinfo.stride); ndindex_iterate<StateBase::ArrayInfo::maxdims> idxiter(info.ndim, info.dim); for(; !idxiter.done; idxiter.next()) { const void *src = pyinfo .raw(idxiter.index); void *dest = info.raw(idxiter.index); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } if(info.ndim==1) { for(size_t i=0; i<info.dim[0]; i++) { const void *src = PyArray_GETPTR1(arr.py(), i); void *dest = info.raw(&i); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } } else if(info.ndim==2) { size_t idx[2]; for(idx[0]=0; idx[0]<info.dim[0]; idx[0]++) { for(idx[1]=0; idx[1]<info.dim[1]; idx[1]++) { const void *src = PyArray_GETPTR2(arr.py(), idx[0], idx[1]); void *dest = info.raw(idx); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } } } return 0; } CATCH3(std::exception, RuntimeError, -1) } static PyObject* PyState_str(PyObject *raw) { TRY { std::ostringstream strm; state->state->show(strm, 0); return PyString_FromString(strm.str().c_str()); } CATCH() } static PyObject* PyState_iter(PyObject *raw) { TRY { return PyObject_GetIter(state->attrs); }CATCH() } static Py_ssize_t PyState_len(PyObject *raw) { TRY{ return PyObject_Length(state->attrs); }CATCH1(-1) } static PySequenceMethods PyState_seq = { &PyState_len }; static PyObject* PyState_clone(PyObject *raw, PyObject *unused) { TRY { std::auto_ptr<StateBase> newstate(state->state->clone()); PyObject *ret = wrapstate(newstate.get()); newstate.release(); return ret; } CATCH() } static PyMethodDef PyState_methods[] = { {"clone", (PyCFunction)&PyState_clone, METH_NOARGS, "clone()\n\n" "Returns a new State instance which is a copy of this one" }, {NULL, NULL, 0, NULL} }; static PyTypeObject PyStateType = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, #endif "flame._internal.State", sizeof(PyState), }; } // namespace PyObject* wrapstate(StateBase* b) { try { PyRef<PyState> state(PyStateType.tp_alloc(&PyStateType, 0)); state->state = b; state->attrs = state->weak = state->dict = 0; state->attrs = PyDict_New(); if(!state->attrs) return NULL; for(unsigned i=0; true; i++) { StateBase::ArrayInfo info; if(!b->getArray(i, info)) break; bool skip = info.ndim>3; switch(info.type) { case StateBase::ArrayInfo::Double: case StateBase::ArrayInfo::Sizet: break; default: skip = true; } if(skip) continue; PyRef<> name(PyInt_FromLong(i)); if(PyDict_SetItemString(state->attrs, info.name, name.py())) throw std::runtime_error("Failed to insert into Dict"); } return state.releasePy(); } CATCH() } StateBase* unwrapstate(PyObject* raw) { if(!PyObject_TypeCheck(raw, &PyStateType)) throw std::invalid_argument("Argument is not a State"); PyState *state = (PyState*)raw; return state->state; } static const char pymdoc[] = "The interface to a sub-class of C++ StateBase.\n" "Can't be constructed from python, see Machine.allocState()\n" "\n" "Provides access to some C++ member variables via the Machine::getArray() interface.\n" ; int registerModState(PyObject *mod) { PyStateType.tp_doc = pymdoc; PyStateType.tp_str = &PyState_str; PyStateType.tp_repr = &PyState_str; PyStateType.tp_dealloc = &PyState_free; PyStateType.tp_iter = &PyState_iter; PyStateType.tp_as_sequence = &PyState_seq; PyStateType.tp_weaklistoffset = offsetof(PyState, weak); PyStateType.tp_traverse = &PyState_traverse; PyStateType.tp_clear = &PyState_clear; PyStateType.tp_dictoffset = offsetof(PyState, dict); PyStateType.tp_getattro = &PyState_getattro; PyStateType.tp_setattro = &PyState_setattro; PyStateType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC; PyStateType.tp_methods = PyState_methods; if(PyType_Ready(&PyStateType)) return -1; Py_INCREF(&PyStateType); if(PyModule_AddObject(mod, "State", (PyObject*)&PyStateType)) { Py_DECREF(&PyStateType); return -1; } return 0; } <commit_msg>expose StateBase::show()<commit_after> #include <string> #include <sstream> #include "flame/base.h" #include "pyflame.h" #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL FLAME_PyArray_API #include <numpy/ndarrayobject.h> #if SIZE_MAX==NPY_MAX_UINT32 #define NPY_SIZE_T NPY_UINT32 #elif SIZE_MAX==NPY_MAX_UINT64 #define NPY_SIZE_T NPY_UINT64 #else #error logic error with SIZE_MAX #endif #define TRY PyState *state = (PyState*)raw; try namespace { struct PyState { PyObject_HEAD PyObject *dict, *weak; // __dict__ and __weakref__ PyObject *attrs; // lookup name to attribute index (for StateBase) StateBase *state; }; static int PyState_traverse(PyObject *raw, visitproc visit, void *arg) { PyState *state = (PyState*)raw; Py_VISIT(state->attrs); Py_VISIT(state->dict); return 0; } static int PyState_clear(PyObject *raw) { PyState *state = (PyState*)raw; Py_CLEAR(state->dict); Py_CLEAR(state->attrs); return 0; } static void PyState_free(PyObject *raw) { TRY { std::auto_ptr<StateBase> S(state->state); state->state = NULL; if(state->weak) PyObject_ClearWeakRefs(raw); PyState_clear(raw); Py_TYPE(raw)->tp_free(raw); } CATCH2V(std::exception, RuntimeError) } static PyObject *PyState_getattro(PyObject *raw, PyObject *attr) { TRY { PyObject *idx = PyDict_GetItem(state->attrs, attr); if(!idx) { return PyObject_GenericGetAttr(raw, attr); } int i = PyInt_AsLong(idx); StateBase::ArrayInfo info; if(!state->state->getArray(i, info)) return PyErr_Format(PyExc_RuntimeError, "invalid attribute name (sub-class forgot %d)", i); if(info.ndim==0) { // Scalar switch(info.type) { case StateBase::ArrayInfo::Double: return PyFloat_FromDouble(*(double*)info.ptr); case StateBase::ArrayInfo::Sizet: return PyLong_FromSize_t(*(size_t*)info.ptr); } return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } int pytype; switch(info.type) { case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break; case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break; default: return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } npy_intp dims[StateBase::ArrayInfo::maxdims]; std::copy(info.dim, info.dim+StateBase::ArrayInfo::maxdims, dims); // Alloc new array and copy in PyRef<PyArrayObject> obj(PyArray_SimpleNew(info.ndim, dims, pytype)); // pull parts from PyArray into ArrayInfo so we can use ArrayInfo::raw() to access StateBase::ArrayInfo pyinfo; pyinfo.ptr = PyArray_BYTES(obj.py()); pyinfo.ndim= PyArray_NDIM(obj.get()); std::copy(PyArray_DIMS(obj.get()), PyArray_DIMS(obj.get())+pyinfo.ndim, pyinfo.dim); std::copy(PyArray_STRIDES(obj.get()), PyArray_STRIDES(obj.get())+pyinfo.ndim, pyinfo.stride); ndindex_iterate<StateBase::ArrayInfo::maxdims> idxiter(info.ndim, info.dim); for(; !idxiter.done; idxiter.next()) { void *dest = pyinfo.raw(idxiter.index); const void *src = info .raw(idxiter.index); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } return obj.releasePy(); } CATCH() } static int PyState_setattro(PyObject *raw, PyObject *attr, PyObject *val) { TRY { PyObject *idx = PyDict_GetItem(state->attrs, attr); if(!idx) return PyObject_GenericSetAttr(raw, attr, val); int i = PyInt_AsLong(idx); StateBase::ArrayInfo info; if(!state->state->getArray(i, info)) { PyErr_Format(PyExc_RuntimeError, "invalid attribute name (sub-class forgot %d)", i); return -1; } if(info.ndim==0) { // Scalar (use python primative types) switch(info.type) { case StateBase::ArrayInfo::Double: { double *dest = (double*)info.ptr; if(PyFloat_Check(val)) *dest = PyFloat_AsDouble(val); else if(PyLong_Check(val)) *dest = PyLong_AsDouble(val); else if(PyInt_Check(val)) *dest = PyInt_AsLong(val); else PyErr_Format(PyExc_ValueError, "Can't assign to double field"); } break; case StateBase::ArrayInfo::Sizet: { size_t *dest = (size_t*)info.ptr; if(PyFloat_Check(val)) *dest = PyFloat_AsDouble(val); else if(PyLong_Check(val)) *dest = PyLong_AsUnsignedLongLong(val); else if(PyInt_Check(val)) *dest = PyInt_AsLong(val); else PyErr_Format(PyExc_ValueError, "Can't assign to double field"); } break; default: PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); } return PyErr_Occurred() ? -1 : 0; } // array (use numpy) int pytype; switch(info.type) { case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break; case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break; default: PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type); return -1; } PyRef<PyArrayObject> arr(PyArray_FromObject(val, pytype, 1, 2)); if(info.ndim!=(size_t)PyArray_NDIM(arr.py())) { PyErr_Format(PyExc_ValueError, "cardinality don't match"); return -1; } else if(!std::equal(info.dim, info.dim+info.ndim, PyArray_DIMS(arr.py()))) { PyErr_Format(PyExc_ValueError, "shape does not match don't match"); return -1; } // pull parts from PyArray into ArrayInfo so we can use ArrayInfo::raw() to access StateBase::ArrayInfo pyinfo; pyinfo.ptr = PyArray_BYTES(arr.py()); pyinfo.ndim= PyArray_NDIM(arr.get()); std::copy(PyArray_DIMS(arr.get()), PyArray_DIMS(arr.get())+pyinfo.ndim, pyinfo.dim); std::copy(PyArray_STRIDES(arr.get()), PyArray_STRIDES(arr.get())+pyinfo.ndim, pyinfo.stride); ndindex_iterate<StateBase::ArrayInfo::maxdims> idxiter(info.ndim, info.dim); for(; !idxiter.done; idxiter.next()) { const void *src = pyinfo .raw(idxiter.index); void *dest = info.raw(idxiter.index); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } if(info.ndim==1) { for(size_t i=0; i<info.dim[0]; i++) { const void *src = PyArray_GETPTR1(arr.py(), i); void *dest = info.raw(&i); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } } else if(info.ndim==2) { size_t idx[2]; for(idx[0]=0; idx[0]<info.dim[0]; idx[0]++) { for(idx[1]=0; idx[1]<info.dim[1]; idx[1]++) { const void *src = PyArray_GETPTR2(arr.py(), idx[0], idx[1]); void *dest = info.raw(idx); switch(info.type) { case StateBase::ArrayInfo::Double: *(double*)dest = *(double*)src; break; case StateBase::ArrayInfo::Sizet: *(size_t*)dest = *(size_t*)src; break; } } } } return 0; } CATCH3(std::exception, RuntimeError, -1) } static PyObject* PyState_str(PyObject *raw) { TRY { std::ostringstream strm; state->state->show(strm, 0); return PyString_FromString(strm.str().c_str()); } CATCH() } static PyObject* PyState_iter(PyObject *raw) { TRY { return PyObject_GetIter(state->attrs); }CATCH() } static Py_ssize_t PyState_len(PyObject *raw) { TRY{ return PyObject_Length(state->attrs); }CATCH1(-1) } static PySequenceMethods PyState_seq = { &PyState_len }; static PyObject* PyState_clone(PyObject *raw, PyObject *unused) { TRY { std::auto_ptr<StateBase> newstate(state->state->clone()); PyObject *ret = wrapstate(newstate.get()); newstate.release(); return ret; } CATCH() } static PyObject* PyState_show(PyObject *raw, PyObject *args, PyObject *kws) { TRY { unsigned long level = 1; const char *names[] = {"level", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kws, "|k", (char**)names, &level)) return NULL; std::ostringstream strm; state->state->show(strm, level); return PyString_FromString(strm.str().c_str()); } CATCH() } static PyMethodDef PyState_methods[] = { {"clone", (PyCFunction)&PyState_clone, METH_NOARGS, "clone()\n\n" "Returns a new State instance which is a copy of this one" }, {"show", (PyCFunction)&PyState_show, METH_VARARGS|METH_KEYWORDS, "show(level=1)" }, {NULL, NULL, 0, NULL} }; static PyTypeObject PyStateType = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, #endif "flame._internal.State", sizeof(PyState), }; } // namespace PyObject* wrapstate(StateBase* b) { try { PyRef<PyState> state(PyStateType.tp_alloc(&PyStateType, 0)); state->state = b; state->attrs = state->weak = state->dict = 0; state->attrs = PyDict_New(); if(!state->attrs) return NULL; for(unsigned i=0; true; i++) { StateBase::ArrayInfo info; if(!b->getArray(i, info)) break; bool skip = info.ndim>3; switch(info.type) { case StateBase::ArrayInfo::Double: case StateBase::ArrayInfo::Sizet: break; default: skip = true; } if(skip) continue; PyRef<> name(PyInt_FromLong(i)); if(PyDict_SetItemString(state->attrs, info.name, name.py())) throw std::runtime_error("Failed to insert into Dict"); } return state.releasePy(); } CATCH() } StateBase* unwrapstate(PyObject* raw) { if(!PyObject_TypeCheck(raw, &PyStateType)) throw std::invalid_argument("Argument is not a State"); PyState *state = (PyState*)raw; return state->state; } static const char pymdoc[] = "The interface to a sub-class of C++ StateBase.\n" "Can't be constructed from python, see Machine.allocState()\n" "\n" "Provides access to some C++ member variables via the Machine::getArray() interface.\n" ; int registerModState(PyObject *mod) { PyStateType.tp_doc = pymdoc; PyStateType.tp_str = &PyState_str; PyStateType.tp_repr = &PyState_str; PyStateType.tp_dealloc = &PyState_free; PyStateType.tp_iter = &PyState_iter; PyStateType.tp_as_sequence = &PyState_seq; PyStateType.tp_weaklistoffset = offsetof(PyState, weak); PyStateType.tp_traverse = &PyState_traverse; PyStateType.tp_clear = &PyState_clear; PyStateType.tp_dictoffset = offsetof(PyState, dict); PyStateType.tp_getattro = &PyState_getattro; PyStateType.tp_setattro = &PyState_setattro; PyStateType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC; PyStateType.tp_methods = PyState_methods; if(PyType_Ready(&PyStateType)) return -1; Py_INCREF(&PyStateType); if(PyModule_AddObject(mod, "State", (PyObject*)&PyStateType)) { Py_DECREF(&PyStateType); return -1; } return 0; } <|endoftext|>
<commit_before>#include "ofQtUtils.h" static bool bQuicktimeInitialized = false; //---------------------------------------- void initializeQuicktime(){ if (bQuicktimeInitialized == false){ //---------------------------------- // do we have quicktime installed at all? // http://www.apple.com/quicktime/download/win.html // can gestalt help with versions, or is that only after init? OSErr myErr = noErr; #ifdef TARGET_WIN32 myErr = InitializeQTML(0); if (myErr != noErr){ printf("----------------------------------------------------- \n"); printf("sorry, there is a problem with quicktime starting up \nplease check!"); OF_EXIT_APP(0); } #endif myErr = EnterMovies (); if (myErr != noErr){ printf("----------------------------------------------------- \n"); printf("sorry, there is a problem with quicktime starting up \nplease check!"); OF_EXIT_APP(0); } bQuicktimeInitialized = true; } } //---------------------------------------- void closeQuicktime(){ if (bQuicktimeInitialized == true){ ExitMovies(); #ifdef TARGET_WIN32 TerminateQTML(); #endif bQuicktimeInitialized = false; } } //---------------------------------------- void convertPixels(unsigned char * gWorldPixels, unsigned char * rgbPixels, int w, int h){ // ok for macs? // ok for intel macs? int * rgbaPtr = (int *) gWorldPixels; pix24 * rgbPtr = (pix24 *) rgbPixels; int totalPixelCount = w * h; unsigned char * rgbaStart; // putting in the boolean, so we can work on // 0,0 in top right... // bool bFlipVertically = true; bool bFlipVertically = false; // ------------------------------------------- // we flip vertically because the 0,0 position in OF // is the bottom left (not top left, like processing) // since the 0,0 of a picture is top left // if we upload and drawf the data as is // it will be upside-down.... // ------------------------------------------- if (!bFlipVertically){ //----- argb->rgb for (int i = 0; i < h; i++){ pix24 * rgbPtr = (pix24 *) rgbPixels + ((i) * w); for (int j = 0; j < w; j++){ rgbaStart = (unsigned char *)rgbaPtr; memcpy (rgbPtr, rgbaStart+1, sizeof(pix24)); rgbPtr++; rgbaPtr++; } } } else { //----- flip while argb->rgb for (int i = 0; i < h; i++){ pix24 * rgbPtr = (pix24 *) rgbPixels + ((h-i-1) * w); for (int j = 0; j < w; j++){ rgbaStart = (unsigned char *)rgbaPtr; memcpy (rgbPtr, rgbaStart+1, sizeof(pix24)); rgbPtr++; rgbaPtr++; } } } } //---------------------------------------- // osx needs this for modal dialogs. Boolean SeqGrabberModalFilterUPP (DialogPtr theDialog, const EventRecord *theEvent, short *itemHit, long refCon){ #pragma unused(theDialog, itemHit) Boolean handled = false; if ((theEvent->what == updateEvt) && ((WindowPtr) theEvent->message == (WindowPtr) refCon)) { BeginUpdate ((WindowPtr) refCon); EndUpdate ((WindowPtr) refCon); handled = true; } return (handled); } //---------------------------------------- #ifdef TARGET_OSX // GetSettingsPreference // Returns a preference for a specified key as QuickTime UserData // It is your responsibility to dispose of the returned UserData OSErr GetSettingsPreference(CFStringRef inKey, UserData *outUserData) { CFPropertyListRef theCFSettings; Handle theHandle = NULL; UserData theUserData = NULL; OSErr err = paramErr; // read the new setttings from our preferences theCFSettings = CFPreferencesCopyAppValue(inKey, kCFPreferencesCurrentApplication); if (theCFSettings) { err = PtrToHand(CFDataGetBytePtr((CFDataRef)theCFSettings), &theHandle, CFDataGetLength((CFDataRef)theCFSettings)); CFRelease(theCFSettings); if (theHandle) { err = NewUserDataFromHandle(theHandle, &theUserData); if (theUserData) { *outUserData = theUserData; } DisposeHandle(theHandle); } } return err; } //---------------------------------------- // SaveSettingsPreference // Saves a preference for a specified key from QuickTime UserData OSErr SaveSettingsPreference(CFStringRef inKey, UserData inUserData) { CFDataRef theCFSettings; Handle hSettings; OSErr err; if (NULL == inUserData) return paramErr; hSettings = NewHandle(0); err = MemError(); if (noErr == err) { err = PutUserDataIntoHandle(inUserData, hSettings); if (noErr == err) { HLock(hSettings); theCFSettings = CFDataCreate(kCFAllocatorDefault, (UInt8 *)*hSettings, GetHandleSize(hSettings)); if (theCFSettings) { CFPreferencesSetAppValue(inKey, theCFSettings, kCFPreferencesCurrentApplication); CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); CFRelease(theCFSettings); } } DisposeHandle(hSettings); } return err; } #define kCharacteristicHasVideoFrameRate FOUR_CHAR_CODE('vfrr') #define kCharacteristicIsAnMpegTrack FOUR_CHAR_CODE('mpeg') /* Calculate the static frame rate for a given movie. */ void MovieGetStaticFrameRate(Movie inMovie, double *outStaticFrameRate) { assert(inMovie != NULL); assert(outStaticFrameRate != NULL); *outStaticFrameRate = 0; Media movieMedia; MediaHandler movieMediaHandler; /* get the media identifier for the media that contains the first video track's sample data, and also get the media handler for this media. */ MovieGetVideoMediaAndMediaHandler(inMovie, &movieMedia, &movieMediaHandler); if (movieMedia && movieMediaHandler) { Boolean isMPEG = false; /* is this the MPEG-1/MPEG-2 media handler? */ OSErr err = IsMPEGMediaHandler(movieMediaHandler, &isMPEG); if (err == noErr) { if (isMPEG) /* working with MPEG-1/MPEG-2 media */ { Fixed staticFrameRate; ComponentResult err = MPEGMediaGetStaticFrameRate(movieMediaHandler, &staticFrameRate); if (err == noErr) { /* convert Fixed data result to type double */ *outStaticFrameRate = Fix2X(staticFrameRate); } } else /* working with non-MPEG-1/MPEG-2 media */ { OSErr err = MediaGetStaticFrameRate(movieMedia, outStaticFrameRate); assert(err == noErr); } } } } /* Get the media identifier for the media that contains the first video track's sample data, and also get the media handler for this media. */ void MovieGetVideoMediaAndMediaHandler(Movie inMovie, Media *outMedia, MediaHandler *outMediaHandler) { assert(inMovie != NULL); assert(outMedia != NULL); assert(outMediaHandler != NULL); *outMedia = NULL; *outMediaHandler = NULL; /* get first video track */ Track videoTrack = GetMovieIndTrackType(inMovie, 1, kCharacteristicHasVideoFrameRate, movieTrackCharacteristic | movieTrackEnabledOnly); if (videoTrack != NULL) { /* get media ref. for track's sample data */ *outMedia = GetTrackMedia(videoTrack); if (*outMedia) { /* get a reference to the media handler component */ *outMediaHandler = GetMediaHandler(*outMedia); } } } /* Return true if media handler reference is from the MPEG-1/MPEG-2 media handler. Return false otherwise. */ OSErr IsMPEGMediaHandler(MediaHandler inMediaHandler, Boolean *outIsMPEG) { assert(inMediaHandler != NULL); assert(outIsMPEG != NULL); /* is this the MPEG-1/MPEG-2 media handler? */ return(MediaHasCharacteristic(inMediaHandler, kCharacteristicIsAnMpegTrack, outIsMPEG)); } /* Given a reference to the media handler used for media in a MPEG-1/MPEG-2 track, return the static frame rate. */ ComponentResult MPEGMediaGetStaticFrameRate(MediaHandler inMPEGMediaHandler, Fixed *outStaticFrameRate) { assert(inMPEGMediaHandler != NULL); assert(outStaticFrameRate != NULL); *outStaticFrameRate = 0; MHInfoEncodedFrameRateRecord encodedFrameRate; Size encodedFrameRateSize = sizeof(encodedFrameRate); /* get the static frame rate */ ComponentResult err = MediaGetPublicInfo(inMPEGMediaHandler, kMHInfoEncodedFrameRate, &encodedFrameRate, &encodedFrameRateSize); if (err == noErr) { /* return frame rate at which the track was encoded */ *outStaticFrameRate = encodedFrameRate.encodedFrameRate; } return err; } /* Given a reference to the media that contains the sample data for a track, calculate the static frame rate. */ OSErr MediaGetStaticFrameRate(Media inMovieMedia, double *outFPS) { assert(inMovieMedia != NULL); assert(outFPS != NULL); *outFPS = 0; /* get the number of samples in the media */ long sampleCount = GetMediaSampleCount(inMovieMedia); OSErr err = GetMoviesError(); if (sampleCount && err == noErr) { /* find the media duration */ TimeValue64 duration = GetMediaDisplayDuration(inMovieMedia); err = GetMoviesError(); if (err == noErr) { /* get the media time scale */ TimeValue64 timeScale = GetMediaTimeScale(inMovieMedia); err = GetMoviesError(); if (err == noErr) { /* calculate the frame rate: frame rate = (sample count * media time scale) / media duration */ *outFPS = (double)sampleCount * (double)timeScale / (double)duration; } } } return err; } #endif <commit_msg>Redone overwritten changes for platform especific ifdefs<commit_after>#include "ofQtUtils.h" #ifndef TARGET_LINUX static bool bQuicktimeInitialized = false; //---------------------------------------- void initializeQuicktime(){ if (bQuicktimeInitialized == false){ //---------------------------------- // do we have quicktime installed at all? // http://www.apple.com/quicktime/download/win.html // can gestalt help with versions, or is that only after init? OSErr myErr = noErr; #ifdef TARGET_WIN32 myErr = InitializeQTML(0); if (myErr != noErr){ printf("----------------------------------------------------- \n"); printf("sorry, there is a problem with quicktime starting up \nplease check!"); OF_EXIT_APP(0); } #endif myErr = EnterMovies (); if (myErr != noErr){ printf("----------------------------------------------------- \n"); printf("sorry, there is a problem with quicktime starting up \nplease check!"); OF_EXIT_APP(0); } bQuicktimeInitialized = true; } } //---------------------------------------- void closeQuicktime(){ if (bQuicktimeInitialized == true){ ExitMovies(); #ifdef TARGET_WIN32 TerminateQTML(); #endif bQuicktimeInitialized = false; } } //---------------------------------------- void convertPixels(unsigned char * gWorldPixels, unsigned char * rgbPixels, int w, int h){ // ok for macs? // ok for intel macs? int * rgbaPtr = (int *) gWorldPixels; pix24 * rgbPtr = (pix24 *) rgbPixels; int totalPixelCount = w * h; unsigned char * rgbaStart; // putting in the boolean, so we can work on // 0,0 in top right... // bool bFlipVertically = true; bool bFlipVertically = false; // ------------------------------------------- // we flip vertically because the 0,0 position in OF // is the bottom left (not top left, like processing) // since the 0,0 of a picture is top left // if we upload and drawf the data as is // it will be upside-down.... // ------------------------------------------- if (!bFlipVertically){ //----- argb->rgb for (int i = 0; i < h; i++){ pix24 * rgbPtr = (pix24 *) rgbPixels + ((i) * w); for (int j = 0; j < w; j++){ rgbaStart = (unsigned char *)rgbaPtr; memcpy (rgbPtr, rgbaStart+1, sizeof(pix24)); rgbPtr++; rgbaPtr++; } } } else { //----- flip while argb->rgb for (int i = 0; i < h; i++){ pix24 * rgbPtr = (pix24 *) rgbPixels + ((h-i-1) * w); for (int j = 0; j < w; j++){ rgbaStart = (unsigned char *)rgbaPtr; memcpy (rgbPtr, rgbaStart+1, sizeof(pix24)); rgbPtr++; rgbaPtr++; } } } } //---------------------------------------- // osx needs this for modal dialogs. Boolean SeqGrabberModalFilterUPP (DialogPtr theDialog, const EventRecord *theEvent, short *itemHit, long refCon){ #pragma unused(theDialog, itemHit) Boolean handled = false; if ((theEvent->what == updateEvt) && ((WindowPtr) theEvent->message == (WindowPtr) refCon)) { BeginUpdate ((WindowPtr) refCon); EndUpdate ((WindowPtr) refCon); handled = true; } return (handled); } //---------------------------------------- #ifdef TARGET_OSX // GetSettingsPreference // Returns a preference for a specified key as QuickTime UserData // It is your responsibility to dispose of the returned UserData OSErr GetSettingsPreference(CFStringRef inKey, UserData *outUserData) { CFPropertyListRef theCFSettings; Handle theHandle = NULL; UserData theUserData = NULL; OSErr err = paramErr; // read the new setttings from our preferences theCFSettings = CFPreferencesCopyAppValue(inKey, kCFPreferencesCurrentApplication); if (theCFSettings) { err = PtrToHand(CFDataGetBytePtr((CFDataRef)theCFSettings), &theHandle, CFDataGetLength((CFDataRef)theCFSettings)); CFRelease(theCFSettings); if (theHandle) { err = NewUserDataFromHandle(theHandle, &theUserData); if (theUserData) { *outUserData = theUserData; } DisposeHandle(theHandle); } } return err; } //---------------------------------------- // SaveSettingsPreference // Saves a preference for a specified key from QuickTime UserData OSErr SaveSettingsPreference(CFStringRef inKey, UserData inUserData) { CFDataRef theCFSettings; Handle hSettings; OSErr err; if (NULL == inUserData) return paramErr; hSettings = NewHandle(0); err = MemError(); if (noErr == err) { err = PutUserDataIntoHandle(inUserData, hSettings); if (noErr == err) { HLock(hSettings); theCFSettings = CFDataCreate(kCFAllocatorDefault, (UInt8 *)*hSettings, GetHandleSize(hSettings)); if (theCFSettings) { CFPreferencesSetAppValue(inKey, theCFSettings, kCFPreferencesCurrentApplication); CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); CFRelease(theCFSettings); } } DisposeHandle(hSettings); } return err; } #define kCharacteristicHasVideoFrameRate FOUR_CHAR_CODE('vfrr') #define kCharacteristicIsAnMpegTrack FOUR_CHAR_CODE('mpeg') /* Calculate the static frame rate for a given movie. */ void MovieGetStaticFrameRate(Movie inMovie, double *outStaticFrameRate) { assert(inMovie != NULL); assert(outStaticFrameRate != NULL); *outStaticFrameRate = 0; Media movieMedia; MediaHandler movieMediaHandler; /* get the media identifier for the media that contains the first video track's sample data, and also get the media handler for this media. */ MovieGetVideoMediaAndMediaHandler(inMovie, &movieMedia, &movieMediaHandler); if (movieMedia && movieMediaHandler) { Boolean isMPEG = false; /* is this the MPEG-1/MPEG-2 media handler? */ OSErr err = IsMPEGMediaHandler(movieMediaHandler, &isMPEG); if (err == noErr) { if (isMPEG) /* working with MPEG-1/MPEG-2 media */ { Fixed staticFrameRate; ComponentResult err = MPEGMediaGetStaticFrameRate(movieMediaHandler, &staticFrameRate); if (err == noErr) { /* convert Fixed data result to type double */ *outStaticFrameRate = Fix2X(staticFrameRate); } } else /* working with non-MPEG-1/MPEG-2 media */ { OSErr err = MediaGetStaticFrameRate(movieMedia, outStaticFrameRate); assert(err == noErr); } } } } /* Get the media identifier for the media that contains the first video track's sample data, and also get the media handler for this media. */ void MovieGetVideoMediaAndMediaHandler(Movie inMovie, Media *outMedia, MediaHandler *outMediaHandler) { assert(inMovie != NULL); assert(outMedia != NULL); assert(outMediaHandler != NULL); *outMedia = NULL; *outMediaHandler = NULL; /* get first video track */ Track videoTrack = GetMovieIndTrackType(inMovie, 1, kCharacteristicHasVideoFrameRate, movieTrackCharacteristic | movieTrackEnabledOnly); if (videoTrack != NULL) { /* get media ref. for track's sample data */ *outMedia = GetTrackMedia(videoTrack); if (*outMedia) { /* get a reference to the media handler component */ *outMediaHandler = GetMediaHandler(*outMedia); } } } /* Return true if media handler reference is from the MPEG-1/MPEG-2 media handler. Return false otherwise. */ OSErr IsMPEGMediaHandler(MediaHandler inMediaHandler, Boolean *outIsMPEG) { assert(inMediaHandler != NULL); assert(outIsMPEG != NULL); /* is this the MPEG-1/MPEG-2 media handler? */ return(MediaHasCharacteristic(inMediaHandler, kCharacteristicIsAnMpegTrack, outIsMPEG)); } /* Given a reference to the media handler used for media in a MPEG-1/MPEG-2 track, return the static frame rate. */ ComponentResult MPEGMediaGetStaticFrameRate(MediaHandler inMPEGMediaHandler, Fixed *outStaticFrameRate) { assert(inMPEGMediaHandler != NULL); assert(outStaticFrameRate != NULL); *outStaticFrameRate = 0; MHInfoEncodedFrameRateRecord encodedFrameRate; Size encodedFrameRateSize = sizeof(encodedFrameRate); /* get the static frame rate */ ComponentResult err = MediaGetPublicInfo(inMPEGMediaHandler, kMHInfoEncodedFrameRate, &encodedFrameRate, &encodedFrameRateSize); if (err == noErr) { /* return frame rate at which the track was encoded */ *outStaticFrameRate = encodedFrameRate.encodedFrameRate; } return err; } /* Given a reference to the media that contains the sample data for a track, calculate the static frame rate. */ OSErr MediaGetStaticFrameRate(Media inMovieMedia, double *outFPS) { assert(inMovieMedia != NULL); assert(outFPS != NULL); *outFPS = 0; /* get the number of samples in the media */ long sampleCount = GetMediaSampleCount(inMovieMedia); OSErr err = GetMoviesError(); if (sampleCount && err == noErr) { /* find the media duration */ TimeValue64 duration = GetMediaDisplayDuration(inMovieMedia); err = GetMoviesError(); if (err == noErr) { /* get the media time scale */ TimeValue64 timeScale = GetMediaTimeScale(inMovieMedia); err = GetMoviesError(); if (err == noErr) { /* calculate the frame rate: frame rate = (sample count * media time scale) / media duration */ *outFPS = (double)sampleCount * (double)timeScale / (double)duration; } } } return err; } #endif #endif <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_Image.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_PYBIND11_IMAGE_HPP_ #define EOS_PYBIND11_IMAGE_HPP_ #include "pybind11/numpy.h" #include "Eigen/Core" #include <cstddef> #include <vector> NAMESPACE_BEGIN(pybind11) NAMESPACE_BEGIN(detail) /** * @file python/pybind11_Image.hpp * @brief Transparent conversion to and from Python for eos::core::Image. * * Numpy uses row-major storage order by default. * eos::core::Image uses col-major storage (like Eigen). * * If given non-standard strides or something from numpy, probably doesn't work. * May need to .clone()? in numpy before passing to the C++ function. */ /** * @brief Transparent conversion for eos::core::Image3u to and from Python. * * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image3u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 3) { return false; // We expected a 3-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image3u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); } } return true; }; static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 3; std::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. // numpy: 'f' = fortran = col-major // 'c' = c = row-major = default I think. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]")); }; /** * @brief Transparent conversion for eos::core::Image4u to and from Python. * * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image4u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 4) { return false; // We expected a 4-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image4u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); value(r, c)[3] = buf_as_array.at(r, c, 3); } } return true; }; static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_chanels = 4; std::vector<std::size_t> shape; shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_chanels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<size_t> strides = { num_chanels, num_chanels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]")); }; NAMESPACE_END(detail) NAMESPACE_END(pybind11) #endif /* EOS_PYBIND11_IMAGE_HPP_ */ <commit_msg>Fix small typo in variable name<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_Image.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_PYBIND11_IMAGE_HPP_ #define EOS_PYBIND11_IMAGE_HPP_ #include "pybind11/numpy.h" #include "Eigen/Core" #include <cstddef> #include <vector> NAMESPACE_BEGIN(pybind11) NAMESPACE_BEGIN(detail) /** * @file python/pybind11_Image.hpp * @brief Transparent conversion to and from Python for eos::core::Image. * * Numpy uses row-major storage order by default. * eos::core::Image uses col-major storage (like Eigen). * * If given non-standard strides or something from numpy, probably doesn't work. * May need to .clone()? in numpy before passing to the C++ function. */ /** * @brief Transparent conversion for eos::core::Image3u to and from Python. * * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image3u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 3) { return false; // We expected a 3-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image3u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); } } return true; }; static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 3; std::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. // numpy: 'f' = fortran = col-major // 'c' = c = row-major = default I think. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]")); }; /** * @brief Transparent conversion for eos::core::Image4u to and from Python. * * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image4u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 4) { return false; // We expected a 4-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image4u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); value(r, c)[3] = buf_as_array.at(r, c, 3); } } return true; }; static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 4; std::vector<std::size_t> shape; shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]")); }; NAMESPACE_END(detail) NAMESPACE_END(pybind11) #endif /* EOS_PYBIND11_IMAGE_HPP_ */ <|endoftext|>
<commit_before>#include "material.h" #include "simconf.h" #include "functions.h" #include <cmath> #include <iostream> void materialBase::prepare() { double tt = 0.0; // get total stoichiometry for( int i = 0; i < element.size(); i++ ) { if( element[i]->t < 0.0 ) element[i]->t = 0.0; tt += element[i]->t; } // normalize relative probabilities to 1 for( int i = 0; i < element.size(); i++ ) element[i]->t /= tt; // average am = 0.0; az = 0.0; for( int i = 0; i < element.size(); i++ ) { am += element[i]->m * element[i]->t; az += double( element[i]->z ) * element[i]->t; } arho = rho * 0.6022 / am; //[TRI00310] atoms/Ang^3 } // make sure layers are prepare'd first! void materialBase::average( const ionBase *pka ) { mu = pka->m1 / am; // universal or firsov screening length a = .5292 * .8853 / ( pow( double(pka->z1), 0.23 ) + pow( az, 0.23 ) ); //a = .5292 * .8853 / pow( pow( double(pka.z1), 0.5 ) + pow( az, 0.5 ), 2.0/3.0 ); // mean flight path0 f = a * am / ( az * double(pka->z1) * 14.4 * ( pka->m1 + am ) ); //eps0 = e0 * f; epsdg = simconf->tmin * f * pow( 1.0 + mu, 2.0 ) / ( 4.0 * mu ); // fd and kd determine how much recoil energy goes into el. loss and vaccancies fd = pow( 0.01 * az, -7.0 / 3.0 ); kd = pow( 0.1334 * az, 2.0 / 3.0 ) / sqrtf( am ); for( int i = 0; i < element.size(); i++ ) { element[i]->my = pka->m1 / element[i]->m; element[i]->ec = 4.0 * element[i]->my / pow( 1.0 + element[i]->my, 2.0 ); element[i]->ai = .5292 * .8853 / ( pow( double(pka->z1), 0.23 ) + pow( element[i]->m, 0.23 ) ); //ai = .5292 * .8853 / pow( pow( double(pka.z1), 0.5 ) + pow( element[i].m, 0.5 ), 2.0/3.0 ); element[i]->fi = element[i]->ai * element[i]->m / ( double(pka->z1) * double(element[i]->z) * 14.4 * ( pka->m1 + element[i]->m ) ); } dirty = false; } // make sure layers are prepare'd and averaged first! double materialBase::getrstop( const ionBase *pka ) { double se = 0.0; for( int i = 0; i < element.size(); i++ ) se += rstop( pka, element[i]->z ) * element[i]->t * arho; return se; } double materialBase::rpstop( int z2p, double e ) { double pe, pe0, sl, sh, sp, velpwr; int z2 = z2p-1; // velocity proportional stopping below pe0 pe0 = 25.0; pe = fmax( pe0, e ); // pcoef indices are one less than in the fortran version! sl = ( simconf->pcoef[z2][0] * pow( pe, simconf->pcoef[z2][1] ) ) + ( simconf->pcoef[z2][2] * pow( pe, simconf->pcoef[z2][3] ) ); sh = simconf->pcoef[z2][4] / pow( pe, simconf->pcoef[z2][5] ) * logf( simconf->pcoef[z2][6] / pe + simconf->pcoef[z2][7] * pe ); sp = sl * sh / (sl + sh ); if( e <= pe0 ) { // velpwr is the power of velocity stopping below pe0 if( z2p <= 6 ) velpwr = 0.25; else velpwr = 0.45; sp *= pow( e/pe0, velpwr ); } return sp; } double materialBase::rstop( const ionBase *ion, int z2 ) { double e, vrmin, yrmin, v, vr, yr, vmin, m1; double a, b, q, q1, l, l0, l1; double zeta; int z1 = ion->z1; double fz1 = double(z1), fz2 = double(z2); double eee, sp, power; double se; // scoeff double lfctr = simconf->scoef[z1-1].lfctr; double mm1 = simconf->scoef[z1-1].mm1; double vfermi = simconf->scoef[z2-1].vfermi; double atrho = simconf->scoef[z2-1].atrho; if( ion->m1 == 0.0 ) m1 = mm1; else m1 = ion->m1; e = 0.001 * ion->e / m1; if( z1 == 1 ) { cerr << "proton stopping not yet implemented!\n"; } else if( z1 == 2 ) { cerr << "alpha stopping not yet implemented!\n"; } else { yrmin = 0.13; vrmin = 1.0; v = sqrtf( e / 25.0) / vfermi; if( v >= 1.0 ) vr = v * vfermi * ( 1.0 + 1.0 / ( 5.0 * v*v ) ); else vr = ( 3.0 * vfermi / 4.0 ) * ( 1.0 + ( 2.0 * v*v / 3.0 ) - pow( v, 4.0 ) / 15.0 ); yr = fmax( yrmin, vr / pow(fz1,0.6667) ); yr = fmax( yr, vrmin / pow(fz1,0.6667) ); a = -0.803 * pow( yr, 0.3 ) + 1.3167 * pow( yr, 0.6 ) + 0.38157 * yr + 0.008983 * yr*yr; // ionization level of the ion at velocity yr q = fmin( 1.0, fmax( 0.0, 1.0 - exp( -fmin( a, 50.0 ) ) ) ); b = ( fmin( 0.43, fmax( 0.32, 0.12 + 0.025 * fz1 ) ) ) / pow( fz1, 0.3333 ); l0 = ( 0.8 - q * fmin( 1.2, 0.6 + fz1 / 30.0) ) / pow( fz1, 0.3333 ); if( q < 0.2 ) l1 = 0.0; else if( q < fmax( 0.0, 0.9 - 0.025 * fz1 ) ) {//210 q1 = 0.2; l1 = b * ( q - 0.2 ) / fabs( fmax( 0.0, 0.9 - 0.025 * fz1 ) - 0.2000001 ); } else if( q < fmax( 0.0, 1.0 - 0.025 * fmin( 16.0, fz1 ) ) ) l1 = b; else l1 = b * ( 1.0 - q ) / ( 0.025 * fmin( 16.0, fz1 ) ); l = fmax( l1, l0 * lfctr ); zeta = q + ( 1.0 / ( 2.0 * vfermi*vfermi ) ) * ( 1.0 - q ) * logf( 1.0 + sqr( 4.0 * l * vfermi / 1.919 ) ); // add z1^3 effect a = -sqr( 7.6 - fmax( 0.0, logf( e ) ) ); zeta *= 1.0 + ( 1.0 / (fz1*fz1) ) * ( 0.18 + 0.0015 * fz2 ) * expf( a ); if( yr <= fmax( yrmin, vrmin / pow( fz1, 0.6667 ) ) ) { // calculate velocity stopping for yr < yrmin vrmin = fmax( vrmin, yrmin * pow( fz1, 0.6667 ) ); vmin = 0.5 * ( vrmin + sqrtf( fmax( 0.0, vrmin*vrmin - 0.8 * vfermi*vfermi ) ) ); eee = 25.0 * vmin*vmin; sp = rpstop( z2, eee ); if( z2 == 6 || ( ( z2 == 14 || z2 == 32 ) && z1 <= 19 ) ) power = 0.375; else power = 0.5; se = sp * sqr( zeta * fz1 ) * pow( e/eee, power ); } else { sp = rpstop( z2, e ); se = sp * sqr( zeta * fz1 ); } } // END: heavy-ions return se * 10.0; } <commit_msg>fix m/z mix-up in screening length calculation (thanks Topher Matthews for spotting this)<commit_after>#include "material.h" #include "simconf.h" #include "functions.h" #include <cmath> #include <iostream> void materialBase::prepare() { double tt = 0.0; // get total stoichiometry for( int i = 0; i < element.size(); i++ ) { if( element[i]->t < 0.0 ) element[i]->t = 0.0; tt += element[i]->t; } // normalize relative probabilities to 1 for( int i = 0; i < element.size(); i++ ) element[i]->t /= tt; // average am = 0.0; az = 0.0; for( int i = 0; i < element.size(); i++ ) { am += element[i]->m * element[i]->t; az += double( element[i]->z ) * element[i]->t; } arho = rho * 0.6022 / am; //[TRI00310] atoms/Ang^3 } // make sure layers are prepare'd first! void materialBase::average( const ionBase *pka ) { mu = pka->m1 / am; // universal or firsov screening length a = .5292 * .8853 / ( pow( double(pka->z1), 0.23 ) + pow( az, 0.23 ) ); //a = .5292 * .8853 / pow( pow( double(pka.z1), 0.5 ) + pow( az, 0.5 ), 2.0/3.0 ); // mean flight path0 f = a * am / ( az * double(pka->z1) * 14.4 * ( pka->m1 + am ) ); //eps0 = e0 * f; epsdg = simconf->tmin * f * pow( 1.0 + mu, 2.0 ) / ( 4.0 * mu ); // fd and kd determine how much recoil energy goes into el. loss and vaccancies fd = pow( 0.01 * az, -7.0 / 3.0 ); kd = pow( 0.1334 * az, 2.0 / 3.0 ) / sqrtf( am ); for( int i = 0; i < element.size(); i++ ) { element[i]->my = pka->m1 / element[i]->m; element[i]->ec = 4.0 * element[i]->my / pow( 1.0 + element[i]->my, 2.0 ); element[i]->ai = .5292 * .8853 / ( pow( double(pka->z1), 0.23 ) + pow( element[i]->z, 0.23 ) ); //ai = .5292 * .8853 / pow( pow( double(pka.z1), 0.5 ) + pow( element[i].z, 0.5 ), 2.0/3.0 ); element[i]->fi = element[i]->ai * element[i]->m / ( double(pka->z1) * double(element[i]->z) * 14.4 * ( pka->m1 + element[i]->m ) ); } dirty = false; } // make sure layers are prepare'd and averaged first! double materialBase::getrstop( const ionBase *pka ) { double se = 0.0; for( int i = 0; i < element.size(); i++ ) se += rstop( pka, element[i]->z ) * element[i]->t * arho; return se; } double materialBase::rpstop( int z2p, double e ) { double pe, pe0, sl, sh, sp, velpwr; int z2 = z2p-1; // velocity proportional stopping below pe0 pe0 = 25.0; pe = fmax( pe0, e ); // pcoef indices are one less than in the fortran version! sl = ( simconf->pcoef[z2][0] * pow( pe, simconf->pcoef[z2][1] ) ) + ( simconf->pcoef[z2][2] * pow( pe, simconf->pcoef[z2][3] ) ); sh = simconf->pcoef[z2][4] / pow( pe, simconf->pcoef[z2][5] ) * logf( simconf->pcoef[z2][6] / pe + simconf->pcoef[z2][7] * pe ); sp = sl * sh / (sl + sh ); if( e <= pe0 ) { // velpwr is the power of velocity stopping below pe0 if( z2p <= 6 ) velpwr = 0.25; else velpwr = 0.45; sp *= pow( e/pe0, velpwr ); } return sp; } double materialBase::rstop( const ionBase *ion, int z2 ) { double e, vrmin, yrmin, v, vr, yr, vmin, m1; double a, b, q, q1, l, l0, l1; double zeta; int z1 = ion->z1; double fz1 = double(z1), fz2 = double(z2); double eee, sp, power; double se; // scoeff double lfctr = simconf->scoef[z1-1].lfctr; double mm1 = simconf->scoef[z1-1].mm1; double vfermi = simconf->scoef[z2-1].vfermi; double atrho = simconf->scoef[z2-1].atrho; if( ion->m1 == 0.0 ) m1 = mm1; else m1 = ion->m1; e = 0.001 * ion->e / m1; if( z1 == 1 ) { cerr << "proton stopping not yet implemented!\n"; } else if( z1 == 2 ) { cerr << "alpha stopping not yet implemented!\n"; } else { yrmin = 0.13; vrmin = 1.0; v = sqrtf( e / 25.0) / vfermi; if( v >= 1.0 ) vr = v * vfermi * ( 1.0 + 1.0 / ( 5.0 * v*v ) ); else vr = ( 3.0 * vfermi / 4.0 ) * ( 1.0 + ( 2.0 * v*v / 3.0 ) - pow( v, 4.0 ) / 15.0 ); yr = fmax( yrmin, vr / pow(fz1,0.6667) ); yr = fmax( yr, vrmin / pow(fz1,0.6667) ); a = -0.803 * pow( yr, 0.3 ) + 1.3167 * pow( yr, 0.6 ) + 0.38157 * yr + 0.008983 * yr*yr; // ionization level of the ion at velocity yr q = fmin( 1.0, fmax( 0.0, 1.0 - exp( -fmin( a, 50.0 ) ) ) ); b = ( fmin( 0.43, fmax( 0.32, 0.12 + 0.025 * fz1 ) ) ) / pow( fz1, 0.3333 ); l0 = ( 0.8 - q * fmin( 1.2, 0.6 + fz1 / 30.0) ) / pow( fz1, 0.3333 ); if( q < 0.2 ) l1 = 0.0; else if( q < fmax( 0.0, 0.9 - 0.025 * fz1 ) ) {//210 q1 = 0.2; l1 = b * ( q - 0.2 ) / fabs( fmax( 0.0, 0.9 - 0.025 * fz1 ) - 0.2000001 ); } else if( q < fmax( 0.0, 1.0 - 0.025 * fmin( 16.0, fz1 ) ) ) l1 = b; else l1 = b * ( 1.0 - q ) / ( 0.025 * fmin( 16.0, fz1 ) ); l = fmax( l1, l0 * lfctr ); zeta = q + ( 1.0 / ( 2.0 * vfermi*vfermi ) ) * ( 1.0 - q ) * logf( 1.0 + sqr( 4.0 * l * vfermi / 1.919 ) ); // add z1^3 effect a = -sqr( 7.6 - fmax( 0.0, logf( e ) ) ); zeta *= 1.0 + ( 1.0 / (fz1*fz1) ) * ( 0.18 + 0.0015 * fz2 ) * expf( a ); if( yr <= fmax( yrmin, vrmin / pow( fz1, 0.6667 ) ) ) { // calculate velocity stopping for yr < yrmin vrmin = fmax( vrmin, yrmin * pow( fz1, 0.6667 ) ); vmin = 0.5 * ( vrmin + sqrtf( fmax( 0.0, vrmin*vrmin - 0.8 * vfermi*vfermi ) ) ); eee = 25.0 * vmin*vmin; sp = rpstop( z2, eee ); if( z2 == 6 || ( ( z2 == 14 || z2 == 32 ) && z1 <= 19 ) ) power = 0.375; else power = 0.5; se = sp * sqr( zeta * fz1 ) * pow( e/eee, power ); } else { sp = rpstop( z2, e ); se = sp * sqr( zeta * fz1 ); } } // END: heavy-ions return se * 10.0; } <|endoftext|>
<commit_before>#include "SingleElimination.hpp" std::vector<std::shared_ptr<lionheart::Player>> lionheart::SingleElimination::run() { std::vector<std::shared_ptr<Player>> winners; auto fortMap = lionheart::makeMap("forts.in"); auto infantryPaths = std::make_shared<lionheart::Paths>(fortMap, 1); auto mountedPaths = std::make_shared<lionheart::Paths>(fortMap, 5); auto round = 0; while (players.size() > 1) { winners.clear(); while (players.size() > 1) { auto p1 = players.back(); players.pop_back(); auto p2 = players.back(); players.pop_back(); lionheart::Game game(p1, p2, fortMap, infantryPaths, mountedPaths); game.start(); std::cout << p1->getBlazon().name << " vs. " << p2->getBlazon().name << ": "; if (display) { display->setOutput(std::string("se") + p1->getBlazon().name + "-" + p2->getBlazon().name); display->show(game.getReport(), p1->getBlazon(), p2->getBlazon()); } for (auto i = 0; i < 200; ++i) { game.doTurn(nullptr); if (display) { display->show(game.getReport(), p1->getBlazon(), p2->getBlazon()); } if (!game.canContinue()) break; } auto winner = game.winner(); if (winner) { winners.push_back(winner); std::cout << winner->getBlazon().name << " wins!" << std::endl; } else { auto tie = game.tiebreaker(); if (tie) { std::cout << winner->getBlazon().name << " wins by tie break!" << std::endl; winners.push_back(tie); } else { winners.push_back(p1); std::cout << p1->getBlazon().name << " moves on." << std::endl; } } } std::swap(players, winners); ++round; std::cout << "Single Elimination Round " << round << std::endl; for(auto&& p:players) { std::cout << " " << p->getBlazon().name << std::endl; } } return players; } <commit_msg>Fix null pointer error on tie with tiebreaks<commit_after>#include "SingleElimination.hpp" std::vector<std::shared_ptr<lionheart::Player>> lionheart::SingleElimination::run() { std::vector<std::shared_ptr<Player>> winners; auto fortMap = lionheart::makeMap("forts.in"); auto infantryPaths = std::make_shared<lionheart::Paths>(fortMap, 1); auto mountedPaths = std::make_shared<lionheart::Paths>(fortMap, 5); auto round = 0; while (players.size() > 1) { winners.clear(); while (players.size() > 1) { auto p1 = players.back(); players.pop_back(); auto p2 = players.back(); players.pop_back(); lionheart::Game game(p1, p2, fortMap, infantryPaths, mountedPaths); game.start(); std::cout << p1->getBlazon().name << " vs. " << p2->getBlazon().name << ": "; if (display) { display->setOutput(std::string("se") + p1->getBlazon().name + "-" + p2->getBlazon().name); display->show(game.getReport(), p1->getBlazon(), p2->getBlazon()); } for (auto i = 0; i < 200; ++i) { game.doTurn(nullptr); if (display) { display->show(game.getReport(), p1->getBlazon(), p2->getBlazon()); } if (!game.canContinue()) break; } auto winner = game.winner(); if (winner) { winners.push_back(winner); std::cout << winner->getBlazon().name << " wins!" << std::endl; } else { auto tie = game.tiebreaker(); if (tie) { std::cout << tie->getBlazon().name << " wins by tie break!" << std::endl; winners.push_back(tie); } else { winners.push_back(p1); std::cout << p1->getBlazon().name << " moves on." << std::endl; } } } std::swap(players, winners); ++round; std::cout << "Single Elimination Round " << round << std::endl; for(auto&& p:players) { std::cout << " " << p->getBlazon().name << std::endl; } } return players; } <|endoftext|>
<commit_before><commit_msg>08/07/2017<commit_after><|endoftext|>
<commit_before>/**************************************************************** * Copyright (c) 2014, The Pennsylvania State University * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted for * personal and commercial purposes provided that the * following conditions are met: * * 1. Redistribution of source code must retain the * above copyright notice, this list of conditions * and the following Disclaimer. * * 2. Redistribution in binary form must reproduce the * above copyright notice, this list of conditions * and the following disclaimer * * 3. Neither the name of The Pennsylvania State University * nor the names of its contributors may be used to * endorse or promote products derived from this software * without the specific prior written permission of The * Pennsylvania State University * * THIS SOFTWARE IS PROVIDED BY THE PENNSYLVANIA STATE UNIVERSITY * "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF * INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN NO EVENT * SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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 "filepath.h" #include "functions.h" #include "gtest/gtest.h" #include <string> #include <fstream> //This is to put a delay in the test...hopefully #include <unistd.h> #ifdef _MSC_VER #define UNLINK _unlink #else #define UNLINK unlink #endif TEST(FilePathTests, Directory) { std::string testString; #ifdef _WIN32 testString = "C:\\Windows"; #else testString = "/usr"; #endif stadic::FilePath dir(testString); EXPECT_TRUE(dir.exists()); EXPECT_TRUE(dir.isDir()); EXPECT_FALSE(dir.isFile()); EXPECT_FALSE(dir.isUpdated()); #ifdef _WIN32 testString = "C:\\Windows\\"; #else testString = "/usr/"; #endif stadic::FilePath dir1(testString); EXPECT_TRUE(dir1.exists()); EXPECT_TRUE(dir1.isDir()); EXPECT_FALSE(dir1.isFile()); EXPECT_FALSE(dir1.isUpdated()); stadic::FilePath dir2("DOESNOTEXIST"); EXPECT_FALSE(dir2.exists()); } TEST(FilePathTests, File) { std::string testString = "testfile.txt"; UNLINK(testString.c_str()); stadic::FilePath file(testString); EXPECT_FALSE(file.exists()); std::ofstream testOut(testString); testOut << "This is a test file"; testOut.close(); EXPECT_TRUE(file.exists()); EXPECT_TRUE(file.isFile()); EXPECT_FALSE(file.isDir()); EXPECT_FALSE(file.isUpdated()); sleep(3); //There may need to be a delay inserted here so the updated time actually changes std::ofstream reWrite(testString); reWrite << "I'm doing this as hard as I can"; reWrite.close(); EXPECT_TRUE(file.exists()); EXPECT_TRUE(file.isFile()); EXPECT_FALSE(file.isDir()); EXPECT_TRUE(file.isUpdated()); } <commit_msg>Reduced delay in filepathtest to 1 second from 3<commit_after>/**************************************************************** * Copyright (c) 2014, The Pennsylvania State University * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted for * personal and commercial purposes provided that the * following conditions are met: * * 1. Redistribution of source code must retain the * above copyright notice, this list of conditions * and the following Disclaimer. * * 2. Redistribution in binary form must reproduce the * above copyright notice, this list of conditions * and the following disclaimer * * 3. Neither the name of The Pennsylvania State University * nor the names of its contributors may be used to * endorse or promote products derived from this software * without the specific prior written permission of The * Pennsylvania State University * * THIS SOFTWARE IS PROVIDED BY THE PENNSYLVANIA STATE UNIVERSITY * "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF * INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN NO EVENT * SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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 "filepath.h" #include "functions.h" #include "gtest/gtest.h" #include <string> #include <fstream> //This is to put a delay in the test...hopefully #include <unistd.h> #ifdef _MSC_VER #define UNLINK _unlink #else #define UNLINK unlink #endif TEST(FilePathTests, Directory) { std::string testString; #ifdef _WIN32 testString = "C:\\Windows"; #else testString = "/usr"; #endif stadic::FilePath dir(testString); EXPECT_TRUE(dir.exists()); EXPECT_TRUE(dir.isDir()); EXPECT_FALSE(dir.isFile()); EXPECT_FALSE(dir.isUpdated()); #ifdef _WIN32 testString = "C:\\Windows\\"; #else testString = "/usr/"; #endif stadic::FilePath dir1(testString); EXPECT_TRUE(dir1.exists()); EXPECT_TRUE(dir1.isDir()); EXPECT_FALSE(dir1.isFile()); EXPECT_FALSE(dir1.isUpdated()); stadic::FilePath dir2("DOESNOTEXIST"); EXPECT_FALSE(dir2.exists()); } TEST(FilePathTests, File) { std::string testString = "testfile.txt"; UNLINK(testString.c_str()); stadic::FilePath file(testString); EXPECT_FALSE(file.exists()); std::ofstream testOut(testString); testOut << "This is a test file"; testOut.close(); EXPECT_TRUE(file.exists()); EXPECT_TRUE(file.isFile()); EXPECT_FALSE(file.isDir()); EXPECT_FALSE(file.isUpdated()); sleep(1); //There may need to be a delay inserted here so the updated time actually changes std::ofstream reWrite(testString); reWrite << "I'm doing this as hard as I can"; reWrite.close(); EXPECT_TRUE(file.exists()); EXPECT_TRUE(file.isFile()); EXPECT_FALSE(file.isDir()); EXPECT_TRUE(file.isUpdated()); } <|endoftext|>
<commit_before>#include "svgpath.h" #include "svgutils.h" #include "graphicscontext.h" SvgPath::SvgPath(const std::string &str) { setPath(str); } void SvgPath::setPath(const std::string &str) { data.commands.clear(); data.coords.clear(); ok = true; lastError = ""; if (str.empty()) { ok = false; return; } pathString = str; auto it = str.begin(); try { SvgUtils::readSvgPath(it, str.end(), std::back_inserter(data.commands), std::back_inserter(data.coords)); } catch (std::exception &e) { lastError = e.what(); ok = false; } } const std::string &SvgPath::getPath() const { return pathString; } const SvgPath::PathData &SvgPath::getPathData() const { return data; } bool SvgPath::isOk() const { return ok; } std::string SvgPath::getLastError() const { return lastError; } void SvgPath::draw(GraphicsContext *g) const { if (!ok) return; std::vector<PathElement>::const_iterator commandIt = data.commands.begin(); std::vector<double>::const_iterator coordsIt = data.coords.begin(); PathElement prevCommand = PathElement::ClosePath; double x = 0, y = 0; double x1 = 0, y1 = 0; double x2 = 0, y2 = 0; double cx = 0, cy = 0; double prevX = 0, prevY = 0; double prevX1 = 0, prevY1 = 0; double prevX2 = 0, prevY2 = 0; while (commandIt != data.commands.end()) { if (*commandIt == PathElement::MoveTo || *commandIt == PathElement::MoveToRel || *commandIt == PathElement::LineTo || *commandIt == PathElement::LineToRel) { x = *(coordsIt + 0); y = *(coordsIt + 1); std::advance(coordsIt, 2); } else if (*commandIt == PathElement::LineToHorizontal || *commandIt == PathElement::LineToHorizontalRel) { x = *coordsIt; coordsIt++; } else if(*commandIt == PathElement::LineToVertical || *commandIt == PathElement::LineToVerticalRel) { y = *coordsIt; coordsIt++; } else if(*commandIt == PathElement::CurveToCubic || *commandIt == PathElement::CurveToCubicRel) { x1 = *(coordsIt + 0); y1 = *(coordsIt + 1); x2 = *(coordsIt + 2); y2 = *(coordsIt + 3); x = *(coordsIt + 4); y = *(coordsIt + 5); std::advance(coordsIt, 6); } else if(*commandIt == PathElement::CurveToCubicSmooth || *commandIt == PathElement::CurveToCubicSmoothRel) { x2 = *(coordsIt + 0); y2 = *(coordsIt + 1); x = *(coordsIt + 2); y = *(coordsIt + 3); std::advance(coordsIt, 4); } else if(*commandIt == PathElement::CurveToQuadratic || *commandIt == PathElement::CurveToQuadraticRel) { x1 = *(coordsIt + 0); y1 = *(coordsIt + 1); x = *(coordsIt + 2); y = *(coordsIt + 3); std::advance(coordsIt, 4); } else if(*commandIt == PathElement::CurveToQuadraticSmooth || *commandIt == PathElement::CurveToQuadraticSmoothRel) { x = *(coordsIt + 0); y = *(coordsIt + 1); std::advance(coordsIt, 2); } g->getCurrentPoint(cx, cy); if (*commandIt == PathElement::MoveTo || *commandIt == PathElement::MoveToRel) { if (prevCommand != PathElement::ClosePath && std::distance(commandIt, data.commands.begin()) != 0) g->closePath(); if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } g->moveTo(x, y); } else if (*commandIt == PathElement::LineTo || *commandIt == PathElement::LineToRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } g->lineTo(x, y); } else if (*commandIt == PathElement::LineToHorizontal || *commandIt == PathElement::LineToHorizontalRel) { if (SvgUtils::isCommandRelative(*commandIt)) x += cx; g->lineTo(x, cy); } else if (*commandIt == PathElement::LineToVertical || *commandIt == PathElement::LineToVerticalRel) { if (SvgUtils::isCommandRelative(*commandIt)) y += cy; g->lineTo(cx, y); } else if (*commandIt == PathElement::CurveToCubic || *commandIt == PathElement::CurveToCubicRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x1 += cx; y1 += cy; x2 += cx; y2 += cy; } g->curveTo(x1, y1, x2, y2, x, y); } else if (*commandIt == PathElement::CurveToCubicSmooth || *commandIt == PathElement::CurveToCubicSmoothRel) { if (SvgUtils::isCurveToCubic(prevCommand)) { x1 = 2 * prevX - prevX2; y1 = 2 * prevY - prevY2; } else { x1 = cx; y1 = cy; } if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x2 += cx; y2 += cy; } g->curveTo(x1, y1, x2, y2, x, y); } else if (*commandIt == PathElement::CurveToQuadratic || *commandIt == PathElement::CurveToQuadraticRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x1 += cx; y1 += cy; } double qx1 = x1; double qy1 = y1; x1 = cx + 2.0 / 3.0 * (qx1 - cx); y1 = cy + 2.0 / 3.0 * (qy1 - cy); x2 = x + 2.0 / 3.0 * (qx1 - x); y2 = y + 2.0 / 3.0 * (qy1 - y); g->curveTo(x1, y1, x2, y2, x, y); // restore control point coordinate x1 = qx1; y1 = qy1; } else if (*commandIt == PathElement::CurveToQuadraticSmooth || *commandIt == PathElement::CurveToQuadraticSmoothRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } if (SvgUtils::isCurveToQuadratic(prevCommand)) { x1 = 2 * prevX - prevX1; y1 = 2 * prevY - prevY1; } else { x1 = cx; y1 = cy; } double qx1 = x1; double qy1 = y1; x1 = cx + 2.0 / 3.0 * (qx1 - cx); y1 = cy + 2.0 / 3.0 * (qy1 - cy); x2 = x + 2.0 / 3.0 * (qx1 - x); y2 = y + 2.0 / 3.0 * (qy1 - y); g->curveTo(x1, y1, x2, y2, x, y); // restore control point coordinate x1 = qx1; y1 = qy1; } else if (*commandIt == PathElement::ClosePath) { g->closePath(); } prevX = x; prevY = y; prevX1 = x1; prevY1 = y1; prevX2 = x2; prevY2 = y2; prevCommand = *commandIt++; } }<commit_msg>don't explicit close path for moveTo command<commit_after>#include "svgpath.h" #include "svgutils.h" #include "graphicscontext.h" SvgPath::SvgPath(const std::string &str) { setPath(str); } void SvgPath::setPath(const std::string &str) { data.commands.clear(); data.coords.clear(); ok = true; lastError = ""; if (str.empty()) { ok = false; return; } pathString = str; auto it = str.begin(); try { SvgUtils::readSvgPath(it, str.end(), std::back_inserter(data.commands), std::back_inserter(data.coords)); } catch (std::exception &e) { lastError = e.what(); ok = false; } } const std::string &SvgPath::getPath() const { return pathString; } const SvgPath::PathData &SvgPath::getPathData() const { return data; } bool SvgPath::isOk() const { return ok; } std::string SvgPath::getLastError() const { return lastError; } void SvgPath::draw(GraphicsContext *g) const { if (!ok) return; std::vector<PathElement>::const_iterator commandIt = data.commands.begin(); std::vector<double>::const_iterator coordsIt = data.coords.begin(); PathElement prevCommand = PathElement::ClosePath; double x = 0, y = 0; double x1 = 0, y1 = 0; double x2 = 0, y2 = 0; double cx = 0, cy = 0; double prevX = 0, prevY = 0; double prevX1 = 0, prevY1 = 0; double prevX2 = 0, prevY2 = 0; while (commandIt != data.commands.end()) { if (*commandIt == PathElement::MoveTo || *commandIt == PathElement::MoveToRel || *commandIt == PathElement::LineTo || *commandIt == PathElement::LineToRel) { x = *(coordsIt + 0); y = *(coordsIt + 1); std::advance(coordsIt, 2); } else if (*commandIt == PathElement::LineToHorizontal || *commandIt == PathElement::LineToHorizontalRel) { x = *coordsIt; coordsIt++; } else if(*commandIt == PathElement::LineToVertical || *commandIt == PathElement::LineToVerticalRel) { y = *coordsIt; coordsIt++; } else if(*commandIt == PathElement::CurveToCubic || *commandIt == PathElement::CurveToCubicRel) { x1 = *(coordsIt + 0); y1 = *(coordsIt + 1); x2 = *(coordsIt + 2); y2 = *(coordsIt + 3); x = *(coordsIt + 4); y = *(coordsIt + 5); std::advance(coordsIt, 6); } else if(*commandIt == PathElement::CurveToCubicSmooth || *commandIt == PathElement::CurveToCubicSmoothRel) { x2 = *(coordsIt + 0); y2 = *(coordsIt + 1); x = *(coordsIt + 2); y = *(coordsIt + 3); std::advance(coordsIt, 4); } else if(*commandIt == PathElement::CurveToQuadratic || *commandIt == PathElement::CurveToQuadraticRel) { x1 = *(coordsIt + 0); y1 = *(coordsIt + 1); x = *(coordsIt + 2); y = *(coordsIt + 3); std::advance(coordsIt, 4); } else if(*commandIt == PathElement::CurveToQuadraticSmooth || *commandIt == PathElement::CurveToQuadraticSmoothRel) { x = *(coordsIt + 0); y = *(coordsIt + 1); std::advance(coordsIt, 2); } g->getCurrentPoint(cx, cy); if (*commandIt == PathElement::MoveTo || *commandIt == PathElement::MoveToRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } g->moveTo(x, y); } else if (*commandIt == PathElement::LineTo || *commandIt == PathElement::LineToRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } g->lineTo(x, y); } else if (*commandIt == PathElement::LineToHorizontal || *commandIt == PathElement::LineToHorizontalRel) { if (SvgUtils::isCommandRelative(*commandIt)) x += cx; g->lineTo(x, cy); } else if (*commandIt == PathElement::LineToVertical || *commandIt == PathElement::LineToVerticalRel) { if (SvgUtils::isCommandRelative(*commandIt)) y += cy; g->lineTo(cx, y); } else if (*commandIt == PathElement::CurveToCubic || *commandIt == PathElement::CurveToCubicRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x1 += cx; y1 += cy; x2 += cx; y2 += cy; } g->curveTo(x1, y1, x2, y2, x, y); } else if (*commandIt == PathElement::CurveToCubicSmooth || *commandIt == PathElement::CurveToCubicSmoothRel) { if (SvgUtils::isCurveToCubic(prevCommand)) { x1 = 2 * prevX - prevX2; y1 = 2 * prevY - prevY2; } else { x1 = cx; y1 = cy; } if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x2 += cx; y2 += cy; } g->curveTo(x1, y1, x2, y2, x, y); } else if (*commandIt == PathElement::CurveToQuadratic || *commandIt == PathElement::CurveToQuadraticRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; x1 += cx; y1 += cy; } double qx1 = x1; double qy1 = y1; x1 = cx + 2.0 / 3.0 * (qx1 - cx); y1 = cy + 2.0 / 3.0 * (qy1 - cy); x2 = x + 2.0 / 3.0 * (qx1 - x); y2 = y + 2.0 / 3.0 * (qy1 - y); g->curveTo(x1, y1, x2, y2, x, y); // restore control point coordinate x1 = qx1; y1 = qy1; } else if (*commandIt == PathElement::CurveToQuadraticSmooth || *commandIt == PathElement::CurveToQuadraticSmoothRel) { if (SvgUtils::isCommandRelative(*commandIt)) { x += cx; y += cy; } if (SvgUtils::isCurveToQuadratic(prevCommand)) { x1 = 2 * prevX - prevX1; y1 = 2 * prevY - prevY1; } else { x1 = cx; y1 = cy; } double qx1 = x1; double qy1 = y1; x1 = cx + 2.0 / 3.0 * (qx1 - cx); y1 = cy + 2.0 / 3.0 * (qy1 - cy); x2 = x + 2.0 / 3.0 * (qx1 - x); y2 = y + 2.0 / 3.0 * (qy1 - y); g->curveTo(x1, y1, x2, y2, x, y); // restore control point coordinate x1 = qx1; y1 = qy1; } else if (*commandIt == PathElement::ClosePath) { g->closePath(); } prevX = x; prevY = y; prevX1 = x1; prevY1 = y1; prevX2 = x2; prevY2 = y2; prevCommand = *commandIt++; } }<|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <infra/config/config.h> #include <mips/mips_memory.h> #include <mips/mips_rf.h> #include "perf_sim.h" static const uint32 PORT_LATENCY = 1; static const uint32 PORT_FANOUT = 1; static const uint32 PORT_BW = 1; static const uint32 FLUSHED_STAGES_NUM = 4; namespace config { static Value<std::string> bp_mode = { "bp-mode", "dynamic_two_bit", "branch prediction mode"}; static Value<uint32> bp_size = { "bp-size", 128, "BTB size in entries"}; static Value<uint32> bp_ways = { "bp-ways", 16, "number of ways in BTB"}; } // namespace config PerfMIPS::PerfMIPS(bool log) : Log( log), rf( new RF), checker( false) { executed_instrs = 0; wp_fetch_2_decode = make_write_port<IfIdData>("FETCH_2_DECODE", PORT_BW, PORT_FANOUT); rp_fetch_2_decode = make_read_port<IfIdData>("FETCH_2_DECODE", PORT_LATENCY); wp_decode_2_fetch_stall = make_write_port<bool>("DECODE_2_FETCH_STALL", PORT_BW, PORT_FANOUT); rp_decode_2_fetch_stall = make_read_port<bool>("DECODE_2_FETCH_STALL", PORT_LATENCY); wp_decode_2_decode = make_write_port<FuncInstr>("DECODE_2_DECODE", PORT_BW, PORT_FANOUT); rp_decode_2_decode = make_read_port<FuncInstr>("DECODE_2_DECODE", PORT_LATENCY); wp_decode_2_execute = make_write_port<FuncInstr>("DECODE_2_EXECUTE", PORT_BW, PORT_FANOUT); rp_decode_2_execute = make_read_port<FuncInstr>("DECODE_2_EXECUTE", PORT_LATENCY); wp_execute_2_memory = make_write_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_BW, PORT_FANOUT); rp_execute_2_memory = make_read_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_LATENCY); wp_memory_2_writeback = make_write_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_BW, PORT_FANOUT); rp_memory_2_writeback = make_read_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_LATENCY); /* branch misprediction unit ports */ wp_memory_2_all_flush = make_write_port<bool>("MEMORY_2_ALL_FLUSH", PORT_BW, FLUSHED_STAGES_NUM); rp_fetch_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_decode_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_execute_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_memory_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); wp_memory_2_fetch_target = make_write_port<Addr>("MEMORY_2_FETCH_TARGET", PORT_BW, PORT_FANOUT); rp_memory_2_fetch_target = make_read_port<Addr>("MEMORY_2_FETCH_TARGET", PORT_LATENCY); BPFactory bp_factory; bp = bp_factory.create( config::bp_mode, config::bp_size, config::bp_ways); init_ports(); } FuncInstr PerfMIPS::read_instr(uint64 cycle) { if (rp_decode_2_decode->is_ready( cycle)) { rp_fetch_2_decode->ignore( cycle); return rp_decode_2_decode->read( cycle); } const auto& _data = rp_fetch_2_decode->read( cycle); FuncInstr instr( _data.raw, _data.PC, _data.predicted_taken, _data.predicted_target); return instr; } void PerfMIPS::run( const std::string& tr, uint64 instrs_to_run) { assert( instrs_to_run < MAX_VAL32); Cycles cycle = 0; memory = new MIPSMemory( tr); checker.init( tr); new_PC = memory->startPC(); auto t_start = std::chrono::high_resolution_clock::now(); while (executed_instrs < instrs_to_run) { clock_writeback( cycle); clock_fetch( cycle); clock_decode( cycle); clock_execute( cycle); clock_memory( cycle); ++cycle; sout << "Executed instructions: " << executed_instrs << std::endl << std::endl; check_ports( cycle); } auto t_end = std::chrono::high_resolution_clock::now(); auto time = std::chrono::duration<double, std::milli>(t_end - t_start).count(); auto frequency = cycle / time; // cycles per millisecond = kHz auto ipc = 1.0 * executed_instrs / cycle; auto simips = executed_instrs / time; std::cout << std::endl << "****************************" << std::endl << "instrs: " << executed_instrs << std::endl << "cycles: " << cycle << std::endl << "IPC: " << ipc << std::endl << "sim freq: " << frequency << " kHz" << std::endl << "sim IPS: " << simips << " kips" << std::endl << "****************************" << std::endl; } void PerfMIPS::clock_fetch( int cycle) { /* receive flush and stall signals */ const bool is_flush = rp_fetch_flush->is_ready( cycle) && rp_fetch_flush->read( cycle); const bool is_stall = rp_decode_2_fetch_stall->is_ready( cycle) && rp_decode_2_fetch_stall->read( cycle); /* updating PC */ if ( is_flush) PC = rp_memory_2_fetch_target->read( cycle); // fixing PC else if ( !is_stall) PC = new_PC; /* creating structure to be sent to decode stage */ IfIdData data; /* fetching instruction */ data.raw = memory->fetch( PC); /* saving predictions and updating PC according to them */ data.PC = PC; data.predicted_taken = bp->is_taken( PC); data.predicted_target = bp->get_target( PC); /* updating PC according to prediction */ new_PC = data.predicted_target; /* sending to decode */ wp_fetch_2_decode->write( data, cycle); /* log */ sout << "fetch cycle " << std::dec << cycle << ": 0x" << std::hex << PC << ": 0x" << data.raw << std::endl; } void PerfMIPS::clock_decode( int cycle) { sout << "decode cycle " << std::dec << cycle << ": "; /* receive flush signal */ const bool is_flush = rp_decode_flush->is_ready( cycle) && rp_decode_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* ignoring the upcoming instruction as it is invalid */ rp_fetch_2_decode->ignore( cycle); rp_decode_2_decode->ignore( cycle); sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_fetch_2_decode->is_ready( cycle) && !rp_decode_2_decode->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = read_instr( cycle); /* TODO: replace all this code by introducing Forwarding unit */ if( rf->check_sources( instr)) { rf->read_sources( &instr); wp_decode_2_execute->write( instr, cycle); /* log */ sout << instr << std::endl; } else // data hazard, stalling pipeline { wp_decode_2_fetch_stall->write( true, cycle); wp_decode_2_decode->write( instr, cycle); sout << instr << " (data hazard)\n"; } } void PerfMIPS::clock_execute( int cycle) { sout << "execute cycle " << std::dec << cycle << ": "; /* receive flush signal */ const bool is_flush = rp_execute_flush->is_ready( cycle) && rp_execute_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* ignoring the upcoming instruction as it is invalid */ if ( rp_decode_2_execute->is_ready( cycle)) { const auto& instr = rp_decode_2_execute->read( cycle); rf->cancel( instr); } sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_decode_2_execute->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = rp_decode_2_execute->read( cycle); /* preform execution */ instr.execute(); wp_execute_2_memory->write( instr, cycle); /* log */ sout << instr << std::endl; } void PerfMIPS::clock_memory( int cycle) { sout << "memory cycle " << std::dec << cycle << ": "; /* receieve flush signal */ const bool is_flush = rp_memory_flush->is_ready( cycle) && rp_memory_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* drop instruction as it is invalid */ if ( rp_execute_2_memory->is_ready( cycle)) { const auto& instr = rp_execute_2_memory->read( cycle); rf->cancel( instr); } sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_execute_2_memory->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = rp_execute_2_memory->read( cycle); if (instr.is_jump()) { /* acquiring real information for BPU */ bool actually_taken = instr.is_jump_taken(); Addr real_target = instr.get_new_PC(); bp->update( actually_taken, instr.get_PC(), real_target); /* handle misprediction */ if ( instr.is_misprediction()) { /* flushing the pipeline */ wp_memory_2_all_flush->write( true, cycle); /* sending valid PC to fetch stage */ wp_memory_2_fetch_target->write( real_target, cycle); sout << "misprediction on "; } } /* perform required loads and stores */ memory->load_store( &instr); wp_memory_2_writeback->write( instr, cycle); /* log */ sout << instr << std::endl; } void PerfMIPS::clock_writeback( int cycle) { sout << "wb cycle " << std::dec << cycle << ": "; /* check if there is something to process */ if ( !rp_memory_2_writeback->is_ready( cycle)) { sout << "bubble\n"; if ( cycle - last_writeback_cycle >= 10) { serr << "Deadlock was detected. The process will be aborted." << std::endl << std::endl << critical; } return; } FuncInstr instr = rp_memory_2_writeback->read( cycle); /* perform writeback */ rf->write_dst( instr); /* check for traps */ instr.check_trap(); /* log */ sout << instr << std::endl; /* perform checks */ check( instr); /* update simulator cycles info */ ++executed_instrs; last_writeback_cycle = cycle; } void PerfMIPS::check( const FuncInstr& instr) { const auto func_dump = checker.step(); if ( func_dump.Dump() != instr.Dump()) serr << "****************************" << std::endl << "Mismatch: " << std::endl << "Checker output: " << func_dump << std::endl << "PerfSim output: " << instr.Dump() << std::endl << critical; } <commit_msg>Dump sizeof(FuncInstr) in PerfSim<commit_after>#include <iostream> #include <chrono> #include <infra/config/config.h> #include <mips/mips_memory.h> #include <mips/mips_rf.h> #include "perf_sim.h" static const uint32 PORT_LATENCY = 1; static const uint32 PORT_FANOUT = 1; static const uint32 PORT_BW = 1; static const uint32 FLUSHED_STAGES_NUM = 4; namespace config { static Value<std::string> bp_mode = { "bp-mode", "dynamic_two_bit", "branch prediction mode"}; static Value<uint32> bp_size = { "bp-size", 128, "BTB size in entries"}; static Value<uint32> bp_ways = { "bp-ways", 16, "number of ways in BTB"}; } // namespace config PerfMIPS::PerfMIPS(bool log) : Log( log), rf( new RF), checker( false) { executed_instrs = 0; wp_fetch_2_decode = make_write_port<IfIdData>("FETCH_2_DECODE", PORT_BW, PORT_FANOUT); rp_fetch_2_decode = make_read_port<IfIdData>("FETCH_2_DECODE", PORT_LATENCY); wp_decode_2_fetch_stall = make_write_port<bool>("DECODE_2_FETCH_STALL", PORT_BW, PORT_FANOUT); rp_decode_2_fetch_stall = make_read_port<bool>("DECODE_2_FETCH_STALL", PORT_LATENCY); wp_decode_2_decode = make_write_port<FuncInstr>("DECODE_2_DECODE", PORT_BW, PORT_FANOUT); rp_decode_2_decode = make_read_port<FuncInstr>("DECODE_2_DECODE", PORT_LATENCY); wp_decode_2_execute = make_write_port<FuncInstr>("DECODE_2_EXECUTE", PORT_BW, PORT_FANOUT); rp_decode_2_execute = make_read_port<FuncInstr>("DECODE_2_EXECUTE", PORT_LATENCY); wp_execute_2_memory = make_write_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_BW, PORT_FANOUT); rp_execute_2_memory = make_read_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_LATENCY); wp_memory_2_writeback = make_write_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_BW, PORT_FANOUT); rp_memory_2_writeback = make_read_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_LATENCY); /* branch misprediction unit ports */ wp_memory_2_all_flush = make_write_port<bool>("MEMORY_2_ALL_FLUSH", PORT_BW, FLUSHED_STAGES_NUM); rp_fetch_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_decode_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_execute_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); rp_memory_flush = make_read_port<bool>("MEMORY_2_ALL_FLUSH", PORT_LATENCY); wp_memory_2_fetch_target = make_write_port<Addr>("MEMORY_2_FETCH_TARGET", PORT_BW, PORT_FANOUT); rp_memory_2_fetch_target = make_read_port<Addr>("MEMORY_2_FETCH_TARGET", PORT_LATENCY); BPFactory bp_factory; bp = bp_factory.create( config::bp_mode, config::bp_size, config::bp_ways); init_ports(); } FuncInstr PerfMIPS::read_instr(uint64 cycle) { if (rp_decode_2_decode->is_ready( cycle)) { rp_fetch_2_decode->ignore( cycle); return rp_decode_2_decode->read( cycle); } const auto& _data = rp_fetch_2_decode->read( cycle); FuncInstr instr( _data.raw, _data.PC, _data.predicted_taken, _data.predicted_target); return instr; } void PerfMIPS::run( const std::string& tr, uint64 instrs_to_run) { assert( instrs_to_run < MAX_VAL32); Cycles cycle = 0; memory = new MIPSMemory( tr); checker.init( tr); new_PC = memory->startPC(); auto t_start = std::chrono::high_resolution_clock::now(); while (executed_instrs < instrs_to_run) { clock_writeback( cycle); clock_fetch( cycle); clock_decode( cycle); clock_execute( cycle); clock_memory( cycle); ++cycle; sout << "Executed instructions: " << executed_instrs << std::endl << std::endl; check_ports( cycle); } auto t_end = std::chrono::high_resolution_clock::now(); auto time = std::chrono::duration<double, std::milli>(t_end - t_start).count(); auto frequency = cycle / time; // cycles per millisecond = kHz auto ipc = 1.0 * executed_instrs / cycle; auto simips = executed_instrs / time; std::cout << std::endl << "****************************" << std::endl << "instrs: " << executed_instrs << std::endl << "cycles: " << cycle << std::endl << "IPC: " << ipc << std::endl << "sim freq: " << frequency << " kHz" << std::endl << "sim IPS: " << simips << " kips" << std::endl << "instr size: " << sizeof(FuncInstr) << " bytes" << std::endl << "****************************" << std::endl; } void PerfMIPS::clock_fetch( int cycle) { /* receive flush and stall signals */ const bool is_flush = rp_fetch_flush->is_ready( cycle) && rp_fetch_flush->read( cycle); const bool is_stall = rp_decode_2_fetch_stall->is_ready( cycle) && rp_decode_2_fetch_stall->read( cycle); /* updating PC */ if ( is_flush) PC = rp_memory_2_fetch_target->read( cycle); // fixing PC else if ( !is_stall) PC = new_PC; /* creating structure to be sent to decode stage */ IfIdData data; /* fetching instruction */ data.raw = memory->fetch( PC); /* saving predictions and updating PC according to them */ data.PC = PC; data.predicted_taken = bp->is_taken( PC); data.predicted_target = bp->get_target( PC); /* updating PC according to prediction */ new_PC = data.predicted_target; /* sending to decode */ wp_fetch_2_decode->write( data, cycle); /* log */ sout << "fetch cycle " << std::dec << cycle << ": 0x" << std::hex << PC << ": 0x" << data.raw << std::endl; } void PerfMIPS::clock_decode( int cycle) { sout << "decode cycle " << std::dec << cycle << ": "; /* receive flush signal */ const bool is_flush = rp_decode_flush->is_ready( cycle) && rp_decode_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* ignoring the upcoming instruction as it is invalid */ rp_fetch_2_decode->ignore( cycle); rp_decode_2_decode->ignore( cycle); sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_fetch_2_decode->is_ready( cycle) && !rp_decode_2_decode->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = read_instr( cycle); /* TODO: replace all this code by introducing Forwarding unit */ if( rf->check_sources( instr)) { rf->read_sources( &instr); wp_decode_2_execute->write( instr, cycle); /* log */ sout << instr << std::endl; } else // data hazard, stalling pipeline { wp_decode_2_fetch_stall->write( true, cycle); wp_decode_2_decode->write( instr, cycle); sout << instr << " (data hazard)\n"; } } void PerfMIPS::clock_execute( int cycle) { sout << "execute cycle " << std::dec << cycle << ": "; /* receive flush signal */ const bool is_flush = rp_execute_flush->is_ready( cycle) && rp_execute_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* ignoring the upcoming instruction as it is invalid */ if ( rp_decode_2_execute->is_ready( cycle)) { const auto& instr = rp_decode_2_execute->read( cycle); rf->cancel( instr); } sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_decode_2_execute->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = rp_decode_2_execute->read( cycle); /* preform execution */ instr.execute(); wp_execute_2_memory->write( instr, cycle); /* log */ sout << instr << std::endl; } void PerfMIPS::clock_memory( int cycle) { sout << "memory cycle " << std::dec << cycle << ": "; /* receieve flush signal */ const bool is_flush = rp_memory_flush->is_ready( cycle) && rp_memory_flush->read( cycle); /* branch misprediction */ if ( is_flush) { /* drop instruction as it is invalid */ if ( rp_execute_2_memory->is_ready( cycle)) { const auto& instr = rp_execute_2_memory->read( cycle); rf->cancel( instr); } sout << "flush\n"; return; } /* check if there is something to process */ if ( !rp_execute_2_memory->is_ready( cycle)) { sout << "bubble\n"; return; } auto instr = rp_execute_2_memory->read( cycle); if (instr.is_jump()) { /* acquiring real information for BPU */ bool actually_taken = instr.is_jump_taken(); Addr real_target = instr.get_new_PC(); bp->update( actually_taken, instr.get_PC(), real_target); /* handle misprediction */ if ( instr.is_misprediction()) { /* flushing the pipeline */ wp_memory_2_all_flush->write( true, cycle); /* sending valid PC to fetch stage */ wp_memory_2_fetch_target->write( real_target, cycle); sout << "misprediction on "; } } /* perform required loads and stores */ memory->load_store( &instr); wp_memory_2_writeback->write( instr, cycle); /* log */ sout << instr << std::endl; } void PerfMIPS::clock_writeback( int cycle) { sout << "wb cycle " << std::dec << cycle << ": "; /* check if there is something to process */ if ( !rp_memory_2_writeback->is_ready( cycle)) { sout << "bubble\n"; if ( cycle - last_writeback_cycle >= 10) { serr << "Deadlock was detected. The process will be aborted." << std::endl << std::endl << critical; } return; } FuncInstr instr = rp_memory_2_writeback->read( cycle); /* perform writeback */ rf->write_dst( instr); /* check for traps */ instr.check_trap(); /* log */ sout << instr << std::endl; /* perform checks */ check( instr); /* update simulator cycles info */ ++executed_instrs; last_writeback_cycle = cycle; } void PerfMIPS::check( const FuncInstr& instr) { const auto func_dump = checker.step(); if ( func_dump.Dump() != instr.Dump()) serr << "****************************" << std::endl << "Mismatch: " << std::endl << "Checker output: " << func_dump << std::endl << "PerfSim output: " << instr.Dump() << std::endl << critical; } <|endoftext|>
<commit_before>#include "builtin/data.hpp" #include "builtin/class.hpp" #include "objectmemory.hpp" #include "object_utils.hpp" #include "gc/gc.hpp" #include "capi/capi.hpp" #include "ontology.hpp" namespace rubinius { void Data::init(STATE) { GO(data).set(ontology::new_class(state, "Data", G(object))); G(data)->set_object_type(state, DataType); } Data* Data::create(STATE, void* data_ptr, Data::MarkFunctor mark, Data::FreeFunctor free) { Data* data; data = state->new_object<Data>(G(data)); // Data is just a heap alias for the handle, so go ahead and create // the handle and populate it as an RData now. capi::Handle* handle = data->handle(state); assert(!handle && "can't already have a handle, it's brand new!"); handle = state->shared().add_global_handle(state, data); // Don't call ->ref() on handle! We don't want the handle to keep the object // alive by default. The handle needs to have the lifetime of the object. RDataShadow* rdata = reinterpret_cast<RDataShadow*>(handle->as_rdata(0)); rdata->data = data_ptr; rdata->dmark = mark; rdata->dfree = free; data->internal_ = rdata; data->freed_ = false; // If this Data requires a free function, register this object // as needing finalization. if(free) { state->memory()->needs_finalization(data, (FinalizerFunction)&Data::finalize); } return data; } RDataShadow* Data::slow_rdata(STATE) { capi::Handle* handle = this->handle(state); assert(handle && handle->is_rdata() && "invalid initialized Data object"); return reinterpret_cast<RDataShadow*>(handle->as_rdata(0)); } void* Data::data(STATE) { return rdata(state)->data; } Data::FreeFunctor Data::free(STATE) { return rdata(state)->dfree; } Data::MarkFunctor Data::mark(STATE) { return rdata(state)->dmark; } void Data::finalize(STATE, Data* data) { // MRI only calls free if the data_ptr is not NULL. void* data_ptr = data->data(state); if(data_ptr && !data->freed_p()) { Data::FreeFunctor f = data->free(state); if(f) { // If the user specifies -1, then we call free. We check here rather // than when Data_Make_Struct is called because the user is allowed to // change dfree. if(reinterpret_cast<intptr_t>(f) == -1) { ::free(data_ptr); } else { f(data_ptr); } } data->set_freed(); } } void Data::Info::mark(Object* t, ObjectMark& mark) { auto_mark(t, mark); Data* data = force_as<Data>(t); if(data->freed_p()) return; RDataShadow* rdata = data->rdata(); if(rdata->dmark) { ObjectMark* cur = capi::current_mark(); capi::set_current_mark(&mark); (*rdata->dmark)(rdata->data); capi::set_current_mark(cur); } } } <commit_msg>Always enable finalizers for Data objects<commit_after>#include "builtin/data.hpp" #include "builtin/class.hpp" #include "objectmemory.hpp" #include "object_utils.hpp" #include "gc/gc.hpp" #include "capi/capi.hpp" #include "ontology.hpp" namespace rubinius { void Data::init(STATE) { GO(data).set(ontology::new_class(state, "Data", G(object))); G(data)->set_object_type(state, DataType); } Data* Data::create(STATE, void* data_ptr, Data::MarkFunctor mark, Data::FreeFunctor free) { Data* data; data = state->new_object<Data>(G(data)); // Data is just a heap alias for the handle, so go ahead and create // the handle and populate it as an RData now. capi::Handle* handle = data->handle(state); assert(!handle && "can't already have a handle, it's brand new!"); handle = state->shared().add_global_handle(state, data); // Don't call ->ref() on handle! We don't want the handle to keep the object // alive by default. The handle needs to have the lifetime of the object. RDataShadow* rdata = reinterpret_cast<RDataShadow*>(handle->as_rdata(0)); rdata->data = data_ptr; rdata->dmark = mark; rdata->dfree = free; data->internal_ = rdata; data->freed_ = false; if(mark || free) { state->memory()->needs_finalization(data, (FinalizerFunction)&Data::finalize); } return data; } RDataShadow* Data::slow_rdata(STATE) { capi::Handle* handle = this->handle(state); assert(handle && handle->is_rdata() && "invalid initialized Data object"); return reinterpret_cast<RDataShadow*>(handle->as_rdata(0)); } void* Data::data(STATE) { return rdata(state)->data; } Data::FreeFunctor Data::free(STATE) { return rdata(state)->dfree; } Data::MarkFunctor Data::mark(STATE) { return rdata(state)->dmark; } void Data::finalize(STATE, Data* data) { // MRI only calls free if the data_ptr is not NULL. void* data_ptr = data->data(state); if(data_ptr && !data->freed_p()) { Data::FreeFunctor f = data->free(state); if(f) { // If the user specifies -1, then we call free. We check here rather // than when Data_Make_Struct is called because the user is allowed to // change dfree. if(reinterpret_cast<intptr_t>(f) == -1) { ::free(data_ptr); } else { f(data_ptr); } } data->set_freed(); } } void Data::Info::mark(Object* t, ObjectMark& mark) { auto_mark(t, mark); Data* data = force_as<Data>(t); if(data->freed_p()) return; RDataShadow* rdata = data->rdata(); if(rdata->dmark) { ObjectMark* cur = capi::current_mark(); capi::set_current_mark(&mark); (*rdata->dmark)(rdata->data); capi::set_current_mark(cur); } } } <|endoftext|>
<commit_before>#include "PlatformEntity.h" PlatformEntity::PlatformEntity(){} PlatformEntity::~PlatformEntity() { this->Shutdown(); } int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp) { int result = 0; this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp); return result; } int PlatformEntity::Shutdown() { int result = 0; if (this->m_ActiveSound != nullptr) this->m_ActiveSound->drop(); return result; } int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler) { int result = 0; this->SyncComponents(); // Adjust misplaced graphics component - hack... this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector( DirectX::XMVectorSubtract(this->m_pComp->PC_pos, DirectX::XMVECTOR{ m_gComp->modelPtr->GetOBBData().position.x, m_gComp->modelPtr->GetOBBData().position.y, m_gComp->modelPtr->GetOBBData().position.z, 0}))); if (this->GetAIComponent()->AC_triggered) { if (this->m_ActiveSound == nullptr) { DirectX::XMFLOAT3 pos; DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos); this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true); } else { if (this->m_ActiveSound->getIsPaused()) { this->m_ActiveSound->setIsPaused(false); } } } else { if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused()) { this->m_ActiveSound->setPlayPosition(0); this->m_ActiveSound->setIsPaused(true); //Pause the walking sound } } return result; } int PlatformEntity::React(int entityID, EVENT reactEvent) { switch (reactEvent) { //case FIELD_CONTAINS: // break; //case FIELD_ENTERED: // break; //case FIELD_EXITED: // break; //case FIELD_CONDITIONS_MET: // break; //case FIELD_ENABLED: // break; //case FIELD_DISABLED: // break; case BUTTON_DEACTIVE: this->GetAIComponent()->AC_triggered = false; break; case BUTTON_ACTIVE: this->GetAIComponent()->AC_triggered = true; break; case LEVER_DEACTIVE: this->GetAIComponent()->AC_triggered = false; break; case LEVER_ACTIVE: this->GetAIComponent()->AC_triggered = true; break; //case LEVER_ENABLED: // break; //case LEVER_DISABLED: // break; default: break; } return 1; }<commit_msg>ADD basic wheel reaction<commit_after>#include "PlatformEntity.h" PlatformEntity::PlatformEntity() {} PlatformEntity::~PlatformEntity() { this->Shutdown(); } int PlatformEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, AIComponent * aiComp) { int result = 0; this->InitializeBase(entityID, pComp, gComp, nullptr, aiComp); return result; } int PlatformEntity::Shutdown() { int result = 0; if (this->m_ActiveSound != nullptr) this->m_ActiveSound->drop(); return result; } int PlatformEntity::Update(float deltaTime, InputHandler * inputHandler) { int result = 0; this->SyncComponents(); // Adjust misplaced graphics component - hack... this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector( DirectX::XMVectorSubtract(this->m_pComp->PC_pos, DirectX::XMVECTOR{ m_gComp->modelPtr->GetOBBData().position.x, m_gComp->modelPtr->GetOBBData().position.y, m_gComp->modelPtr->GetOBBData().position.z, 0}))); if (this->GetAIComponent()->AC_triggered) { if (this->m_ActiveSound == nullptr) { DirectX::XMFLOAT3 pos; DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos); this->m_ActiveSound = SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LIFT, pos, true, true); } else { if (this->m_ActiveSound->getIsPaused()) { this->m_ActiveSound->setIsPaused(false); } } } else { if (this->m_ActiveSound != nullptr && !this->m_ActiveSound->getIsPaused()) { this->m_ActiveSound->setPlayPosition(0); this->m_ActiveSound->setIsPaused(true); //Pause the walking sound } } return result; } int PlatformEntity::React(int entityID, EVENT reactEvent) { switch (reactEvent) { //case FIELD_CONTAINS: // break; //case FIELD_ENTERED: // break; //case FIELD_EXITED: // break; //case FIELD_CONDITIONS_MET: // break; //case FIELD_ENABLED: // break; //case FIELD_DISABLED: // break; case BUTTON_DEACTIVE: this->GetAIComponent()->AC_triggered = false; break; case BUTTON_ACTIVE: this->GetAIComponent()->AC_triggered = true; break; case LEVER_DEACTIVE: this->GetAIComponent()->AC_triggered = false; break; case LEVER_ACTIVE: this->GetAIComponent()->AC_triggered = true; break; case WHEEL_INCREASING: this->GetAIComponent()->AC_triggered = true; break; case WHEEL_RESET: this->GetAIComponent()->AC_triggered = false; break; default: break; } return 1; }<|endoftext|>
<commit_before>// // // The Laxkit, a windowing toolkit // Please consult http://laxkit.sourceforge.net about where to send any // correspondence about this software. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright (C) 2012 by Tom Lechner // #include <lax/undo.h> #include <sys/times.h> #include <iostream> using namespace std; #define DBG namespace Laxkit { #define REDOABLE 2 #define UNDOABLE 1 //--------------------------------------------- Undoable ------------------------------------------ /*! \class Undoable * \brief Subclass from this if you want an object that can act as an agent of undoing. */ //--------------------------------------------- UndoData ------------------------------------------ /*! \class UndoData * \brief Undo node for UndoManager. * * Objects classed from this will be passed to Undoable objects to either undo or redo. * If direction is 1, then the item is undoable, else 2 is redoable. * * Subclasses must provide enough information to either redo OR undo, otherwise modify * the data to reflect what must be done after Undoable::Undo() or Redo() is called. */ static unsigned long getUniqueUndoId() { static unsigned long uniquenumber=1; return uniquenumber++; } UndoData::UndoData(int nisauto) { isauto=nisauto; //whether this undo element must exist connected to the previous undo element if (nisauto) undogroup=getUniqueUndoId(); else undogroup=0; description=NULL; data=NULL; time=0; context=NULL; direction=UNDOABLE; prev=next=NULL; } /*! If prev==NULL, then delete next, else just remove *this from chain. */ UndoData::~UndoData() { if (prev) { //is just a link in chain, remove from chain if (next) next->prev=prev; prev->next=next; prev=next=NULL; } else { //is head of chain, remove whole chain if (next) { next->prev=NULL; delete next; next=NULL; } } delete[] description; } int UndoData::isUndoable() { return direction==UNDOABLE; } int UndoData::isRedoable() { return direction==REDOABLE; } //--------------------------------------------- UndoManager ------------------------------------------ /*! \class UndoManager * \brief Simple class to keep track of undoes. */ UndoManager::UndoManager() { head=current=NULL; } UndoManager::~UndoManager() { if (head) delete head; } /*! Takes possession of data, and will delete it when done. */ int UndoManager::AddUndo(UndoData *data) { //current points to an UndoData that is ready to be undone. It must have isauto==0. //If there are no UndoData nodes, then //current is NULL. In this case, if head is not NULL, then it is a list of redoables. data->time=times(NULL); //if any after current, remove them if (current) { while (current->next && current->next->isRedoable()) { delete current->next; } } else if (head) { delete head; head=NULL; } if (current) { current->next=data; data->prev=current; current=current->next; } else { if (head) { //head would be pointing to a redoable, but there are no undoables data->next=head; head->prev=data; head=data; } else head=current=data; } return 0; } //! Default is to call current->context->Undo(), and move current. int UndoManager::Undo() { if (!current) return 1; if (!current->context) { cerr <<" *** missing undo context!"<<endl; return 2; } if (current->context->Undo(current)==0) { current->direction=REDOABLE; current=current->prev; return 0; } return 3; //undo failed } //! Default is to call current->context->Redo(), and move current. int UndoManager::Redo() { if (!head) return 1; if (current && !current->next) return 2; if (current) current=current->next; else current=head; if (!current->context) { cerr <<" *** missing undo context!"<<endl; return 3; } if (current->context->Redo(current)==0) { current->direction=UNDOABLE; return 0; } return 4; //redo failed } //--------------------------------------------- UndoManager manager ------------------------------------------ static UndoManager *default_undo_manager=NULL; UndoManager *GetUndoManager() { if (!default_undo_manager) default_undo_manager=new UndoManager; return default_undo_manager; } /*! Any old manager will be deleted, and the newmanager pointer taken. */ UndoManager *SetUndoManager(UndoManager *newmanager) { if (default_undo_manager) delete default_undo_manager; default_undo_manager=newmanager; return default_undo_manager; } } //namespace Laxkit <commit_msg>laying groundwork for undo<commit_after>// // // The Laxkit, a windowing toolkit // Please consult http://laxkit.sourceforge.net about where to send any // correspondence about this software. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright (C) 2012 by Tom Lechner // #include <lax/undo.h> #include <sys/times.h> #include <iostream> using namespace std; #define DBG namespace Laxkit { #define REDOABLE 2 #define UNDOABLE 1 //--------------------------------------------- Undoable ------------------------------------------ /*! \class Undoable * \brief Subclass from this if you want an object that can act as an agent of undoing. */ //--------------------------------------------- UndoData ------------------------------------------ /*! \class UndoData * \brief Undo node for UndoManager. * * Objects classed from this will be passed to Undoable objects to either undo or redo. * If direction is 1, then the item is undoable, else 2 is redoable. * * Subclasses must provide enough information to either redo OR undo, otherwise modify * the data to reflect what must be done after Undoable::Undo() or Redo() is called. */ static unsigned long getUniqueUndoId() { static unsigned long uniquenumber=1; return uniquenumber++; } UndoData::UndoData(int nisauto) { isauto=nisauto; //whether this undo element must exist connected to the previous undo element if (nisauto) undogroup=getUniqueUndoId(); else undogroup=0; description=NULL; data=NULL; time=0; context=NULL; direction=UNDOABLE; prev=next=NULL; } /*! If prev==NULL, then delete next, else just remove *this from chain. * * If context is an anObject, then dec_count it. */ UndoData::~UndoData() { if (prev) { //is just a link in chain, remove from chain if (next) next->prev=prev; prev->next=next; prev=next=NULL; } else { //is head of chain, remove whole chain if (next) { next->prev=NULL; delete next; next=NULL; } } if (dynamic_cast<anObject*>(context)) dynamic_cast<anObject*>(context)->dec_count(); delete[] description; } int UndoData::isUndoable() { return direction==UNDOABLE; } int UndoData::isRedoable() { return direction==REDOABLE; } //--------------------------------------------- UndoManager ------------------------------------------ /*! \class UndoManager * \brief Simple class to keep track of undoes. */ UndoManager::UndoManager() { head=current=NULL; } UndoManager::~UndoManager() { if (head) delete head; } /*! Takes possession of data, and will delete it when done. */ int UndoManager::AddUndo(UndoData *data) { //current points to an UndoData that is ready to be undone. It must have isauto==0. //If there are no UndoData nodes, then //current is NULL. In this case, if head is not NULL, then it is a list of redoables. data->time=times(NULL); //if any after current, remove them if (current) { while (current->next && current->next->isRedoable()) { delete current->next; } } else if (head) { delete head; head=NULL; } if (current) { current->next=data; data->prev=current; current=current->next; } else { if (head) { //head would be pointing to a redoable, but there are no undoables data->next=head; head->prev=data; head=data; } else head=current=data; } return 0; } //! Default is to call current->context->Undo(), and move current. int UndoManager::Undo() { if (!current) return 1; if (!current->context) { cerr <<" *** missing undo context!"<<endl; return 2; } if (current->context->Undo(current)==0) { current->direction=REDOABLE; current=current->prev; return 0; } return 3; //undo failed } //! Default is to call current->context->Redo(), and move current. int UndoManager::Redo() { if (!head) return 1; if (current && !current->next) return 2; if (current) current=current->next; else current=head; if (!current->context) { cerr <<" *** missing undo context!"<<endl; return 3; } if (current->context->Redo(current)==0) { current->direction=UNDOABLE; return 0; } return 4; //redo failed } //--------------------------------------------- UndoManager manager ------------------------------------------ static UndoManager *default_undo_manager=NULL; UndoManager *GetUndoManager() { if (!default_undo_manager) default_undo_manager=new UndoManager; return default_undo_manager; } /*! Any old manager will be deleted, and the newmanager pointer taken. */ UndoManager *SetUndoManager(UndoManager *newmanager) { if (default_undo_manager) delete default_undo_manager; default_undo_manager=newmanager; return default_undo_manager; } } //namespace Laxkit <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <assert.h> #include <string> #include "common.h" #include "bzfgl.h" #include "TextureManager.h" #include "TextureFont.h" #include "bzfio.h" #include "OpenGLGState.h" TextureFont::TextureFont() { for (int i = 0; i < 128; i++) { listIDs[i] = _GL_INVALID_ID; fontMetrics[i].charWidth = -1; } size = -1; textureID = -1; textureXSize = -1; textureYSize = -1; textureZStep = -1; numberOfCharacters = -1; } TextureFont::~TextureFont() { for (int i = 0; i < 128; i++) { if (listIDs[i] != _GL_INVALID_ID) glDeleteLists(listIDs[i], 1); } } int TextureFont::getSize() { return size; } const char* TextureFont::getFaceName() { return faceName.c_str(); } /* read values in Key: Value form from font metrics (.fmt) files */ bool TextureFont::fmtRead(OSFile &file, std::string expectedLeft, std::string &retval) { static std::string workingFile; static int line = 0; // reset line number if we've switched files if (workingFile != file.getFileName()) { workingFile = file.getFileName(); line = 0; } std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); // keep a line counter line++; } if (tmpBuf.substr(0, tmpBuf.find(":")) == expectedLeft) { retval = tmpBuf.substr(tmpBuf.find(":") + 1, tmpBuf.size()); return true; } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName(), line, expectedLeft.c_str()); return false; } } bool TextureFont::load(OSFile &file) { const char *extension = file.getExtension(); if (!extension) return false; if (!file.open("rb")) return false; std::string tmpBuf; if (!fmtRead(file, "NumChars", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &numberOfCharacters); if (!fmtRead(file, "TextureWidth", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureXSize); if (!fmtRead(file, "TextureHeight", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureYSize); if (!fmtRead(file, "TextZStep", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureZStep); int i; for (i = 0; i < numberOfCharacters; i++) { // check character if (!fmtRead(file, "Char", tmpBuf)) return false; if ((tmpBuf.size() < 3) || (tmpBuf[1] != '\"' || tmpBuf[2] != (i + 32) || tmpBuf[3] != '\"')) { DEBUG2("Unexpected character: %s, in font metrics file %s (expected \"%c\").\n", tmpBuf.c_str(), file.getFileName(), (char)(i + 32)); return false; } // read metrics if (!fmtRead(file, "InitialDist", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].initialDist); if (!fmtRead(file, "Width", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].charWidth); if (!fmtRead(file, "Whitespace", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].whiteSpaceDist); if (!fmtRead(file, "StartX", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].startX); if (!fmtRead(file, "EndX", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].endX); if (!fmtRead(file, "StartY", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].startY); if (!fmtRead(file, "EndY", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].endY); } file.close(); // now compute the names std::string fullName = file.getStdName(); char *temp; // get just the file part temp = strrchr(fullName.c_str(), '/'); if (temp) faceName = temp + 1; else faceName = fullName; // now get the texture name texture = faceName; // now wack off the extension; if (extension) faceName.erase(faceName.size() - sizeof(extension), faceName.size()); temp = strrchr(faceName.c_str(), '_'); if (temp) { size = atoi(temp+1); faceName.resize(temp - faceName.c_str()); } // faceName.erase(faceName.size()-sizeof(temp),faceName.size()); if (extension) texture.erase(texture.size() - sizeof(extension), texture.size()); return (numberOfCharacters > 0); } void TextureFont::build(void) { preLoadLists(); } void TextureFont::preLoadLists(void) { if (texture.size() < 1) { DEBUG2("Font %s does not have an associated texture name, not loading\n", texture.c_str()); return; } // load up the texture TextureManager &tm = TextureManager::instance(); std::string textureAndDir = "fonts/" + texture; textureID = tm.getTextureID(textureAndDir.c_str()); DEBUG4("Font %s (face %s) has texture ID %d\n", texture.c_str(), faceName.c_str(), textureID); if (textureID == -1) { DEBUG2("Font texture %s has invalid ID\n", texture.c_str()); return; } glPushMatrix(); for (int i = 0; i < numberOfCharacters; i++) { if (listIDs[i] != _GL_INVALID_ID) glDeleteLists(listIDs[i], 1); listIDs[i] = glGenLists(1); glLoadIdentity(); glNewList(listIDs[i], GL_COMPILE); glTranslatef((float)fontMetrics[i].initialDist, 0, 0); float fFontY = (float)fontMetrics[i].endY - fontMetrics[i].startY; float fFontX = (float)fontMetrics[i].endX - fontMetrics[i].startX; glBegin(GL_QUADS); glNormal3f(0, 0, 1); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(0, fFontY, 0); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(0, 0, 0); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(fFontX, 0, 0); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(fFontX, fFontY, 0); glEnd(); glTranslatef(fFontX, 0, 0); glEndList(); } glPopMatrix(); // create GState OpenGLGStateBuilder builder(gstate); builder.setTexture(textureID); builder.setBlending(); builder.setAlphaFunc(); builder.enableTextureReplace(false); gstate = builder.getState(); } float TextureFont::getStrLength(float scale, const char *str) { int len = (int)strlen(str); int charToUse = 0; int lastCharacter = 0; float totalLen = 0; float thisPassLen = 0; for (int i = 0; i < len; i++) { if (str[i] == '\n') { // newline, get back to the intial X and push down thisPassLen = 0; } else { lastCharacter = charToUse; if ((str[i] < 32) || (str[i] < 9)) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { if (i == 0) thisPassLen += fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth+fontMetrics[charToUse].whiteSpaceDist; else thisPassLen += fontMetrics[lastCharacter].whiteSpaceDist + fontMetrics[charToUse].whiteSpaceDist+fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth; } else { float fFontX = (float)fontMetrics[charToUse].endX - fontMetrics[charToUse].startX; thisPassLen += fFontX + (float)fontMetrics[charToUse].initialDist; } } if (thisPassLen > totalLen) totalLen = thisPassLen; } return totalLen * scale; } void TextureFont::free(void) { textureID = -1; } void TextureFont::drawString(float scale, GLfloat color[3], const char *str) { if (!str) return; if (textureID == -1) preLoadLists(); if (textureID == -1) return; gstate.setState(); TextureManager &tm = TextureManager::instance(); if (!tm.bind(textureID)) return; if (color[0] >= 0) glColor3fv(color); glPushMatrix(); glScalef(scale, scale, 1); glPushMatrix(); int len = (int)strlen(str); int charToUse = 0; int lastCharacter = 0; for (int i = 0; i < len; i++) { if (str[i] == '\n') { // newline, get back to the intial X and push down glPopMatrix(); glTranslatef(0, -(float)textureZStep, 0); glPushMatrix(); } else { lastCharacter = charToUse; if ((str[i] < 32) || (str[i] < 9)) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { if (i == 0) glTranslatef((float)fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth + (float)fontMetrics[charToUse].whiteSpaceDist, 0, 0); else glTranslatef((float)fontMetrics[lastCharacter].whiteSpaceDist + (float)fontMetrics[charToUse].whiteSpaceDist + fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth, 0, 0); } else { glCallList(listIDs[charToUse]); } } } glPopMatrix(); if (color[0] >= 0) glColor4f(1, 1, 1, 1); glPopMatrix(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>sizeof a char pointer is not necessarily the same thing as the length of the string. modified version of hdunkel's amd64 patch.<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <assert.h> #include <string> #include <string.h> #include "common.h" #include "bzfgl.h" #include "TextureManager.h" #include "TextureFont.h" #include "bzfio.h" #include "OpenGLGState.h" TextureFont::TextureFont() { for (int i = 0; i < 128; i++) { listIDs[i] = _GL_INVALID_ID; fontMetrics[i].charWidth = -1; } size = -1; textureID = -1; textureXSize = -1; textureYSize = -1; textureZStep = -1; numberOfCharacters = -1; } TextureFont::~TextureFont() { for (int i = 0; i < 128; i++) { if (listIDs[i] != _GL_INVALID_ID) glDeleteLists(listIDs[i], 1); } } int TextureFont::getSize() { return size; } const char* TextureFont::getFaceName() { return faceName.c_str(); } /* read values in Key: Value form from font metrics (.fmt) files */ bool TextureFont::fmtRead(OSFile &file, std::string expectedLeft, std::string &retval) { static std::string workingFile; static int line = 0; // reset line number if we've switched files if (workingFile != file.getFileName()) { workingFile = file.getFileName(); line = 0; } std::string tmpBuf; // allow for blank lines with native or foreign linebreaks, comment lines while (tmpBuf.size() == 0 || tmpBuf[0] == '#' || tmpBuf[0] == 10 || tmpBuf[0] == 13) { tmpBuf = file.readLine(); // keep a line counter line++; } if (tmpBuf.substr(0, tmpBuf.find(":")) == expectedLeft) { retval = tmpBuf.substr(tmpBuf.find(":") + 1, tmpBuf.size()); return true; } else { DEBUG2("Unexpected line in font metrics file %s, line %d (expected %s)\n", file.getFileName(), line, expectedLeft.c_str()); return false; } } bool TextureFont::load(OSFile &file) { const char *extension = file.getExtension(); if (!extension) return false; if (!file.open("rb")) return false; std::string tmpBuf; if (!fmtRead(file, "NumChars", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &numberOfCharacters); if (!fmtRead(file, "TextureWidth", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureXSize); if (!fmtRead(file, "TextureHeight", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureYSize); if (!fmtRead(file, "TextZStep", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &textureZStep); int i; for (i = 0; i < numberOfCharacters; i++) { // check character if (!fmtRead(file, "Char", tmpBuf)) return false; if ((tmpBuf.size() < 3) || (tmpBuf[1] != '\"' || tmpBuf[2] != (i + 32) || tmpBuf[3] != '\"')) { DEBUG2("Unexpected character: %s, in font metrics file %s (expected \"%c\").\n", tmpBuf.c_str(), file.getFileName(), (char)(i + 32)); return false; } // read metrics if (!fmtRead(file, "InitialDist", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].initialDist); if (!fmtRead(file, "Width", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].charWidth); if (!fmtRead(file, "Whitespace", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].whiteSpaceDist); if (!fmtRead(file, "StartX", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].startX); if (!fmtRead(file, "EndX", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].endX); if (!fmtRead(file, "StartY", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].startY); if (!fmtRead(file, "EndY", tmpBuf)) return false; sscanf(tmpBuf.c_str(), " %d", &fontMetrics[i].endY); } file.close(); // now compute the names std::string fullName = file.getStdName(); char *temp; // get just the file part temp = strrchr(fullName.c_str(), '/'); if (temp) faceName = temp + 1; else faceName = fullName; // now get the texture name texture = faceName; // now wack off the extension; if (extension) faceName.erase(faceName.size() - strlen(extension), faceName.size()); temp = strrchr(faceName.c_str(), '_'); if (temp) { size = atoi(temp+1); faceName.resize(temp - faceName.c_str()); } // faceName.erase(faceName.size()-strlen(temp),faceName.size()); if (extension) texture.erase(texture.size() - strlen(extension), texture.size()); return (numberOfCharacters > 0); } void TextureFont::build(void) { preLoadLists(); } void TextureFont::preLoadLists(void) { if (texture.size() < 1) { DEBUG2("Font %s does not have an associated texture name, not loading\n", texture.c_str()); return; } // load up the texture TextureManager &tm = TextureManager::instance(); std::string textureAndDir = "fonts/" + texture; textureID = tm.getTextureID(textureAndDir.c_str()); DEBUG4("Font %s (face %s) has texture ID %d\n", texture.c_str(), faceName.c_str(), textureID); if (textureID == -1) { DEBUG2("Font texture %s has invalid ID\n", texture.c_str()); return; } glPushMatrix(); for (int i = 0; i < numberOfCharacters; i++) { if (listIDs[i] != _GL_INVALID_ID) glDeleteLists(listIDs[i], 1); listIDs[i] = glGenLists(1); glLoadIdentity(); glNewList(listIDs[i], GL_COMPILE); glTranslatef((float)fontMetrics[i].initialDist, 0, 0); float fFontY = (float)fontMetrics[i].endY - fontMetrics[i].startY; float fFontX = (float)fontMetrics[i].endX - fontMetrics[i].startX; glBegin(GL_QUADS); glNormal3f(0, 0, 1); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(0, fFontY, 0); glTexCoord2f((float)fontMetrics[i].startX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(0, 0, 0); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].endY / (float)textureYSize); glVertex3f(fFontX, 0, 0); glTexCoord2f((float)fontMetrics[i].endX / (float)textureXSize, 1.0f - (float)fontMetrics[i].startY / (float)textureYSize); glVertex3f(fFontX, fFontY, 0); glEnd(); glTranslatef(fFontX, 0, 0); glEndList(); } glPopMatrix(); // create GState OpenGLGStateBuilder builder(gstate); builder.setTexture(textureID); builder.setBlending(); builder.setAlphaFunc(); builder.enableTextureReplace(false); gstate = builder.getState(); } float TextureFont::getStrLength(float scale, const char *str) { int len = (int)strlen(str); int charToUse = 0; int lastCharacter = 0; float totalLen = 0; float thisPassLen = 0; for (int i = 0; i < len; i++) { if (str[i] == '\n') { // newline, get back to the intial X and push down thisPassLen = 0; } else { lastCharacter = charToUse; if ((str[i] < 32) || (str[i] < 9)) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { if (i == 0) thisPassLen += fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth+fontMetrics[charToUse].whiteSpaceDist; else thisPassLen += fontMetrics[lastCharacter].whiteSpaceDist + fontMetrics[charToUse].whiteSpaceDist+fontMetrics[charToUse].initialDist + fontMetrics[charToUse].charWidth; } else { float fFontX = (float)fontMetrics[charToUse].endX - fontMetrics[charToUse].startX; thisPassLen += fFontX + (float)fontMetrics[charToUse].initialDist; } } if (thisPassLen > totalLen) totalLen = thisPassLen; } return totalLen * scale; } void TextureFont::free(void) { textureID = -1; } void TextureFont::drawString(float scale, GLfloat color[3], const char *str) { if (!str) return; if (textureID == -1) preLoadLists(); if (textureID == -1) return; gstate.setState(); TextureManager &tm = TextureManager::instance(); if (!tm.bind(textureID)) return; if (color[0] >= 0) glColor3fv(color); glPushMatrix(); glScalef(scale, scale, 1); glPushMatrix(); int len = (int)strlen(str); int charToUse = 0; int lastCharacter = 0; for (int i = 0; i < len; i++) { if (str[i] == '\n') { // newline, get back to the intial X and push down glPopMatrix(); glTranslatef(0, -(float)textureZStep, 0); glPushMatrix(); } else { lastCharacter = charToUse; if ((str[i] < 32) || (str[i] < 9)) charToUse = 32; else if (str[i] > numberOfCharacters + 32) charToUse = 32; else charToUse = str[i]; charToUse -= 32; if (charToUse == 0) { if (i == 0) glTranslatef((float)fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth + (float)fontMetrics[charToUse].whiteSpaceDist, 0, 0); else glTranslatef((float)fontMetrics[lastCharacter].whiteSpaceDist + (float)fontMetrics[charToUse].whiteSpaceDist + fontMetrics[charToUse].initialDist + (float)fontMetrics[charToUse].charWidth, 0, 0); } else { glCallList(listIDs[charToUse]); } } } glPopMatrix(); if (color[0] >= 0) glColor4f(1, 1, 1, 1); glPopMatrix(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 <time.h> #include "paddle/fluid/framework/device_worker.h" #include "paddle/fluid/framework/fleet/fleet_wrapper.h" namespace paddle { namespace framework { std::shared_ptr<PullDenseWorker> PullDenseWorker::s_instance_ = NULL; std::mutex PullDenseWorker::mutex_for_version_; std::map<uint64_t, uint64_t> PullDenseWorker::last_versions_; std::map<uint64_t, uint64_t> PullDenseWorker::current_version_; std::map<uint64_t, std::vector<uint64_t>> PullDenseWorker::training_versions_; std::map<uint64_t, std::vector<std::string>> PullDenseWorker::dense_value_names_; void PullDenseWorker::Initialize(const TrainerDesc& param) { running_ = false; param_ = param.pull_dense_param(); dwp_param_ = param.downpour_param(); threshold_ = param_.threshold(); thread_num_ = param_.device_num(); sleep_time_ms_ = param_.sleep_time_ms(); for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); TableParameter table; for (auto i : param_.dense_table()) { if (i.table_id() == tid) { table = i; break; } } // setup dense variables for each table int var_num = table.dense_value_name_size(); dense_value_names_[tid].resize(var_num); for (int j = 0; j < var_num; ++j) { dense_value_names_[tid][j] = table.dense_value_name(j); } // setup training version for each table training_versions_[tid].resize(thread_num_, 0); last_versions_[tid] = 0; current_version_[tid] = 0; } fleet_ptr_ = FleetWrapper::GetInstance(); #ifdef PADDLE_WITH_CUDA copy_streams_.clear(); #endif #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) places_.clear(); thread_scopes_.clear(); #endif } void PullDenseWorker::CreatePinVar() { #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_PSLIB) // for (auto& v : dense_value_names_) { // for (auto& name : v.second) { for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); for (size_t j = 0; j < dense_value_names_[tid].size(); j++) { auto& name = dense_value_names_[tid][j]; Variable* var = root_scope_->FindVar(name); LoDTensor* tensor = var->GetMutable<LoDTensor>(); auto* ptr = root_scope_->Var(name + "pin"); InitializeVariable(ptr, proto::VarType::LOD_TENSOR); LoDTensor* pin_tensor = ptr->GetMutable<LoDTensor>(); #ifdef PADDLE_WITH_CUDA pin_tensor->mutable_data<float>(tensor->dims(), platform::CUDAPinnedPlace()); #endif #ifdef PADDLE_WITH_XPU pin_tensor->mutable_data<float>(tensor->dims(), platform::CPUPlace()); #endif } } #endif } void PullDenseWorker::Wait(std::vector<::std::future<int32_t>>* status_vec) { for (auto& t : *status_vec) { t.wait(); auto status = t.get(); if (status != 0) { LOG(WARNING) << "Current Pull Dense Thread Failed Times" << ++pull_dense_fail_times_; } } size_t MAX_FAIL_NUM = 20; if (pull_dense_fail_times_ > MAX_FAIL_NUM) { PADDLE_THROW(platform::errors::Fatal( "Pull dense failed more than %d times.", MAX_FAIL_NUM)); exit(-1); } status_vec->resize(0); #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) for (size_t i = 0; i < places_.size(); ++i) { // for (auto& v : dense_value_names_) { // for (auto& name : v.second) { for (int x = 0; x < dwp_param_.program_config(0).pull_dense_table_id_size(); ++x) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(x)); for (size_t j = 0; j < dense_value_names_[tid].size(); j++) { auto& name = dense_value_names_[tid][j]; Variable* pin_var = root_scope_->FindVar(name + "pin"); LoDTensor* pin_tensor = pin_var->GetMutable<LoDTensor>(); float* pin_w = pin_tensor->data<float>(); Variable* var = thread_scopes_[i]->FindVar(name); LoDTensor* tensor = var->GetMutable<LoDTensor>(); float* w = tensor->data<float>(); #ifdef PADDLE_WITH_CUDA memory::Copy(BOOST_GET_CONST(platform::CUDAPlace, places_[i]), w, platform::CUDAPinnedPlace(), pin_w, sizeof(float) * tensor->numel(), copy_streams_[i]); #endif #ifdef PADDLE_WITH_XPU memory::Copy(BOOST_GET_CONST(platform::XPUPlace, places_[i]), w, platform::CPUPlace(), pin_w, sizeof(float) * tensor->numel()); #endif } } } #endif } void PullDenseWorker::Stop() { if (running_) { running_ = false; t_.join(); } } void PullDenseWorker::PullDense(bool force_update) { pull_dense_status_.resize(0); for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); if (force_update || CheckUpdateParam(tid)) { #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) VLOG(3) << "pull dense " << force_update << " " << tid; fleet_ptr_->PullDenseVarsAsync(*root_scope_, tid, dense_value_names_[tid], &pull_dense_status_, false); #else fleet_ptr_->PullDenseVarsAsync(*root_scope_, tid, dense_value_names_[tid], &pull_dense_status_, true); #endif ResetThreadVersion(tid); } } if (pull_dense_status_.size() != 0) { Wait(&pull_dense_status_); } } int PullDenseWorker::Start() { running_ = true; // before training, we can pull dense from pserver first. PullDense(true); t_ = std::thread(&PullDenseWorker::Run, this); return 0; } void PullDenseWorker::Run() { while (running_) { PullDense(false); #ifndef _WIN32 usleep(sleep_time_ms_ * 1000); #endif } } void PullDenseWorker::IncreaseThreadVersion(int thread_id, uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); training_versions_[table_id][thread_id]++; } bool PullDenseWorker::CheckUpdateParam(uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); auto& version = training_versions_[table_id]; current_version_[table_id] = *(std::min_element(version.begin(), version.end())); if (current_version_[table_id] - last_versions_[table_id] < static_cast<size_t>(threshold_)) { return false; } return true; } void PullDenseWorker::ResetThreadVersion(uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); last_versions_[table_id] = current_version_[table_id]; } int PullDenseWorker::GetThreadIdByScope(const Scope* scope) { if (scope_to_thread_id_.find(scope) != scope_to_thread_id_.end()) { return scope_to_thread_id_[scope]; } return -1; } void PullDenseWorker::SetThreadIdByScope(const Scope* scope, int tid) { scope_to_thread_id_[scope] = tid; } } // namespace framework } // namespace paddle <commit_msg>solve bug in pull_dense_worker (#27918)<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 <time.h> #include "paddle/fluid/framework/device_worker.h" #include "paddle/fluid/framework/fleet/fleet_wrapper.h" namespace paddle { namespace framework { std::shared_ptr<PullDenseWorker> PullDenseWorker::s_instance_ = NULL; std::mutex PullDenseWorker::mutex_for_version_; std::map<uint64_t, uint64_t> PullDenseWorker::last_versions_; std::map<uint64_t, uint64_t> PullDenseWorker::current_version_; std::map<uint64_t, std::vector<uint64_t>> PullDenseWorker::training_versions_; std::map<uint64_t, std::vector<std::string>> PullDenseWorker::dense_value_names_; void PullDenseWorker::Initialize(const TrainerDesc& param) { running_ = false; param_ = param.pull_dense_param(); dwp_param_ = param.downpour_param(); threshold_ = param_.threshold(); thread_num_ = param_.device_num(); sleep_time_ms_ = param_.sleep_time_ms(); for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); TableParameter table; for (auto i : param_.dense_table()) { if (i.table_id() == tid) { table = i; break; } } // setup dense variables for each table int var_num = table.dense_value_name_size(); dense_value_names_[tid].resize(var_num); for (int j = 0; j < var_num; ++j) { dense_value_names_[tid][j] = table.dense_value_name(j); } // setup training version for each table training_versions_[tid].resize(thread_num_, 0); last_versions_[tid] = 0; current_version_[tid] = 0; } fleet_ptr_ = FleetWrapper::GetInstance(); #ifdef PADDLE_WITH_CUDA copy_streams_.clear(); #endif #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) places_.clear(); thread_scopes_.clear(); #endif } void PullDenseWorker::CreatePinVar() { #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) // for (auto& v : dense_value_names_) { // for (auto& name : v.second) { for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); for (size_t j = 0; j < dense_value_names_[tid].size(); j++) { auto& name = dense_value_names_[tid][j]; Variable* var = root_scope_->FindVar(name); LoDTensor* tensor = var->GetMutable<LoDTensor>(); auto* ptr = root_scope_->Var(name + "pin"); InitializeVariable(ptr, proto::VarType::LOD_TENSOR); LoDTensor* pin_tensor = ptr->GetMutable<LoDTensor>(); #ifdef PADDLE_WITH_CUDA pin_tensor->mutable_data<float>(tensor->dims(), platform::CUDAPinnedPlace()); #endif #ifdef PADDLE_WITH_XPU pin_tensor->mutable_data<float>(tensor->dims(), platform::CPUPlace()); #endif } } #endif } void PullDenseWorker::Wait(std::vector<::std::future<int32_t>>* status_vec) { for (auto& t : *status_vec) { t.wait(); auto status = t.get(); if (status != 0) { LOG(WARNING) << "Current Pull Dense Thread Failed Times" << ++pull_dense_fail_times_; } } size_t MAX_FAIL_NUM = 20; if (pull_dense_fail_times_ > MAX_FAIL_NUM) { PADDLE_THROW(platform::errors::Fatal( "Pull dense failed more than %d times.", MAX_FAIL_NUM)); exit(-1); } status_vec->resize(0); #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) for (size_t i = 0; i < places_.size(); ++i) { // for (auto& v : dense_value_names_) { // for (auto& name : v.second) { for (int x = 0; x < dwp_param_.program_config(0).pull_dense_table_id_size(); ++x) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(x)); for (size_t j = 0; j < dense_value_names_[tid].size(); j++) { auto& name = dense_value_names_[tid][j]; Variable* pin_var = root_scope_->FindVar(name + "pin"); LoDTensor* pin_tensor = pin_var->GetMutable<LoDTensor>(); float* pin_w = pin_tensor->data<float>(); Variable* var = thread_scopes_[i]->FindVar(name); LoDTensor* tensor = var->GetMutable<LoDTensor>(); float* w = tensor->data<float>(); #ifdef PADDLE_WITH_CUDA memory::Copy(BOOST_GET_CONST(platform::CUDAPlace, places_[i]), w, platform::CUDAPinnedPlace(), pin_w, sizeof(float) * tensor->numel(), copy_streams_[i]); #endif #ifdef PADDLE_WITH_XPU memory::Copy(BOOST_GET_CONST(platform::XPUPlace, places_[i]), w, platform::CPUPlace(), pin_w, sizeof(float) * tensor->numel()); #endif } } } #endif } void PullDenseWorker::Stop() { if (running_) { running_ = false; t_.join(); } } void PullDenseWorker::PullDense(bool force_update) { pull_dense_status_.resize(0); for (int i = 0; i < dwp_param_.program_config(0).pull_dense_table_id_size(); ++i) { uint64_t tid = static_cast<uint64_t>( dwp_param_.program_config(0).pull_dense_table_id(i)); if (force_update || CheckUpdateParam(tid)) { #if (defined PADDLE_WITH_CUDA) || (defined PADDLE_WITH_XPU) VLOG(3) << "pull dense " << force_update << " " << tid; fleet_ptr_->PullDenseVarsAsync(*root_scope_, tid, dense_value_names_[tid], &pull_dense_status_, false); #else fleet_ptr_->PullDenseVarsAsync(*root_scope_, tid, dense_value_names_[tid], &pull_dense_status_, true); #endif ResetThreadVersion(tid); } } if (pull_dense_status_.size() != 0) { Wait(&pull_dense_status_); } } int PullDenseWorker::Start() { running_ = true; // before training, we can pull dense from pserver first. PullDense(true); t_ = std::thread(&PullDenseWorker::Run, this); return 0; } void PullDenseWorker::Run() { while (running_) { PullDense(false); #ifndef _WIN32 usleep(sleep_time_ms_ * 1000); #endif } } void PullDenseWorker::IncreaseThreadVersion(int thread_id, uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); training_versions_[table_id][thread_id]++; } bool PullDenseWorker::CheckUpdateParam(uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); auto& version = training_versions_[table_id]; current_version_[table_id] = *(std::min_element(version.begin(), version.end())); if (current_version_[table_id] - last_versions_[table_id] < static_cast<size_t>(threshold_)) { return false; } return true; } void PullDenseWorker::ResetThreadVersion(uint64_t table_id) { std::lock_guard<std::mutex> lock(mutex_for_version_); last_versions_[table_id] = current_version_[table_id]; } int PullDenseWorker::GetThreadIdByScope(const Scope* scope) { if (scope_to_thread_id_.find(scope) != scope_to_thread_id_.end()) { return scope_to_thread_id_[scope]; } return -1; } void PullDenseWorker::SetThreadIdByScope(const Scope* scope, int tid) { scope_to_thread_id_[scope] = tid; } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/************************************************* * Servo * * read joystick data, normalize, write to servo * * * * @author: Navid Kalaei <navidkalaie@gmail.com> * * @github: @navid-kalaei * * @license: MIT * *************************************************/ #include "Arduino.h" #include "Servo.h" // time to wait in millis #define DELAY_TIME 200 #define SERIAL_RATE 9600 #define JOY_PIN_X 0 #define JOY_PIN_Y 1 #define SERVO_PIN 9 // boundries of analogRead() #define ANALOG_READ_LOW 0 #define ANALOG_READ_HIGH 1023 // boundries for normalizing analogRead() from -90 to +90 #define NORMALIZE_BOUND_LOW -90 #define NORMALIZE_BOUND_HIGH 90 // use this number to shift normalize value be between 0 to 180 #define NORMALIZE_ORIGIN 90 // the value that joystick has at first // they're usefull in normalizing short int joyXOrigin = 0; short int joyYOrigin = 0; short int joyXOriginNormalized = 0; short int joyYOriginNormalized = 0; short int joyValueX = 0; short int joyValueY = 0; short int joyValueXNormalized = 0; short int joyValueYNormalized = 0; Servo myServo; int myServoPos = 0; short int normalize(short int value){ /* * a wrapper for map built-in function * * @param value: is within analogRead boundries * @return: normalize value within normalize boundries */ // https://www.arduino.cc/en/Reference/Map // map(value, fromLow, fromHigh, toLow, toHigh) return map(value, ANALOG_READ_LOW, ANALOG_READ_HIGH, NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH); } void checkBoundries(short int &value){ /* * check if value is between normalized boudries or reset it to a boundry * * @param value: to check * @return: void */ if(value > NORMALIZE_BOUND_HIGH){ value = NORMALIZE_BOUND_HIGH; } else if(value < NORMALIZE_BOUND_LOW){ value = NORMALIZE_BOUND_LOW; } } void setup(){ myServo.attach(SERVO_PIN); // initialize joystick pins pinMode(JOY_PIN_X, INPUT); pinMode(JOY_PIN_Y, INPUT); joyXOrigin = analogRead(JOY_PIN_X); joyYOrigin = analogRead(JOY_PIN_Y); joyXOriginNormalized = normalize(joyXOrigin); joyYOriginNormalized = normalize(joyYOrigin); // wait until Serail is not available while(!Serial); Serial.begin(SERIAL_RATE); } void loop(){ joyValueX = analogRead(JOY_PIN_X); joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized; checkBoundries(joyValueXNormalized); joyValueY = analogRead(JOY_PIN_Y); joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized; checkBoundries(joyValueYNormalized); myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN; myServo.write(myServoPos); //Serial.println(myServoPos); // delay(DELAY_TIME); } <commit_msg>remove Y axe from servo/src/main.cpp (because servo is 2 dimential)<commit_after>/************************************************* * Servo * * read joystick data, normalize, write to servo * * * * @author: Navid Kalaei <navidkalaie@gmail.com> * * @github: @navid-kalaei * * @license: MIT * *************************************************/ #include "Arduino.h" #include "Servo.h" // time to wait in millis #define DELAY_TIME 200 #define SERIAL_RATE 9600 #define JOY_PIN_X 0 #define JOY_PIN_Y 1 #define SERVO_PIN 9 // boundries of analogRead() #define ANALOG_READ_LOW 0 #define ANALOG_READ_HIGH 1023 // boundries for normalizing analogRead() from -90 to +90 #define NORMALIZE_BOUND_LOW -90 #define NORMALIZE_BOUND_HIGH 90 // use this number to shift normalize value be between 0 to 180 #define NORMALIZE_ORIGIN 90 // the value that joystick has at first // they're usefull in normalizing short int joyXOrigin = 0; short int joyXOriginNormalized = 0; short int joyValueX = 0; short int joyValueXNormalized = 0; Servo myServo; int myServoPos = 0; short int normalize(short int value){ /* * a wrapper for map built-in function * * @param value: is within analogRead boundries * @return: normalize value within normalize boundries */ // https://www.arduino.cc/en/Reference/Map // map(value, fromLow, fromHigh, toLow, toHigh) return map(value, ANALOG_READ_LOW, ANALOG_READ_HIGH, NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH); } void checkBoundries(short int &value){ /* * check if value is between normalized boudries or reset it to a boundry * * @param value: to check * @return: void */ if(value > NORMALIZE_BOUND_HIGH){ value = NORMALIZE_BOUND_HIGH; } else if(value < NORMALIZE_BOUND_LOW){ value = NORMALIZE_BOUND_LOW; } } void setup(){ myServo.attach(SERVO_PIN); // initialize joystick pins pinMode(JOY_PIN_X, INPUT); joyXOrigin = analogRead(JOY_PIN_X); joyXOriginNormalized = normalize(joyXOrigin); // wait until Serail is not available while(!Serial); Serial.begin(SERIAL_RATE); } void loop(){ joyValueX = analogRead(JOY_PIN_X); joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized; checkBoundries(joyValueXNormalized); myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN; myServo.write(myServoPos); //Serial.println(myServoPos); // delay(DELAY_TIME); } <|endoftext|>
<commit_before>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. 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 Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which head is the index of the location // to which to write the next incoming character and tail is the index of the // location from which to read. #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer tx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; ring_buffer tx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } #if !defined(USART_RX_vect) && !defined(SIG_USART0_RECV) && \ !defined(SIG_UART0_RECV) && !defined(USART0_RX_vect) && \ !defined(SIG_UART_RECV) #error Don't know what the Data Received vector is called for the first UART #else #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) #elif defined(SIG_USART0_RECV) SIGNAL(SIG_USART0_RECV) #elif defined(SIG_UART0_RECV) SIGNAL(SIG_UART0_RECV) #elif defined(USART0_RX_vect) SIGNAL(USART0_RX_vect) #elif defined(SIG_UART_RECV) SIGNAL(SIG_UART_RECV) #endif { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; #else #error UDR not defined #endif store_char(c, &rx_buffer); } #endif //#if defined(SIG_USART1_RECV) #if defined(USART1_RX_vect) //SIGNAL(SIG_USART1_RECV) SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) #error Don't know what the Data Register Empty vector is called for the first UART #else #if defined(UART0_UDRE_vect) ISR(UART0_UDRE_vect) #elif defined(UART_UDRE_vect) ISR(UART_UDRE_vect) #elif defined(USART0_UDRE_vect) ISR(USART0_UDRE_vect) #elif defined(USART_UDRE_vect) ISR(USART_UDRE_vect) #endif { if (tx_buffer.head == tx_buffer.tail) { // Buffer empty, so disable interrupts #if defined(UCSR0B) cbi(UCSR0B, UDRIE0); #else cbi(UCSRB, UDRIE); #endif } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer.buffer[tx_buffer.tail]; tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE; #if defined(UDR0) UDR0 = c; #elif defined(UDR) UDR = c; #else #error UDR not defined #endif } } #endif #ifdef USART1_UDRE_vect ISR(USART1_UDRE_vect) { if (tx_buffer1.head == tx_buffer1.tail) { // Buffer empty, so disable interrupts cbi(UCSR1B, UDRIE1); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer1.buffer[tx_buffer1.tail]; tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE; UDR1 = c; } } #endif #ifdef USART2_UDRE_vect ISR(USART2_UDRE_vect) { if (tx_buffer2.head == tx_buffer2.tail) { // Buffer empty, so disable interrupts cbi(UCSR2B, UDRIE2); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer2.buffer[tx_buffer2.tail]; tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE; UDR2 = c; } } #endif #ifdef USART3_UDRE_vect ISR(USART3_UDRE_vect) { if (tx_buffer3.head == tx_buffer3.tail) { // Buffer empty, so disable interrupts cbi(UCSR3B, UDRIE3); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer3.buffer[tx_buffer3.tail]; tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE; UDR3 = c; } } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x) { _rx_buffer = rx_buffer; _tx_buffer = tx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udrie = udrie; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail) ; cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); // clear any received data _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { while (_tx_buffer->head != _tx_buffer->tail) ; } void HardwareSerial::write(uint8_t c) { int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer->tail) ; _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; sbi(*_ucsrb, _udrie); } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3); #endif #endif // whole file <commit_msg>Adding serialEvent(), serialEvent1(), etc.<commit_after>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. 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 Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which head is the index of the location // to which to write the next incoming character and tail is the index of the // location from which to read. #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer tx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; ring_buffer tx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } #if !defined(USART_RX_vect) && !defined(SIG_USART0_RECV) && \ !defined(SIG_UART0_RECV) && !defined(USART0_RX_vect) && \ !defined(SIG_UART_RECV) #error Don't know what the Data Received vector is called for the first UART #else void serialEvent() __attribute__((weak)); void serialEvent() {} #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) #elif defined(SIG_USART0_RECV) SIGNAL(SIG_USART0_RECV) #elif defined(SIG_UART0_RECV) SIGNAL(SIG_UART0_RECV) #elif defined(USART0_RX_vect) SIGNAL(USART0_RX_vect) #elif defined(SIG_UART_RECV) SIGNAL(SIG_UART_RECV) #endif { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; #else #error UDR not defined #endif store_char(c, &rx_buffer); serialEvent(); } #endif #if defined(USART1_RX_vect) void serialEvent1() __attribute__((weak)); void serialEvent1() {} SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); serialEvent1(); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) void serialEvent2() __attribute__((weak)); void serialEvent2() {} SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); serialEvent2(); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) void serialEvent3() __attribute__((weak)); void serialEvent3() {} SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); serialEvent3(); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) #error Don't know what the Data Register Empty vector is called for the first UART #else #if defined(UART0_UDRE_vect) ISR(UART0_UDRE_vect) #elif defined(UART_UDRE_vect) ISR(UART_UDRE_vect) #elif defined(USART0_UDRE_vect) ISR(USART0_UDRE_vect) #elif defined(USART_UDRE_vect) ISR(USART_UDRE_vect) #endif { if (tx_buffer.head == tx_buffer.tail) { // Buffer empty, so disable interrupts #if defined(UCSR0B) cbi(UCSR0B, UDRIE0); #else cbi(UCSRB, UDRIE); #endif } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer.buffer[tx_buffer.tail]; tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE; #if defined(UDR0) UDR0 = c; #elif defined(UDR) UDR = c; #else #error UDR not defined #endif } } #endif #ifdef USART1_UDRE_vect ISR(USART1_UDRE_vect) { if (tx_buffer1.head == tx_buffer1.tail) { // Buffer empty, so disable interrupts cbi(UCSR1B, UDRIE1); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer1.buffer[tx_buffer1.tail]; tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE; UDR1 = c; } } #endif #ifdef USART2_UDRE_vect ISR(USART2_UDRE_vect) { if (tx_buffer2.head == tx_buffer2.tail) { // Buffer empty, so disable interrupts cbi(UCSR2B, UDRIE2); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer2.buffer[tx_buffer2.tail]; tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE; UDR2 = c; } } #endif #ifdef USART3_UDRE_vect ISR(USART3_UDRE_vect) { if (tx_buffer3.head == tx_buffer3.tail) { // Buffer empty, so disable interrupts cbi(UCSR3B, UDRIE3); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer3.buffer[tx_buffer3.tail]; tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE; UDR3 = c; } } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x) { _rx_buffer = rx_buffer; _tx_buffer = tx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udrie = udrie; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail) ; cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); // clear any received data _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { while (_tx_buffer->head != _tx_buffer->tail) ; } void HardwareSerial::write(uint8_t c) { int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer->tail) ; _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; sbi(*_ucsrb, _udrie); } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3); #endif #endif // whole file <|endoftext|>
<commit_before>// irview : simple viewer for adding false colour to IR or thermal images // / video / camera feed // usage: prog {image/video file} // Author : Toby Breckon, toby.breckon@durham.ac.uk // Copyright (c) 2008 School of Engineering, Cranfield University // Copyright (c) 2017 School of Engineering and Computing Sciences, Durham University // License : GPL - http://www.gnu.org/licenses/gpl.html /******************************************************************************/ #include "cv.h" // open cv general include file #if (CV_MAJOR_VERSION > 2) // includes for OpenCV 3.x and onward #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> // standard C++ I/O #include <string> // standard C++ I/O #include <algorithm> // includes max() using namespace cv; // OpenCV API is in the C++ "cv" namespace using namespace std; #else // includes for older OpenCV 2.4.x #include "highgui.h" // open cv GUI include file #include <stdio.h> #include <ctype.h> #endif /******************************************************************************/ // setup the camera index properly based on OS platform // 0 in linux gives first camera for v4l //-1 in windows gives first device or user dialog selection #ifdef linux #define CAMERA_INDEX 0 #else #define CAMERA_INDEX -1 #endif /******************************************************************************/ #define PROG_ID_STRING "IrView v0.2- (c) Toby Breckon, 2008-2017+" #define LICENSE_STRING "GPL - http://www.gnu.org/licenses/gpl.html" static void print_help(char **name){ printf("\n%s\n", PROG_ID_STRING); printf ("\t with OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION); printf("%s\n\n", LICENSE_STRING); printf("Usage :%s [image/video file]\n", name[0]); printf("Camera interface: run with no file agrument for direct camera use\n"); printf("\nKeyboard commands\n"); printf("\t a - automatic scaling (default: on)\n"); printf("\t b - show both false colour and original (default: off)\n"); printf("\t c - toggle false colour (default: on)\n"); printf("\t e - exit (as per x or ESC)\n"); printf("\t f - toggle full screen (default: off)\n"); printf("\t x - exit\n\n"); } /******************************************************************************/ // concatenate 2 OpenCV Mat Objects side-by-side (in general) Mat concatImages(Mat img1, Mat img2) { Mat out = Mat(img1.rows, img1.cols + img2.cols, img1.type()); Mat roi = out(Rect(0, 0, img1.cols, img1.rows)); Mat roi2 = out(Rect(img1.cols, 0, img2.cols, img2.rows)); img1.copyTo(roi); // depth of img1 is master, depth of img2 is slave // so convert if needed if (img1.depth() != img2.depth()) { // e.g. if img2 is 8-bit and img1 32-bit - scale to range 0->1 (32-bit) // otherwise img2 is 32-bit and img1 is 8-bit - scale to 0->255 (8-bit) img2.convertTo(roi2, img1.depth(), (img2.depth() < img1.depth()) ? 1.0 / 255.0 : 255); } else { img2.copyTo(roi2); } return out; } /******************************************************************************/ int main( int argc, char** argv ) { IplImage* img = NULL; // image object CvCapture* capture = NULL; // capture object const char* windowNameHSV = PROG_ID_STRING; // window name IplImage* HSV = NULL; // HSV image IplImage* singleChannelH = NULL; // Hue plain (from input image) IplImage* singleChannelPlain = NULL; // constant plane for S & V bool keepProcessing = true; // loop control flag char key = '\0'; // user input int EVENT_LOOP_DELAY = 40; // 40ms equates to 1000ms/25fps = // 40ms per frame bool useFalseColour = true; // process flag - false colour bool useNormalisation = true; // process flag - normalisation bool useConcatImage = false; // process flag - show concatenated images bool useFullScreen = false; // process flag - run full screen // if command line arguments are provided try to read image/video_name // otherwise default to capture from attached H/W camera if( ( argc == 2 && (img = cvLoadImage( argv[1], 1)) != 0 ) || ( argc == 2 && (capture = cvCreateFileCapture( argv[1] )) != 0 ) || ( argc != 2 && (capture = cvCreateCameraCapture( CAMERA_INDEX )) != 0 ) ) { // print help print_help(argv); // create window object (use flag=0 to allow resize, 1 to auto fix size) cvNamedWindow(windowNameHSV, CV_WINDOW_NORMAL); // if capture object in use (i.e. video/camera) // get initial image from capture object if (capture) { // cvQueryFrame s just a combination of cvGrabFrame // and cvRetrieveFrame in one call. img = cvQueryFrame(capture); if(!img){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } cvResizeWindow(windowNameHSV, img->width, img->height); // setup output image in HSV HSV = cvCloneImage(img); singleChannelH = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelH->origin = img->origin; IplImage* singleChannelV = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelV->origin = img->origin; // set single channel up for Saturation / Variance singleChannelPlain = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelPlain->origin = img->origin; cvSet(singleChannelPlain, cvScalar(255)); // start main loop while (keepProcessing) { // if capture object in use (i.e. video/camera) // get image from capture object if (capture) { // cvQueryFrame is just a combination of cvGrabFrame // and cvRetrieveFrame in one call. img = cvQueryFrame(capture); // cvQueryFrame s just a combination of cvGrabFrame // and cvRetrieveFrame in one call. if(!img){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } // extract first (or only input image channel) if (img->nChannels > 1) { cvSetImageCOI(img, 1); // select channel 1, 0 means all channels } // we will use this for the Hue and Variance channels cvCopy(img, singleChannelH); cvCopy(img, singleChannelV); cvSetImageCOI(img, 0); // do colour normalisation (makes it look more impressive) if (useNormalisation){ cvNormalize(singleChannelH, singleChannelH, 0, 255, CV_MINMAX, NULL); cvNormalize(singleChannelV, singleChannelV, 0, 255, CV_MINMAX, NULL); } // do scaling to avoid Hue space wrap around (i.e. dark == bright!) // N.B. changing the scaling factor and addition will vary the colour // effect - OpenCV 8-bit Hue in range 0->120 => 0.5 * Hue + 90 maps // all values to (wrap-around) 180->60 range in Hue. cvConvertScale(singleChannelH, singleChannelH, 0.5, 90); // put it all back together in RGB cvMerge(singleChannelH, singleChannelPlain, singleChannelV, NULL, HSV); cvCvtColor(HSV, HSV, CV_HSV2BGR); // display image in window if (useConcatImage){ imshow(windowNameHSV, concatImages(cv::cvarrToMat(img), cv::cvarrToMat(HSV))); } else { if (useFalseColour){ cvShowImage(windowNameHSV, HSV); } else { cvShowImage(windowNameHSV, img); } } // start event processing loop key = cvWaitKey(EVENT_LOOP_DELAY); // process any keyboard input switch (tolower(key)) { case 'x': case 'e': case char(27): // ESC key // if user presses "x" then exit keepProcessing = false; ; break; case 'a': // toggle automatic scaling useNormalisation = (!useNormalisation); ; break; case 'b': // toggle concatenated images useConcatImage = (!useConcatImage); ; break; case 'c': // toggle false colour useFalseColour = (!useFalseColour); ; break; case 'f': // toggle false colour useFullScreen = (!useFullScreen); // set or unset the CV_WINDOW_FULLSCREEN flag via logical AND with toggle boolean cvSetWindowProperty(windowNameHSV, CV_WND_PROP_FULLSCREEN, (CV_WINDOW_FULLSCREEN & useFullScreen)); ; break; } } // destroy window objects cvDestroyAllWindows(); // destroy image object (if it does not originate from a capture object) if (!capture){ cvReleaseImage( &img ); } cvReleaseImage( &HSV ); cvReleaseImage( &singleChannelH ); cvReleaseImage( &singleChannelPlain ); // all OK : main returns 0 return 0; } // not OK : main returns -1 print_help(argv); return -1; } /******************************************************************************/ <commit_msg>align comments<commit_after>// irview : simple viewer for adding false colour to IR or thermal images // / video / camera feed // usage: prog {image/video file} // Author : Toby Breckon, toby.breckon@durham.ac.uk // Copyright (c) 2008 School of Engineering, Cranfield University // Copyright (c) 2017 School of Engineering and Computing Sciences, Durham University // License : GPL - http://www.gnu.org/licenses/gpl.html /******************************************************************************/ #include "cv.h" // open cv general include file #if (CV_MAJOR_VERSION > 2) // includes for OpenCV 3.x and onward #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> // standard C++ I/O #include <string> // standard C++ I/O #include <algorithm> // includes max() using namespace cv; // OpenCV API is in the C++ "cv" namespace using namespace std; #else // includes for older OpenCV 2.4.x #include "highgui.h" // open cv GUI include file #include <stdio.h> #include <ctype.h> #endif /******************************************************************************/ // setup the camera index properly based on OS platform // 0 in linux gives first camera for v4l //-1 in windows gives first device or user dialog selection #ifdef linux #define CAMERA_INDEX 0 #else #define CAMERA_INDEX -1 #endif /******************************************************************************/ #define PROG_ID_STRING "IrView v0.2- (c) Toby Breckon, 2008-2017+" #define LICENSE_STRING "GPL - http://www.gnu.org/licenses/gpl.html" static void print_help(char **name){ printf("\n%s\n", PROG_ID_STRING); printf ("\t with OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION); printf("%s\n\n", LICENSE_STRING); printf("Usage :%s [image/video file]\n", name[0]); printf("Camera interface: run with no file agrument for direct camera use\n"); printf("\nKeyboard commands\n"); printf("\t a - automatic scaling (default: on)\n"); printf("\t b - show both false colour and original (default: off)\n"); printf("\t c - toggle false colour (default: on)\n"); printf("\t e - exit (as per x or ESC)\n"); printf("\t f - toggle full screen (default: off)\n"); printf("\t x - exit\n\n"); } /******************************************************************************/ // concatenate 2 OpenCV Mat Objects side-by-side (in general) Mat concatImages(Mat img1, Mat img2) { Mat out = Mat(img1.rows, img1.cols + img2.cols, img1.type()); Mat roi = out(Rect(0, 0, img1.cols, img1.rows)); Mat roi2 = out(Rect(img1.cols, 0, img2.cols, img2.rows)); img1.copyTo(roi); // depth of img1 is master, depth of img2 is slave // so convert if needed if (img1.depth() != img2.depth()) { // e.g. if img2 is 8-bit and img1 32-bit - scale to range 0->1 (32-bit) // otherwise img2 is 32-bit and img1 is 8-bit - scale to 0->255 (8-bit) img2.convertTo(roi2, img1.depth(), (img2.depth() < img1.depth()) ? 1.0 / 255.0 : 255); } else { img2.copyTo(roi2); } return out; } /******************************************************************************/ int main( int argc, char** argv ) { IplImage* img = NULL; // image object CvCapture* capture = NULL; // capture object const char* windowNameHSV = PROG_ID_STRING; // window name IplImage* HSV = NULL; // HSV image IplImage* singleChannelH = NULL; // Hue plain (from input image) IplImage* singleChannelPlain = NULL; // constant plane for S & V bool keepProcessing = true; // loop control flag char key = '\0'; // user input int EVENT_LOOP_DELAY = 40; // 40ms equates to 1000ms/25fps = // 40ms per frame bool useFalseColour = true; // process flag - false colour bool useNormalisation = true; // process flag - normalisation bool useConcatImage = false; // process flag - show concatenated images bool useFullScreen = false; // process flag - run full screen // if command line arguments are provided try to read image/video_name // otherwise default to capture from attached H/W camera if( ( argc == 2 && (img = cvLoadImage( argv[1], 1)) != 0 ) || ( argc == 2 && (capture = cvCreateFileCapture( argv[1] )) != 0 ) || ( argc != 2 && (capture = cvCreateCameraCapture( CAMERA_INDEX )) != 0 ) ) { // print help print_help(argv); // create window object (use flag=0 to allow resize, 1 to auto fix size) cvNamedWindow(windowNameHSV, CV_WINDOW_NORMAL); // if capture object in use (i.e. video/camera) // get initial image from capture object if (capture) { // cvQueryFrame s just a combination of cvGrabFrame // and cvRetrieveFrame in one call. img = cvQueryFrame(capture); if(!img){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } cvResizeWindow(windowNameHSV, img->width, img->height); // setup output image in HSV HSV = cvCloneImage(img); singleChannelH = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelH->origin = img->origin; IplImage* singleChannelV = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelV->origin = img->origin; // set single channel up for Saturation / Variance singleChannelPlain = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1); singleChannelPlain->origin = img->origin; cvSet(singleChannelPlain, cvScalar(255)); // start main loop while (keepProcessing) { // if capture object in use (i.e. video/camera) // get image from capture object if (capture) { // cvQueryFrame is just a combination of cvGrabFrame // and cvRetrieveFrame in one call. img = cvQueryFrame(capture); // cvQueryFrame s just a combination of cvGrabFrame // and cvRetrieveFrame in one call. if(!img){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } // extract first (or only input image channel) if (img->nChannels > 1) { cvSetImageCOI(img, 1); // select channel 1, 0 means all channels } // we will use this for the Hue and Variance channels cvCopy(img, singleChannelH); cvCopy(img, singleChannelV); cvSetImageCOI(img, 0); // do colour normalisation (makes it look more impressive) if (useNormalisation){ cvNormalize(singleChannelH, singleChannelH, 0, 255, CV_MINMAX, NULL); cvNormalize(singleChannelV, singleChannelV, 0, 255, CV_MINMAX, NULL); } // do scaling to avoid Hue space wrap around (i.e. dark == bright!) // N.B. changing the scaling factor and addition will vary the colour // effect - OpenCV 8-bit Hue in range 0->120 => 0.5 * Hue + 90 maps // all values to (wrap-around) 180->60 range in Hue. cvConvertScale(singleChannelH, singleChannelH, 0.5, 90); // put it all back together in RGB cvMerge(singleChannelH, singleChannelPlain, singleChannelV, NULL, HSV); cvCvtColor(HSV, HSV, CV_HSV2BGR); // display image in window if (useConcatImage){ imshow(windowNameHSV, concatImages(cv::cvarrToMat(img), cv::cvarrToMat(HSV))); } else { if (useFalseColour){ cvShowImage(windowNameHSV, HSV); } else { cvShowImage(windowNameHSV, img); } } // start event processing loop key = cvWaitKey(EVENT_LOOP_DELAY); // process any keyboard input switch (tolower(key)) { case 'x': case 'e': case char(27): // ESC key // if user presses "x" then exit keepProcessing = false; ; break; case 'a': // toggle automatic scaling useNormalisation = (!useNormalisation); ; break; case 'b': // toggle concatenated images useConcatImage = (!useConcatImage); ; break; case 'c': // toggle false colour useFalseColour = (!useFalseColour); ; break; case 'f': // toggle false colour useFullScreen = (!useFullScreen); // set or unset the CV_WINDOW_FULLSCREEN flag via logical AND with toggle boolean cvSetWindowProperty(windowNameHSV, CV_WND_PROP_FULLSCREEN, (CV_WINDOW_FULLSCREEN & useFullScreen)); ; break; } } // destroy window objects cvDestroyAllWindows(); // destroy image object (if it does not originate from a capture object) if (!capture){ cvReleaseImage( &img ); } cvReleaseImage( &HSV ); cvReleaseImage( &singleChannelH ); cvReleaseImage( &singleChannelPlain ); // all OK : main returns 0 return 0; } // not OK : main returns -1 print_help(argv); return -1; } /******************************************************************************/ <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include "io/PPMLoader.hpp" #include "converter/RGBToYCbCrConverter.hpp" #include "converter/YCbCrToRGBConverter.hpp" #include "helper/Test.hpp" #include "Huffman.hpp" #include "DCT.hpp" #include "Arai.hpp" #include <math.h> #include "bitstream/Bitstream.hpp" #include "segments/JPEGSegments.hpp" using namespace JPEGSegments; #define TEST_ITERATIONS 10000000 #define TEST_REPEAT 10 std::vector<int> generateTestHuffman(); // --------------------------------------------------------------- // | // | PPM Image Processing // | // --------------------------------------------------------------- void testImage() { std::cout << "Loading image ..." << std::endl; Test::performance([]{ PPMLoader loader; auto image = loader.load("../data/singapore4k.test.ppm"); // RGBToYCbCrConverter converter1; // converter1.convert(image); // // image->print(); // // image->channel2->reduceBySubSampling( image->imageSize.width, image->imageSize.height ); // image->channel3->reduceBySubSampling( image->imageSize.width, image->imageSize.height ); // // YCbCrToRGBConverter converter2; // converter2.convert(image); // // image->reduceBySubSample(2, 2); // image->reduceByAverage(2, 2); // image->print(); // Test::performance([&loader, &image]{ // loader.write("data/output.test.ppm", image); // }); }); } // --------------------------------------------------------------- // | // | JPEG Writer // | // --------------------------------------------------------------- void testJPEGWriter() { // Bitstream bitStream; // bitStream.add(1); // bitStream.add(0); // bitStream.add(1); // bitStream.add(1); // bitStream.add(0); // bitStream.print(); // bitStream.fillup(1); // bitStream.print(); // bitStream.saveToFile("out.txt"); // // // std::cout << "Testing, Bitstream" << std::endl; // // std::cout << "Write single bit: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [](size_t numberOfElements){ // Bitstream bitstream; // while (numberOfElements--) { // bitstream.add(numberOfElements % 2); // } // }); // // // std::cout << "Write byte bits: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [](size_t numberOfElements){ // Bitstream bitstream; // // bitstream.add(1); // while (numberOfElements--) { // bitstream.add(0xd2, 8); // } // }); // // // // create random bitstream for reading // Bitstream testStream; // size_t fillRandom = TEST_ITERATIONS; // while (fillRandom--) // testStream.add( arc4random() % 2 ); // // // std::cout << "Read single bit: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [&testStream](size_t numberOfElements){ // size_t maxRead = testStream.numberOfBits() - 2; // size_t idx = 0; // while (numberOfElements--) { // testStream.read(idx++); // if (idx > maxRead) // idx = 0; // } // }); // // // std::cout << "Write file: "; // Test::performance([&testStream] { // testStream.saveToFile("../data/writeOleg.txt"); // }); // PPMLoader loader; auto image = loader.load("../data/very_small.ppm"); JPEGWriter writer; auto testData = generateTestHuffman(); Huffman huffman(testData); writer.writeJPEGImage(image, "../data/Test1.test.jpg", huffman.canonicalEncoding(16)); } std::vector<Symbol> getWord() { std::vector<Symbol> input; input.push_back(1); input.push_back(4); input.push_back(6); return input; } void addTestSymbol(int amount, int symbol, std::vector<int> &input) { for (int i = 0; i < amount; ++i) { input.push_back(symbol); } } std::vector<int> generateTestHuffman() { std::vector<int>input; addTestSymbol(5, 1, input); addTestSymbol(12, 5, input); addTestSymbol(13, 6, input); addTestSymbol(6, 2, input); addTestSymbol(8, 3, input); addTestSymbol(8, 4, input); return input; } std::vector<int> generateTestHuffman2() { std::vector<int>input; addTestSymbol(5, 1, input); addTestSymbol(5, 2, input); addTestSymbol(6, 3, input); addTestSymbol(11, 4, input); addTestSymbol(12, 5, input); addTestSymbol(12, 6, input); addTestSymbol(26, 7, input); return input; } void testhuffmann() { std::vector<Symbol> testData; auto input = generateTestHuffman(); Huffman huffman = Huffman(input); huffman.preventAllOnesPath(true); // auto encodingTable = huffman.canonicalEncoding(); auto encodingTable = huffman.canonicalEncoding(4); // Node* rootTree = huffman.standardTree(); Node* rootTree = huffman.treeFromEncodingTable(encodingTable); for (auto pair: encodingTable) { std::cout << pair.first << ": " << pair.second << std::endl; } rootTree->print(); rootTree->exportTree(); Bitstream bitsteam; std::vector<Symbol> word = getWord(); for (int i = 0; i < word.size(); ++i) { Encoding enc = encodingTable.at(word[i]); std::cout << "füge " << enc << " hinzu (" << word[i] << ")" << std::endl; bitsteam.add(enc.code, enc.numberOfBits); } bitsteam.print(); } void testDirectDCT() { Mat input; input.initiate((float[]){ 2, 2, 2, 2 }, 2, 2); Mat out = DCT::transform(input); out.print(); } void testIDCT() { Mat input; input.initiate((float[]){ 2, 2, 2, 2, 2, 2, 2, 2, 2 }, 3, 3); Mat out = DCT::transform2(input); std::cout << "DCT Mat:" << std::endl; out.print(); Mat inverse = DCT::inverse(out); std::cout << "Inverse Mat:" << std::endl; inverse.print(); } void testMat() { Mat a; a.initiate((float[]){ 1, 0, 0, 0, 1, 0, 0, 0, 1}, 3 , 3); Mat b; b.initiate((float[]){ 1, 2, 3, 0, 1, 4, 0, 5, 1}, 3 , 3); Mat c = a * b; c.print(); } void testAraiLine() { float *values = new float[8]; values[0] = 1; values[1] = 7; values[2] = 3; values[3] = 4; values[4] = 5; values[5] = 4; values[6] = 3; values[7] = 2; Arai::transformLine(values); bool test = true; float tolerance = 0.0001; test = test && (fabsf(values[0] - (10.253f)) < tolerance); test = test && (fabsf(values[1] - (0.797218f)) < tolerance); test = test && (fabsf(values[2] - (-2.19761f)) < tolerance); test = test && (fabsf(values[3] - (-0.0377379f)) < tolerance); test = test && (fabsf(values[4] - (-1.76777f)) < tolerance); test = test && (fabsf(values[5] - (-2.75264f)) < tolerance); test = test && (fabsf(values[6] - (-2.53387f)) < tolerance); test = test && (fabsf(values[7] - (-1.13403f)) < tolerance); if ( test ) { std::cout << "All values are correct." << std::endl; } else { std::cout << "Something went wrong." << std::endl; } } void testAraiMatrix() { Mat matrix; matrix.initiate((float[]) { 1, 7, 3, 4, 5, 4, 3, 2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 8, 8); matrix = Arai::transform(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(); } void testTransformations() { Mat matrix; matrix.initiate((float[]) { 1, 7, 3, 4, 5, 4, 3, 2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 8, 8); matrix = DCT::transform(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::transform2(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(); std::cout << std::endl; matrix = Arai::transform(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(); std::cout << std::endl; } // ################################################################ // # // # Main // # // ################################################################ int main(int argc, const char *argv[]) { //testhuffmann(); //testJPEGWriter(); //testDirectDCT(); //testIDCT(); //testMat(); //testImage(); testAraiLine(); testAraiMatrix(); return 0; } <commit_msg>Modified main method<commit_after>#include <iostream> #include <stdlib.h> #include "io/PPMLoader.hpp" #include "converter/RGBToYCbCrConverter.hpp" #include "converter/YCbCrToRGBConverter.hpp" #include "helper/Test.hpp" #include "Huffman.hpp" #include "DCT.hpp" #include "Arai.hpp" #include <math.h> #include "bitstream/Bitstream.hpp" #include "segments/JPEGSegments.hpp" using namespace JPEGSegments; #define TEST_ITERATIONS 10000000 #define TEST_REPEAT 10 std::vector<int> generateTestHuffman(); // --------------------------------------------------------------- // | // | PPM Image Processing // | // --------------------------------------------------------------- void testImage() { std::cout << "Loading image ..." << std::endl; Test::performance([]{ PPMLoader loader; auto image = loader.load("../data/singapore4k.test.ppm"); // RGBToYCbCrConverter converter1; // converter1.convert(image); // // image->print(); // // image->channel2->reduceBySubSampling( image->imageSize.width, image->imageSize.height ); // image->channel3->reduceBySubSampling( image->imageSize.width, image->imageSize.height ); // // YCbCrToRGBConverter converter2; // converter2.convert(image); // // image->reduceBySubSample(2, 2); // image->reduceByAverage(2, 2); // image->print(); // Test::performance([&loader, &image]{ // loader.write("data/output.test.ppm", image); // }); }); } // --------------------------------------------------------------- // | // | JPEG Writer // | // --------------------------------------------------------------- void testJPEGWriter() { // Bitstream bitStream; // bitStream.add(1); // bitStream.add(0); // bitStream.add(1); // bitStream.add(1); // bitStream.add(0); // bitStream.print(); // bitStream.fillup(1); // bitStream.print(); // bitStream.saveToFile("out.txt"); // // // std::cout << "Testing, Bitstream" << std::endl; // // std::cout << "Write single bit: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [](size_t numberOfElements){ // Bitstream bitstream; // while (numberOfElements--) { // bitstream.add(numberOfElements % 2); // } // }); // // // std::cout << "Write byte bits: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [](size_t numberOfElements){ // Bitstream bitstream; // // bitstream.add(1); // while (numberOfElements--) { // bitstream.add(0xd2, 8); // } // }); // // // // create random bitstream for reading // Bitstream testStream; // size_t fillRandom = TEST_ITERATIONS; // while (fillRandom--) // testStream.add( arc4random() % 2 ); // // // std::cout << "Read single bit: "; // Test::performance(TEST_ITERATIONS, TEST_REPEAT, [&testStream](size_t numberOfElements){ // size_t maxRead = testStream.numberOfBits() - 2; // size_t idx = 0; // while (numberOfElements--) { // testStream.read(idx++); // if (idx > maxRead) // idx = 0; // } // }); // // // std::cout << "Write file: "; // Test::performance([&testStream] { // testStream.saveToFile("../data/writeOleg.txt"); // }); // PPMLoader loader; auto image = loader.load("../data/very_small.ppm"); JPEGWriter writer; auto testData = generateTestHuffman(); Huffman huffman(testData); writer.writeJPEGImage(image, "../data/Test1.test.jpg", huffman.canonicalEncoding(16)); } std::vector<Symbol> getWord() { std::vector<Symbol> input; input.push_back(1); input.push_back(4); input.push_back(6); return input; } void addTestSymbol(int amount, int symbol, std::vector<int> &input) { for (int i = 0; i < amount; ++i) { input.push_back(symbol); } } std::vector<int> generateTestHuffman() { std::vector<int>input; addTestSymbol(5, 1, input); addTestSymbol(12, 5, input); addTestSymbol(13, 6, input); addTestSymbol(6, 2, input); addTestSymbol(8, 3, input); addTestSymbol(8, 4, input); return input; } std::vector<int> generateTestHuffman2() { std::vector<int>input; addTestSymbol(5, 1, input); addTestSymbol(5, 2, input); addTestSymbol(6, 3, input); addTestSymbol(11, 4, input); addTestSymbol(12, 5, input); addTestSymbol(12, 6, input); addTestSymbol(26, 7, input); return input; } void testhuffmann() { std::vector<Symbol> testData; auto input = generateTestHuffman(); Huffman huffman = Huffman(input); huffman.preventAllOnesPath(true); // auto encodingTable = huffman.canonicalEncoding(); auto encodingTable = huffman.canonicalEncoding(4); // Node* rootTree = huffman.standardTree(); Node* rootTree = huffman.treeFromEncodingTable(encodingTable); for (auto pair: encodingTable) { std::cout << pair.first << ": " << pair.second << std::endl; } rootTree->print(); rootTree->exportTree(); Bitstream bitsteam; std::vector<Symbol> word = getWord(); for (int i = 0; i < word.size(); ++i) { Encoding enc = encodingTable.at(word[i]); std::cout << "füge " << enc << " hinzu (" << word[i] << ")" << std::endl; bitsteam.add(enc.code, enc.numberOfBits); } bitsteam.print(); } void testDirectDCT() { Mat input; input.initiate((float[]){ 2, 2, 2, 2 }, 2, 2); Mat out = DCT::transform(input); out.print(); } void testIDCT() { Mat input; input.initiate((float[]){ 2, 2, 2, 2, 2, 2, 2, 2, 2 }, 3, 3); Mat out = DCT::transform2(input); std::cout << "DCT Mat:" << std::endl; out.print(); Mat inverse = DCT::inverse(out); std::cout << "Inverse Mat:" << std::endl; inverse.print(); } void testMat() { Mat a; a.initiate((float[]){ 1, 0, 0, 0, 1, 0, 0, 0, 1}, 3 , 3); Mat b; b.initiate((float[]){ 1, 2, 3, 0, 1, 4, 0, 5, 1}, 3 , 3); Mat c = a * b; c.print(); } void testAraiLine() { float *values = new float[8]; values[0] = 1; values[1] = 7; values[2] = 3; values[3] = 4; values[4] = 5; values[5] = 4; values[6] = 3; values[7] = 2; Arai::transformLine(values); bool test = true; float tolerance = 0.0001; test = test && (fabsf(values[0] - (10.253f)) < tolerance); test = test && (fabsf(values[1] - (0.797218f)) < tolerance); test = test && (fabsf(values[2] - (-2.19761f)) < tolerance); test = test && (fabsf(values[3] - (-0.0377379f)) < tolerance); test = test && (fabsf(values[4] - (-1.76777f)) < tolerance); test = test && (fabsf(values[5] - (-2.75264f)) < tolerance); test = test && (fabsf(values[6] - (-2.53387f)) < tolerance); test = test && (fabsf(values[7] - (-1.13403f)) < tolerance); if ( test ) { std::cout << "All values are correct." << std::endl; } else { std::cout << "Something went wrong." << std::endl; } } void testAraiMatrix() { Mat matrix; matrix.initiate((float[]) { 1, 7, 3, 4, 5, 4, 3, 2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 8, 8); matrix = Arai::transform(matrix); matrix.print(); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(); } void testTransformations(int digits = 5) { Mat matrix; matrix.initiate((float[]) { 1, 7, 3, 4, 5, 4, 3, 2, 7, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 8, 8); matrix = DCT::transform(matrix); matrix.print(digits); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(digits); std::cout << std::endl; matrix = DCT::transform2(matrix); matrix.print(digits); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(digits); std::cout << std::endl; matrix = Arai::transform(matrix); matrix.print(digits); std::cout << std::endl; matrix = DCT::inverse(matrix); matrix.print(digits); std::cout << std::endl; } // ################################################################ // # // # Main // # // ################################################################ int main(int argc, const char *argv[]) { //testhuffmann(); //testJPEGWriter(); //testDirectDCT(); //testIDCT(); //testMat(); //testImage(); // testAraiLine(); // testAraiMatrix(); testTransformations(0); return 0; } <|endoftext|>
<commit_before>//===--- Alloc.cpp - Swift Language ABI Allocation Support ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Allocation ABI Shims While the Language is Bootstrapped // //===----------------------------------------------------------------------===// #include "Alloc.h" #include <stdlib.h> #include <unistd.h> struct SwiftHeapObject * swift_alloc(struct SwiftHeapMetadata *metadata, size_t requiredSize, size_t requiredAlignment) { size_t mask = requiredAlignment - 1; struct SwiftHeapMetadata **object; for (;;) { object = reinterpret_cast<struct SwiftHeapMetadata **>( calloc(1, (requiredSize + mask) & ~mask)); if (object) { break; } sleep(1); // XXX FIXME -- Enqueue this thread and resume after free() } *object = metadata; return reinterpret_cast<struct SwiftHeapObject *>(object); } struct SwiftHeapObject * swift_retain(struct SwiftHeapObject *object) { if (!object) { return NULL; } ++object->runtimePrivateData; return object; } void swift_release(struct SwiftHeapObject *object) { if (!object) { return; } if (--object->runtimePrivateData > 0) { return; } size_t allocSize = object->metadata->destroy(object); if (allocSize) { swift_dealloc(object, allocSize); } } void swift_dealloc(struct SwiftHeapObject *object, size_t allocatedSize) { free(object); } <commit_msg>switch to c++-style standard header.<commit_after>//===--- Alloc.cpp - Swift Language ABI Allocation Support ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Allocation ABI Shims While the Language is Bootstrapped // //===----------------------------------------------------------------------===// #include "Alloc.h" #include <cstdlib> #include <unistd.h> struct SwiftHeapObject * swift_alloc(struct SwiftHeapMetadata *metadata, size_t requiredSize, size_t requiredAlignment) { size_t mask = requiredAlignment - 1; struct SwiftHeapMetadata **object; for (;;) { object = reinterpret_cast<struct SwiftHeapMetadata **>( calloc(1, (requiredSize + mask) & ~mask)); if (object) { break; } sleep(1); // XXX FIXME -- Enqueue this thread and resume after free() } *object = metadata; return reinterpret_cast<struct SwiftHeapObject *>(object); } struct SwiftHeapObject * swift_retain(struct SwiftHeapObject *object) { if (!object) { return NULL; } ++object->runtimePrivateData; return object; } void swift_release(struct SwiftHeapObject *object) { if (!object) { return; } if (--object->runtimePrivateData > 0) { return; } size_t allocSize = object->metadata->destroy(object); if (allocSize) { swift_dealloc(object, allocSize); } } void swift_dealloc(struct SwiftHeapObject *object, size_t allocatedSize) { free(object); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xformsexport.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:12:03 $ * * 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 _XMLOFF_XFORMSEXPORT_HXX #define _XMLOFF_XFORMSEXPORT_HXX class SvXMLExport; namespace com { namespace sun { namespace star { namespace uno { template<typename T> class Reference; } namespace frame { class XModel; } namespace beans { class XPropertySet; } } } } namespace rtl { class OUString; } /** export an XForms model. */ void SAL_DLLPRIVATE exportXForms( SvXMLExport& ); rtl::OUString SAL_DLLPRIVATE getXFormsBindName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); rtl::OUString SAL_DLLPRIVATE getXFormsListBindName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); rtl::OUString SAL_DLLPRIVATE getXFormsSubmissionName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); #endif <commit_msg>INTEGRATION: CWS warnings01 (1.4.34); FILE MERGED 2005/11/04 14:50:28 cl 1.4.34.1: warning free code changes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xformsexport.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 17:57:59 $ * * 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 _XMLOFF_XFORMSEXPORT_HXX #define _XMLOFF_XFORMSEXPORT_HXX #ifndef INCLUDED_XMLOFF_DLLAPI_H #include "xmloff/dllapi.h" #endif class SvXMLExport; namespace com { namespace sun { namespace star { namespace uno { template<typename T> class Reference; } namespace frame { class XModel; } namespace beans { class XPropertySet; } } } } namespace rtl { class OUString; } /** export an XForms model. */ void SAL_DLLPRIVATE exportXForms( SvXMLExport& ); rtl::OUString SAL_DLLPRIVATE getXFormsBindName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); rtl::OUString SAL_DLLPRIVATE getXFormsListBindName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); rtl::OUString SAL_DLLPRIVATE getXFormsSubmissionName( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& xBinding ); #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: registerservices.cxx,v $ * * $Revision: 1.30 $ * * last change: $Author: vg $ $Date: 2005-02-16 16:42:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // includes of my own project //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_ #include <macros/registration.hxx> #endif /*================================================================================================================= Add new include and new register info to for new services. Example: #ifndef __YOUR_SERVICE_1_HXX_ #include <service1.hxx> #endif #ifndef __YOUR_SERVICE_2_HXX_ #include <service2.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( Service1 ) COMPONENTINFO( Service2 ) ) COMPONENTGETFACTORY ( IFFACTORIE( Service1 ) else IFFACTORIE( Service2 ) ) =================================================================================================================*/ #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #include <services/urltransformer.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_ #include <services/desktop.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_ #include <services/documentproperties.hxx> #endif #ifndef __FRAMEWORK_SERVICES_FRAME_HXX_ #include <services/frame.hxx> #endif #ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_ #include <services/modulemanager.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_ #include <dispatch/soundhandler.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_ #include <recording/dispatchrecordersupplier.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_ #include <dispatch/servicehandler.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_ #include <jobs/jobdispatch.hxx> #endif #ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_ #include <services/backingcomp.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_ #include <services/dispatchhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_ #include <services/layoutmanager.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_ #include <services/license.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_ #include <uifactory/uielementfactorymanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_ #include <uifactory/popupmenucontrollerfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_ #include <uielement/fontmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_ #include <uielement/fontsizemenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_ #include <uielement/objectmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_ #include <uielement/headermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_ #include <uielement/footermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_ #include <uielement/controlmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_ #include <uielement/macrosmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_ #include <uielement/uicommanddescription.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #include <uiconfiguration/uiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_ #include <uiconfiguration/moduleuicfgsupplier.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_ #include <uiconfiguration/moduleuiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_ #include <uifactory/menubarfactory.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_ #include <accelerators/globalacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_ #include <accelerators/moduleacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_ #include <accelerators/documentacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_ #include <uifactory/addonstoolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_ #include "uiconfiguration/windowstateconfiguration.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_ #include "uifactory/toolbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_ #include "uifactory/statusbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_ #include <services/autorecovery.hxx> #endif #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_ #include <helper/statusindicatorfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_ #include <uielement/recentfilesmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_ #include <uifactory/statusbarfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_ #include <uiconfiguration/uicategorydescription.hxx> #endif #ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_ #include <services/sessionlistener.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_NEWMENUCONTROLLER_HXX_ #include <uielement/newmenucontroller.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer ) COMPONENTINFO( ::framework::Desktop ) COMPONENTINFO( ::framework::Frame ) COMPONENTINFO( ::framework::DocumentProperties ) COMPONENTINFO( ::framework::SoundHandler ) COMPONENTINFO( ::framework::JobExecutor ) COMPONENTINFO( ::framework::DispatchRecorderSupplier ) COMPONENTINFO( ::framework::DispatchRecorder ) COMPONENTINFO( ::framework::MailToDispatcher ) COMPONENTINFO( ::framework::ServiceHandler ) COMPONENTINFO( ::framework::JobDispatch ) COMPONENTINFO( ::framework::BackingComp ) COMPONENTINFO( ::framework::DispatchHelper ) COMPONENTINFO( ::framework::LayoutManager ) COMPONENTINFO( ::framework::License ) COMPONENTINFO( ::framework::UIElementFactoryManager ) COMPONENTINFO( ::framework::PopupMenuControllerFactory ) COMPONENTINFO( ::framework::FontMenuController ) COMPONENTINFO( ::framework::FontSizeMenuController ) COMPONENTINFO( ::framework::ObjectMenuController ) COMPONENTINFO( ::framework::HeaderMenuController ) COMPONENTINFO( ::framework::FooterMenuController ) COMPONENTINFO( ::framework::ControlMenuController ) COMPONENTINFO( ::framework::MacrosMenuController ) COMPONENTINFO( ::framework::UICommandDescription ) COMPONENTINFO( ::framework::ModuleManager ) COMPONENTINFO( ::framework::UIConfigurationManager ) COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier ) COMPONENTINFO( ::framework::ModuleUIConfigurationManager ) COMPONENTINFO( ::framework::MenuBarFactory ) COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration ) COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration ) COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration ) COMPONENTINFO( ::framework::ToolBoxFactory ) COMPONENTINFO( ::framework::AddonsToolBoxFactory ) COMPONENTINFO( ::framework::WindowStateConfiguration ) COMPONENTINFO( ::framework::ToolbarControllerFactory ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::AutoRecovery ) COMPONENTINFO( ::framework::StatusIndicatorFactory ) COMPONENTINFO( ::framework::RecentFilesMenuController ) COMPONENTINFO( ::framework::StatusBarFactory ) COMPONENTINFO( ::framework::UICategoryDescription ) COMPONENTINFO( ::framework::StatusbarControllerFactory ) COMPONENTINFO( ::framework::SessionListener ) COMPONENTINFO( ::framework::NewMenuController ) ) COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else IFFACTORY( ::framework::Desktop ) else IFFACTORY( ::framework::Frame ) else IFFACTORY( ::framework::DocumentProperties ) else IFFACTORY( ::framework::SoundHandler ) else IFFACTORY( ::framework::JobExecutor ) else IFFACTORY( ::framework::DispatchRecorderSupplier ) else IFFACTORY( ::framework::DispatchRecorder ) else IFFACTORY( ::framework::MailToDispatcher ) else IFFACTORY( ::framework::ServiceHandler ) else IFFACTORY( ::framework::JobDispatch ) else IFFACTORY( ::framework::BackingComp ) else IFFACTORY( ::framework::DispatchHelper ) else IFFACTORY( ::framework::LayoutManager ) else IFFACTORY( ::framework::License ) else IFFACTORY( ::framework::UIElementFactoryManager ) else IFFACTORY( ::framework::PopupMenuControllerFactory ) else IFFACTORY( ::framework::FontMenuController ) else IFFACTORY( ::framework::FontSizeMenuController ) else IFFACTORY( ::framework::ObjectMenuController ) else IFFACTORY( ::framework::HeaderMenuController ) else IFFACTORY( ::framework::FooterMenuController ) else IFFACTORY( ::framework::ControlMenuController ) else IFFACTORY( ::framework::MacrosMenuController ) else IFFACTORY( ::framework::UICommandDescription ) else IFFACTORY( ::framework::ModuleManager ) else IFFACTORY( ::framework::UIConfigurationManager ) else IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else IFFACTORY( ::framework::ModuleUIConfigurationManager ) else IFFACTORY( ::framework::MenuBarFactory ) else IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else IFFACTORY( ::framework::ToolBoxFactory ) else IFFACTORY( ::framework::AddonsToolBoxFactory ) else IFFACTORY( ::framework::WindowStateConfiguration ) else IFFACTORY( ::framework::ToolbarControllerFactory ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::AutoRecovery ) else IFFACTORY( ::framework::StatusIndicatorFactory ) else IFFACTORY( ::framework::RecentFilesMenuController ) else IFFACTORY( ::framework::StatusBarFactory ) else IFFACTORY( ::framework::UICategoryDescription ) else IFFACTORY( ::framework::SessionListener ) else IFFACTORY( ::framework::StatusbarControllerFactory ) else IFFACTORY( ::framework::NewMenuController ) ) <commit_msg>INTEGRATION: CWS c01v005 (1.29.26); FILE MERGED 2005/03/05 00:31:27 hjs 1.29.26.2: RESYNC: (1.29-1.30); FILE MERGED 2005/02/22 17:01:19 cd 1.29.26.1: #119876# new statusbar logo controllers<commit_after>/************************************************************************* * * $RCSfile: registerservices.cxx,v $ * * $Revision: 1.31 $ * * last change: $Author: obo $ $Date: 2005-03-15 12:57:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // includes of my own project //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_ #include <macros/registration.hxx> #endif /*================================================================================================================= Add new include and new register info to for new services. Example: #ifndef __YOUR_SERVICE_1_HXX_ #include <service1.hxx> #endif #ifndef __YOUR_SERVICE_2_HXX_ #include <service2.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( Service1 ) COMPONENTINFO( Service2 ) ) COMPONENTGETFACTORY ( IFFACTORIE( Service1 ) else IFFACTORIE( Service2 ) ) =================================================================================================================*/ #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #include <services/urltransformer.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_ #include <services/desktop.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_ #include <services/documentproperties.hxx> #endif #ifndef __FRAMEWORK_SERVICES_FRAME_HXX_ #include <services/frame.hxx> #endif #ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_ #include <services/modulemanager.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_ #include <jobs/jobexecutor.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_ #include <dispatch/soundhandler.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_ #include <recording/dispatchrecordersupplier.hxx> #endif #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_ #include <dispatch/mailtodispatcher.hxx> #endif #ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_ #include <dispatch/servicehandler.hxx> #endif #ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_ #include <jobs/jobdispatch.hxx> #endif #ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_ #include <services/backingcomp.hxx> #endif #ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_ #include <services/dispatchhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_ #include <services/layoutmanager.hxx> #endif #ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_ #include <services/license.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_ #include <uifactory/uielementfactorymanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_ #include <uifactory/popupmenucontrollerfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_ #include <uielement/fontmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_ #include <uielement/fontsizemenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_ #include <uielement/objectmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_ #include <uielement/headermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_ #include <uielement/footermenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_ #include <uielement/controlmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_ #include <uielement/macrosmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_ #include <uielement/uicommanddescription.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #include <uiconfiguration/uiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_ #include <uiconfiguration/moduleuicfgsupplier.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_ #include <uiconfiguration/moduleuiconfigurationmanager.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_ #include <uifactory/menubarfactory.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_ #include <accelerators/globalacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_ #include <accelerators/moduleacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_ #include <accelerators/documentacceleratorconfiguration.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_ #include <uifactory/addonstoolboxfactory.hxx> #endif #ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_ #include "uiconfiguration/windowstateconfiguration.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_ #include "uifactory/toolbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_ #include "uifactory/statusbarcontrollerfactory.hxx" #endif #ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_ #include <uielement/toolbarsmenucontroller.hxx> #endif #ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_ #include <services/autorecovery.hxx> #endif #ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_ #include <helper/statusindicatorfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_ #include <uielement/recentfilesmenucontroller.hxx> #endif #ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_ #include <uifactory/statusbarfactory.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_ #include <uiconfiguration/uicategorydescription.hxx> #endif #ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_ #include <services/sessionlistener.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_LOGOIMAGESTATUSBARCONTROLLER_HXX_ #include <uielement/logoimagestatusbarcontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_LOGOTEXTSTATUSBARCONTROLLER_HXX_ #include <uielement/logotextstatusbarcontroller.hxx> #endif #ifndef __FRAMEWORK_UIELEMENT_NEWMENUCONTROLLER_HXX_ #include <uielement/newmenucontroller.hxx> #endif COMPONENTGETIMPLEMENTATIONENVIRONMENT COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer ) COMPONENTINFO( ::framework::Desktop ) COMPONENTINFO( ::framework::Frame ) COMPONENTINFO( ::framework::DocumentProperties ) COMPONENTINFO( ::framework::SoundHandler ) COMPONENTINFO( ::framework::JobExecutor ) COMPONENTINFO( ::framework::DispatchRecorderSupplier ) COMPONENTINFO( ::framework::DispatchRecorder ) COMPONENTINFO( ::framework::MailToDispatcher ) COMPONENTINFO( ::framework::ServiceHandler ) COMPONENTINFO( ::framework::JobDispatch ) COMPONENTINFO( ::framework::BackingComp ) COMPONENTINFO( ::framework::DispatchHelper ) COMPONENTINFO( ::framework::LayoutManager ) COMPONENTINFO( ::framework::License ) COMPONENTINFO( ::framework::UIElementFactoryManager ) COMPONENTINFO( ::framework::PopupMenuControllerFactory ) COMPONENTINFO( ::framework::FontMenuController ) COMPONENTINFO( ::framework::FontSizeMenuController ) COMPONENTINFO( ::framework::ObjectMenuController ) COMPONENTINFO( ::framework::HeaderMenuController ) COMPONENTINFO( ::framework::FooterMenuController ) COMPONENTINFO( ::framework::ControlMenuController ) COMPONENTINFO( ::framework::MacrosMenuController ) COMPONENTINFO( ::framework::UICommandDescription ) COMPONENTINFO( ::framework::ModuleManager ) COMPONENTINFO( ::framework::UIConfigurationManager ) COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier ) COMPONENTINFO( ::framework::ModuleUIConfigurationManager ) COMPONENTINFO( ::framework::MenuBarFactory ) COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration ) COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration ) COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration ) COMPONENTINFO( ::framework::ToolBoxFactory ) COMPONENTINFO( ::framework::AddonsToolBoxFactory ) COMPONENTINFO( ::framework::WindowStateConfiguration ) COMPONENTINFO( ::framework::ToolbarControllerFactory ) COMPONENTINFO( ::framework::ToolbarsMenuController ) COMPONENTINFO( ::framework::AutoRecovery ) COMPONENTINFO( ::framework::StatusIndicatorFactory ) COMPONENTINFO( ::framework::RecentFilesMenuController ) COMPONENTINFO( ::framework::StatusBarFactory ) COMPONENTINFO( ::framework::UICategoryDescription ) COMPONENTINFO( ::framework::StatusbarControllerFactory ) COMPONENTINFO( ::framework::SessionListener ) COMPONENTINFO( ::framework::LogoImageStatusbarController ) COMPONENTINFO( ::framework::LogoTextStatusbarController ) COMPONENTINFO( ::framework::NewMenuController ) ) COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else IFFACTORY( ::framework::Desktop ) else IFFACTORY( ::framework::Frame ) else IFFACTORY( ::framework::DocumentProperties ) else IFFACTORY( ::framework::SoundHandler ) else IFFACTORY( ::framework::JobExecutor ) else IFFACTORY( ::framework::DispatchRecorderSupplier ) else IFFACTORY( ::framework::DispatchRecorder ) else IFFACTORY( ::framework::MailToDispatcher ) else IFFACTORY( ::framework::ServiceHandler ) else IFFACTORY( ::framework::JobDispatch ) else IFFACTORY( ::framework::BackingComp ) else IFFACTORY( ::framework::DispatchHelper ) else IFFACTORY( ::framework::LayoutManager ) else IFFACTORY( ::framework::License ) else IFFACTORY( ::framework::UIElementFactoryManager ) else IFFACTORY( ::framework::PopupMenuControllerFactory ) else IFFACTORY( ::framework::FontMenuController ) else IFFACTORY( ::framework::FontSizeMenuController ) else IFFACTORY( ::framework::ObjectMenuController ) else IFFACTORY( ::framework::HeaderMenuController ) else IFFACTORY( ::framework::FooterMenuController ) else IFFACTORY( ::framework::ControlMenuController ) else IFFACTORY( ::framework::MacrosMenuController ) else IFFACTORY( ::framework::UICommandDescription ) else IFFACTORY( ::framework::ModuleManager ) else IFFACTORY( ::framework::UIConfigurationManager ) else IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else IFFACTORY( ::framework::ModuleUIConfigurationManager ) else IFFACTORY( ::framework::MenuBarFactory ) else IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else IFFACTORY( ::framework::ToolBoxFactory ) else IFFACTORY( ::framework::AddonsToolBoxFactory ) else IFFACTORY( ::framework::WindowStateConfiguration ) else IFFACTORY( ::framework::ToolbarControllerFactory ) else IFFACTORY( ::framework::ToolbarsMenuController ) else IFFACTORY( ::framework::AutoRecovery ) else IFFACTORY( ::framework::StatusIndicatorFactory ) else IFFACTORY( ::framework::RecentFilesMenuController ) else IFFACTORY( ::framework::StatusBarFactory ) else IFFACTORY( ::framework::UICategoryDescription ) else IFFACTORY( ::framework::SessionListener ) else IFFACTORY( ::framework::StatusbarControllerFactory ) else IFFACTORY( ::framework::SessionListener ) else IFFACTORY( ::framework::LogoImageStatusbarController ) else IFFACTORY( ::framework::LogoTextStatusbarController ) else IFFACTORY( ::framework::NewMenuController ) ) <|endoftext|>
<commit_before>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio 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 // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __math_explog_hpp__ # define __math_explog_hpp__ # include <Eigen/Geometry> # include "pinocchio/math/sincos.hpp" # include "pinocchio/spatial/motion.hpp" # include "pinocchio/spatial/skew.hpp" # include "pinocchio/spatial/se3.hpp" namespace se3 { /// \brief Exp: so3 -> SO3. /// /// Return the integral of the input angular velocity during time 1. template <typename D> Eigen::Matrix<typename D::Scalar,3,3,D::Options> exp3(const Eigen::MatrixBase<D> & v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,3); return Eigen::AngleAxis<typename D::Scalar>(v.norm(), v).matrix(); } /// \brief Log: SO3 -> so3. /// /// Pseudo-inverse of log from SO3 -> { v \in so3, ||v|| < 2pi }. template <typename D> Eigen::Matrix<typename D::Scalar,3,1,D::Options> log3(const Eigen::MatrixBase<D> & R) { EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(D, 3, 3); Eigen::AngleAxis<typename D::Scalar> angleAxis(R); return angleAxis.axis() * angleAxis.angle(); } /// \brief Exp: se3 -> SE3. /// /// Return the integral of the input spatial velocity during time 1. template <typename _Scalar, int _Options> SE3Tpl<_Scalar, _Options> exp6(const MotionTpl<_Scalar,_Options> & nu) { typedef _Scalar Scalar; typedef typename MotionTpl<Scalar,_Options>::Vector3 Vector3; typedef typename MotionTpl<Scalar,_Options>::Matrix3 Matrix3; const Vector3 & w = nu.angular(); const Vector3 & v = nu.linear(); Scalar t = w.norm(); if (t > 1e-15) { Matrix3 R(exp3(w)); Matrix3 S(skew(w)); Matrix3 V( Matrix3::Identity() + (1 - cos(t)) / (t * t) * S + (t - sin(t)) / (t * t * t) * S * S); Vector3 p(V * v); return SE3Tpl<_Scalar, _Options>(R, p); } else { return SE3Tpl<_Scalar, _Options>(Matrix3::Identity(), v); } } /// \brief Exp: se3 -> SE3. /// /// Return the integral of the input spatial velocity during time 1. template <typename D> Eigen::Matrix<typename D::Scalar,6,6,D::Options> exp6(const Eigen::MatrixBase<D> & v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,6); MotionTpl<typename D::Scalar,D::Options> nu(v); SE3Tpl<typename D::Scalar,D::Options> m(exp6(nu)); return m.toActionMatrix(); } /// \brief Log: SE3 -> se3. /// /// Pseudo-inverse of exp from SE3 -> { v,w \in se3, ||w|| < 2pi }. template <typename _Scalar, int _Options> MotionTpl<_Scalar,_Options> log6(const SE3Tpl<_Scalar, _Options> & m) { typedef _Scalar Scalar; typedef typename SE3Tpl<Scalar,_Options>::Vector3 Vector3; typedef typename SE3Tpl<Scalar,_Options>::Matrix3 Matrix3; const Matrix3 & R = m.rotation(); const Vector3 & p = m.translation(); Vector3 w(log3(R)); Vector3 v; Scalar t = w.norm(); if (t > 1e-15) { Matrix3 S(skew(w)); Matrix3 V( Matrix3::Identity() + (1 - cos(t)) / (t * t) * S + (t - sin(t)) / (t * t * t) * S * S); v = V.inverse() * p; } else { v = p; } return MotionTpl<_Scalar,_Options>(v, w); } /// \brief Log: SE3 -> se3. /// /// Pseudo-inverse of exp from SE3 -> { v,w \in se3, ||w|| < 2pi }. template <typename D> Eigen::Matrix<typename D::Scalar,6,1,D::Options> log6(const Eigen::MatrixBase<D> & M) { EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(D, 6, 6); typedef typename SE3Tpl<typename D::Scalar,D::Options>::Vector3 Vector3; typedef typename SE3Tpl<typename D::Scalar,D::Options>::Matrix3 Matrix3; enum { LINEAR = SE3Tpl<typename D::Scalar,D::Options>::LINEAR, ANGULAR = SE3Tpl<typename D::Scalar,D::Options>::ANGULAR }; Matrix3 rot(M.template block<3,3>(ANGULAR,ANGULAR)); Matrix3 skew(M.template block<3,3>(LINEAR,ANGULAR) * rot.transpose()); Vector3 trans(skew(2,1), skew(0,2), skew(1,0)); SE3Tpl<typename D::Scalar,D::Options> m(rot, trans); MotionTpl<typename D::Scalar,D::Options> nu(log6(m)); return nu.toVector(); } } // namespace se3 #endif //#ifndef __math_explog_hpp__ <commit_msg>[Minor] Update copyright in explog.hpp.<commit_after>// // Copyright (c) 2015 CNRS // Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France. // // This file is part of Pinocchio // Pinocchio 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 // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __math_explog_hpp__ # define __math_explog_hpp__ # include <Eigen/Geometry> # include "pinocchio/math/sincos.hpp" # include "pinocchio/spatial/motion.hpp" # include "pinocchio/spatial/skew.hpp" # include "pinocchio/spatial/se3.hpp" namespace se3 { /// \brief Exp: so3 -> SO3. /// /// Return the integral of the input angular velocity during time 1. template <typename D> Eigen::Matrix<typename D::Scalar,3,3,D::Options> exp3(const Eigen::MatrixBase<D> & v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,3); return Eigen::AngleAxis<typename D::Scalar>(v.norm(), v).matrix(); } /// \brief Log: SO3 -> so3. /// /// Pseudo-inverse of log from SO3 -> { v \in so3, ||v|| < 2pi }. template <typename D> Eigen::Matrix<typename D::Scalar,3,1,D::Options> log3(const Eigen::MatrixBase<D> & R) { EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(D, 3, 3); Eigen::AngleAxis<typename D::Scalar> angleAxis(R); return angleAxis.axis() * angleAxis.angle(); } /// \brief Exp: se3 -> SE3. /// /// Return the integral of the input spatial velocity during time 1. template <typename _Scalar, int _Options> SE3Tpl<_Scalar, _Options> exp6(const MotionTpl<_Scalar,_Options> & nu) { typedef _Scalar Scalar; typedef typename MotionTpl<Scalar,_Options>::Vector3 Vector3; typedef typename MotionTpl<Scalar,_Options>::Matrix3 Matrix3; const Vector3 & w = nu.angular(); const Vector3 & v = nu.linear(); Scalar t = w.norm(); if (t > 1e-15) { Matrix3 R(exp3(w)); Matrix3 S(skew(w)); Matrix3 V( Matrix3::Identity() + (1 - cos(t)) / (t * t) * S + (t - sin(t)) / (t * t * t) * S * S); Vector3 p(V * v); return SE3Tpl<_Scalar, _Options>(R, p); } else { return SE3Tpl<_Scalar, _Options>(Matrix3::Identity(), v); } } /// \brief Exp: se3 -> SE3. /// /// Return the integral of the input spatial velocity during time 1. template <typename D> Eigen::Matrix<typename D::Scalar,6,6,D::Options> exp6(const Eigen::MatrixBase<D> & v) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(D,6); MotionTpl<typename D::Scalar,D::Options> nu(v); SE3Tpl<typename D::Scalar,D::Options> m(exp6(nu)); return m.toActionMatrix(); } /// \brief Log: SE3 -> se3. /// /// Pseudo-inverse of exp from SE3 -> { v,w \in se3, ||w|| < 2pi }. template <typename _Scalar, int _Options> MotionTpl<_Scalar,_Options> log6(const SE3Tpl<_Scalar, _Options> & m) { typedef _Scalar Scalar; typedef typename SE3Tpl<Scalar,_Options>::Vector3 Vector3; typedef typename SE3Tpl<Scalar,_Options>::Matrix3 Matrix3; const Matrix3 & R = m.rotation(); const Vector3 & p = m.translation(); Vector3 w(log3(R)); Vector3 v; Scalar t = w.norm(); if (t > 1e-15) { Matrix3 S(skew(w)); Matrix3 V( Matrix3::Identity() + (1 - cos(t)) / (t * t) * S + (t - sin(t)) / (t * t * t) * S * S); v = V.inverse() * p; } else { v = p; } return MotionTpl<_Scalar,_Options>(v, w); } /// \brief Log: SE3 -> se3. /// /// Pseudo-inverse of exp from SE3 -> { v,w \in se3, ||w|| < 2pi }. template <typename D> Eigen::Matrix<typename D::Scalar,6,1,D::Options> log6(const Eigen::MatrixBase<D> & M) { EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(D, 6, 6); typedef typename SE3Tpl<typename D::Scalar,D::Options>::Vector3 Vector3; typedef typename SE3Tpl<typename D::Scalar,D::Options>::Matrix3 Matrix3; enum { LINEAR = SE3Tpl<typename D::Scalar,D::Options>::LINEAR, ANGULAR = SE3Tpl<typename D::Scalar,D::Options>::ANGULAR }; Matrix3 rot(M.template block<3,3>(ANGULAR,ANGULAR)); Matrix3 skew(M.template block<3,3>(LINEAR,ANGULAR) * rot.transpose()); Vector3 trans(skew(2,1), skew(0,2), skew(1,0)); SE3Tpl<typename D::Scalar,D::Options> m(rot, trans); MotionTpl<typename D::Scalar,D::Options> nu(log6(m)); return nu.toVector(); } } // namespace se3 #endif //#ifndef __math_explog_hpp__ <|endoftext|>
<commit_before>#include <stdio.h> #include "sprocket.h" #define DEBUG 0 int main(int argc, char ** argv) { int i; char mode; char origin; char input[128]; char outfile[128]; char infile[128]; FILE * source; FILE * dest; for(i = 0; i < 25; i++) printf("\n"); printf("Welcome to Sprocket\n-------------------\n\n"); while(1) { printf("What do you want to do?\n\n\t1. Reverse File\n\t2. Binary to ASM\n\t9. Quit\n\n"); mode = getMode(); if(mode == '9') { break; } printf("Enter the name of the file to process (.bin):\n"); scanf("%s", input); sprintf(infile, "%s.bin", input); source = fopen(infile, "rb"); if(!source) { printf("Could not open file: %s", input[1]); getchar(); return 0; } if(mode == '1') { sprintf(outfile, "%s_r.bin", input); dest = fopen(outfile, "wb"); if(!dest) { printf("Could not open file for output: %s", outfile); getchar(); return 0; } } else if(mode == '2') { printf("Enter the name of the file to create:\n"); scanf("%s", outfile); dest = fopen(outfile, "wb"); if(!dest) { printf("Could not open file for output: %s", outfile); getchar(); return 0; } printf("Top left origin (1) or centered (2)?\n"); origin = getMode(); } if(mode == '1') reverseFile(source, dest); else if(mode == '2') bin2asm(input, source, dest, origin); fclose(source); fclose(dest); } printf("\n\nDone. Hit enter to exit.\n"); getchar(); getchar(); return 0; } char getMode(void) { char mode = 0; while(mode < '1' || mode > '9') { mode = getchar(); } return mode; } void reverseFile(FILE * source, FILE * dest) { long location; char byte; fseek(source, -1, SEEK_END); /* want to include the last byte! */ location = 1 + ftell(source); while(location) { byte = fgetc(source); fputc(byte, dest); fseek(source, -2, SEEK_CUR); location--; } } void bin2asm(char * name, FILE * source, FILE * dest, char origin) { printf("Writing sprite routine...\n"); writeSprite(name, source, dest, origin, 0); printf("Writing sprite clear routine...\n"); fseek(source, 0, SEEK_SET); writeSprite(name, source, dest, origin, 1); } void writeSprite(char * name, FILE * source, FILE * dest, char origin, int clear) { unsigned short int pixel = 0; int working = 1; int clearCount = 0; int count = 0; int totalCount = 0; int lineOffset = 0; int spriteCount = 0; /* skip the sprite mask fseek(source, 16*16*2, SEEK_SET);*/ if(clear) { fprintf(dest, "\t\tsection text\r\n%s%iclear:\r\n", name, spriteCount); } else { fprintf(dest, "\t\tsection text\r\n%s%i:\r\n", name, spriteCount); } while(working) { working = fread(&pixel, 1, 2, source); count ++; totalCount++; if(!working) { break; } if(pixel) { if(clearCount) { fprintf(dest, "\t\tadda.l\t#%i+(scr_w-16)*%i,a0\r\n", (clearCount * 2), (lineOffset * 2)); if(clear) { fprintf(dest, "\t\tadda.l\t#%i+(scr_w-16)*%i,a1\r\n", (clearCount * 2), (lineOffset * 2)); } clearCount = 0; lineOffset = 0; if(DEBUG) fprintf(dest, "; reset clear and offset\r\n"); } if(lineOffset) { fprintf(dest, "\t\tadda.l\t#(scr_w-16)*%i,a0\r\n", lineOffset * 2); if(clear) { fprintf(dest, "\t\tadda.l\t#(scr_w-16)*%i,a1\r\n", lineOffset * 2); } lineOffset = 0; if(DEBUG) fprintf(dest, "; reset offset\r\n"); } if(clear) { fprintf(dest, "\t\tmove.w\t(a1)+,(a0)+\r\n"); } else { fprintf(dest, "\t\tmove.w\t#$%04X,(a0)+\r\n", pixel); } } else { clearCount ++; } if(count == 16) { count = 0; lineOffset ++; if(DEBUG) fprintf(dest, "; set offset\r\n"); } if(totalCount == 16*16) { fprintf(dest, "\t\trts\r\n\r\n"); if(clear) { fprintf(dest, "\t\tsection text\r\n%s%iclear:\r\n", name, ++spriteCount); } else { fprintf(dest, "\t\tsection text\r\n%s%i:\r\n", name, ++spriteCount); } totalCount = 0; clearCount = 0; lineOffset = 0; count = 0; } } fprintf(dest, "\t\trts\r\n\r\n"); } <commit_msg>Modified pixel writing to support long words reducing the output size.<commit_after>#include <stdio.h> #include "sprocket.h" #define DEBUG 0 int main(int argc, char ** argv) { int i; char mode; char origin; char input[128]; char outfile[128]; char infile[128]; FILE * source; FILE * dest; for(i = 0; i < 25; i++) printf("\n"); printf("Welcome to Sprocket\n-------------------\n\n"); while(1) { printf("What do you want to do?\n\n\t1. Reverse File\n\t2. Binary to ASM\n\t9. Quit\n\n"); mode = getMode(); if(mode == '9') { break; } printf("Enter the name of the file to process (.bin):\n"); scanf("%s", input); sprintf(infile, "%s.bin", input); source = fopen(infile, "rb"); if(!source) { printf("Could not open file: %s", input[1]); getchar(); return 0; } if(mode == '1') { sprintf(outfile, "%s_r.bin", input); dest = fopen(outfile, "wb"); if(!dest) { printf("Could not open file for output: %s", outfile); getchar(); return 0; } } else if(mode == '2') { printf("Enter the name of the file to create:\n"); scanf("%s", outfile); dest = fopen(outfile, "wb"); if(!dest) { printf("Could not open file for output: %s", outfile); getchar(); return 0; } printf("Top left origin (1) or centered (2)?\n"); origin = getMode(); } if(mode == '1') reverseFile(source, dest); else if(mode == '2') bin2asm(input, source, dest, origin); fclose(source); fclose(dest); } printf("\n\nDone. Hit enter to exit.\n"); getchar(); getchar(); return 0; } char getMode(void) { char mode = 0; while(mode < '1' || mode > '9') { mode = getchar(); } return mode; } void reverseFile(FILE * source, FILE * dest) { long location; char byte; fseek(source, -1, SEEK_END); /* want to include the last byte! */ location = 1 + ftell(source); while(location) { byte = fgetc(source); fputc(byte, dest); fseek(source, -2, SEEK_CUR); location--; } } void bin2asm(char * name, FILE * source, FILE * dest, char origin) { printf("Writing sprite routine...\n"); writeSprite(name, source, dest, origin, 0); printf("Writing sprite clear routine...\n"); fseek(source, 0, SEEK_SET); writeSprite(name, source, dest, origin, 1); } void writeSprite(char * name, FILE * source, FILE * dest, char origin, int clear) { unsigned short int pixel = 0; unsigned short int pixel2 = 0; int working = 1; int clearCount = 0; int count = 0; int totalCount = 0; int lineOffset = 0; int spriteCount = 0; /* skip the sprite mask fseek(source, 16*16*2, SEEK_SET);*/ if(clear) { fprintf(dest, "\t\tsection text\r\n%s%iclear:\r\n", name, spriteCount); } else { fprintf(dest, "\t\tsection text\r\n%s%i:\r\n", name, spriteCount); } while(working) { working = fread(&pixel, 1, 2, source); working |= fread(&pixel2, 1, 2, source); count += 2; totalCount += 2; if(!working) { break; } // if the first pixel is blank we need to allow for that if(!pixel && pixel2) { clearCount++; } // if there's a value in one and we were previously processing blank pixels then // offset the memory address accordingly if(pixel || pixel2) { if(clearCount) { fprintf(dest, "\t\tadda.l\t#%i+(scr_w-16)*%i,a0\r\n", (clearCount * 2), (lineOffset * 2)); if(clear) { fprintf(dest, "\t\tadda.l\t#%i+(scr_w-16)*%i,a1\r\n", (clearCount * 2), (lineOffset * 2)); } clearCount = 0; lineOffset = 0; if(DEBUG) fprintf(dest, "; reset clear and offset\r\n"); } if(lineOffset) { fprintf(dest, "\t\tadda.l\t#(scr_w-16)*%i,a0\r\n", lineOffset * 2); if(clear) { fprintf(dest, "\t\tadda.l\t#(scr_w-16)*%i,a1\r\n", lineOffset * 2); } lineOffset = 0; if(DEBUG) fprintf(dest, "; reset offset\r\n"); } } if(pixel && pixel2) { if(clear) { fprintf(dest, "\t\tmove.l\t(a1)+,(a0)+\r\n"); } else { fprintf(dest, "\t\tmove.l\t#$%04X%04X,(a0)+\r\n", pixel, pixel2); } } else if(pixel || pixel2) { if(clear) { fprintf(dest, "\t\tmove.w\t(a1)+,(a0)+\r\n"); } else { fprintf(dest, "\t\tmove.w\t#$%04X,(a0)+\r\n", pixel | pixel2); } if(pixel) { clearCount ++; } } else { clearCount += 2; } if(count == 16) { count = 0; lineOffset ++; if(DEBUG) fprintf(dest, "; set offset\r\n"); } if(totalCount == 16*16) { fprintf(dest, "\t\trts\r\n\r\n"); if(clear) { fprintf(dest, "\t\tsection text\r\n%s%iclear:\r\n", name, ++spriteCount); } else { fprintf(dest, "\t\tsection text\r\n%s%i:\r\n", name, ++spriteCount); } totalCount = 0; clearCount = 0; lineOffset = 0; count = 0; } } fprintf(dest, "\t\trts\r\n\r\n"); } <|endoftext|>
<commit_before>#include "config.h" #include "vm.hpp" #include "vm/object_utils.hpp" #include "objectmemory.hpp" #include "primitives.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/integer.hpp" #include "builtin/string.hpp" #include "builtin/time.hpp" #include "ontology.hpp" #include "util/time.h" #include <sys/time.h> #include <time.h> #include "windows_compat.h" #include "configuration.hpp" namespace rubinius { void Time::init(STATE) { GO(time_class).set(ontology::new_class(state, "Time", G(object))); G(time_class)->set_object_type(state, TimeType); } Time* Time::now(STATE, Object* self) { Time* tm = state->new_object<Time>(as<Class>(self)); #ifdef HAVE_CLOCK_GETTIME struct timespec ts; ::clock_gettime(CLOCK_REALTIME, &ts); tm->seconds_ = ts.tv_sec; tm->nanoseconds_ = ts.tv_nsec; #else struct timeval tv; /* don't fill in the 2nd argument here. getting the timezone here * this way is not portable and broken anyway. */ ::gettimeofday(&tv, NULL); tm->seconds_ = tv.tv_sec; tm->nanoseconds_ = tv.tv_usec * 1000; #endif tm->is_gmt(state, cFalse); return tm; } // Taken from MRI #define NDIV(x,y) (-(-((x)+1)/(y))-1) #define NMOD(x,y) ((y)-(-((x)+1)%(y))-1) Time* Time::specific(STATE, Object* self, Integer* sec, Integer* nsec, Object* gmt, Object* offset) { Time* tm = state->new_object<Time>(as<Class>(self)); if(sizeof(time_t) == sizeof(long long)) { tm->seconds_ = sec->to_long_long(); tm->nanoseconds_ = nsec->to_long_long(); } else { tm->seconds_ = sec->to_native(); tm->nanoseconds_ = nsec->to_native(); } // Do a little overflow cleanup. if(tm->nanoseconds_ >= 1000000000) { tm->seconds_ += tm->nanoseconds_ / 1000000000; tm->nanoseconds_ %= 1000000000; } if(tm->nanoseconds_ < 0) { tm->seconds_ += NDIV(tm->nanoseconds_, 1000000000); tm->nanoseconds_ = NMOD(tm->nanoseconds_, 1000000000); } if(LANGUAGE_18_ENABLED(state)) { tm->nanoseconds_ -= (tm->nanoseconds_ % 1000); } tm->is_gmt(state, CBOOL(gmt) ? cTrue : cFalse); tm->offset(state, offset); return tm; } Time* Time::from_array(STATE, Object* self, Fixnum* sec, Fixnum* min, Fixnum* hour, Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* nsec, Fixnum* isdst, Object* from_gmt, Object* offset) { struct tm tm; tm.tm_sec = sec->to_native(); if(tm.tm_sec < 0 || tm.tm_sec > 60) { Exception::argument_error(state, "sec must be in 0..60"); } tm.tm_min = min->to_native(); if(tm.tm_min < 0 || tm.tm_min > 60) { Exception::argument_error(state, "min must be in 0..60"); } tm.tm_hour = hour->to_native(); if(tm.tm_hour < 0 || tm.tm_hour > 24) { Exception::argument_error(state, "hour must be in 0..24"); } tm.tm_mday = mday->to_native(); if(tm.tm_mday < 1 || tm.tm_mday > 31) { Exception::argument_error(state, "mday must be in 1..31"); } tm.tm_mon = mon->to_native() - 1; if(tm.tm_mon < 0 || tm.tm_mon > 11) { Exception::argument_error(state, "mon must be in 0..11"); } tm.tm_wday = -1; #ifdef HAVE_TM_GMTOFF tm.tm_gmtoff = 0; #endif #ifdef HAVE_TM_ZONE tm.tm_zone = 0; #endif tm.tm_year = year->to_native() - 1900; tm.tm_isdst = isdst->to_native(); time_t seconds = -1; if(CBOOL(from_gmt) || !offset->nil_p()) { seconds = ::timegm(&tm); } else { tzset(); seconds = ::mktime(&tm); } int err = 0; if(seconds == -1) { int utc_p = (CBOOL(from_gmt) || !offset->nil_p()) ? 1 : 0; seconds = mktime_extended(&tm, utc_p, &err); } if(err) Exception::argument_error(state, "time out of range"); Time* obj = state->new_object<Time>(as<Class>(self)); obj->seconds_ = seconds; obj->nanoseconds_ = nsec->to_native(); obj->is_gmt(state, CBOOL(from_gmt) ? cTrue : cFalse); if(Fixnum* off = try_as<Fixnum>(offset)) { obj->seconds_ -= off->to_native(); obj->offset(state, offset); } return obj; } Time* Time::dup(STATE, Object* self, Time* other) { Time* tm = state->new_object<Time>(as<Class>(self)); tm->seconds_ = other->seconds_; tm->nanoseconds_ = other->nanoseconds_; tm->is_gmt(state, other->is_gmt_); return tm; } struct tm Time::get_tm() { time_t seconds = seconds_; struct tm tm = {0}; if(Fixnum* off = try_as<Fixnum>(offset_)) { seconds += off->to_native(); gmtime_r(&seconds, &tm); } else if(CBOOL(is_gmt_)) { gmtime_r(&seconds, &tm); } else { tzset(); localtime_r(&seconds, &tm); } return tm; } Object* Time::utc_offset(STATE) { if(CBOOL(is_gmt_)) { return Fixnum::from(0); } else if(!offset_->nil_p()) { return offset_; } native_int off; #ifdef HAVE_TM_NAME struct tm tm = get_tm(); off = -tm.tm_tzadj; #else /* !HAVE_TM_NAME */ #ifdef HAVE_TM_ZONE #ifdef HAVE_TM_GMTOFF struct tm tm = get_tm(); off = tm.tm_gmtoff; #else off = _timezone; #endif #else /* !HAVE_TM_ZONE */ #if HAVE_VAR_TIMEZONE #if HAVE_VAR_ALTZONE off = -(daylight ? timezone : altzone); #else off = -timezone; #endif #else /* !HAVE_VAR_TIMEZONE */ #ifdef HAVE_GETTIMEOFDAY gettimeofday(&tv, &zone); off = -zone.tz_minuteswest * 60; #else /* no timezone info, then calc by myself */ { struct tm utc; time_t now; time(&now); utc = *gmtime(&now); off = (now - mktime(&utc)); } #endif #endif /* !HAVE_VAR_TIMEZONE */ #endif /* !HAVE_TM_ZONE */ #endif /* !HAVE_TM_NAME */ return Fixnum::from(off); } Array* Time::calculate_decompose(STATE) { if(!decomposed_->nil_p()) return decomposed_; struct tm tm = get_tm(); /* update Time::TM_FIELDS when changing order of fields */ Array* ary = Array::create(state, 11); ary->set(state, 0, Integer::from(state, tm.tm_sec)); ary->set(state, 1, Integer::from(state, tm.tm_min)); ary->set(state, 2, Integer::from(state, tm.tm_hour)); ary->set(state, 3, Integer::from(state, tm.tm_mday)); ary->set(state, 4, Integer::from(state, tm.tm_mon + 1)); ary->set(state, 5, Integer::from(state, tm.tm_year + 1900)); ary->set(state, 6, Integer::from(state, tm.tm_wday)); ary->set(state, 7, Integer::from(state, tm.tm_yday + 1)); ary->set(state, 8, tm.tm_isdst ? cTrue : cFalse); const char* tmzone; if(offset_->nil_p() && (tmzone = timezone_extended(&tm))) { ary->set(state, 9, String::create(state, tmzone)); } else { ary->set(state, 9, cNil); } // Cache it. decomposed(state, ary); return ary; } #define STRFTIME_OUTPUT_BUF 128 String* Time::strftime(STATE, String* format) { struct tm tm = get_tm(); struct timespec ts; ts.tv_sec = seconds_; ts.tv_nsec = nanoseconds_; int off = 0; if(Fixnum* offset = try_as<Fixnum>(utc_offset(state))) { off = offset->to_int(); } size_t buf_size = STRFTIME_OUTPUT_BUF; char* str = (char*)malloc(buf_size); size_t chars = ::strftime_extended(str, buf_size, format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0, off); while (chars == 0 && format->byte_size() > 0) { buf_size *= 2; str = (char*)realloc(str, buf_size); chars = ::strftime_extended(str, buf_size, format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0, off); } String* result = String::create(state, str, chars); free(str); return result; } } <commit_msg>Use stack allocated + dynamic allocated buffers<commit_after>#include "config.h" #include "vm.hpp" #include "vm/object_utils.hpp" #include "objectmemory.hpp" #include "primitives.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/integer.hpp" #include "builtin/string.hpp" #include "builtin/time.hpp" #include "ontology.hpp" #include "util/time.h" #include <sys/time.h> #include <time.h> #include "windows_compat.h" #include "configuration.hpp" namespace rubinius { void Time::init(STATE) { GO(time_class).set(ontology::new_class(state, "Time", G(object))); G(time_class)->set_object_type(state, TimeType); } Time* Time::now(STATE, Object* self) { Time* tm = state->new_object<Time>(as<Class>(self)); #ifdef HAVE_CLOCK_GETTIME struct timespec ts; ::clock_gettime(CLOCK_REALTIME, &ts); tm->seconds_ = ts.tv_sec; tm->nanoseconds_ = ts.tv_nsec; #else struct timeval tv; /* don't fill in the 2nd argument here. getting the timezone here * this way is not portable and broken anyway. */ ::gettimeofday(&tv, NULL); tm->seconds_ = tv.tv_sec; tm->nanoseconds_ = tv.tv_usec * 1000; #endif tm->is_gmt(state, cFalse); return tm; } // Taken from MRI #define NDIV(x,y) (-(-((x)+1)/(y))-1) #define NMOD(x,y) ((y)-(-((x)+1)%(y))-1) Time* Time::specific(STATE, Object* self, Integer* sec, Integer* nsec, Object* gmt, Object* offset) { Time* tm = state->new_object<Time>(as<Class>(self)); if(sizeof(time_t) == sizeof(long long)) { tm->seconds_ = sec->to_long_long(); tm->nanoseconds_ = nsec->to_long_long(); } else { tm->seconds_ = sec->to_native(); tm->nanoseconds_ = nsec->to_native(); } // Do a little overflow cleanup. if(tm->nanoseconds_ >= 1000000000) { tm->seconds_ += tm->nanoseconds_ / 1000000000; tm->nanoseconds_ %= 1000000000; } if(tm->nanoseconds_ < 0) { tm->seconds_ += NDIV(tm->nanoseconds_, 1000000000); tm->nanoseconds_ = NMOD(tm->nanoseconds_, 1000000000); } if(LANGUAGE_18_ENABLED(state)) { tm->nanoseconds_ -= (tm->nanoseconds_ % 1000); } tm->is_gmt(state, CBOOL(gmt) ? cTrue : cFalse); tm->offset(state, offset); return tm; } Time* Time::from_array(STATE, Object* self, Fixnum* sec, Fixnum* min, Fixnum* hour, Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* nsec, Fixnum* isdst, Object* from_gmt, Object* offset) { struct tm tm; tm.tm_sec = sec->to_native(); if(tm.tm_sec < 0 || tm.tm_sec > 60) { Exception::argument_error(state, "sec must be in 0..60"); } tm.tm_min = min->to_native(); if(tm.tm_min < 0 || tm.tm_min > 60) { Exception::argument_error(state, "min must be in 0..60"); } tm.tm_hour = hour->to_native(); if(tm.tm_hour < 0 || tm.tm_hour > 24) { Exception::argument_error(state, "hour must be in 0..24"); } tm.tm_mday = mday->to_native(); if(tm.tm_mday < 1 || tm.tm_mday > 31) { Exception::argument_error(state, "mday must be in 1..31"); } tm.tm_mon = mon->to_native() - 1; if(tm.tm_mon < 0 || tm.tm_mon > 11) { Exception::argument_error(state, "mon must be in 0..11"); } tm.tm_wday = -1; #ifdef HAVE_TM_GMTOFF tm.tm_gmtoff = 0; #endif #ifdef HAVE_TM_ZONE tm.tm_zone = 0; #endif tm.tm_year = year->to_native() - 1900; tm.tm_isdst = isdst->to_native(); time_t seconds = -1; if(CBOOL(from_gmt) || !offset->nil_p()) { seconds = ::timegm(&tm); } else { tzset(); seconds = ::mktime(&tm); } int err = 0; if(seconds == -1) { int utc_p = (CBOOL(from_gmt) || !offset->nil_p()) ? 1 : 0; seconds = mktime_extended(&tm, utc_p, &err); } if(err) Exception::argument_error(state, "time out of range"); Time* obj = state->new_object<Time>(as<Class>(self)); obj->seconds_ = seconds; obj->nanoseconds_ = nsec->to_native(); obj->is_gmt(state, CBOOL(from_gmt) ? cTrue : cFalse); if(Fixnum* off = try_as<Fixnum>(offset)) { obj->seconds_ -= off->to_native(); obj->offset(state, offset); } return obj; } Time* Time::dup(STATE, Object* self, Time* other) { Time* tm = state->new_object<Time>(as<Class>(self)); tm->seconds_ = other->seconds_; tm->nanoseconds_ = other->nanoseconds_; tm->is_gmt(state, other->is_gmt_); return tm; } struct tm Time::get_tm() { time_t seconds = seconds_; struct tm tm = {0}; if(Fixnum* off = try_as<Fixnum>(offset_)) { seconds += off->to_native(); gmtime_r(&seconds, &tm); } else if(CBOOL(is_gmt_)) { gmtime_r(&seconds, &tm); } else { tzset(); localtime_r(&seconds, &tm); } return tm; } Object* Time::utc_offset(STATE) { if(CBOOL(is_gmt_)) { return Fixnum::from(0); } else if(!offset_->nil_p()) { return offset_; } native_int off; #ifdef HAVE_TM_NAME struct tm tm = get_tm(); off = -tm.tm_tzadj; #else /* !HAVE_TM_NAME */ #ifdef HAVE_TM_ZONE #ifdef HAVE_TM_GMTOFF struct tm tm = get_tm(); off = tm.tm_gmtoff; #else off = _timezone; #endif #else /* !HAVE_TM_ZONE */ #if HAVE_VAR_TIMEZONE #if HAVE_VAR_ALTZONE off = -(daylight ? timezone : altzone); #else off = -timezone; #endif #else /* !HAVE_VAR_TIMEZONE */ #ifdef HAVE_GETTIMEOFDAY gettimeofday(&tv, &zone); off = -zone.tz_minuteswest * 60; #else /* no timezone info, then calc by myself */ { struct tm utc; time_t now; time(&now); utc = *gmtime(&now); off = (now - mktime(&utc)); } #endif #endif /* !HAVE_VAR_TIMEZONE */ #endif /* !HAVE_TM_ZONE */ #endif /* !HAVE_TM_NAME */ return Fixnum::from(off); } Array* Time::calculate_decompose(STATE) { if(!decomposed_->nil_p()) return decomposed_; struct tm tm = get_tm(); /* update Time::TM_FIELDS when changing order of fields */ Array* ary = Array::create(state, 11); ary->set(state, 0, Integer::from(state, tm.tm_sec)); ary->set(state, 1, Integer::from(state, tm.tm_min)); ary->set(state, 2, Integer::from(state, tm.tm_hour)); ary->set(state, 3, Integer::from(state, tm.tm_mday)); ary->set(state, 4, Integer::from(state, tm.tm_mon + 1)); ary->set(state, 5, Integer::from(state, tm.tm_year + 1900)); ary->set(state, 6, Integer::from(state, tm.tm_wday)); ary->set(state, 7, Integer::from(state, tm.tm_yday + 1)); ary->set(state, 8, tm.tm_isdst ? cTrue : cFalse); const char* tmzone; if(offset_->nil_p() && (tmzone = timezone_extended(&tm))) { ary->set(state, 9, String::create(state, tmzone)); } else { ary->set(state, 9, cNil); } // Cache it. decomposed(state, ary); return ary; } #define STRFTIME_STACK_BUF 128 String* Time::strftime(STATE, String* format) { struct tm tm = get_tm(); struct timespec ts; ts.tv_sec = seconds_; ts.tv_nsec = nanoseconds_; int off = 0; if(Fixnum* offset = try_as<Fixnum>(utc_offset(state))) { off = offset->to_int(); } char stack_str[STRFTIME_STACK_BUF]; char* malloc_str = 0; size_t chars = ::strftime_extended(stack_str, STRFTIME_STACK_BUF, format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0, off); size_t buf_size = format->byte_size(); String* result = 0; if (chars == 0 && format->byte_size() > 0) { malloc_str = (char*)malloc(buf_size); chars = ::strftime_extended(malloc_str, buf_size, format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0, off); while (chars == 0 && format->byte_size() > 0) { buf_size *= 2; malloc_str = (char*)realloc(malloc_str, buf_size); chars = ::strftime_extended(malloc_str, buf_size, format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0, off); } result = String::create(state, malloc_str, chars); free(malloc_str); } else { result = String::create(state, stack_str, chars); } return result; } } <|endoftext|>
<commit_before>#include <eosio/chain/webassembly/eos-vm-oc/executor.hpp> #include <eosio/chain/webassembly/eos-vm-oc/code_cache.hpp> #include <eosio/chain/webassembly/eos-vm-oc/memory.hpp> #include <eosio/chain/webassembly/eos-vm-oc/intrinsic_mapping.hpp> #include <eosio/chain/webassembly/eos-vm-oc/intrinsic.hpp> #include <eosio/chain/webassembly/eos-vm-oc/eos-vm-oc.h> #include <eosio/chain/wasm_eosio_constraints.hpp> #include <eosio/chain/apply_context.hpp> #include <eosio/chain/transaction_context.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/types.hpp> #include <fc/scoped_exit.hpp> #include <boost/hana/equal.hpp> #include <mutex> #include <asm/prctl.h> #include <sys/prctl.h> #include <sys/syscall.h> extern "C" int arch_prctl(int code, unsigned long* addr); namespace eosio { namespace chain { namespace eosvmoc { static constexpr auto signal_sentinel = 0x4D56534F45534559ul; static std::mutex inited_signal_mutex; static bool inited_signal; static void(*chained_handler)(int,siginfo_t*,void*); [[noreturn]] static void segv_handler(int sig, siginfo_t* info, void* ctx) { control_block* cb_in_main_segment; //a 0 GS value is an indicator an executor hasn't been active on this thread recently uint64_t current_gs; syscall(SYS_arch_prctl, ARCH_GET_GS, &current_gs); if(current_gs == 0) goto notus; cb_in_main_segment = reinterpret_cast<control_block*>(current_gs - memory::cb_offset); //as a double check that the control block pointer is what we expect, look for the magic if(cb_in_main_segment->magic != signal_sentinel) goto notus; //was wasm running? If not, this SEGV was not due to us if(cb_in_main_segment->is_running == false) goto notus; //was the segfault within code? if((uintptr_t)info->si_addr >= cb_in_main_segment->execution_thread_code_start && (uintptr_t)info->si_addr < cb_in_main_segment->execution_thread_code_start+cb_in_main_segment->execution_thread_code_length) siglongjmp(*cb_in_main_segment->jmp, EOSVMOC_EXIT_CHECKTIME_FAIL); //was the segfault within data? if((uintptr_t)info->si_addr >= cb_in_main_segment->execution_thread_memory_start && (uintptr_t)info->si_addr < cb_in_main_segment->execution_thread_memory_start+cb_in_main_segment->execution_thread_memory_length) siglongjmp(*cb_in_main_segment->jmp, EOSVMOC_EXIT_SEGV); notus: if(chained_handler) chained_handler(sig, info, ctx); ::signal(sig, SIG_DFL); ::raise(sig); __builtin_unreachable(); } static intrinsic grow_memory_intrinsic EOSVMOC_INTRINSIC_INIT_PRIORITY("eosvmoc_internal.grow_memory", IR::FunctionType::get(IR::ResultType::i32,{IR::ValueType::i32,IR::ValueType::i32}), (void*)&eos_vm_oc_grow_memory, boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING("eosvmoc_internal.grow_memory"))).value() ); //This is effectively overriding the eosio_exit intrinsic in wasm_interface static void eosio_exit(int32_t code) { siglongjmp(*eos_vm_oc_get_jmp_buf(), EOSVMOC_EXIT_CLEAN_EXIT); __builtin_unreachable(); } static intrinsic eosio_exit_intrinsic("env.eosio_exit", IR::FunctionType::get(IR::ResultType::none,{IR::ValueType::i32}), (void*)&eosio_exit, boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING("env.eosio_exit"))).value() ); static void throw_internal_exception(const char* const s) { *reinterpret_cast<std::exception_ptr*>(eos_vm_oc_get_exception_ptr()) = std::make_exception_ptr(wasm_execution_error(FC_LOG_MESSAGE(error, s))); siglongjmp(*eos_vm_oc_get_jmp_buf(), EOSVMOC_EXIT_EXCEPTION); __builtin_unreachable(); } #define DEFINE_EOSVMOC_TRAP_INTRINSIC(module,name) \ void name(); \ static intrinsic name##Function EOSVMOC_INTRINSIC_INIT_PRIORITY(#module "." #name,IR::FunctionType::get(),(void*)&name, \ boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING(#module "." #name))).value() \ ); \ void name() DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,depth_assert) { throw_internal_exception("Exceeded call depth maximum"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,div0_or_overflow) { throw_internal_exception("Division by 0 or integer overflow trapped"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,indirect_call_mismatch) { throw_internal_exception("Indirect call function type mismatch"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,indirect_call_oob) { throw_internal_exception("Indirect call index out of bounds"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,unreachable) { throw_internal_exception("Unreachable reached"); } executor::executor(const code_cache_base& cc) { //if we're the first executor created, go setup the signal handling. For now we'll just leave this attached forever if(std::lock_guard g(inited_signal_mutex); inited_signal == false) { struct sigaction sig_action, old_sig_action; sig_action.sa_sigaction = segv_handler; sigemptyset(&sig_action.sa_mask); sig_action.sa_flags = SA_SIGINFO | SA_NODEFER; sigaction(SIGSEGV, &sig_action, &old_sig_action); if(old_sig_action.sa_flags & SA_SIGINFO) chained_handler = old_sig_action.sa_sigaction; else if(old_sig_action.sa_handler != SIG_IGN && old_sig_action.sa_handler != SIG_DFL) chained_handler = (void (*)(int,siginfo_t*,void*))old_sig_action.sa_handler; inited_signal = true; } struct stat s; fstat(cc.fd(), &s); code_mapping = (uint8_t*)mmap(nullptr, s.st_size, PROT_EXEC|PROT_READ, MAP_SHARED, cc.fd(), 0); code_mapping_size = s.st_size; mapping_is_executable = true; } void executor::execute(const code_descriptor& code, const memory& mem, apply_context& context) { if(mapping_is_executable == false) { mprotect(code_mapping, code_mapping_size, PROT_EXEC|PROT_READ); mapping_is_executable = true; } //prepare initial memory, mutable globals, and table data if(code.starting_memory_pages > 0 ) { arch_prctl(ARCH_SET_GS, (unsigned long*)(mem.zero_page_memory_base()+code.starting_memory_pages*memory::stride)); memset(mem.full_page_memory_base(), 0, 64u*1024u*code.starting_memory_pages); } else arch_prctl(ARCH_SET_GS, (unsigned long*)mem.zero_page_memory_base()); memcpy(mem.full_page_memory_base() - code.initdata_prologue_size, code_mapping + code.initdata_begin, code.initdata_size); control_block* const cb = mem.get_control_block(); cb->magic = signal_sentinel; cb->execution_thread_code_start = (uintptr_t)code_mapping; cb->execution_thread_code_length = code_mapping_size; cb->execution_thread_memory_start = (uintptr_t)mem.start_of_memory_slices(); cb->execution_thread_memory_length = mem.size_of_memory_slice_mapping(); cb->ctx = &context; executors_exception_ptr = nullptr; cb->eptr = &executors_exception_ptr; cb->current_call_depth_remaining = eosio::chain::wasm_constraints::maximum_call_depth+2; cb->current_linear_memory_pages = code.starting_memory_pages; cb->first_invalid_memory_address = code.starting_memory_pages*64*1024; cb->full_linear_memory_start = (char*)mem.full_page_memory_base(); cb->jmp = &executors_sigjmp_buf; cb->bounce_buffers = &executors_bounce_buffers; cb->running_code_base = (uintptr_t)(code_mapping + code.code_begin); cb->is_running = true; context.trx_context.transaction_timer.set_expiration_callback([](void* user) { executor* self = (executor*)user; syscall(SYS_mprotect, self->code_mapping, self->code_mapping_size, PROT_NONE); self->mapping_is_executable = false; }, this); context.trx_context.checktime(); //catch any expiration that might have occurred before setting up callback auto reset_is_running = fc::make_scoped_exit([cb](){cb->is_running = false;}); auto reset_bounce_buffers = fc::make_scoped_exit([cb](){cb->bounce_buffers->clear();}); auto reset_expiry_cb = fc::make_scoped_exit([&tt=context.trx_context.transaction_timer](){tt.set_expiration_callback(nullptr, nullptr);}); void(*apply_func)(uint64_t, uint64_t, uint64_t) = (void(*)(uint64_t, uint64_t, uint64_t))(cb->running_code_base + code.apply_offset); switch(sigsetjmp(*cb->jmp, 0)) { case 0: code.start.visit(overloaded { [&](const no_offset&) {}, [&](const intrinsic_ordinal& i) { void(*start_func)() = (void(*)())(*(uintptr_t*)((uintptr_t)mem.zero_page_memory_base() - memory::first_intrinsic_offset - i.ordinal*8)); start_func(); }, [&](const code_offset& offs) { void(*start_func)() = (void(*)())(cb->running_code_base + offs.offset); start_func(); } }); apply_func(context.get_receiver().to_uint64_t(), context.get_action().account.to_uint64_t(), context.get_action().name.to_uint64_t()); break; //case 1: clean eosio_exit case EOSVMOC_EXIT_CHECKTIME_FAIL: context.trx_context.checktime(); break; case EOSVMOC_EXIT_SEGV: EOS_ASSERT(false, wasm_execution_error, "access violation"); break; case EOSVMOC_EXIT_EXCEPTION: //exception std::rethrow_exception(*cb->eptr); break; } } executor::~executor() { arch_prctl(ARCH_SET_GS, nullptr); } }}} <commit_msg>do not fall through after calling the chained SEGV handler<commit_after>#include <eosio/chain/webassembly/eos-vm-oc/executor.hpp> #include <eosio/chain/webassembly/eos-vm-oc/code_cache.hpp> #include <eosio/chain/webassembly/eos-vm-oc/memory.hpp> #include <eosio/chain/webassembly/eos-vm-oc/intrinsic_mapping.hpp> #include <eosio/chain/webassembly/eos-vm-oc/intrinsic.hpp> #include <eosio/chain/webassembly/eos-vm-oc/eos-vm-oc.h> #include <eosio/chain/wasm_eosio_constraints.hpp> #include <eosio/chain/apply_context.hpp> #include <eosio/chain/transaction_context.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/types.hpp> #include <fc/scoped_exit.hpp> #include <boost/hana/equal.hpp> #include <mutex> #include <asm/prctl.h> #include <sys/prctl.h> #include <sys/syscall.h> extern "C" int arch_prctl(int code, unsigned long* addr); namespace eosio { namespace chain { namespace eosvmoc { static constexpr auto signal_sentinel = 0x4D56534F45534559ul; static std::mutex inited_signal_mutex; static bool inited_signal; static void(*chained_handler)(int,siginfo_t*,void*); static void segv_handler(int sig, siginfo_t* info, void* ctx) { control_block* cb_in_main_segment; //a 0 GS value is an indicator an executor hasn't been active on this thread recently uint64_t current_gs; syscall(SYS_arch_prctl, ARCH_GET_GS, &current_gs); if(current_gs == 0) goto notus; cb_in_main_segment = reinterpret_cast<control_block*>(current_gs - memory::cb_offset); //as a double check that the control block pointer is what we expect, look for the magic if(cb_in_main_segment->magic != signal_sentinel) goto notus; //was wasm running? If not, this SEGV was not due to us if(cb_in_main_segment->is_running == false) goto notus; //was the segfault within code? if((uintptr_t)info->si_addr >= cb_in_main_segment->execution_thread_code_start && (uintptr_t)info->si_addr < cb_in_main_segment->execution_thread_code_start+cb_in_main_segment->execution_thread_code_length) siglongjmp(*cb_in_main_segment->jmp, EOSVMOC_EXIT_CHECKTIME_FAIL); //was the segfault within data? if((uintptr_t)info->si_addr >= cb_in_main_segment->execution_thread_memory_start && (uintptr_t)info->si_addr < cb_in_main_segment->execution_thread_memory_start+cb_in_main_segment->execution_thread_memory_length) siglongjmp(*cb_in_main_segment->jmp, EOSVMOC_EXIT_SEGV); notus: if(chained_handler) { chained_handler(sig, info, ctx); return; } ::signal(sig, SIG_DFL); ::raise(sig); __builtin_unreachable(); } static intrinsic grow_memory_intrinsic EOSVMOC_INTRINSIC_INIT_PRIORITY("eosvmoc_internal.grow_memory", IR::FunctionType::get(IR::ResultType::i32,{IR::ValueType::i32,IR::ValueType::i32}), (void*)&eos_vm_oc_grow_memory, boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING("eosvmoc_internal.grow_memory"))).value() ); //This is effectively overriding the eosio_exit intrinsic in wasm_interface static void eosio_exit(int32_t code) { siglongjmp(*eos_vm_oc_get_jmp_buf(), EOSVMOC_EXIT_CLEAN_EXIT); __builtin_unreachable(); } static intrinsic eosio_exit_intrinsic("env.eosio_exit", IR::FunctionType::get(IR::ResultType::none,{IR::ValueType::i32}), (void*)&eosio_exit, boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING("env.eosio_exit"))).value() ); static void throw_internal_exception(const char* const s) { *reinterpret_cast<std::exception_ptr*>(eos_vm_oc_get_exception_ptr()) = std::make_exception_ptr(wasm_execution_error(FC_LOG_MESSAGE(error, s))); siglongjmp(*eos_vm_oc_get_jmp_buf(), EOSVMOC_EXIT_EXCEPTION); __builtin_unreachable(); } #define DEFINE_EOSVMOC_TRAP_INTRINSIC(module,name) \ void name(); \ static intrinsic name##Function EOSVMOC_INTRINSIC_INIT_PRIORITY(#module "." #name,IR::FunctionType::get(),(void*)&name, \ boost::hana::index_if(intrinsic_table, ::boost::hana::equal.to(BOOST_HANA_STRING(#module "." #name))).value() \ ); \ void name() DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,depth_assert) { throw_internal_exception("Exceeded call depth maximum"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,div0_or_overflow) { throw_internal_exception("Division by 0 or integer overflow trapped"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,indirect_call_mismatch) { throw_internal_exception("Indirect call function type mismatch"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,indirect_call_oob) { throw_internal_exception("Indirect call index out of bounds"); } DEFINE_EOSVMOC_TRAP_INTRINSIC(eosvmoc_internal,unreachable) { throw_internal_exception("Unreachable reached"); } executor::executor(const code_cache_base& cc) { //if we're the first executor created, go setup the signal handling. For now we'll just leave this attached forever if(std::lock_guard g(inited_signal_mutex); inited_signal == false) { struct sigaction sig_action, old_sig_action; sig_action.sa_sigaction = segv_handler; sigemptyset(&sig_action.sa_mask); sig_action.sa_flags = SA_SIGINFO | SA_NODEFER; sigaction(SIGSEGV, &sig_action, &old_sig_action); if(old_sig_action.sa_flags & SA_SIGINFO) chained_handler = old_sig_action.sa_sigaction; else if(old_sig_action.sa_handler != SIG_IGN && old_sig_action.sa_handler != SIG_DFL) chained_handler = (void (*)(int,siginfo_t*,void*))old_sig_action.sa_handler; inited_signal = true; } struct stat s; fstat(cc.fd(), &s); code_mapping = (uint8_t*)mmap(nullptr, s.st_size, PROT_EXEC|PROT_READ, MAP_SHARED, cc.fd(), 0); code_mapping_size = s.st_size; mapping_is_executable = true; } void executor::execute(const code_descriptor& code, const memory& mem, apply_context& context) { if(mapping_is_executable == false) { mprotect(code_mapping, code_mapping_size, PROT_EXEC|PROT_READ); mapping_is_executable = true; } //prepare initial memory, mutable globals, and table data if(code.starting_memory_pages > 0 ) { arch_prctl(ARCH_SET_GS, (unsigned long*)(mem.zero_page_memory_base()+code.starting_memory_pages*memory::stride)); memset(mem.full_page_memory_base(), 0, 64u*1024u*code.starting_memory_pages); } else arch_prctl(ARCH_SET_GS, (unsigned long*)mem.zero_page_memory_base()); memcpy(mem.full_page_memory_base() - code.initdata_prologue_size, code_mapping + code.initdata_begin, code.initdata_size); control_block* const cb = mem.get_control_block(); cb->magic = signal_sentinel; cb->execution_thread_code_start = (uintptr_t)code_mapping; cb->execution_thread_code_length = code_mapping_size; cb->execution_thread_memory_start = (uintptr_t)mem.start_of_memory_slices(); cb->execution_thread_memory_length = mem.size_of_memory_slice_mapping(); cb->ctx = &context; executors_exception_ptr = nullptr; cb->eptr = &executors_exception_ptr; cb->current_call_depth_remaining = eosio::chain::wasm_constraints::maximum_call_depth+2; cb->current_linear_memory_pages = code.starting_memory_pages; cb->first_invalid_memory_address = code.starting_memory_pages*64*1024; cb->full_linear_memory_start = (char*)mem.full_page_memory_base(); cb->jmp = &executors_sigjmp_buf; cb->bounce_buffers = &executors_bounce_buffers; cb->running_code_base = (uintptr_t)(code_mapping + code.code_begin); cb->is_running = true; context.trx_context.transaction_timer.set_expiration_callback([](void* user) { executor* self = (executor*)user; syscall(SYS_mprotect, self->code_mapping, self->code_mapping_size, PROT_NONE); self->mapping_is_executable = false; }, this); context.trx_context.checktime(); //catch any expiration that might have occurred before setting up callback auto reset_is_running = fc::make_scoped_exit([cb](){cb->is_running = false;}); auto reset_bounce_buffers = fc::make_scoped_exit([cb](){cb->bounce_buffers->clear();}); auto reset_expiry_cb = fc::make_scoped_exit([&tt=context.trx_context.transaction_timer](){tt.set_expiration_callback(nullptr, nullptr);}); void(*apply_func)(uint64_t, uint64_t, uint64_t) = (void(*)(uint64_t, uint64_t, uint64_t))(cb->running_code_base + code.apply_offset); switch(sigsetjmp(*cb->jmp, 0)) { case 0: code.start.visit(overloaded { [&](const no_offset&) {}, [&](const intrinsic_ordinal& i) { void(*start_func)() = (void(*)())(*(uintptr_t*)((uintptr_t)mem.zero_page_memory_base() - memory::first_intrinsic_offset - i.ordinal*8)); start_func(); }, [&](const code_offset& offs) { void(*start_func)() = (void(*)())(cb->running_code_base + offs.offset); start_func(); } }); apply_func(context.get_receiver().to_uint64_t(), context.get_action().account.to_uint64_t(), context.get_action().name.to_uint64_t()); break; //case 1: clean eosio_exit case EOSVMOC_EXIT_CHECKTIME_FAIL: context.trx_context.checktime(); break; case EOSVMOC_EXIT_SEGV: EOS_ASSERT(false, wasm_execution_error, "access violation"); break; case EOSVMOC_EXIT_EXCEPTION: //exception std::rethrow_exception(*cb->eptr); break; } } executor::~executor() { arch_prctl(ARCH_SET_GS, nullptr); } }}} <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xformsimport.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-11-16 10:04:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XFORMSIMPORT_HXX #define _XMLOFF_XFORMSIMPORT_HXX #include <tools/solar.h> // for USHORT #include <com/sun/star/uno/Reference.hxx> class SvXMLImport; class SvXMLImportContext; namespace rtl { class OUString; } namespace std { template<typename A, typename B> struct pair; } namespace com { namespace sun { namespace star { namespace uno { template<typename T> class Reference; } namespace beans { class XPropertySet; } namespace frame { class XModel; } } } } /** create import context for xforms:model element. */ SvXMLImportContext* createXFormsModelContext( SvXMLImport& rImport, USHORT nPrefix, const rtl::OUString& rLocalName ); /** perform the actual binding of an XForms-binding with the suitable control * @param document which contains the XForms-model(s) * @param pair<XForms binding ID, reference to control> */ void bindXFormsValueBinding( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); /** perform the actual binding of an XForms-binding as list source with a list control * @param document which contains the XForms-model(s) * @param pair<XForms binding ID, reference to control> */ void bindXFormsListBinding( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); /** perform the actual binding of an XForms submission with the suitable control * @param document which contains the XForms-model(s) * @param pair<XForms submission ID, reference to control> */ void bindXFormsSubmission( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); #endif <commit_msg>INTEGRATION: CWS sb25 (1.2.16); FILE MERGED 2004/12/13 12:34:22 sb 1.2.16.1: #i37077# Added missing XMLOFF_DLLPUBLIC to new xforms stuff.<commit_after>/************************************************************************* * * $RCSfile: xformsimport.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-01-11 14:20:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XFORMSIMPORT_HXX #define _XMLOFF_XFORMSIMPORT_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_XMLOFF_DLLAPI_H #include "xmloff/dllapi.h" #endif #include <tools/solar.h> // for USHORT #include <com/sun/star/uno/Reference.hxx> class SvXMLImport; class SvXMLImportContext; namespace rtl { class OUString; } namespace std { template<typename A, typename B> struct pair; } namespace com { namespace sun { namespace star { namespace uno { template<typename T> class Reference; } namespace beans { class XPropertySet; } namespace frame { class XModel; } } } } /** create import context for xforms:model element. */ XMLOFF_DLLPUBLIC SvXMLImportContext* createXFormsModelContext( SvXMLImport& rImport, USHORT nPrefix, const rtl::OUString& rLocalName ); /** perform the actual binding of an XForms-binding with the suitable control * @param document which contains the XForms-model(s) * @param pair<XForms binding ID, reference to control> */ void bindXFormsValueBinding( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); /** perform the actual binding of an XForms-binding as list source with a list control * @param document which contains the XForms-model(s) * @param pair<XForms binding ID, reference to control> */ void bindXFormsListBinding( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); /** perform the actual binding of an XForms submission with the suitable control * @param document which contains the XForms-model(s) * @param pair<XForms submission ID, reference to control> */ void bindXFormsSubmission( com::sun::star::uno::Reference<com::sun::star::frame::XModel>, std::pair<com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>,rtl::OUString> ); #endif <|endoftext|>
<commit_before>/* ---------------------------------------------------------------------- * Copyright (C) 2010-2018 Arm Limited. All rights reserved. * * * Project: CMSIS NN Library * Title: arm_nnexamples_cifar10.cpp * * Description: Convolutional Neural Network Example * * Target Processor: Cortex-M4/Cortex-M7 * * 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 Arm LIMITED 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. * -------------------------------------------------------------------- */ /** * @ingroup groupExamples */ /** * @defgroup CNNExample Convolutional Neural Network Example * * \par Description: * \par * Demonstrates a convolutional neural network (CNN) example with the use of convolution, * ReLU activation, pooling and fully-connected functions. * * \par Model definition: * \par * The CNN used in this example is based on CIFAR-10 example from Caffe [1]. * The neural network consists * of 3 convolution layers interspersed by ReLU activation and max pooling layers, followed by a * fully-connected layer at the end. The input to the network is a 32x32 pixel color image, which will * be classified into one of the 10 output classes. * This example model implementation needs 32.3 KB to store weights, 40 KB for activations and * 3.1 KB for storing the \c im2col data. * * \image html CIFAR10_CNN.gif "Neural Network model definition" * * \par Variables Description: * \par * \li \c conv1_wt, \c conv2_wt, \c conv3_wt are convolution layer weight matrices * \li \c conv1_bias, \c conv2_bias, \c conv3_bias are convolution layer bias arrays * \li \c ip1_wt, ip1_bias point to fully-connected layer weights and biases * \li \c input_data points to the input image data * \li \c output_data points to the classification output * \li \c col_buffer is a buffer to store the \c im2col output * \li \c scratch_buffer is used to store the activation data (intermediate layer outputs) * * \par CMSIS DSP Software Library Functions Used: * \par * - arm_convolve_HWC_q7_RGB() * - arm_convolve_HWC_q7_fast() * - arm_relu_q7() * - arm_maxpool_q7_HWC() * - arm_avepool_q7_HWC() * - arm_fully_connected_q7_opt() * - arm_fully_connected_q7() * * <b> Refer </b> * \link arm_nnexamples_cifar10.cpp \endlink * * \par [1] https://github.com/BVLC/caffe */ #include <stdint.h> #include <stdio.h> #include "arm_math.h" #include "arm_nnexamples_cifar10_parameter.h" #include "arm_nnexamples_cifar10_weights.h" #include "arm_nnfunctions.h" #include "arm_nnexamples_cifar10_inputs.h" #ifdef _RTE_ #include "RTE_Components.h" #ifdef RTE_Compiler_EventRecorder #include "EventRecorder.h" #endif #endif // include the input and weights static q7_t conv1_wt[CONV1_IM_CH * CONV1_KER_DIM * CONV1_KER_DIM * CONV1_OUT_CH] = CONV1_WT; static q7_t conv1_bias[CONV1_OUT_CH] = CONV1_BIAS; static q7_t conv2_wt[CONV2_IM_CH * CONV2_KER_DIM * CONV2_KER_DIM * CONV2_OUT_CH] = CONV2_WT; static q7_t conv2_bias[CONV2_OUT_CH] = CONV2_BIAS; static q7_t conv3_wt[CONV3_IM_CH * CONV3_KER_DIM * CONV3_KER_DIM * CONV3_OUT_CH] = CONV3_WT; static q7_t conv3_bias[CONV3_OUT_CH] = CONV3_BIAS; static q7_t ip1_wt[IP1_DIM * IP1_OUT] = IP1_WT; static q7_t ip1_bias[IP1_OUT] = IP1_BIAS; /* Here the image_data should be the raw uint8 type RGB image in [RGB, RGB, RGB ... RGB] format */ uint8_t image_data[CONV1_IM_CH * CONV1_IM_DIM * CONV1_IM_DIM] = IMG_DATA; q7_t output_data[IP1_OUT]; //vector buffer: max(im2col buffer,average pool buffer, fully connected buffer) q7_t col_buffer[2 * 5 * 5 * 32 * 2]; q7_t scratch_buffer[32 * 32 * 10 * 4]; int main() { #ifdef RTE_Compiler_EventRecorder EventRecorderInitialize (EventRecordAll, 1); // initialize and start Event Recorder #endif printf("start execution\n"); /* start the execution */ q7_t *img_buffer1 = scratch_buffer; q7_t *img_buffer2 = img_buffer1 + 32 * 32 * 32; /* input pre-processing */ int mean_data[3] = INPUT_MEAN_SHIFT; unsigned int scale_data[3] = INPUT_RIGHT_SHIFT; for (int i=0;i<32*32*3; i+=3) { img_buffer2[i] = (q7_t)__SSAT( ((((int)image_data[i] - mean_data[0])<<7) + (0x1<<(scale_data[0]-1))) >> scale_data[0], 8); img_buffer2[i+1] = (q7_t)__SSAT( ((((int)image_data[i+1] - mean_data[1])<<7) + (0x1<<(scale_data[1]-1))) >> scale_data[1], 8); img_buffer2[i+2] = (q7_t)__SSAT( ((((int)image_data[i+2] - mean_data[2])<<7) + (0x1<<(scale_data[2]-1))) >> scale_data[2], 8); } // conv1 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_RGB(img_buffer2, CONV1_IM_DIM, CONV1_IM_CH, conv1_wt, CONV1_OUT_CH, CONV1_KER_DIM, CONV1_PADDING, CONV1_STRIDE, conv1_bias, CONV1_BIAS_LSHIFT, CONV1_OUT_RSHIFT, img_buffer1, CONV1_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV1_OUT_DIM * CONV1_OUT_DIM * CONV1_OUT_CH); // pool1 img_buffer1 -> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV1_OUT_DIM, CONV1_OUT_CH, POOL1_KER_DIM, POOL1_PADDING, POOL1_STRIDE, POOL1_OUT_DIM, NULL, img_buffer2); // conv2 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_fast(img_buffer2, CONV2_IM_DIM, CONV2_IM_CH, conv2_wt, CONV2_OUT_CH, CONV2_KER_DIM, CONV2_PADDING, CONV2_STRIDE, conv2_bias, CONV2_BIAS_LSHIFT, CONV2_OUT_RSHIFT, img_buffer1, CONV2_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV2_OUT_DIM * CONV2_OUT_DIM * CONV2_OUT_CH); // pool2 img_buffer1 -> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV2_OUT_DIM, CONV2_OUT_CH, POOL2_KER_DIM, POOL2_PADDING, POOL2_STRIDE, POOL2_OUT_DIM, col_buffer, img_buffer2); // conv3 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_fast(img_buffer2, CONV3_IM_DIM, CONV3_IM_CH, conv3_wt, CONV3_OUT_CH, CONV3_KER_DIM, CONV3_PADDING, CONV3_STRIDE, conv3_bias, CONV3_BIAS_LSHIFT, CONV3_OUT_RSHIFT, img_buffer1, CONV3_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV3_OUT_DIM * CONV3_OUT_DIM * CONV3_OUT_CH); // pool3 img_buffer-> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV3_OUT_DIM, CONV3_OUT_CH, POOL3_KER_DIM, POOL3_PADDING, POOL3_STRIDE, POOL3_OUT_DIM, col_buffer, img_buffer2); arm_fully_connected_q7_opt(img_buffer2, ip1_wt, IP1_DIM, IP1_OUT, IP1_BIAS_LSHIFT, IP1_OUT_RSHIFT, ip1_bias, output_data, (q15_t *) img_buffer1); //arm_softmax_q7(output_data, 10, output_data); for (int i = 0; i < 10; i++) { printf("%d: %d\n", i, output_data[i]); } return 0; } <commit_msg>Uncomment the softmax<commit_after>/* ---------------------------------------------------------------------- * Copyright (C) 2010-2018 Arm Limited. All rights reserved. * * * Project: CMSIS NN Library * Title: arm_nnexamples_cifar10.cpp * * Description: Convolutional Neural Network Example * * Target Processor: Cortex-M4/Cortex-M7 * * 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 Arm LIMITED 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. * -------------------------------------------------------------------- */ /** * @ingroup groupExamples */ /** * @defgroup CNNExample Convolutional Neural Network Example * * \par Description: * \par * Demonstrates a convolutional neural network (CNN) example with the use of convolution, * ReLU activation, pooling and fully-connected functions. * * \par Model definition: * \par * The CNN used in this example is based on CIFAR-10 example from Caffe [1]. * The neural network consists * of 3 convolution layers interspersed by ReLU activation and max pooling layers, followed by a * fully-connected layer at the end. The input to the network is a 32x32 pixel color image, which will * be classified into one of the 10 output classes. * This example model implementation needs 32.3 KB to store weights, 40 KB for activations and * 3.1 KB for storing the \c im2col data. * * \image html CIFAR10_CNN.gif "Neural Network model definition" * * \par Variables Description: * \par * \li \c conv1_wt, \c conv2_wt, \c conv3_wt are convolution layer weight matrices * \li \c conv1_bias, \c conv2_bias, \c conv3_bias are convolution layer bias arrays * \li \c ip1_wt, ip1_bias point to fully-connected layer weights and biases * \li \c input_data points to the input image data * \li \c output_data points to the classification output * \li \c col_buffer is a buffer to store the \c im2col output * \li \c scratch_buffer is used to store the activation data (intermediate layer outputs) * * \par CMSIS DSP Software Library Functions Used: * \par * - arm_convolve_HWC_q7_RGB() * - arm_convolve_HWC_q7_fast() * - arm_relu_q7() * - arm_maxpool_q7_HWC() * - arm_avepool_q7_HWC() * - arm_fully_connected_q7_opt() * - arm_fully_connected_q7() * * <b> Refer </b> * \link arm_nnexamples_cifar10.cpp \endlink * * \par [1] https://github.com/BVLC/caffe */ #include <stdint.h> #include <stdio.h> #include "arm_math.h" #include "arm_nnexamples_cifar10_parameter.h" #include "arm_nnexamples_cifar10_weights.h" #include "arm_nnfunctions.h" #include "arm_nnexamples_cifar10_inputs.h" #ifdef _RTE_ #include "RTE_Components.h" #ifdef RTE_Compiler_EventRecorder #include "EventRecorder.h" #endif #endif // include the input and weights static q7_t conv1_wt[CONV1_IM_CH * CONV1_KER_DIM * CONV1_KER_DIM * CONV1_OUT_CH] = CONV1_WT; static q7_t conv1_bias[CONV1_OUT_CH] = CONV1_BIAS; static q7_t conv2_wt[CONV2_IM_CH * CONV2_KER_DIM * CONV2_KER_DIM * CONV2_OUT_CH] = CONV2_WT; static q7_t conv2_bias[CONV2_OUT_CH] = CONV2_BIAS; static q7_t conv3_wt[CONV3_IM_CH * CONV3_KER_DIM * CONV3_KER_DIM * CONV3_OUT_CH] = CONV3_WT; static q7_t conv3_bias[CONV3_OUT_CH] = CONV3_BIAS; static q7_t ip1_wt[IP1_DIM * IP1_OUT] = IP1_WT; static q7_t ip1_bias[IP1_OUT] = IP1_BIAS; /* Here the image_data should be the raw uint8 type RGB image in [RGB, RGB, RGB ... RGB] format */ uint8_t image_data[CONV1_IM_CH * CONV1_IM_DIM * CONV1_IM_DIM] = IMG_DATA; q7_t output_data[IP1_OUT]; //vector buffer: max(im2col buffer,average pool buffer, fully connected buffer) q7_t col_buffer[2 * 5 * 5 * 32 * 2]; q7_t scratch_buffer[32 * 32 * 10 * 4]; int main() { #ifdef RTE_Compiler_EventRecorder EventRecorderInitialize (EventRecordAll, 1); // initialize and start Event Recorder #endif printf("start execution\n"); /* start the execution */ q7_t *img_buffer1 = scratch_buffer; q7_t *img_buffer2 = img_buffer1 + 32 * 32 * 32; /* input pre-processing */ int mean_data[3] = INPUT_MEAN_SHIFT; unsigned int scale_data[3] = INPUT_RIGHT_SHIFT; for (int i=0;i<32*32*3; i+=3) { img_buffer2[i] = (q7_t)__SSAT( ((((int)image_data[i] - mean_data[0])<<7) + (0x1<<(scale_data[0]-1))) >> scale_data[0], 8); img_buffer2[i+1] = (q7_t)__SSAT( ((((int)image_data[i+1] - mean_data[1])<<7) + (0x1<<(scale_data[1]-1))) >> scale_data[1], 8); img_buffer2[i+2] = (q7_t)__SSAT( ((((int)image_data[i+2] - mean_data[2])<<7) + (0x1<<(scale_data[2]-1))) >> scale_data[2], 8); } // conv1 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_RGB(img_buffer2, CONV1_IM_DIM, CONV1_IM_CH, conv1_wt, CONV1_OUT_CH, CONV1_KER_DIM, CONV1_PADDING, CONV1_STRIDE, conv1_bias, CONV1_BIAS_LSHIFT, CONV1_OUT_RSHIFT, img_buffer1, CONV1_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV1_OUT_DIM * CONV1_OUT_DIM * CONV1_OUT_CH); // pool1 img_buffer1 -> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV1_OUT_DIM, CONV1_OUT_CH, POOL1_KER_DIM, POOL1_PADDING, POOL1_STRIDE, POOL1_OUT_DIM, NULL, img_buffer2); // conv2 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_fast(img_buffer2, CONV2_IM_DIM, CONV2_IM_CH, conv2_wt, CONV2_OUT_CH, CONV2_KER_DIM, CONV2_PADDING, CONV2_STRIDE, conv2_bias, CONV2_BIAS_LSHIFT, CONV2_OUT_RSHIFT, img_buffer1, CONV2_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV2_OUT_DIM * CONV2_OUT_DIM * CONV2_OUT_CH); // pool2 img_buffer1 -> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV2_OUT_DIM, CONV2_OUT_CH, POOL2_KER_DIM, POOL2_PADDING, POOL2_STRIDE, POOL2_OUT_DIM, col_buffer, img_buffer2); // conv3 img_buffer2 -> img_buffer1 arm_convolve_HWC_q7_fast(img_buffer2, CONV3_IM_DIM, CONV3_IM_CH, conv3_wt, CONV3_OUT_CH, CONV3_KER_DIM, CONV3_PADDING, CONV3_STRIDE, conv3_bias, CONV3_BIAS_LSHIFT, CONV3_OUT_RSHIFT, img_buffer1, CONV3_OUT_DIM, (q15_t *) col_buffer, NULL); arm_relu_q7(img_buffer1, CONV3_OUT_DIM * CONV3_OUT_DIM * CONV3_OUT_CH); // pool3 img_buffer-> img_buffer2 arm_maxpool_q7_HWC(img_buffer1, CONV3_OUT_DIM, CONV3_OUT_CH, POOL3_KER_DIM, POOL3_PADDING, POOL3_STRIDE, POOL3_OUT_DIM, col_buffer, img_buffer2); arm_fully_connected_q7_opt(img_buffer2, ip1_wt, IP1_DIM, IP1_OUT, IP1_BIAS_LSHIFT, IP1_OUT_RSHIFT, ip1_bias, output_data, (q15_t *) img_buffer1); arm_softmax_q7(output_data, 10, output_data); for (int i = 0; i < 10; i++) { printf("%d: %d\n", i, output_data[i]); } return 0; } <|endoftext|>
<commit_before>#include "encode_jpeg.h" #include "common_jpeg.h" namespace vision { namespace image { #if !JPEG_FOUND torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { TORCH_CHECK( false, "encode_jpeg: torchvision not compiled with libjpeg support"); } #else using namespace detail; torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { // Define compression structures and error handling struct jpeg_compress_struct cinfo; struct torch_jpeg_error_mgr jerr; // Define buffer to write JPEG information to and its size unsigned long jpegSize = 0; uint8_t* jpegBuf = NULL; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = torch_jpeg_error_exit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object and the buffer. */ jpeg_destroy_compress(&cinfo); if (jpegBuf != NULL) { free(jpegBuf); } TORCH_CHECK(false, (const char*)jerr.jpegLastErrorMsg); } // Check that the input tensor is on CPU TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU"); // Check that the input tensor dtype is uint8 TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8"); // Check that the input tensor is 3-dimensional TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor"); // Get image info int channels = data.size(0); int height = data.size(1); int width = data.size(2); auto input = data.permute({1, 2, 0}).contiguous(); TORCH_CHECK( channels == 1 || channels == 3, "The number of channels should be 1 or 3, got: ", channels); // Initialize JPEG structure jpeg_create_compress(&cinfo); // Set output image information cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = channels; cinfo.in_color_space = channels == 1 ? JCS_GRAYSCALE : JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); // Save JPEG output to a buffer jpeg_mem_dest(&cinfo, &jpegBuf, &jpegSize); // Start JPEG compression jpeg_start_compress(&cinfo, TRUE); auto stride = width * channels; auto ptr = input.data_ptr<uint8_t>(); // Encode JPEG file while (cinfo.next_scanline < cinfo.image_height) { jpeg_write_scanlines(&cinfo, &ptr, 1); ptr += stride; } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); torch::TensorOptions options = torch::TensorOptions{torch::kU8}; auto outTensor = torch::empty({(long)jpegSize}, options); // Copy memory from jpeg buffer, since torch cannot get ownership of it via // `from_blob` auto outPtr = outTensor.data_ptr<uint8_t>(); std::memcpy(outPtr, jpegBuf, sizeof(uint8_t) * outTensor.numel()); free(jpegBuf); return outTensor; } #endif } // namespace image } // namespace vision <commit_msg>use from_blob to avoid memcpy (#4118)<commit_after>#include "encode_jpeg.h" #include "common_jpeg.h" namespace vision { namespace image { #if !JPEG_FOUND torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { TORCH_CHECK( false, "encode_jpeg: torchvision not compiled with libjpeg support"); } #else using namespace detail; torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) { // Define compression structures and error handling struct jpeg_compress_struct cinfo {}; struct torch_jpeg_error_mgr jerr {}; // Define buffer to write JPEG information to and its size unsigned long jpegSize = 0; uint8_t* jpegBuf = nullptr; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = torch_jpeg_error_exit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object and the buffer. */ jpeg_destroy_compress(&cinfo); if (jpegBuf != nullptr) { free(jpegBuf); } TORCH_CHECK(false, (const char*)jerr.jpegLastErrorMsg); } // Check that the input tensor is on CPU TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU"); // Check that the input tensor dtype is uint8 TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8"); // Check that the input tensor is 3-dimensional TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor"); // Get image info int channels = data.size(0); int height = data.size(1); int width = data.size(2); auto input = data.permute({1, 2, 0}).contiguous(); TORCH_CHECK( channels == 1 || channels == 3, "The number of channels should be 1 or 3, got: ", channels); // Initialize JPEG structure jpeg_create_compress(&cinfo); // Set output image information cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = channels; cinfo.in_color_space = channels == 1 ? JCS_GRAYSCALE : JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); // Save JPEG output to a buffer jpeg_mem_dest(&cinfo, &jpegBuf, &jpegSize); // Start JPEG compression jpeg_start_compress(&cinfo, TRUE); auto stride = width * channels; auto ptr = input.data_ptr<uint8_t>(); // Encode JPEG file while (cinfo.next_scanline < cinfo.image_height) { jpeg_write_scanlines(&cinfo, &ptr, 1); ptr += stride; } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); torch::TensorOptions options = torch::TensorOptions{torch::kU8}; auto out_tensor = torch::from_blob(jpegBuf, {(long)jpegSize}, ::free, options); jpegBuf = nullptr; return out_tensor; } #endif } // namespace image } // namespace vision <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "client_connection.h" #include "client_greenstack_connection.h" #include "client_mcbp_connection.h" #include "cJSON_utils.h" #include <cbsasl/cbsasl.h> #include <iostream> #include <libgreenstack/Greenstack.h> #include <memcached/protocol_binary.h> #include <platform/strerror.h> #include <sstream> #include <stdexcept> #include <system_error> #include <string> #include <limits> ///////////////////////////////////////////////////////////////////////// // Implementation of the ConnectionMap class ///////////////////////////////////////////////////////////////////////// MemcachedConnection& ConnectionMap::getConnection(const Protocol& protocol, bool ssl, sa_family_t family, in_port_t port) { for (auto* conn : connections) { if (conn->getProtocol() == protocol && conn->isSsl() == ssl && conn->getFamily() == family && (port == 0 || conn->getPort() == port)) { return *conn; } } throw std::runtime_error("No connection matching the request"); } bool ConnectionMap::contains(const Protocol& protocol, bool ssl, sa_family_t family) { try { (void)getConnection(protocol, ssl, family, 0); return true; } catch (std::runtime_error) { return false; } } void ConnectionMap::initialize(cJSON* ports) { invalidate(); cJSON* array = cJSON_GetObjectItem(ports, "ports"); if (array == nullptr) { char* json = cJSON_PrintUnformatted(ports); std::string msg("ports not found in portnumber file: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto numEntries = cJSON_GetArraySize(array); sa_family_t family; for (int ii = 0; ii < numEntries; ++ii) { auto obj = cJSON_GetArrayItem(array, ii); auto fam = cJSON_GetObjectItem(obj, "family"); if (strcmp(fam->valuestring, "AF_INET") == 0) { family = AF_INET; } else if (strcmp(fam->valuestring, "AF_INET6") == 0) { family = AF_INET6; } else { char* json = cJSON_PrintUnformatted(obj); std::string msg("Unsupported network family: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto ssl = cJSON_GetObjectItem(obj, "ssl"); if (ssl == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("ssl missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto port = cJSON_GetObjectItem(obj, "port"); if (port == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("port missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto protocol = cJSON_GetObjectItem(obj, "protocol"); if (protocol == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("protocol missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto portval = static_cast<in_port_t>(port->valueint); bool useSsl = ssl->type == cJSON_True ? true : false; MemcachedConnection* connection; if (strcmp(protocol->valuestring, "greenstack") == 0) { #ifdef ENABLE_GREENSTACK // Enable when we get greenstack support connection = new MemcachedGreenstackConnection("", portval, family, useSsl); #else throw std::logic_error( "ConnectionMap::initialize: built without greenstack support"); #endif } else { connection = new MemcachedBinprotConnection("", portval, family, useSsl); } connections.push_back(connection); } } void ConnectionMap::invalidate() { for (auto c : connections) { delete c; } connections.resize(0); } ///////////////////////////////////////////////////////////////////////// // Implementation of the MemcachedConnection class ///////////////////////////////////////////////////////////////////////// MemcachedConnection::MemcachedConnection(const std::string& host, in_port_t port, sa_family_t family, bool ssl, const Protocol& protocol) : host(host), port(port), family(family), ssl(ssl), protocol(protocol), context(nullptr), bio(nullptr), sock(INVALID_SOCKET), synchronous(false) { connect(); } MemcachedConnection::~MemcachedConnection() { close(); } void MemcachedConnection::reconnect() { close(); connect(); } void MemcachedConnection::close() { if (ssl) { // the socket is closed by the underlying BIO stuctures if (bio != nullptr) { BIO_free_all(bio); bio = nullptr; } if (context != nullptr) { SSL_CTX_free(context); context = nullptr; } } else { if (sock != INVALID_SOCKET) { ::closesocket(sock); sock = INVALID_SOCKET; } } } SOCKET new_socket(std::string& host, in_port_t port, sa_family_t family) { struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_protocol = IPPROTO_TCP; hints.ai_socktype = SOCK_STREAM; hints.ai_family = family; int error; struct addrinfo* ai; if (host.empty() || host == "localhost") { if (family == AF_INET) { host.assign("127.0.0.1"); } else if (family == AF_INET6){ host.assign("::1"); } else if (family == AF_UNSPEC) { host.assign("localhost"); } } error = getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &ai); if (error != 0) { throw std::system_error(error, std::system_category(), "Failed to resolve address \"" + host + "\""); } for (struct addrinfo* next = ai; next; next = next->ai_next) { SOCKET sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sfd != INVALID_SOCKET) { #ifdef WIN32 // BIO_new_socket pass the socket as an int, but it is a SOCKET on // Windows.. On windows a socket is an unsigned value, and may // get an overflow inside openssl (I don't know the exact width of // the SOCKET, and how openssl use the value internally). This // class is mostly used from the test framework so let's throw // an exception instead and treat it like a test failure (to be // on the safe side). We'll be refactoring to SCHANNEL in the // future anyway. if (sfd > std::numeric_limits<int>::max()) { closesocket(sfd); throw std::runtime_error("Socket value too big " "(may trigger behavior openssl)"); } #endif if (connect(sfd, ai->ai_addr, ai->ai_addrlen) != SOCKET_ERROR) { freeaddrinfo(ai); return sfd; } closesocket(sfd); } } freeaddrinfo(ai); return INVALID_SOCKET; } void MemcachedConnection::connect() { sock = new_socket(host, port, family); if (sock == INVALID_SOCKET) { std::string msg("Failed to connect to: "); if (family == AF_INET || family == AF_UNSPEC) { msg += host + ":"; } else { msg += "[" + host + "]:"; } msg.append(std::to_string(port)); throw std::runtime_error(msg); } /* we're connected */ if (ssl) { if ((context = SSL_CTX_new(SSLv23_client_method())) == NULL) { BIO_free_all(bio); throw std::runtime_error("Failed to create openssl client contex"); } /* Ensure read/write operations only return after the * handshake and successful completion. */ SSL_CTX_set_mode(context, SSL_MODE_AUTO_RETRY); bio = BIO_new_ssl(context, 1); BIO_push(bio, BIO_new_socket(sock, 0)); if (BIO_do_handshake(bio) <= 0) { BIO_free_all(bio); SSL_CTX_free(context); bio = nullptr; context = nullptr; throw std::runtime_error("Failed to do SSL handshake!"); } } } void MemcachedConnection::sendBufferSsl(cb::const_byte_buffer buf) { const char* data = reinterpret_cast<const char*>(buf.data()); cb::const_byte_buffer::size_type nbytes = buf.size(); cb::const_byte_buffer::size_type offset = 0; while (offset < nbytes) { int nw = BIO_write(bio, data + offset, nbytes - offset); if (nw < 0) { if (BIO_should_retry(bio) == 0) { throw std::runtime_error("Failed to write data"); } } else { offset += nw; } } } void MemcachedConnection::sendBufferPlain(cb::const_byte_buffer buf) { const char* data = reinterpret_cast<const char*>(buf.data()); cb::const_byte_buffer::size_type nbytes = buf.size(); cb::const_byte_buffer::size_type offset = 0; while (offset < nbytes) { auto nw = send(sock, data + offset, nbytes - offset, 0); if (nw <= 0) { throw std::system_error(get_socket_error(), std::system_category(), "MemcachedConnection::sendFramePlain: failed to send data"); } else { offset += nw; } } } void MemcachedConnection::readSsl(Frame& frame, size_t bytes) { Frame::size_type offset = frame.payload.size(); frame.payload.resize(bytes + offset); char* data = reinterpret_cast<char*>(frame.payload.data()) + offset; size_t total = 0; while (total < bytes) { int nr = BIO_read(bio, data + total, bytes - total); if (nr < 0) { if (BIO_should_retry(bio) == 0) { throw std::runtime_error("Failed to read data"); } } else { total += nr; } } } void MemcachedConnection::readPlain(Frame& frame, size_t bytes) { Frame::size_type offset = frame.payload.size(); frame.payload.resize(bytes + offset); char* data = reinterpret_cast<char*>(frame.payload.data()) + offset; size_t total = 0; while (total < bytes) { auto nr = recv(sock, data + total, bytes - total, 0); if (nr <= 0) { auto error = get_socket_error(); if (nr == 0) { // nr == 0 means that the other end closed the connection. // Given that we expected to read more data, let's throw // an connection reset exception error = ECONNRESET; } throw std::system_error(error, std::system_category(), "MemcachedConnection::readPlain: failed to read data"); } else { total += nr; } } } void MemcachedConnection::sendFrame(const Frame& frame) { if (ssl) { sendFrameSsl(frame); } else { sendFramePlain(frame); } } void MemcachedConnection::sendBuffer(cb::const_byte_buffer& buf) { if (ssl) { sendBufferSsl(buf); } else { sendBufferPlain(buf); } } void MemcachedConnection::sendPartialFrame(Frame& frame, Frame::size_type length) { // Move the remainder to a new frame. auto rem_first = frame.payload.begin() + length; auto rem_last = frame.payload.end(); std::vector<uint8_t> remainder; std::copy(rem_first, rem_last, std::back_inserter(remainder)); frame.payload.erase(rem_first, rem_last); // Send the partial frame. sendFrame(frame); // Swap the old payload with the remainder. frame.payload.swap(remainder); } void MemcachedConnection::read(Frame& frame, size_t bytes) { if (ssl) { readSsl(frame, bytes); } else { readPlain(frame, bytes); } } unique_cJSON_ptr MemcachedConnection::stats(const std::string& subcommand) { unique_cJSON_ptr ret(cJSON_CreateObject()); for (auto& pair : statsMap(subcommand)) { const std::string& key = pair.first; const std::string& value = pair.second; if (value == "false") { cJSON_AddFalseToObject(ret.get(), key.c_str()); } else if (value == "true") { cJSON_AddTrueToObject(ret.get(), key.c_str()); } else { try { int64_t val = std::stoll(value); cJSON_AddNumberToObject(ret.get(), key.c_str(), val); } catch (...) { cJSON_AddStringToObject(ret.get(), key.c_str(), value.c_str()); } } } return ret; } <commit_msg>MemcachedConnection: always close fd<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "client_connection.h" #include "client_greenstack_connection.h" #include "client_mcbp_connection.h" #include "cJSON_utils.h" #include <cbsasl/cbsasl.h> #include <iostream> #include <libgreenstack/Greenstack.h> #include <memcached/protocol_binary.h> #include <platform/strerror.h> #include <sstream> #include <stdexcept> #include <system_error> #include <string> #include <limits> ///////////////////////////////////////////////////////////////////////// // Implementation of the ConnectionMap class ///////////////////////////////////////////////////////////////////////// MemcachedConnection& ConnectionMap::getConnection(const Protocol& protocol, bool ssl, sa_family_t family, in_port_t port) { for (auto* conn : connections) { if (conn->getProtocol() == protocol && conn->isSsl() == ssl && conn->getFamily() == family && (port == 0 || conn->getPort() == port)) { return *conn; } } throw std::runtime_error("No connection matching the request"); } bool ConnectionMap::contains(const Protocol& protocol, bool ssl, sa_family_t family) { try { (void)getConnection(protocol, ssl, family, 0); return true; } catch (std::runtime_error) { return false; } } void ConnectionMap::initialize(cJSON* ports) { invalidate(); cJSON* array = cJSON_GetObjectItem(ports, "ports"); if (array == nullptr) { char* json = cJSON_PrintUnformatted(ports); std::string msg("ports not found in portnumber file: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto numEntries = cJSON_GetArraySize(array); sa_family_t family; for (int ii = 0; ii < numEntries; ++ii) { auto obj = cJSON_GetArrayItem(array, ii); auto fam = cJSON_GetObjectItem(obj, "family"); if (strcmp(fam->valuestring, "AF_INET") == 0) { family = AF_INET; } else if (strcmp(fam->valuestring, "AF_INET6") == 0) { family = AF_INET6; } else { char* json = cJSON_PrintUnformatted(obj); std::string msg("Unsupported network family: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto ssl = cJSON_GetObjectItem(obj, "ssl"); if (ssl == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("ssl missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto port = cJSON_GetObjectItem(obj, "port"); if (port == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("port missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto protocol = cJSON_GetObjectItem(obj, "protocol"); if (protocol == nullptr) { char* json = cJSON_PrintUnformatted(obj); std::string msg("protocol missing for entry: "); msg.append(json); cJSON_Free(json); throw std::runtime_error(msg); } auto portval = static_cast<in_port_t>(port->valueint); bool useSsl = ssl->type == cJSON_True ? true : false; MemcachedConnection* connection; if (strcmp(protocol->valuestring, "greenstack") == 0) { #ifdef ENABLE_GREENSTACK // Enable when we get greenstack support connection = new MemcachedGreenstackConnection("", portval, family, useSsl); #else throw std::logic_error( "ConnectionMap::initialize: built without greenstack support"); #endif } else { connection = new MemcachedBinprotConnection("", portval, family, useSsl); } connections.push_back(connection); } } void ConnectionMap::invalidate() { for (auto c : connections) { delete c; } connections.resize(0); } ///////////////////////////////////////////////////////////////////////// // Implementation of the MemcachedConnection class ///////////////////////////////////////////////////////////////////////// MemcachedConnection::MemcachedConnection(const std::string& host, in_port_t port, sa_family_t family, bool ssl, const Protocol& protocol) : host(host), port(port), family(family), ssl(ssl), protocol(protocol), context(nullptr), bio(nullptr), sock(INVALID_SOCKET), synchronous(false) { connect(); } MemcachedConnection::~MemcachedConnection() { close(); } void MemcachedConnection::reconnect() { close(); connect(); } void MemcachedConnection::close() { if (ssl) { if (bio != nullptr) { BIO_free_all(bio); bio = nullptr; } if (context != nullptr) { SSL_CTX_free(context); context = nullptr; } } if (sock != INVALID_SOCKET) { ::closesocket(sock); sock = INVALID_SOCKET; } } SOCKET new_socket(std::string& host, in_port_t port, sa_family_t family) { struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_protocol = IPPROTO_TCP; hints.ai_socktype = SOCK_STREAM; hints.ai_family = family; int error; struct addrinfo* ai; if (host.empty() || host == "localhost") { if (family == AF_INET) { host.assign("127.0.0.1"); } else if (family == AF_INET6){ host.assign("::1"); } else if (family == AF_UNSPEC) { host.assign("localhost"); } } error = getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &ai); if (error != 0) { throw std::system_error(error, std::system_category(), "Failed to resolve address \"" + host + "\""); } for (struct addrinfo* next = ai; next; next = next->ai_next) { SOCKET sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sfd != INVALID_SOCKET) { #ifdef WIN32 // BIO_new_socket pass the socket as an int, but it is a SOCKET on // Windows.. On windows a socket is an unsigned value, and may // get an overflow inside openssl (I don't know the exact width of // the SOCKET, and how openssl use the value internally). This // class is mostly used from the test framework so let's throw // an exception instead and treat it like a test failure (to be // on the safe side). We'll be refactoring to SCHANNEL in the // future anyway. if (sfd > std::numeric_limits<int>::max()) { closesocket(sfd); throw std::runtime_error("Socket value too big " "(may trigger behavior openssl)"); } #endif if (connect(sfd, ai->ai_addr, ai->ai_addrlen) != SOCKET_ERROR) { freeaddrinfo(ai); return sfd; } closesocket(sfd); } } freeaddrinfo(ai); return INVALID_SOCKET; } void MemcachedConnection::connect() { sock = new_socket(host, port, family); if (sock == INVALID_SOCKET) { std::string msg("Failed to connect to: "); if (family == AF_INET || family == AF_UNSPEC) { msg += host + ":"; } else { msg += "[" + host + "]:"; } msg.append(std::to_string(port)); throw std::runtime_error(msg); } /* we're connected */ if (ssl) { if ((context = SSL_CTX_new(SSLv23_client_method())) == NULL) { BIO_free_all(bio); throw std::runtime_error("Failed to create openssl client contex"); } /* Ensure read/write operations only return after the * handshake and successful completion. */ SSL_CTX_set_mode(context, SSL_MODE_AUTO_RETRY); bio = BIO_new_ssl(context, 1); BIO_push(bio, BIO_new_socket(sock, 0)); if (BIO_do_handshake(bio) <= 0) { BIO_free_all(bio); SSL_CTX_free(context); bio = nullptr; context = nullptr; throw std::runtime_error("Failed to do SSL handshake!"); } } } void MemcachedConnection::sendBufferSsl(cb::const_byte_buffer buf) { const char* data = reinterpret_cast<const char*>(buf.data()); cb::const_byte_buffer::size_type nbytes = buf.size(); cb::const_byte_buffer::size_type offset = 0; while (offset < nbytes) { int nw = BIO_write(bio, data + offset, nbytes - offset); if (nw < 0) { if (BIO_should_retry(bio) == 0) { throw std::runtime_error("Failed to write data"); } } else { offset += nw; } } } void MemcachedConnection::sendBufferPlain(cb::const_byte_buffer buf) { const char* data = reinterpret_cast<const char*>(buf.data()); cb::const_byte_buffer::size_type nbytes = buf.size(); cb::const_byte_buffer::size_type offset = 0; while (offset < nbytes) { auto nw = send(sock, data + offset, nbytes - offset, 0); if (nw <= 0) { throw std::system_error(get_socket_error(), std::system_category(), "MemcachedConnection::sendFramePlain: failed to send data"); } else { offset += nw; } } } void MemcachedConnection::readSsl(Frame& frame, size_t bytes) { Frame::size_type offset = frame.payload.size(); frame.payload.resize(bytes + offset); char* data = reinterpret_cast<char*>(frame.payload.data()) + offset; size_t total = 0; while (total < bytes) { int nr = BIO_read(bio, data + total, bytes - total); if (nr < 0) { if (BIO_should_retry(bio) == 0) { throw std::runtime_error("Failed to read data"); } } else { total += nr; } } } void MemcachedConnection::readPlain(Frame& frame, size_t bytes) { Frame::size_type offset = frame.payload.size(); frame.payload.resize(bytes + offset); char* data = reinterpret_cast<char*>(frame.payload.data()) + offset; size_t total = 0; while (total < bytes) { auto nr = recv(sock, data + total, bytes - total, 0); if (nr <= 0) { auto error = get_socket_error(); if (nr == 0) { // nr == 0 means that the other end closed the connection. // Given that we expected to read more data, let's throw // an connection reset exception error = ECONNRESET; } throw std::system_error(error, std::system_category(), "MemcachedConnection::readPlain: failed to read data"); } else { total += nr; } } } void MemcachedConnection::sendFrame(const Frame& frame) { if (ssl) { sendFrameSsl(frame); } else { sendFramePlain(frame); } } void MemcachedConnection::sendBuffer(cb::const_byte_buffer& buf) { if (ssl) { sendBufferSsl(buf); } else { sendBufferPlain(buf); } } void MemcachedConnection::sendPartialFrame(Frame& frame, Frame::size_type length) { // Move the remainder to a new frame. auto rem_first = frame.payload.begin() + length; auto rem_last = frame.payload.end(); std::vector<uint8_t> remainder; std::copy(rem_first, rem_last, std::back_inserter(remainder)); frame.payload.erase(rem_first, rem_last); // Send the partial frame. sendFrame(frame); // Swap the old payload with the remainder. frame.payload.swap(remainder); } void MemcachedConnection::read(Frame& frame, size_t bytes) { if (ssl) { readSsl(frame, bytes); } else { readPlain(frame, bytes); } } unique_cJSON_ptr MemcachedConnection::stats(const std::string& subcommand) { unique_cJSON_ptr ret(cJSON_CreateObject()); for (auto& pair : statsMap(subcommand)) { const std::string& key = pair.first; const std::string& value = pair.second; if (value == "false") { cJSON_AddFalseToObject(ret.get(), key.c_str()); } else if (value == "true") { cJSON_AddTrueToObject(ret.get(), key.c_str()); } else { try { int64_t val = std::stoll(value); cJSON_AddNumberToObject(ret.get(), key.c_str(), val); } catch (...) { cJSON_AddStringToObject(ret.get(), key.c_str(), value.c_str()); } } } return ret; } <|endoftext|>
<commit_before>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bootstrap_natives.h" #include "vm/exceptions.h" #include "vm/native_entry.h" #include "vm/object.h" #include "vm/symbols.h" #include "vm/unicode.h" namespace dart { DEFINE_NATIVE_ENTRY(StringBase_createFromCodePoints, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, list, arguments->NativeArgAt(0)); if (!list.IsGrowableObjectArray() && !list.IsArray()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, list); Exceptions::ThrowByType(Exceptions::kArgument, args); } Array& a = Array::Handle(); intptr_t array_len; if (list.IsGrowableObjectArray()) { const GrowableObjectArray& growableArray = GrowableObjectArray::Cast(list); a ^= growableArray.data(); array_len = growableArray.Length(); } else { a ^= Array::Cast(list).raw(); array_len = a.Length(); } Zone* zone = isolate->current_zone(); // Unbox the array and determine the maximum element width. bool is_one_byte_string = true; intptr_t utf16_len = array_len; int32_t* utf32_array = zone->Alloc<int32_t>(array_len); Object& index_object = Object::Handle(isolate); for (intptr_t i = 0; i < array_len; i++) { index_object = a.At(i); if (!index_object.IsSmi()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, index_object); Exceptions::ThrowByType(Exceptions::kArgument, args); } intptr_t value = Smi::Cast(index_object).Value(); if (Utf::IsOutOfRange(value)) { Exceptions::ThrowByType(Exceptions::kArgument, Object::empty_array()); } else { if (!Utf::IsLatin1(value)) { is_one_byte_string = false; if (Utf::IsSupplementary(value)) { utf16_len += 1; } } } utf32_array[i] = value; } if (is_one_byte_string) { return OneByteString::New(utf32_array, array_len, Heap::kNew); } return TwoByteString::New(utf16_len, utf32_array, array_len, Heap::kNew); } DEFINE_NATIVE_ENTRY(StringBase_substringUnchecked, 3) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2)); intptr_t start = start_obj.Value(); intptr_t end = end_obj.Value(); return String::SubString(receiver, start, (end - start)); } DEFINE_NATIVE_ENTRY(OneByteString_substringUnchecked, 3) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2)); const intptr_t start = start_obj.Value(); const intptr_t end = end_obj.Value(); return OneByteString::New(receiver, start, end - start, Heap::kNew); } // This is high-performance code. DEFINE_NATIVE_ENTRY(OneByteString_splitWithCharCode, 2) { const String& receiver = String::CheckedHandle(isolate, arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, smi_split_code, arguments->NativeArgAt(1)); const intptr_t len = receiver.Length(); const intptr_t split_code = smi_split_code.Value(); const GrowableObjectArray& result = GrowableObjectArray::Handle( isolate, GrowableObjectArray::New(16, Heap::kNew)); String& str = String::Handle(isolate); intptr_t start = 0; intptr_t i = 0; for (; i < len; i++) { if (split_code == OneByteString::CharAt(receiver, i)) { str = OneByteString::SubStringUnchecked(receiver, start, (i - start), Heap::kNew); result.Add(str); start = i + 1; } } str = OneByteString::SubStringUnchecked(receiver, start, (i - start), Heap::kNew); result.Add(str); return result.raw(); } DEFINE_NATIVE_ENTRY(OneByteString_allocate, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Smi, length_obj, arguments->NativeArgAt(0)); return OneByteString::New(length_obj.Value(), Heap::kNew); } DEFINE_NATIVE_ENTRY(OneByteString_setAt, 3) { GET_NON_NULL_NATIVE_ARGUMENT(String, receiver, arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, index_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, code_point_obj, arguments->NativeArgAt(2)); ASSERT((0 <= code_point_obj.Value()) && (code_point_obj.Value() <= 0xFF)); OneByteString::SetCharAt(receiver, index_obj.Value(), code_point_obj.Value()); return Object::null(); } DEFINE_NATIVE_ENTRY(String_getHashCode, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); intptr_t hash_val = receiver.Hash(); ASSERT(hash_val > 0); ASSERT(Smi::IsValid(hash_val)); return Smi::New(hash_val); } DEFINE_NATIVE_ENTRY(String_getLength, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); return Smi::New(receiver.Length()); } static int32_t StringValueAt(const String& str, const Integer& index) { if (index.IsSmi()) { const Smi& smi = Smi::Cast(index); int32_t index = smi.Value(); if ((index < 0) || (index >= str.Length())) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, smi); Exceptions::ThrowByType(Exceptions::kRange, args); } return str.CharAt(index); } else { // An index larger than Smi is always illegal. const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, index); Exceptions::ThrowByType(Exceptions::kRange, args); return 0; } } DEFINE_NATIVE_ENTRY(String_charAt, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1)); uint32_t value = StringValueAt(receiver, index); ASSERT(value <= 0x10FFFF); return Symbols::FromCharCode(value); } DEFINE_NATIVE_ENTRY(String_codeUnitAt, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1)); int32_t value = StringValueAt(receiver, index); ASSERT(value >= 0); ASSERT(value <= 0xFFFF); return Smi::New(value); } DEFINE_NATIVE_ENTRY(String_concat, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(String, b, arguments->NativeArgAt(1)); return String::Concat(receiver, b); } DEFINE_NATIVE_ENTRY(String_toLowerCase, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(!receiver.IsNull()); return String::ToLowerCase(receiver); } DEFINE_NATIVE_ENTRY(String_toUpperCase, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(!receiver.IsNull()); return String::ToUpperCase(receiver); } DEFINE_NATIVE_ENTRY(Strings_concatAll, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Array, strings, arguments->NativeArgAt(0)); ASSERT(!strings.IsNull()); // Check that the array contains strings. Instance& elem = Instance::Handle(); for (intptr_t i = 0; i < strings.Length(); i++) { elem ^= strings.At(i); if (!elem.IsString()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, elem); Exceptions::ThrowByType(Exceptions::kArgument, args); } } return String::ConcatAll(strings); } DEFINE_NATIVE_ENTRY(StringBuffer_createStringFromUint16Array, 3) { GET_NON_NULL_NATIVE_ARGUMENT(TypedData, codeUnits, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, length, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Bool, isLatin1, arguments->NativeArgAt(2)); intptr_t array_length = codeUnits.Length(); intptr_t length_value = length.Value(); if (length_value < 0 || length_value > array_length) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, length); Exceptions::ThrowByType(Exceptions::kRange, args); } const String& result = isLatin1.value() ? String::Handle(OneByteString::New(length_value, Heap::kNew)) : String::Handle(TwoByteString::New(length_value, Heap::kNew)); NoGCScope no_gc; uint16_t* data_position = reinterpret_cast<uint16_t*>(codeUnits.DataAddr(0)); String::Copy(result, 0, data_position, length_value); return result.raw(); } } // namespace dart <commit_msg>Treat final variables initialized with a literal as constants. Also sneak in a small cleanup.<commit_after>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bootstrap_natives.h" #include "vm/exceptions.h" #include "vm/native_entry.h" #include "vm/object.h" #include "vm/symbols.h" #include "vm/unicode.h" namespace dart { DEFINE_NATIVE_ENTRY(StringBase_createFromCodePoints, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, list, arguments->NativeArgAt(0)); if (!list.IsGrowableObjectArray() && !list.IsArray()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, list); Exceptions::ThrowByType(Exceptions::kArgument, args); } Array& a = Array::Handle(); intptr_t array_len; if (list.IsGrowableObjectArray()) { const GrowableObjectArray& growableArray = GrowableObjectArray::Cast(list); a ^= growableArray.data(); array_len = growableArray.Length(); } else { a ^= Array::Cast(list).raw(); array_len = a.Length(); } Zone* zone = isolate->current_zone(); // Unbox the array and determine the maximum element width. bool is_one_byte_string = true; intptr_t utf16_len = array_len; int32_t* utf32_array = zone->Alloc<int32_t>(array_len); Object& index_object = Object::Handle(isolate); for (intptr_t i = 0; i < array_len; i++) { index_object = a.At(i); if (!index_object.IsSmi()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, index_object); Exceptions::ThrowByType(Exceptions::kArgument, args); } intptr_t value = Smi::Cast(index_object).Value(); if (Utf::IsOutOfRange(value)) { Exceptions::ThrowByType(Exceptions::kArgument, Object::empty_array()); } else { if (!Utf::IsLatin1(value)) { is_one_byte_string = false; if (Utf::IsSupplementary(value)) { utf16_len += 1; } } } utf32_array[i] = value; } if (is_one_byte_string) { return OneByteString::New(utf32_array, array_len, Heap::kNew); } return TwoByteString::New(utf16_len, utf32_array, array_len, Heap::kNew); } DEFINE_NATIVE_ENTRY(StringBase_substringUnchecked, 3) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2)); intptr_t start = start_obj.Value(); intptr_t end = end_obj.Value(); return String::SubString(receiver, start, (end - start)); } DEFINE_NATIVE_ENTRY(OneByteString_substringUnchecked, 3) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, start_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, end_obj, arguments->NativeArgAt(2)); const intptr_t start = start_obj.Value(); const intptr_t end = end_obj.Value(); return OneByteString::New(receiver, start, end - start, Heap::kNew); } // This is high-performance code. DEFINE_NATIVE_ENTRY(OneByteString_splitWithCharCode, 2) { const String& receiver = String::CheckedHandle(isolate, arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, smi_split_code, arguments->NativeArgAt(1)); const intptr_t len = receiver.Length(); const intptr_t split_code = smi_split_code.Value(); const GrowableObjectArray& result = GrowableObjectArray::Handle( isolate, GrowableObjectArray::New(16, Heap::kNew)); String& str = String::Handle(isolate); intptr_t start = 0; intptr_t i = 0; for (; i < len; i++) { if (split_code == OneByteString::CharAt(receiver, i)) { str = OneByteString::SubStringUnchecked(receiver, start, (i - start), Heap::kNew); result.Add(str); start = i + 1; } } str = OneByteString::SubStringUnchecked(receiver, start, (i - start), Heap::kNew); result.Add(str); return result.raw(); } DEFINE_NATIVE_ENTRY(OneByteString_allocate, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Smi, length_obj, arguments->NativeArgAt(0)); return OneByteString::New(length_obj.Value(), Heap::kNew); } DEFINE_NATIVE_ENTRY(OneByteString_setAt, 3) { GET_NON_NULL_NATIVE_ARGUMENT(String, receiver, arguments->NativeArgAt(0)); ASSERT(receiver.IsOneByteString()); GET_NON_NULL_NATIVE_ARGUMENT(Smi, index_obj, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, code_point_obj, arguments->NativeArgAt(2)); ASSERT((0 <= code_point_obj.Value()) && (code_point_obj.Value() <= 0xFF)); OneByteString::SetCharAt(receiver, index_obj.Value(), code_point_obj.Value()); return Object::null(); } DEFINE_NATIVE_ENTRY(String_getHashCode, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); intptr_t hash_val = receiver.Hash(); ASSERT(hash_val > 0); ASSERT(Smi::IsValid(hash_val)); return Smi::New(hash_val); } DEFINE_NATIVE_ENTRY(String_getLength, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); return Smi::New(receiver.Length()); } static int32_t StringValueAt(const String& str, const Integer& index) { if (index.IsSmi()) { const Smi& smi = Smi::Cast(index); int32_t index = smi.Value(); if ((index < 0) || (index >= str.Length())) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, smi); Exceptions::ThrowByType(Exceptions::kRange, args); } return str.CharAt(index); } else { // An index larger than Smi is always illegal. const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, index); Exceptions::ThrowByType(Exceptions::kRange, args); return 0; } } DEFINE_NATIVE_ENTRY(String_charAt, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1)); uint32_t value = StringValueAt(receiver, index); ASSERT(value <= 0x10FFFF); return Symbols::FromCharCode(value); } DEFINE_NATIVE_ENTRY(String_codeUnitAt, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Integer, index, arguments->NativeArgAt(1)); int32_t value = StringValueAt(receiver, index); ASSERT(value >= 0); ASSERT(value <= 0xFFFF); return Smi::New(value); } DEFINE_NATIVE_ENTRY(String_concat, 2) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(String, b, arguments->NativeArgAt(1)); return String::Concat(receiver, b); } DEFINE_NATIVE_ENTRY(String_toLowerCase, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(!receiver.IsNull()); return String::ToLowerCase(receiver); } DEFINE_NATIVE_ENTRY(String_toUpperCase, 1) { const String& receiver = String::CheckedHandle(arguments->NativeArgAt(0)); ASSERT(!receiver.IsNull()); return String::ToUpperCase(receiver); } DEFINE_NATIVE_ENTRY(Strings_concatAll, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Array, strings, arguments->NativeArgAt(0)); ASSERT(!strings.IsNull()); // Check that the array contains strings. Instance& elem = Instance::Handle(); for (intptr_t i = 0; i < strings.Length(); i++) { elem ^= strings.At(i); if (!elem.IsString()) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, elem); Exceptions::ThrowByType(Exceptions::kArgument, args); } } return String::ConcatAll(strings); } DEFINE_NATIVE_ENTRY(StringBuffer_createStringFromUint16Array, 3) { GET_NON_NULL_NATIVE_ARGUMENT(TypedData, codeUnits, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, length, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(Bool, isLatin1, arguments->NativeArgAt(2)); intptr_t array_length = codeUnits.Length(); intptr_t length_value = length.Value(); if (length_value < 0 || length_value > array_length) { const Array& args = Array::Handle(Array::New(1)); args.SetAt(0, length); Exceptions::ThrowByType(Exceptions::kRange, args); } const String& result = isLatin1.value() ? String::Handle(OneByteString::New(length_value, Heap::kNew)) : String::Handle(TwoByteString::New(length_value, Heap::kNew)); NoGCScope no_gc; uint16_t* data_position = reinterpret_cast<uint16_t*>(codeUnits.DataAddr(0)); String::Copy(result, 0, data_position, length_value); return result.raw(); } } // namespace dart <|endoftext|>
<commit_before>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include "itkImageFileReader.h" #include "itkImageToVectorImageFilter.h" #include "itkImageFileWriter.h" //------------------------------------------------------------------------------------- /** run: A macro to call a function. */ #define run( function, type, dim ) \ if ( ComponentTypeIn == #type && Dimension == dim ) \ { \ typedef itk::Image< type, dim > InputImageType; \ typedef itk::VectorImage< type, dim > OutputImageType; \ function< InputImageType, OutputImageType >( inputFileNames, outputFileName ); \ supported = true; \ } //------------------------------------------------------------------------------------- /** Declare ComposeVectorImage. */ template< class InputImageType, class OutputImageType > void ComposeVectorImage( const std::vector<std::string> & inputFileNames, const std::string & outputFileName ); /** Declare PrintHelp. */ void PrintHelp( void ); //------------------------------------------------------------------------------------- int main( int argc, char ** argv ) { /** Check arguments for help. */ if ( argc < 4 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::vector<std::string> inputFileNames( 0, "" ); bool retin = parser->GetCommandLineArgument( "-in", inputFileNames ); std::string outputFileName = "VECTOR.mhd"; bool retout = parser->GetCommandLineArgument( "-out", outputFileName ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } if ( inputFileNames.size() < 2 ) { std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "short"; std::string PixelType; //we don't use this unsigned int Dimension = 3; unsigned int NumberOfComponents = 1; std::vector<unsigned int> imagesize( Dimension, 0 ); int retgip = GetImageProperties( inputFileNames[ 0 ], PixelType, ComponentTypeIn, Dimension, NumberOfComponents, imagesize ); if ( retgip != 0 ) { return 1; } /** Check for vector images. */ if ( NumberOfComponents > 1 ) { std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl; std::cerr << "Cannot make vector of vector images." << std::endl; return 1; } /** Get rid of the possible "_" in ComponentType. */ ReplaceUnderscoreWithSpace( ComponentTypeIn ); /** Run the program. */ bool supported = false; try { run( ComposeVectorImage, char, 2 ); run( ComposeVectorImage, unsigned char, 2 ); run( ComposeVectorImage, short, 2 ); run( ComposeVectorImage, unsigned short, 2 ); run( ComposeVectorImage, int, 2 ); run( ComposeVectorImage, unsigned int, 2 ); run( ComposeVectorImage, long, 2 ); run( ComposeVectorImage, unsigned long, 2 ); run( ComposeVectorImage, float, 2 ); run( ComposeVectorImage, double, 2 ); run( ComposeVectorImage, char, 3 ); run( ComposeVectorImage, unsigned char, 3 ); run( ComposeVectorImage, short, 3 ); run( ComposeVectorImage, unsigned short, 3 ); run( ComposeVectorImage, int, 3 ); run( ComposeVectorImage, unsigned int, 3 ); run( ComposeVectorImage, long, 3 ); run( ComposeVectorImage, unsigned long, 3 ); run( ComposeVectorImage, float, 3 ); run( ComposeVectorImage, double, 3 ); } catch( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeIn << " ; dimension = " << Dimension << std::endl; return 1; } /** End program. */ return 0; } // end main /** * ******************* ComposeVectorImage ******************* */ template< class InputImageType, class OutputImageType > void ComposeVectorImage( const std::vector<std::string> & inputFileNames, const std::string & outputFileName ) { /** Typedef's. */ typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageToVectorImageFilter< InputImageType > FilterType;; typedef itk::ImageFileWriter< OutputImageType > WriterType; /** Read in the input images. */ std::vector<typename ReaderType::Pointer> readers( inputFileNames.size() ); for ( unsigned int i = 0; i < inputFileNames.size(); ++i ) { readers[ i ] = ReaderType::New(); readers[ i ]->SetFileName( inputFileNames[ i ] ); readers[ i ]->Update(); } /** Create index extractor and writer. */ typename FilterType::Pointer composer = FilterType::New(); for ( unsigned int i = 0; i < inputFileNames.size(); ++i ) { composer->SetNthInput( i, readers[ i ]->GetOutput() ); } /** Write vector image. */ typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFileName ); writer->SetInput( composer->GetOutput() ); writer->Update(); } // end ComposeVectorImage() /** * ******************* PrintHelp ******************* */ void PrintHelp() { std::cout << "Usage:" << std::endl << "pximagetovectorimage" << std::endl; std::cout << " -in inputFilenames, at least 2" << std::endl; std::cout << " [-out] outputFilename, default VECTOR.mhd" << std::endl; std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double." << std::endl; std::cout << "Note: make sure that the input images are of the same type, size, etc." << std::endl; } // end PrintHelp() <commit_msg>MS:<commit_after>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include "itkImageFileReader.h" #include "itkImageToVectorImageFilter.h" #include "itkImageFileWriter.h" //------------------------------------------------------------------------------------- /** run: A macro to call a function. */ #define run( function, type, dim ) \ if ( ComponentTypeIn == #type && Dimension == dim ) \ { \ typedef itk::Image< type, dim > InputImageType; \ typedef itk::VectorImage< type, dim > OutputImageType; \ function< InputImageType, OutputImageType >( inputFileNames, outputFileName, numberOfStreams ); \ supported = true; \ } //------------------------------------------------------------------------------------- /** Declare ComposeVectorImage. */ template< class InputImageType, class OutputImageType > void ComposeVectorImage( const std::vector<std::string> & inputFileNames, const std::string & outputFileName, const unsigned int & numberOfStreams ); /** Declare PrintHelp. */ void PrintHelp( void ); //------------------------------------------------------------------------------------- int main( int argc, char ** argv ) { /** Check arguments for help. */ if ( argc < 4 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::vector<std::string> inputFileNames( 0, "" ); bool retin = parser->GetCommandLineArgument( "-in", inputFileNames ); std::string outputFileName = "VECTOR.mhd"; bool retout = parser->GetCommandLineArgument( "-out", outputFileName ); /** Support for streaming. */ unsigned int numberOfStreams = 1; bool rets = parser->GetCommandLineArgument( "-s", numberOfStreams ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } if ( inputFileNames.size() < 2 ) { std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "short"; std::string PixelType; //we don't use this unsigned int Dimension = 3; unsigned int NumberOfComponents = 1; std::vector<unsigned int> imagesize( Dimension, 0 ); int retgip = GetImageProperties( inputFileNames[ 0 ], PixelType, ComponentTypeIn, Dimension, NumberOfComponents, imagesize ); if ( retgip != 0 ) { return 1; } /** Check for vector images. */ if ( NumberOfComponents > 1 ) { std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl; std::cerr << "Cannot make vector of vector images." << std::endl; return 1; } /** Get rid of the possible "_" in ComponentType. */ ReplaceUnderscoreWithSpace( ComponentTypeIn ); /** Run the program. */ bool supported = false; try { run( ComposeVectorImage, char, 2 ); run( ComposeVectorImage, unsigned char, 2 ); run( ComposeVectorImage, short, 2 ); run( ComposeVectorImage, unsigned short, 2 ); run( ComposeVectorImage, int, 2 ); run( ComposeVectorImage, unsigned int, 2 ); run( ComposeVectorImage, long, 2 ); run( ComposeVectorImage, unsigned long, 2 ); run( ComposeVectorImage, float, 2 ); run( ComposeVectorImage, double, 2 ); run( ComposeVectorImage, char, 3 ); run( ComposeVectorImage, unsigned char, 3 ); run( ComposeVectorImage, short, 3 ); run( ComposeVectorImage, unsigned short, 3 ); run( ComposeVectorImage, int, 3 ); run( ComposeVectorImage, unsigned int, 3 ); run( ComposeVectorImage, long, 3 ); run( ComposeVectorImage, unsigned long, 3 ); run( ComposeVectorImage, float, 3 ); run( ComposeVectorImage, double, 3 ); } catch( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeIn << " ; dimension = " << Dimension << std::endl; return 1; } /** End program. */ return 0; } // end main /** * ******************* ComposeVectorImage ******************* */ template< class InputImageType, class OutputImageType > void ComposeVectorImage( const std::vector<std::string> & inputFileNames, const std::string & outputFileName, const unsigned int & numberOfStreams ) { /** Typedef's. */ typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageToVectorImageFilter< InputImageType > FilterType;; typedef itk::ImageFileWriter< OutputImageType > WriterType; /** Read in the input images. */ std::vector<typename ReaderType::Pointer> readers( inputFileNames.size() ); for ( unsigned int i = 0; i < inputFileNames.size(); ++i ) { readers[ i ] = ReaderType::New(); readers[ i ]->SetFileName( inputFileNames[ i ] ); } /** Create index extractor and writer. */ typename FilterType::Pointer composer = FilterType::New(); for ( unsigned int i = 0; i < inputFileNames.size(); ++i ) { composer->SetNthInput( i, readers[ i ]->GetOutput() ); } /** Write vector image. */ typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFileName ); writer->SetInput( composer->GetOutput() ); writer->SetNumberOfStreamDivisions( numberOfStreams ); writer->Update(); } // end ComposeVectorImage() /** * ******************* PrintHelp ******************* */ void PrintHelp( void ) { std::cout << "Usage:" << std::endl << "pximagetovectorimage\n"; std::cout << " -in inputFilenames, at least 2\n"; std::cout << " [-out] outputFilename, default VECTOR.mhd\n"; std::cout << " [-s] number of streams, default 1.\n"; std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, " << "(unsigned) int, (unsigned) long, float, double.\n"; std::cout << "Note: make sure that the input images are of the same type, size, etc." << std::endl; } // end PrintHelp() <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <cstring> #include "InputPacket.h" #include "Server.h" using namespace ni; Server::Server(short port) : m_socket(createSocket(port)), m_running(true) { } void Server::run() { InputPacket packet; while(m_running) { recvfrom(m_socket, &packet, sizeof(InputPacket), 0, nullptr, nullptr); if(packet.isValid()) { processPacket(packet); } } } void Server::processPacket(const InputPacket& packet) { if(packet.isSafe()) { } } FileDesc Server::createSocket(short port) { sockaddr_in address; FileDesc sock = socket(AF_INET, SOCK_DGRAM, 0); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); bind(sock, (sockaddr *)&address, sizeof(address)); return sock; }<commit_msg>Implement more of the Server.<commit_after>#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <cstring> #include "MouseEvent.h" #include "InputPacket.h" #include "Server.h" using namespace ni; Server::Server(DeviceType devices, short port) : m_inputSystem(devices), m_socket(createSocket(port)), m_running(true) { } void Server::run() { InputPacket packet; while(m_running) { recvfrom(m_socket, &packet, sizeof(InputPacket), 0, nullptr, nullptr); if(packet.isValid()) { processPacket(packet); } } } void Server::processPacket(const InputPacket& packet) { if(packet.isSafe()) { if(packet.type == DeviceType::Mouse && packet.length == sizeof(MouseEvent)) { const MouseEvent event = *reinterpret_cast<const MouseEvent*>(packet.data); m_inputSystem.sendMouseEvent(event); } } } FileDesc Server::createSocket(short port) { sockaddr_in address; FileDesc sock = socket(AF_INET, SOCK_DGRAM, 0); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); bind(sock, (sockaddr *)&address, sizeof(address)); return sock; }<|endoftext|>
<commit_before>#include <string.h> #include <float.h> #include "reductions.h" #include "rand48.h" using namespace LEARNER; struct LRQstate { vw* all; bool lrindices[256]; size_t orig_size[256]; std::vector<std::string> lrpairs; bool dropout; uint64_t seed; uint64_t initial_seed; }; bool valid_int (const char* s) { char* endptr; int v = strtoul (s, &endptr, 0); (void) v; return (*s != '\0' && *endptr == '\0'); } inline bool cheesyrbit (uint64_t& seed) { return merand48 (seed) > 0.5; } inline float cheesyrand (uint32_t x) { uint64_t seed = x; return merand48 (seed); } inline bool example_is_test (example& ec) { return ec.l.simple.label == FLT_MAX; } void reset_seed (LRQstate& lrq) { if (lrq.all->bfgs) lrq.seed = lrq.initial_seed; } template <bool is_learn> void predict_or_learn(LRQstate& lrq, base_learner& base, example& ec) { vw& all = *lrq.all; // Remember original features for (unsigned char* i = ec.indices.begin; i != ec.indices.end; ++i) { if (lrq.lrindices[*i]) lrq.orig_size[*i] = ec.atomics[*i].size (); } size_t which = ec.example_counter; float first_prediction; float first_loss; unsigned int maxiter = (is_learn && ! example_is_test (ec)) ? 2 : 1; bool do_dropout = lrq.dropout && is_learn && ! example_is_test (ec); float scale = (! lrq.dropout || do_dropout) ? 1.f : 0.5f; for (unsigned int iter = 0; iter < maxiter; ++iter, ++which) { // Add left LRQ features, holding right LRQ features fixed // and vice versa // TODO: what happens with --lrq ab2 --lrq ac2 // i.e. namespace occurs multiple times (?) for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { unsigned char left = (*i)[which%2]; unsigned char right = (*i)[(which+1)%2]; unsigned int k = atoi (i->c_str () + 2); for (unsigned int lfn = 0; lfn < lrq.orig_size[left]; ++lfn) { feature* lf = ec.atomics[left].begin + lfn; float lfx = lf->x; size_t lindex = lf->weight_index + ec.ft_offset; for (unsigned int n = 1; n <= k; ++n) { if (! do_dropout || cheesyrbit (lrq.seed)) { uint32_t lwindex = (uint32_t)(lindex + (n << all.reg.stride_shift)); float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask]; // perturb away from saddle point at (0, 0) if (is_learn && ! example_is_test (ec) && *lw == 0) *lw = cheesyrand (lwindex); for (unsigned int rfn = 0; rfn < lrq.orig_size[right]; ++rfn) { feature* rf = ec.atomics[right].begin + rfn; audit_data* ra = ec.audit_features[right].begin + rfn; // NB: ec.ft_offset added by base learner float rfx = rf->x; size_t rindex = rf->weight_index; uint32_t rwindex = (uint32_t)(rindex + (n << all.reg.stride_shift)); feature lrq; lrq.x = scale * *lw * lfx * rfx; lrq.weight_index = rwindex; ec.atomics[right].push_back (lrq); if (all.audit || all.hash_inv) { std::stringstream new_feature_buffer; new_feature_buffer << right << '^' << ra->feature << '^' << n; char* new_space = strdup("lrq"); char* new_feature = strdup (new_feature_buffer.str().c_str()); audit_data ad = { new_space, new_feature, lrq.weight_index, lrq.x, true }; ec.audit_features[right].push_back (ad); } } } } } } if (is_learn) base.learn(ec); else base.predict(ec); // Restore example if (iter == 0) { first_prediction = ec.pred.scalar; first_loss = ec.loss; } else { ec.pred.scalar = first_prediction; ec.loss = first_loss; } for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { unsigned char right = (*i)[(which+1)%2]; ec.atomics[right].end = ec.atomics[right].begin + lrq.orig_size[right]; if (all.audit || all.hash_inv) { for (audit_data* a = ec.audit_features[right].begin + lrq.orig_size[right]; a < ec.audit_features[right].end; ++a) { free (a->space); free (a->feature); } ec.audit_features[right].end = ec.audit_features[right].begin + lrq.orig_size[right]; } } } } base_learner* lrq_setup(vw& all) {//parse and set arguments if (missing_option<vector<string>>(all, "lrq", "use low rank quadratic features")) return NULL; new_options(all, "Lrq options") ("lrqdropout", "use dropout training for low rank quadratic features"); add_options(all); if(!all.vm.count("lrq")) return NULL; LRQstate& lrq = calloc_or_die<LRQstate>(); size_t maxk = 0; lrq.all = &all; size_t random_seed = 0; if (all.vm.count("random_seed")) random_seed = all.vm["random_seed"].as<size_t> (); lrq.initial_seed = lrq.seed = random_seed | 8675309; if (all.vm.count("lrqdropout")) { lrq.dropout = true; *all.file_options << " --lrqdropout "; } else lrq.dropout = false; lrq.lrpairs = all.vm["lrq"].as<vector<string> > (); for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) *all.file_options << " --lrq " << *i; if (! all.quiet) { cerr << "creating low rank quadratic features for pairs: "; if (lrq.dropout) cerr << "(using dropout) "; } for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { if(!all.quiet){ if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) { cerr << endl << "error, low-rank quadratic features must involve two sets and a rank.\n"; throw exception(); } cerr << *i << " "; } // TODO: colon-syntax unsigned int k = atoi (i->c_str () + 2); lrq.lrindices[(int) (*i)[0]] = 1; lrq.lrindices[(int) (*i)[1]] = 1; maxk = max (maxk, k); } if(!all.quiet) cerr<<endl; all.wpp = all.wpp * (uint32_t)(1 + maxk); learner<LRQstate>& l = init_learner(&lrq, setup_base(all), predict_or_learn<true>, predict_or_learn<false>, 1 + maxk); l.set_end_pass(reset_seed); // TODO: leaks memory ? return make_base(l); } <commit_msg>compiler cannot determine these variables are always set, so set them<commit_after>#include <string.h> #include <float.h> #include "reductions.h" #include "rand48.h" using namespace LEARNER; struct LRQstate { vw* all; bool lrindices[256]; size_t orig_size[256]; std::vector<std::string> lrpairs; bool dropout; uint64_t seed; uint64_t initial_seed; }; bool valid_int (const char* s) { char* endptr; int v = strtoul (s, &endptr, 0); (void) v; return (*s != '\0' && *endptr == '\0'); } inline bool cheesyrbit (uint64_t& seed) { return merand48 (seed) > 0.5; } inline float cheesyrand (uint32_t x) { uint64_t seed = x; return merand48 (seed); } inline bool example_is_test (example& ec) { return ec.l.simple.label == FLT_MAX; } void reset_seed (LRQstate& lrq) { if (lrq.all->bfgs) lrq.seed = lrq.initial_seed; } template <bool is_learn> void predict_or_learn(LRQstate& lrq, base_learner& base, example& ec) { vw& all = *lrq.all; // Remember original features for (unsigned char* i = ec.indices.begin; i != ec.indices.end; ++i) { if (lrq.lrindices[*i]) lrq.orig_size[*i] = ec.atomics[*i].size (); } size_t which = ec.example_counter; float first_prediction = 0; float first_loss = 0; unsigned int maxiter = (is_learn && ! example_is_test (ec)) ? 2 : 1; bool do_dropout = lrq.dropout && is_learn && ! example_is_test (ec); float scale = (! lrq.dropout || do_dropout) ? 1.f : 0.5f; for (unsigned int iter = 0; iter < maxiter; ++iter, ++which) { // Add left LRQ features, holding right LRQ features fixed // and vice versa // TODO: what happens with --lrq ab2 --lrq ac2 // i.e. namespace occurs multiple times (?) for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { unsigned char left = (*i)[which%2]; unsigned char right = (*i)[(which+1)%2]; unsigned int k = atoi (i->c_str () + 2); for (unsigned int lfn = 0; lfn < lrq.orig_size[left]; ++lfn) { feature* lf = ec.atomics[left].begin + lfn; float lfx = lf->x; size_t lindex = lf->weight_index + ec.ft_offset; for (unsigned int n = 1; n <= k; ++n) { if (! do_dropout || cheesyrbit (lrq.seed)) { uint32_t lwindex = (uint32_t)(lindex + (n << all.reg.stride_shift)); float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask]; // perturb away from saddle point at (0, 0) if (is_learn && ! example_is_test (ec) && *lw == 0) *lw = cheesyrand (lwindex); for (unsigned int rfn = 0; rfn < lrq.orig_size[right]; ++rfn) { feature* rf = ec.atomics[right].begin + rfn; audit_data* ra = ec.audit_features[right].begin + rfn; // NB: ec.ft_offset added by base learner float rfx = rf->x; size_t rindex = rf->weight_index; uint32_t rwindex = (uint32_t)(rindex + (n << all.reg.stride_shift)); feature lrq; lrq.x = scale * *lw * lfx * rfx; lrq.weight_index = rwindex; ec.atomics[right].push_back (lrq); if (all.audit || all.hash_inv) { std::stringstream new_feature_buffer; new_feature_buffer << right << '^' << ra->feature << '^' << n; char* new_space = strdup("lrq"); char* new_feature = strdup (new_feature_buffer.str().c_str()); audit_data ad = { new_space, new_feature, lrq.weight_index, lrq.x, true }; ec.audit_features[right].push_back (ad); } } } } } } if (is_learn) base.learn(ec); else base.predict(ec); // Restore example if (iter == 0) { first_prediction = ec.pred.scalar; first_loss = ec.loss; } else { ec.pred.scalar = first_prediction; ec.loss = first_loss; } for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { unsigned char right = (*i)[(which+1)%2]; ec.atomics[right].end = ec.atomics[right].begin + lrq.orig_size[right]; if (all.audit || all.hash_inv) { for (audit_data* a = ec.audit_features[right].begin + lrq.orig_size[right]; a < ec.audit_features[right].end; ++a) { free (a->space); free (a->feature); } ec.audit_features[right].end = ec.audit_features[right].begin + lrq.orig_size[right]; } } } } base_learner* lrq_setup(vw& all) {//parse and set arguments if (missing_option<vector<string>>(all, "lrq", "use low rank quadratic features")) return NULL; new_options(all, "Lrq options") ("lrqdropout", "use dropout training for low rank quadratic features"); add_options(all); if(!all.vm.count("lrq")) return NULL; LRQstate& lrq = calloc_or_die<LRQstate>(); size_t maxk = 0; lrq.all = &all; size_t random_seed = 0; if (all.vm.count("random_seed")) random_seed = all.vm["random_seed"].as<size_t> (); lrq.initial_seed = lrq.seed = random_seed | 8675309; if (all.vm.count("lrqdropout")) { lrq.dropout = true; *all.file_options << " --lrqdropout "; } else lrq.dropout = false; lrq.lrpairs = all.vm["lrq"].as<vector<string> > (); for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) *all.file_options << " --lrq " << *i; if (! all.quiet) { cerr << "creating low rank quadratic features for pairs: "; if (lrq.dropout) cerr << "(using dropout) "; } for (vector<string>::iterator i = lrq.lrpairs.begin (); i != lrq.lrpairs.end (); ++i) { if(!all.quiet){ if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) { cerr << endl << "error, low-rank quadratic features must involve two sets and a rank.\n"; throw exception(); } cerr << *i << " "; } // TODO: colon-syntax unsigned int k = atoi (i->c_str () + 2); lrq.lrindices[(int) (*i)[0]] = 1; lrq.lrindices[(int) (*i)[1]] = 1; maxk = max (maxk, k); } if(!all.quiet) cerr<<endl; all.wpp = all.wpp * (uint32_t)(1 + maxk); learner<LRQstate>& l = init_learner(&lrq, setup_base(all), predict_or_learn<true>, predict_or_learn<false>, 1 + maxk); l.set_end_pass(reset_seed); // TODO: leaks memory ? return make_base(l); } <|endoftext|>
<commit_before> #include "include/Shapes.h" double sumOfArea(const std::vector<Shape *> & shapes) { double total =0; for (Shape *shapePoint: shapes) total += shapePoint->area(); return total; } double sumOfPerimeter(const std::vector<Shape *> & shapes){ double total = 0; for (Shape *shapePoint: shapes) total += shapePoint->perimeter(); return total; } Shape* theLargestArea(const std::vector<Shape *> & shapes){ Shape *largestShape = nullptr; double largestArea = 0; for (Shape *shapePoint: shapes) if(shapePoint->area() >= largestArea){ largestArea = shapePoint->area(); largestShape = shapePoint; } return largestShape; } double distanceOfVertexs(const vertex vertex_1, const vertex vertex_2) { double diff_X, diff_Y, distance; diff_X = vertex_1.x - vertex_2.x; diff_Y = vertex_1.y - vertex_2.y; distance = sqrt(((diff_X * diff_X) + (diff_Y * diff_Y))); return distance; } void sortByDecreasingPerimeter(std::vector<Shape *> & shapes) { // use the shakeSort int left = 0; int right = shapes.size()-1; int shift = 0; Shape *temp; while(left < right){ for(int i = left; i < right; i++) { if(shapes[i]->perimeter() < shapes[i+1]->perimeter()){ temp = shapes[i]; shapes[i] = shapes[i+1]; shapes[i+1] = temp; shift = i; } } right = shift; for(int i = right; i > left; i--){ if(shapes[i]->perimeter() > shapes[i-1]->perimeter()){ temp = shapes[i]; shapes[i] = shapes[i-1]; shapes[i-1] = temp; shift = i; } } left = shift; } } <commit_msg>Delete Shapes.cpp<commit_after><|endoftext|>
<commit_before>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <sstream> #include <float.h> #include <math.h> #include "reductions.h" #include "rand48.h" #include "vw_exception.h" #include "vw.h" using namespace std; struct oaa { size_t k; vw* all; // for raw polyprediction* pred; // for multipredict size_t num_subsample; // for randomized subsampling, how many negatives to draw? uint32_t* subsample_order; // for randomized subsampling, in what order should we touch classes size_t subsample_id; // for randomized subsampling, where do we live in the list }; void learn_randomized(oaa& o, LEARNER::base_learner& base, example& ec) { MULTICLASS::label_t ld = ec.l.multi; if (ld.label == 0 || (ld.label > o.k && ld.label != (uint32_t)-1)) cout << "label " << ld.label << " is not in {1,"<< o.k << "} This won't work right." << endl; ec.l.simple = { 1., 0.f, 0.f }; // truth base.learn(ec, ld.label-1); size_t prediction = ld.label; float best_partial_prediction = ec.partial_prediction; ec.l.simple.label = -1.; ec.weight *= ((float)o.k) / (float)o.num_subsample; size_t p = o.subsample_id; size_t count = 0; while (count < o.num_subsample) { uint32_t l = o.subsample_order[p]; p = (p+1) % o.k; if (l == ld.label-1) continue; base.learn(ec, l); if (ec.partial_prediction > best_partial_prediction) { best_partial_prediction = ec.partial_prediction; prediction = l+1; } count++; } o.subsample_id = p; ec.pred.multiclass = (uint32_t)prediction; ec.l.multi = ld; } template <bool is_learn, bool print_all, bool scores> void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) { MULTICLASS::label_t mc_label_data = ec.l.multi; if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1)) cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl; stringstream outputStringStream; uint32_t prediction = 1; v_array<float> scores_array; if (scores) scores_array = ec.pred.scalars; ec.l.simple = { FLT_MAX, 0.f, 0.f }; base.multipredict(ec, 0, o.k, o.pred, true); for (uint32_t i=2; i<=o.k; i++) if (o.pred[i-1].scalar > o.pred[prediction-1].scalar) prediction = i; if (ec.passthrough) for (uint32_t i=1; i<=o.k; i++) add_passthrough_feature(ec, i, o.pred[i-1].scalar); if (is_learn) { for (uint32_t i=1; i<=o.k; i++) { ec.l.simple = { (mc_label_data.label == i) ? 1.f : -1.f, 0.f, 0.f }; ec.pred.scalar = o.pred[i-1].scalar; base.update(ec, i-1); } } if (print_all) { outputStringStream << "1:" << o.pred[0].scalar; for (uint32_t i=2; i<=o.k; i++) outputStringStream << ' ' << i << ':' << o.pred[i-1].scalar; o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag); } if (scores) { scores_array.erase(); for (uint32_t i=0; i<o.k; i++) scores_array.push_back(o.pred[i].scalar); ec.pred.scalars = scores_array; } else ec.pred.multiclass = prediction; ec.l.multi = mc_label_data; } void finish(oaa&o) { free(o.pred); free(o.subsample_order); } // TODO: partial code duplication with multiclass.cc:finish_example template<bool probabilities> void finish_example_scores(vw& all, oaa& o, example& ec) { // === Compute multiclass_log_loss // TODO: // What to do if the correct label is unknown, i.e. (uint32_t)-1? // Suggestion: increase all.sd->weighted_unlabeled_examples???, // but not sd.example_number, so the average loss is not influenced. // What to do if the correct_class_prob==0? // Suggestion: have some maximal multiclass_log_loss limit, e.g. 999. float multiclass_log_loss = 999; // -log(0) = plus infinity float correct_class_prob = 0; if (probabilities) { float sum_prob = 0; for(uint32_t i =0; i< o.k; i++) { ec.pred.scalars[i] = 1.f / (1.f + exp(- o.pred[i].scalar)); sum_prob += ec.pred.scalars[i]; } float inv_sum_prob = 1. / sum_prob; for(uint32_t i =0; i< o.k; i++) ec.pred.scalars[i] *= inv_sum_prob; if (ec.l.multi.label <= o.k) // prevent segmentation fault if labeĺ==(uint32_t)-1 correct_class_prob = ec.pred.scalars[ec.l.multi.label-1]; if (correct_class_prob > 0) multiclass_log_loss = -log(correct_class_prob) * ec.l.multi.weight; if (ec.test_only) all.sd->holdout_multiclass_log_loss += multiclass_log_loss; else all.sd->multiclass_log_loss += multiclass_log_loss; } // === Compute `prediction` and zero_one_loss // We have already computed `prediction` in predict_or_learn, // but we cannot store it in ec.pred union because we store ec.pred.probs there. uint32_t prediction = 0; for (uint32_t i = 1; i < o.k; i++) if (ec.pred.scalars[i] > ec.pred.scalars[prediction]) prediction = i; prediction++; // prediction is 1-based index (not 0-based) float zero_one_loss = 0; if (ec.l.multi.label != prediction) zero_one_loss = ec.l.multi.weight; // === Print probabilities for all classes char temp_str[10]; ostringstream outputStringStream; for (uint32_t i = 0; i < o.k; i++) { if (i > 0) outputStringStream << ' '; if (all.sd->ldict) { substring ss = all.sd->ldict->get(i+1); outputStringStream << string(ss.begin, ss.end - ss.begin); } else outputStringStream << i+1; sprintf(temp_str, "%f", ec.pred.scalars[i]); // 0.123 -> 0.123000 outputStringStream << ':' << temp_str; } for (int sink : all.final_prediction_sink) all.print_text(sink, outputStringStream.str(), ec.tag); // === Report updates using zero-one loss all.sd->update(ec.test_only, zero_one_loss, ec.l.multi.weight, ec.num_features); // Alternatively, we could report multiclass_log_loss. //all.sd->update(ec.test_only, multiclass_log_loss, ec.l.multi.weight, ec.num_features); // Even better would be to report both losses, but this would mean to increase // the number of columns and this would not fit narrow screens. // So let's report (average) multiclass_log_loss only in the final resume. // === Print progress report if (probabilities) MULTICLASS::print_update_with_probability(all, ec, prediction); else MULTICLASS::print_update_with_score(all, ec, prediction); VW::finish_example(all, &ec); } LEARNER::base_learner* oaa_setup(vw& all) { if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels")) return nullptr; new_options(all, "oaa options") ("oaa_subsample", po::value<size_t>(), "subsample this number of negative examples when learning") ("probabilities", "predict probabilites of all classes") ("scores", "output raw scores per class"); add_options(all); oaa* data_ptr = calloc_or_throw<oaa>(1); oaa& data = *data_ptr; data.k = all.vm["oaa"].as<size_t>(); // number of classes if (all.sd->ldict && (data.k != all.sd->ldict->getK())) { free(data_ptr); THROW("error: you have " << all.sd->ldict->getK() << " named labels; use that as the argument to oaa") } data.all = &all; data.pred = calloc_or_throw<polyprediction>(data.k); data.num_subsample = 0; data.subsample_order = nullptr; data.subsample_id = 0; if (all.vm.count("oaa_subsample")) { data.num_subsample = all.vm["oaa_subsample"].as<size_t>(); if (data.num_subsample >= data.k) { data.num_subsample = 0; cerr << "oaa is turning off subsampling because your parameter >= K" << endl; } else { data.subsample_order = calloc_or_throw<uint32_t>(data.k); for (size_t i=0; i<data.k; i++) data.subsample_order[i] = (uint32_t) i; for (size_t i=0; i<data.k; i++) { size_t j = (size_t)(frand48() * (float)(data.k-i)) + i; uint32_t tmp = data.subsample_order[i]; data.subsample_order[i] = data.subsample_order[j]; data.subsample_order[j] = tmp; } } } LEARNER::learner<oaa>* l; if( all.vm.count("probabilities") || all.vm.count("scores") ) { if (!all.vm.count("loss_function") || all.vm["loss_function"].as<string>() != "logistic" ) cerr << "WARNING: --probabilities should be used only with --loss_function=logistic" << endl; // the three boolean template parameters are: is_learn, print_all and scores l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all), predict_or_learn<true, false, true>, predict_or_learn<false, false, true>, all.p, data.k, prediction_type::scalars); all.delete_prediction = delete_scalars; if (all.vm.count("probabilities")) { all.sd->report_multiclass_log_loss = true; l->set_finish_example(finish_example_scores<true>); } else l->set_finish_example(finish_example_scores<false>); } else if (all.raw_prediction > 0) l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all), predict_or_learn<true, true, false>, predict_or_learn<false, true, false>, all.p, data.k, prediction_type::multiclass); else l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all),predict_or_learn<true, false, false>, predict_or_learn<false, false, false>, all.p, data.k, prediction_type::multiclass); if (data.num_subsample > 0) l->set_learn(learn_randomized); l->set_finish(finish); return make_base(*l); } <commit_msg>little bump<commit_after>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <sstream> #include <float.h> #include <math.h> #include "reductions.h" #include "rand48.h" #include "vw_exception.h" #include "vw.h" using namespace std; struct oaa { size_t k; vw* all; // for raw polyprediction* pred; // for multipredict size_t num_subsample; // for randomized subsampling, how many negatives to draw? uint32_t* subsample_order; // for randomized subsampling, in what order should we touch classes size_t subsample_id; // for randomized subsampling, where do we live in the list }; void learn_randomized(oaa& o, LEARNER::base_learner& base, example& ec) { MULTICLASS::label_t ld = ec.l.multi; if (ld.label == 0 || (ld.label > o.k && ld.label != (uint32_t)-1)) cout << "label " << ld.label << " is not in {1,"<< o.k << "} This won't work right." << endl; ec.l.simple = { 1., 0.f, 0.f }; // truth base.learn(ec, ld.label-1); size_t prediction = ld.label; float best_partial_prediction = ec.partial_prediction; ec.l.simple.label = -1.; ec.weight *= ((float)o.k) / (float)o.num_subsample; size_t p = o.subsample_id; size_t count = 0; while (count < o.num_subsample) { uint32_t l = o.subsample_order[p]; p = (p+1) % o.k; if (l == ld.label-1) continue; base.learn(ec, l); if (ec.partial_prediction > best_partial_prediction) { best_partial_prediction = ec.partial_prediction; prediction = l+1; } count++; } o.subsample_id = p; ec.pred.multiclass = (uint32_t)prediction; ec.l.multi = ld; } template <bool is_learn, bool print_all, bool scores> void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) { MULTICLASS::label_t mc_label_data = ec.l.multi; if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1)) cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl; stringstream outputStringStream; uint32_t prediction = 1; v_array<float> scores_array; if (scores) scores_array = ec.pred.scalars; ec.l.simple = { FLT_MAX, 0.f, 0.f }; base.multipredict(ec, 0, o.k, o.pred, true); for (uint32_t i=2; i<=o.k; i++) if (o.pred[i-1].scalar > o.pred[prediction-1].scalar) prediction = i; if (ec.passthrough) for (uint32_t i=1; i<=o.k; i++) add_passthrough_feature(ec, i, o.pred[i-1].scalar); if (is_learn) { for (uint32_t i=1; i<=o.k; i++) { ec.l.simple = { (mc_label_data.label == i) ? 1.f : -1.f, 0.f, 0.f }; ec.pred.scalar = o.pred[i-1].scalar; base.update(ec, i-1); } } if (print_all) { outputStringStream << "1:" << o.pred[0].scalar; for (uint32_t i=2; i<=o.k; i++) outputStringStream << ' ' << i << ':' << o.pred[i-1].scalar; o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag); } if (scores) { scores_array.erase(); for (uint32_t i=0; i<o.k; i++) scores_array.push_back(o.pred[i].scalar); ec.pred.scalars = scores_array; } else ec.pred.multiclass = prediction; ec.l.multi = mc_label_data; } void finish(oaa&o) { free(o.pred); free(o.subsample_order); } // TODO: partial code duplication with multiclass.cc:finish_example template<bool probabilities> void finish_example_scores(vw& all, oaa& o, example& ec) { // === Compute multiclass_log_loss // TODO: // What to do if the correct label is unknown, i.e. (uint32_t)-1? // Suggestion: increase all.sd->weighted_unlabeled_examples???, // but not sd.example_number, so the average loss is not influenced. // What to do if the correct_class_prob==0? // Suggestion: have some maximal multiclass_log_loss limit, e.g. 999. float multiclass_log_loss = 999; // -log(0) = plus infinity float correct_class_prob = 0; if (probabilities) { float sum_prob = 0; for(uint32_t i =0; i< o.k; i++) { ec.pred.scalars[i] = 1.f / (1.f + exp(- o.pred[i].scalar)); sum_prob += ec.pred.scalars[i]; } float inv_sum_prob = 1. / sum_prob; for(uint32_t i =0; i< o.k; i++) ec.pred.scalars[i] *= inv_sum_prob; if (ec.l.multi.label <= o.k) // prevent segmentation fault if labeĺ==(uint32_t)-1 correct_class_prob = ec.pred.scalars[ec.l.multi.label-1]; if (correct_class_prob > 0) multiclass_log_loss = -log(correct_class_prob) * ec.l.multi.weight; if (ec.test_only) all.sd->holdout_multiclass_log_loss += multiclass_log_loss; else all.sd->multiclass_log_loss += multiclass_log_loss; } // === Compute `prediction` and zero_one_loss // We have already computed `prediction` in predict_or_learn, // but we cannot store it in ec.pred union because we store ec.pred.probs there. uint32_t prediction = 0; for (uint32_t i = 1; i < o.k; i++) if (ec.pred.scalars[i] > ec.pred.scalars[prediction]) prediction = i; prediction++; // prediction is 1-based index (not 0-based) float zero_one_loss = 0; if (ec.l.multi.label != prediction) zero_one_loss = ec.l.multi.weight; // === Print probabilities for all classes char temp_str[10]; ostringstream outputStringStream; for (uint32_t i = 0; i < o.k; i++) { if (i > 0) outputStringStream << ' '; if (all.sd->ldict) { substring ss = all.sd->ldict->get(i+1); outputStringStream << string(ss.begin, ss.end - ss.begin); } else outputStringStream << i+1; sprintf(temp_str, "%f", ec.pred.scalars[i]); // 0.123 -> 0.123000 outputStringStream << ':' << temp_str; } for (int sink : all.final_prediction_sink) all.print_text(sink, outputStringStream.str(), ec.tag); // === Report updates using zero-one loss all.sd->update(ec.test_only, zero_one_loss, ec.l.multi.weight, ec.num_features); // Alternatively, we could report multiclass_log_loss. //all.sd->update(ec.test_only, multiclass_log_loss, ec.l.multi.weight, ec.num_features); // Even better would be to report both losses, but this would mean to increase // the number of columns and this would not fit narrow screens. // So let's report (average) multiclass_log_loss only in the final resume. // === Print progress report if (probabilities) MULTICLASS::print_update_with_probability(all, ec, prediction); else MULTICLASS::print_update_with_score(all, ec, prediction); VW::finish_example(all, &ec); } LEARNER::base_learner* oaa_setup(vw& all) { if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels")) return nullptr; new_options(all, "oaa options") ("oaa_subsample", po::value<size_t>(), "subsample this number of negative examples when learning") ("probabilities", "predict probabilites of all classes") ("scores", "output raw scores per class"); add_options(all); oaa* data_ptr = calloc_or_throw<oaa>(1); oaa& data = *data_ptr; data.k = all.vm["oaa"].as<size_t>(); // number of classes if (all.sd->ldict && (data.k != all.sd->ldict->getK())) { free(data_ptr); THROW("error: you have " << all.sd->ldict->getK() << " named labels; use that as the argument to oaa") } data.all = &all; data.pred = calloc_or_throw<polyprediction>(data.k); data.num_subsample = 0; data.subsample_order = nullptr; data.subsample_id = 0; if (all.vm.count("oaa_subsample")) { data.num_subsample = all.vm["oaa_subsample"].as<size_t>(); if (data.num_subsample >= data.k) { data.num_subsample = 0; cerr << "oaa is turning off subsampling because your parameter >= K" << endl; } else { data.subsample_order = calloc_or_throw<uint32_t>(data.k); for (size_t i=0; i<data.k; i++) data.subsample_order[i] = (uint32_t) i; for (size_t i=0; i<data.k; i++) { size_t j = (size_t)(frand48() * (float)(data.k-i)) + i; uint32_t tmp = data.subsample_order[i]; data.subsample_order[i] = data.subsample_order[j]; data.subsample_order[j] = tmp; } } } LEARNER::learner<oaa>* l; if( all.vm.count("probabilities") || all.vm.count("scores") ) { if (!all.vm.count("loss_function") || all.vm["loss_function"].as<string>() != "logistic" ) cerr << "WARNING: --probabilities should be used only with --loss_function=logistic" << endl; // the three boolean template parameters are: is_learn, print_all and scores l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all), predict_or_learn<true, false, true>, predict_or_learn<false, false, true>, all.p, data.k, prediction_type::scalars); all.delete_prediction = delete_scalars; if (all.vm.count("probabilities")) { all.sd->report_multiclass_log_loss = true; l->set_finish_example(finish_example_scores<true>); } else l->set_finish_example(finish_example_scores<false>); } else if (all.raw_prediction > 0) l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all), predict_or_learn<true, true, false>, predict_or_learn<false, true, false>, all.p, data.k, prediction_type::multiclass); else l = &LEARNER::init_multiclass_learner(data_ptr, setup_base(all),predict_or_learn<true, false, false>, predict_or_learn<false, false, false>, all.p, data.k, prediction_type::multiclass); if (data.num_subsample > 0) l->set_learn(learn_randomized); l->set_finish(finish); return make_base(*l); } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Unit tests for the LLL parser. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <liblll/Compiler.h> using namespace std; namespace dev { namespace lll { namespace test { namespace { bool successParse(std::string const& _source) { std::string ret = eth::parseLLL(_source); return ret.size() != 0; } std::string parse(std::string const& _source) { return eth::parseLLL(_source); } } BOOST_AUTO_TEST_SUITE(LLLParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "1"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_CASE(string) { char const* text = "\"string\""; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"("string")"); } BOOST_AUTO_TEST_CASE(symbol) { char const* text = "symbol"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); BOOST_CHECK(successParse("'symbol")); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); } BOOST_AUTO_TEST_CASE(decimals) { char const* text = "1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(1234)"); } BOOST_AUTO_TEST_CASE(hexadecimals) { char const* text = "0x1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(4660)"); BOOST_CHECK(!successParse("0x")); } BOOST_AUTO_TEST_CASE(sequence) { char const* text = "{ 1234 }"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ 1234 })"); } BOOST_AUTO_TEST_CASE(empty_sequence) { char const* text = "{}"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ })"); } BOOST_AUTO_TEST_CASE(mload) { char const* text = "@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@ 0)"); BOOST_CHECK(successParse("@0x0")); BOOST_CHECK(successParse("@symbol")); BOOST_CHECK(!successParse("@")); } BOOST_AUTO_TEST_CASE(sload) { char const* text = "@@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@@ 0)"); BOOST_CHECK(successParse("@@0x0")); BOOST_CHECK(successParse("@@symbol")); BOOST_CHECK(!successParse("@@")); } BOOST_AUTO_TEST_CASE(mstore) { char const* text = "[0]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([ 0 ] 0)"); BOOST_CHECK(successParse("[0] 0")); BOOST_CHECK(successParse("[0x0]:0x0")); BOOST_CHECK(successParse("[symbol]:symbol")); BOOST_CHECK(!successParse("[]")); BOOST_CHECK(!successParse("[0]")); } BOOST_AUTO_TEST_CASE(sstore) { char const* text = "[[0]]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([[ 0 ]] 0)"); BOOST_CHECK(successParse("[[0]] 0")); BOOST_CHECK(successParse("[[0x0]]:0x0")); BOOST_CHECK(successParse("[[symbol]]:symbol")); BOOST_CHECK(!successParse("[[]]")); BOOST_CHECK(!successParse("[[0x0]]")); } BOOST_AUTO_TEST_CASE(calldataload) { char const* text = "$0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"($ 0)"); BOOST_CHECK(successParse("$0x0")); BOOST_CHECK(successParse("$symbol")); BOOST_CHECK(!successParse("$")); } BOOST_AUTO_TEST_CASE(list) { char const* text = "( 1234 )"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(( 1234 ))"); BOOST_CHECK(successParse("( 1234 5467 )")); BOOST_CHECK(!successParse("()")); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Add a test that fails about an LLL macro with no arguments<commit_after>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Unit tests for the LLL parser. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <liblll/Compiler.h> using namespace std; namespace dev { namespace lll { namespace test { namespace { bool successParse(std::string const& _source) { std::string ret = eth::parseLLL(_source); return ret.size() != 0; } std::string parse(std::string const& _source) { return eth::parseLLL(_source); } } BOOST_AUTO_TEST_SUITE(LLLParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "1"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_CASE(string) { char const* text = "\"string\""; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"("string")"); } BOOST_AUTO_TEST_CASE(symbol) { char const* text = "symbol"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); BOOST_CHECK(successParse("'symbol")); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); } BOOST_AUTO_TEST_CASE(decimals) { char const* text = "1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(1234)"); } BOOST_AUTO_TEST_CASE(hexadecimals) { char const* text = "0x1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(4660)"); BOOST_CHECK(!successParse("0x")); } BOOST_AUTO_TEST_CASE(sequence) { char const* text = "{ 1234 }"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ 1234 })"); } BOOST_AUTO_TEST_CASE(empty_sequence) { char const* text = "{}"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ })"); } BOOST_AUTO_TEST_CASE(mload) { char const* text = "@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@ 0)"); BOOST_CHECK(successParse("@0x0")); BOOST_CHECK(successParse("@symbol")); BOOST_CHECK(!successParse("@")); } BOOST_AUTO_TEST_CASE(sload) { char const* text = "@@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@@ 0)"); BOOST_CHECK(successParse("@@0x0")); BOOST_CHECK(successParse("@@symbol")); BOOST_CHECK(!successParse("@@")); } BOOST_AUTO_TEST_CASE(mstore) { char const* text = "[0]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([ 0 ] 0)"); BOOST_CHECK(successParse("[0] 0")); BOOST_CHECK(successParse("[0x0]:0x0")); BOOST_CHECK(successParse("[symbol]:symbol")); BOOST_CHECK(!successParse("[]")); BOOST_CHECK(!successParse("[0]")); } BOOST_AUTO_TEST_CASE(sstore) { char const* text = "[[0]]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([[ 0 ]] 0)"); BOOST_CHECK(successParse("[[0]] 0")); BOOST_CHECK(successParse("[[0x0]]:0x0")); BOOST_CHECK(successParse("[[symbol]]:symbol")); BOOST_CHECK(!successParse("[[]]")); BOOST_CHECK(!successParse("[[0x0]]")); } BOOST_AUTO_TEST_CASE(calldataload) { char const* text = "$0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"($ 0)"); BOOST_CHECK(successParse("$0x0")); BOOST_CHECK(successParse("$symbol")); BOOST_CHECK(!successParse("$")); } BOOST_AUTO_TEST_CASE(list) { char const* text = "( 1234 )"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(( 1234 ))"); BOOST_CHECK(successParse("( 1234 5467 )")); BOOST_CHECK(!successParse("()")); } BOOST_AUTO_TEST_CASE(macro_with_zero_args) { char const* text = "(def 'zeroargs () (asm INVALID))"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before>/* * Copyright (C) 2007,2008,2009 Red Hat, Inc. * * This is part of HarfBuzz, an OpenType Layout engine library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Behdad Esfahbod */ #ifndef HB_OT_LAYOUT_GDEF_PRIVATE_HH #define HB_OT_LAYOUT_GDEF_PRIVATE_HH #include "hb-ot-layout-common-private.hh" #include "hb-font-private.h" struct GlyphClassDef : ClassDef { enum { BaseGlyph = 0x0001u, LigatureGlyph = 0x0002u, MarkGlyph = 0x0003u, ComponentGlyph = 0x0004u, }; }; /* * Attachment List Table */ typedef ArrayOf<USHORT> AttachPoint; /* Array of contour point indices--in * increasing numerical order */ ASSERT_SIZE (AttachPoint, 2); struct AttachList { inline bool get_attach_points (hb_codepoint_t glyph_id, unsigned int *point_count /* IN/OUT */, unsigned int *point_array /* OUT */) const { unsigned int index = (this+coverage) (glyph_id); if (index == NOT_COVERED) { *point_count = 0; return false; } const AttachPoint &points = this+attachPoint[index]; unsigned int count = MIN (points.len, *point_count); for (unsigned int i = 0; i < count; i++) point_array[i] = points[i]; *point_count = points.len; return true; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS2 (coverage, attachPoint); } private: OffsetTo<Coverage> coverage; /* Offset to Coverage table -- from * beginning of AttachList table */ OffsetArrayOf<AttachPoint> attachPoint; /* Array of AttachPoint tables * in Coverage Index order */ }; ASSERT_SIZE (AttachList, 4); /* * Ligature Caret Table */ struct CaretValueFormat1 { friend struct CaretValue; private: inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { /* TODO vertical */ return context->font->x_scale * coordinate / 0x10000; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF (); } private: USHORT caretValueFormat; /* Format identifier--format = 1 */ SHORT coordinate; /* X or Y value, in design units */ }; ASSERT_SIZE (CaretValueFormat1, 4); struct CaretValueFormat2 { friend struct CaretValue; private: inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { return /* TODO contour point */ 0; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF (); } private: USHORT caretValueFormat; /* Format identifier--format = 2 */ USHORT caretValuePoint; /* Contour point index on glyph */ }; ASSERT_SIZE (CaretValueFormat2, 4); struct CaretValueFormat3 { friend struct CaretValue; inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { /* TODO vertical */ return context->font->x_scale * coordinate / 0x10000 + ((this+deviceTable).get_delta (context->font->x_ppem) << 6); } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF () && SANITIZE_THIS (deviceTable); } private: USHORT caretValueFormat; /* Format identifier--format = 3 */ SHORT coordinate; /* X or Y value, in design units */ OffsetTo<Device> deviceTable; /* Offset to Device table for X or Y * value--from beginning of CaretValue * table */ }; ASSERT_SIZE (CaretValueFormat3, 6); struct CaretValue { int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { switch (u.format) { case 1: return u.format1->get_caret_value (context, glyph_id); case 2: return u.format2->get_caret_value (context, glyph_id); case 3: return u.format3->get_caret_value (context, glyph_id); default:return 0; } } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (u.format)) return false; switch (u.format) { case 1: return u.format1->sanitize (SANITIZE_ARG); case 2: return u.format2->sanitize (SANITIZE_ARG); case 3: return u.format3->sanitize (SANITIZE_ARG); default:return true; } } private: union { USHORT format; /* Format identifier */ CaretValueFormat1 format1[]; CaretValueFormat2 format2[]; CaretValueFormat3 format3[]; } u; }; ASSERT_SIZE (CaretValue, 2); struct LigGlyph { inline void get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { unsigned int count = MIN (carets.len, *caret_count); for (unsigned int i = 0; i < count; i++) caret_array[i] = (this+carets[i]).get_caret_value (context, glyph_id); *caret_count = carets.len; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE (carets); } private: OffsetArrayOf<CaretValue> carets; /* Offset rrray of CaretValue tables * --from beginning of LigGlyph table * --in increasing coordinate order */ }; ASSERT_SIZE (LigGlyph, 2); struct LigCaretList { inline bool get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { unsigned int index = (this+coverage) (glyph_id); if (index == NOT_COVERED) { *caret_count = 0; return false; } const LigGlyph &lig_glyph = this+ligGlyph[index]; lig_glyph.get_lig_carets (context, glyph_id, caret_count, caret_array); return true; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS2 (coverage, ligGlyph); } private: OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of LigCaretList table */ OffsetArrayOf<LigGlyph> ligGlyph; /* Array of LigGlyph tables * in Coverage Index order */ }; ASSERT_SIZE (LigCaretList, 4); struct MarkGlyphSetsFormat1 { inline bool covers (unsigned int set_index, hb_codepoint_t glyph_id) const { return (this+coverage[set_index]).get_coverage (glyph_id) != NOT_COVERED; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS (coverage); } private: USHORT format; /* Format identifier--format = 1 */ LongOffsetArrayOf<Coverage> coverage; /* Array of long offsets to mark set * coverage tables */ }; ASSERT_SIZE (MarkGlyphSetsFormat1, 4); struct MarkGlyphSets { inline bool covers (unsigned int set_index, hb_codepoint_t glyph_id) const { switch (u.format) { case 1: return u.format1->covers (set_index, glyph_id); default:return false; } } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (u.format)) return false; switch (u.format) { case 1: return u.format1->sanitize (SANITIZE_ARG); default:return true; } } private: union { USHORT format; /* Format identifier */ MarkGlyphSetsFormat1 format1[]; } u; }; ASSERT_SIZE (MarkGlyphSets, 2); /* * GDEF */ struct GDEF { static const hb_tag_t Tag = HB_OT_TAG_GDEF; enum { UnclassifiedGlyph = 0, BaseGlyph = 1, LigatureGlyph = 2, MarkGlyph = 3, ComponentGlyph = 4, }; STATIC_DEFINE_GET_FOR_DATA_CHECK_MAJOR_VERSION (GDEF, 1, 1); inline bool has_glyph_classes () const { return glyphClassDef != 0; } inline hb_ot_layout_class_t get_glyph_class (hb_codepoint_t glyph) const { return (this+glyphClassDef).get_class (glyph); } inline bool has_mark_attachment_types () const { return markAttachClassDef != 0; } inline hb_ot_layout_class_t get_mark_attachment_type (hb_codepoint_t glyph) const { return (this+markAttachClassDef).get_class (glyph); } inline bool has_attach_points () const { return attachList != 0; } inline bool get_attach_points (hb_codepoint_t glyph_id, unsigned int *point_count /* IN/OUT */, unsigned int *point_array /* OUT */) const { return (this+attachList).get_attach_points (glyph_id, point_count, point_array); } inline bool has_lig_carets () const { return ligCaretList != 0; } inline bool get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { return (this+ligCaretList).get_lig_carets (context, glyph_id, caret_count, caret_array); } inline bool has_mark_sets () const { return version >= 0x00010002 && markGlyphSetsDef[0] != 0; } inline bool mark_set_covers (unsigned int set_index, hb_codepoint_t glyph_id) const { return version >= 0x00010002 && (this+markGlyphSetsDef[0]).covers (set_index, glyph_id); } bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (version)) return false; if (version.major != 1) return true; return SANITIZE_THIS2 (glyphClassDef, attachList) && SANITIZE_THIS2 (ligCaretList, markAttachClassDef) && (version < 0x00010002 || SANITIZE_THIS (markGlyphSetsDef[0])); } private: FixedVersion version; /* Version of the GDEF table--currently * 0x00010002 */ OffsetTo<ClassDef> glyphClassDef; /* Offset to class definition table * for glyph type--from beginning of * GDEF header (may be Null) */ OffsetTo<AttachList> attachList; /* Offset to list of glyphs with * attachment points--from beginning * of GDEF header (may be Null) */ OffsetTo<LigCaretList> ligCaretList; /* Offset to list of positioning points * for ligature carets--from beginning * of GDEF header (may be Null) */ OffsetTo<ClassDef> markAttachClassDef; /* Offset to class definition table for * mark attachment type--from beginning * of GDEF header (may be Null) */ OffsetTo<MarkGlyphSets> markGlyphSetsDef[0]; /* Offset to the table of mark set * definitions--from beginning of GDEF * header (may be NULL). Introduced * in version 00010002. */ }; ASSERT_SIZE (GDEF, 12); #endif /* HB_OT_LAYOUT_GDEF_PRIVATE_HH */ <commit_msg>[HB] Remove unused code<commit_after>/* * Copyright (C) 2007,2008,2009 Red Hat, Inc. * * This is part of HarfBuzz, an OpenType Layout engine library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Behdad Esfahbod */ #ifndef HB_OT_LAYOUT_GDEF_PRIVATE_HH #define HB_OT_LAYOUT_GDEF_PRIVATE_HH #include "hb-ot-layout-common-private.hh" #include "hb-font-private.h" /* * Attachment List Table */ typedef ArrayOf<USHORT> AttachPoint; /* Array of contour point indices--in * increasing numerical order */ ASSERT_SIZE (AttachPoint, 2); struct AttachList { inline bool get_attach_points (hb_codepoint_t glyph_id, unsigned int *point_count /* IN/OUT */, unsigned int *point_array /* OUT */) const { unsigned int index = (this+coverage) (glyph_id); if (index == NOT_COVERED) { *point_count = 0; return false; } const AttachPoint &points = this+attachPoint[index]; unsigned int count = MIN (points.len, *point_count); for (unsigned int i = 0; i < count; i++) point_array[i] = points[i]; *point_count = points.len; return true; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS2 (coverage, attachPoint); } private: OffsetTo<Coverage> coverage; /* Offset to Coverage table -- from * beginning of AttachList table */ OffsetArrayOf<AttachPoint> attachPoint; /* Array of AttachPoint tables * in Coverage Index order */ }; ASSERT_SIZE (AttachList, 4); /* * Ligature Caret Table */ struct CaretValueFormat1 { friend struct CaretValue; private: inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { /* TODO vertical */ return context->font->x_scale * coordinate / 0x10000; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF (); } private: USHORT caretValueFormat; /* Format identifier--format = 1 */ SHORT coordinate; /* X or Y value, in design units */ }; ASSERT_SIZE (CaretValueFormat1, 4); struct CaretValueFormat2 { friend struct CaretValue; private: inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { return /* TODO contour point */ 0; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF (); } private: USHORT caretValueFormat; /* Format identifier--format = 2 */ USHORT caretValuePoint; /* Contour point index on glyph */ }; ASSERT_SIZE (CaretValueFormat2, 4); struct CaretValueFormat3 { friend struct CaretValue; inline int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { /* TODO vertical */ return context->font->x_scale * coordinate / 0x10000 + ((this+deviceTable).get_delta (context->font->x_ppem) << 6); } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_SELF () && SANITIZE_THIS (deviceTable); } private: USHORT caretValueFormat; /* Format identifier--format = 3 */ SHORT coordinate; /* X or Y value, in design units */ OffsetTo<Device> deviceTable; /* Offset to Device table for X or Y * value--from beginning of CaretValue * table */ }; ASSERT_SIZE (CaretValueFormat3, 6); struct CaretValue { int get_caret_value (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id) const { switch (u.format) { case 1: return u.format1->get_caret_value (context, glyph_id); case 2: return u.format2->get_caret_value (context, glyph_id); case 3: return u.format3->get_caret_value (context, glyph_id); default:return 0; } } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (u.format)) return false; switch (u.format) { case 1: return u.format1->sanitize (SANITIZE_ARG); case 2: return u.format2->sanitize (SANITIZE_ARG); case 3: return u.format3->sanitize (SANITIZE_ARG); default:return true; } } private: union { USHORT format; /* Format identifier */ CaretValueFormat1 format1[]; CaretValueFormat2 format2[]; CaretValueFormat3 format3[]; } u; }; ASSERT_SIZE (CaretValue, 2); struct LigGlyph { inline void get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { unsigned int count = MIN (carets.len, *caret_count); for (unsigned int i = 0; i < count; i++) caret_array[i] = (this+carets[i]).get_caret_value (context, glyph_id); *caret_count = carets.len; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE (carets); } private: OffsetArrayOf<CaretValue> carets; /* Offset rrray of CaretValue tables * --from beginning of LigGlyph table * --in increasing coordinate order */ }; ASSERT_SIZE (LigGlyph, 2); struct LigCaretList { inline bool get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { unsigned int index = (this+coverage) (glyph_id); if (index == NOT_COVERED) { *caret_count = 0; return false; } const LigGlyph &lig_glyph = this+ligGlyph[index]; lig_glyph.get_lig_carets (context, glyph_id, caret_count, caret_array); return true; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS2 (coverage, ligGlyph); } private: OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of LigCaretList table */ OffsetArrayOf<LigGlyph> ligGlyph; /* Array of LigGlyph tables * in Coverage Index order */ }; ASSERT_SIZE (LigCaretList, 4); struct MarkGlyphSetsFormat1 { inline bool covers (unsigned int set_index, hb_codepoint_t glyph_id) const { return (this+coverage[set_index]).get_coverage (glyph_id) != NOT_COVERED; } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); return SANITIZE_THIS (coverage); } private: USHORT format; /* Format identifier--format = 1 */ LongOffsetArrayOf<Coverage> coverage; /* Array of long offsets to mark set * coverage tables */ }; ASSERT_SIZE (MarkGlyphSetsFormat1, 4); struct MarkGlyphSets { inline bool covers (unsigned int set_index, hb_codepoint_t glyph_id) const { switch (u.format) { case 1: return u.format1->covers (set_index, glyph_id); default:return false; } } inline bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (u.format)) return false; switch (u.format) { case 1: return u.format1->sanitize (SANITIZE_ARG); default:return true; } } private: union { USHORT format; /* Format identifier */ MarkGlyphSetsFormat1 format1[]; } u; }; ASSERT_SIZE (MarkGlyphSets, 2); /* * GDEF */ struct GDEF { static const hb_tag_t Tag = HB_OT_TAG_GDEF; enum { UnclassifiedGlyph = 0, BaseGlyph = 1, LigatureGlyph = 2, MarkGlyph = 3, ComponentGlyph = 4, }; STATIC_DEFINE_GET_FOR_DATA_CHECK_MAJOR_VERSION (GDEF, 1, 1); inline bool has_glyph_classes () const { return glyphClassDef != 0; } inline hb_ot_layout_class_t get_glyph_class (hb_codepoint_t glyph) const { return (this+glyphClassDef).get_class (glyph); } inline bool has_mark_attachment_types () const { return markAttachClassDef != 0; } inline hb_ot_layout_class_t get_mark_attachment_type (hb_codepoint_t glyph) const { return (this+markAttachClassDef).get_class (glyph); } inline bool has_attach_points () const { return attachList != 0; } inline bool get_attach_points (hb_codepoint_t glyph_id, unsigned int *point_count /* IN/OUT */, unsigned int *point_array /* OUT */) const { return (this+attachList).get_attach_points (glyph_id, point_count, point_array); } inline bool has_lig_carets () const { return ligCaretList != 0; } inline bool get_lig_carets (hb_ot_layout_context_t *context, hb_codepoint_t glyph_id, unsigned int *caret_count /* IN/OUT */, int *caret_array /* OUT */) const { return (this+ligCaretList).get_lig_carets (context, glyph_id, caret_count, caret_array); } inline bool has_mark_sets () const { return version >= 0x00010002 && markGlyphSetsDef[0] != 0; } inline bool mark_set_covers (unsigned int set_index, hb_codepoint_t glyph_id) const { return version >= 0x00010002 && (this+markGlyphSetsDef[0]).covers (set_index, glyph_id); } bool sanitize (SANITIZE_ARG_DEF) { SANITIZE_DEBUG (); if (!SANITIZE (version)) return false; if (version.major != 1) return true; return SANITIZE_THIS2 (glyphClassDef, attachList) && SANITIZE_THIS2 (ligCaretList, markAttachClassDef) && (version < 0x00010002 || SANITIZE_THIS (markGlyphSetsDef[0])); } private: FixedVersion version; /* Version of the GDEF table--currently * 0x00010002 */ OffsetTo<ClassDef> glyphClassDef; /* Offset to class definition table * for glyph type--from beginning of * GDEF header (may be Null) */ OffsetTo<AttachList> attachList; /* Offset to list of glyphs with * attachment points--from beginning * of GDEF header (may be Null) */ OffsetTo<LigCaretList> ligCaretList; /* Offset to list of positioning points * for ligature carets--from beginning * of GDEF header (may be Null) */ OffsetTo<ClassDef> markAttachClassDef; /* Offset to class definition table for * mark attachment type--from beginning * of GDEF header (may be Null) */ OffsetTo<MarkGlyphSets> markGlyphSetsDef[0]; /* Offset to the table of mark set * definitions--from beginning of GDEF * header (may be NULL). Introduced * in version 00010002. */ }; ASSERT_SIZE (GDEF, 12); #endif /* HB_OT_LAYOUT_GDEF_PRIVATE_HH */ <|endoftext|>
<commit_before>#include "clay.hpp" #include "libclaynames.hpp" ExprPtr desugarCharLiteral(char c) { ExprPtr nameRef = prelude_expr_Char(); CallPtr call = new Call(nameRef, new ExprList()); ostringstream out; out << (int)c; call->args->add(new IntLiteral(out.str(), "i8")); return call.ptr(); } ExprPtr desugarFieldRef(FieldRefPtr x) { ExprListPtr args = new ExprList(x->expr); args->add(new ObjectExpr(x->name.ptr())); return new Call(prelude_expr_fieldRef(), args); } ExprPtr desugarStaticIndexing(StaticIndexingPtr x) { ExprListPtr args = new ExprList(x->expr); ValueHolderPtr vh = sizeTToValueHolder(x->index); args->add(new StaticExpr(new ObjectExpr(vh.ptr()))); return new Call(prelude_expr_staticIndex(), args); } ExprPtr desugarUnaryOp(UnaryOpPtr x) { ExprPtr callable; switch (x->op) { case DEREFERENCE : callable = prelude_expr_dereference(); break; case ADDRESS_OF : callable = primitive_expr_addressOf(); break; case PLUS : callable = prelude_expr_plus(); break; case MINUS : callable = prelude_expr_minus(); break; case NOT : callable = primitive_expr_boolNot(); break; default : assert(false); } CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr desugarBinaryOp(BinaryOpPtr x) { ExprPtr callable; switch (x->op) { case ADD : callable = prelude_expr_add(); break; case SUBTRACT : callable = prelude_expr_subtract(); break; case MULTIPLY : callable = prelude_expr_multiply(); break; case DIVIDE : callable = prelude_expr_divide(); break; case REMAINDER : callable = prelude_expr_remainder(); break; case EQUALS : callable = prelude_expr_equalsP(); break; case NOT_EQUALS : callable = prelude_expr_notEqualsP(); break; case LESSER : callable = prelude_expr_lesserP(); break; case LESSER_EQUALS : callable = prelude_expr_lesserEqualsP(); break; case GREATER : callable = prelude_expr_greaterP(); break; case GREATER_EQUALS : callable = prelude_expr_greaterEqualsP(); break; default : assert(false); } CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr1); call->args->add(x->expr2); return call.ptr(); } ExprPtr desugarIfExpr(IfExprPtr x) { ExprPtr callable = prelude_expr_ifExpression(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->condition); call->args->add(x->thenPart); call->args->add(x->elsePart); return call.ptr(); } ExprPtr desugarNew(NewPtr x) { ExprPtr callable = prelude_expr_allocateShared(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr desugarStaticExpr(StaticExprPtr x) { ExprPtr callable = prelude_expr_wrapStatic(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr updateOperatorExpr(int op) { switch (op) { case UPDATE_ADD : return prelude_expr_addAssign(); case UPDATE_SUBTRACT : return prelude_expr_subtractAssign(); case UPDATE_MULTIPLY : return prelude_expr_multiplyAssign(); case UPDATE_DIVIDE : return prelude_expr_divideAssign(); case UPDATE_REMAINDER : return prelude_expr_remainderAssign(); default : assert(false); return NULL; } } static vector<IdentifierPtr> identV(IdentifierPtr x) { vector<IdentifierPtr> v; v.push_back(x); return v; } StatementPtr desugarForStatement(ForPtr x) { IdentifierPtr exprVar = new Identifier("%expr"); IdentifierPtr iterVar = new Identifier("%iter"); BlockPtr block = new Block(); vector<StatementPtr> &bs = block->statements; bs.push_back(new Binding(REF, identV(exprVar), new ExprList(x->expr))); CallPtr iteratorCall = new Call(prelude_expr_iterator(), new ExprList()); iteratorCall->args->add(new NameRef(exprVar)); bs.push_back(new Binding(VAR, identV(iterVar), new ExprList(iteratorCall.ptr()))); CallPtr hasNextCall = new Call(prelude_expr_hasNextP(), new ExprList()); hasNextCall->args->add(new NameRef(iterVar)); CallPtr nextCall = new Call(prelude_expr_next(), new ExprList()); nextCall->args->add(new NameRef(iterVar)); ExprPtr unpackNext = new Unpack(nextCall.ptr()); BlockPtr whileBody = new Block(); vector<StatementPtr> &ws = whileBody->statements; ws.push_back(new Binding(REF, x->variables, new ExprList(unpackNext))); ws.push_back(x->body); bs.push_back(new While(hasNextCall.ptr(), whileBody.ptr())); return block.ptr(); } StatementPtr desugarCatchBlocks(const vector<CatchPtr> &catchBlocks) { bool lastWasAny = false; IfPtr lastIf; StatementPtr result; for (unsigned i = 0; i < catchBlocks.size(); ++i) { CatchPtr x = catchBlocks[i]; if (lastWasAny) error(x, "unreachable catch block"); if (x->exceptionType.ptr()) { ExprListPtr typeArg = new ExprList(x->exceptionType); CallPtr cond = new Call(prelude_expr_exceptionIsP(), typeArg); cond->location = x->exceptionType->location; BlockPtr block = new Block(); CallPtr getter = new Call(prelude_expr_exceptionAs(), typeArg); getter->location = x->exceptionVar->location; BindingPtr binding = new Binding(VAR, vector<IdentifierPtr>(1, x->exceptionVar), new ExprList(getter.ptr())); binding->location = x->exceptionVar->location; block->statements.push_back(binding.ptr()); block->statements.push_back(x->body); IfPtr ifStatement = new If(cond.ptr(), block.ptr()); ifStatement->location = x->location; if (!result) result = ifStatement.ptr(); if (lastIf.ptr()) lastIf->elsePart = ifStatement.ptr(); lastIf = ifStatement; } else { BlockPtr block = new Block(); block->location = x->location; CallPtr getter = new Call(prelude_expr_exceptionAsAny(), new ExprList()); getter->location = x->exceptionVar->location; BindingPtr binding = new Binding(VAR, vector<IdentifierPtr>(1, x->exceptionVar), new ExprList(getter.ptr())); binding->location = x->exceptionVar->location; block->statements.push_back(binding.ptr()); block->statements.push_back(x->body); if (!result) result = block.ptr(); if (lastIf.ptr()) lastIf->elsePart = block.ptr(); lastWasAny = true; lastIf = NULL; } } assert(result.ptr()); if (!lastWasAny) { assert(lastIf.ptr()); BlockPtr block = new Block(); CallPtr continueException = new Call(prelude_expr_continueException(), new ExprList()); StatementPtr stmt = new ExprStatement(continueException.ptr()); block->statements.push_back(stmt); // block->statements.push_back(new Unreachable()); lastIf->elsePart = block.ptr(); } return result; } StatementPtr desugarSwitchStatement(SwitchPtr x) { BlockPtr block = new Block(); block->location = x->location; // %thing is the value being switched on IdentifierPtr thing = new Identifier("%thing"); thing->location = x->expr->location; NameRefPtr thingRef = new NameRef(thing); thingRef->location = x->expr->location; // initialize %thing { BindingPtr b = new Binding(REF, identV(thing), new ExprList(x->expr)); block->statements.push_back(b.ptr()); } StatementPtr root; StatementPtr *nextPtr = &root; // dispatch logic for (unsigned i = 0; i < x->caseBlocks.size(); ++i) { CaseBlockPtr y = x->caseBlocks[i]; ExprPtr condition; for (unsigned j = 0; j < y->caseLabels->size(); ++j) { ExprPtr caseValue = y->caseLabels->exprs[j]; ExprPtr compare = new BinaryOp(EQUALS, thingRef.ptr(), caseValue); compare->location = caseValue->location; if (!condition) { condition = compare; } else { condition = new Or(condition, compare); condition->location = y->location; } } assert(condition.ptr()); IfPtr ifStmt = new If(condition, y->body); ifStmt->location = y->location; *nextPtr = ifStmt.ptr(); nextPtr = &(ifStmt->elsePart); } if (x->defaultCase.ptr()) *nextPtr = x->defaultCase; else *nextPtr = new Break(); block->statements.push_back(root); return block.ptr(); } <commit_msg>oops. uncomment the critical line.<commit_after>#include "clay.hpp" #include "libclaynames.hpp" ExprPtr desugarCharLiteral(char c) { ExprPtr nameRef = prelude_expr_Char(); CallPtr call = new Call(nameRef, new ExprList()); ostringstream out; out << (int)c; call->args->add(new IntLiteral(out.str(), "i8")); return call.ptr(); } ExprPtr desugarFieldRef(FieldRefPtr x) { ExprListPtr args = new ExprList(x->expr); args->add(new ObjectExpr(x->name.ptr())); return new Call(prelude_expr_fieldRef(), args); } ExprPtr desugarStaticIndexing(StaticIndexingPtr x) { ExprListPtr args = new ExprList(x->expr); ValueHolderPtr vh = sizeTToValueHolder(x->index); args->add(new StaticExpr(new ObjectExpr(vh.ptr()))); return new Call(prelude_expr_staticIndex(), args); } ExprPtr desugarUnaryOp(UnaryOpPtr x) { ExprPtr callable; switch (x->op) { case DEREFERENCE : callable = prelude_expr_dereference(); break; case ADDRESS_OF : callable = primitive_expr_addressOf(); break; case PLUS : callable = prelude_expr_plus(); break; case MINUS : callable = prelude_expr_minus(); break; case NOT : callable = primitive_expr_boolNot(); break; default : assert(false); } CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr desugarBinaryOp(BinaryOpPtr x) { ExprPtr callable; switch (x->op) { case ADD : callable = prelude_expr_add(); break; case SUBTRACT : callable = prelude_expr_subtract(); break; case MULTIPLY : callable = prelude_expr_multiply(); break; case DIVIDE : callable = prelude_expr_divide(); break; case REMAINDER : callable = prelude_expr_remainder(); break; case EQUALS : callable = prelude_expr_equalsP(); break; case NOT_EQUALS : callable = prelude_expr_notEqualsP(); break; case LESSER : callable = prelude_expr_lesserP(); break; case LESSER_EQUALS : callable = prelude_expr_lesserEqualsP(); break; case GREATER : callable = prelude_expr_greaterP(); break; case GREATER_EQUALS : callable = prelude_expr_greaterEqualsP(); break; default : assert(false); } CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr1); call->args->add(x->expr2); return call.ptr(); } ExprPtr desugarIfExpr(IfExprPtr x) { ExprPtr callable = prelude_expr_ifExpression(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->condition); call->args->add(x->thenPart); call->args->add(x->elsePart); return call.ptr(); } ExprPtr desugarNew(NewPtr x) { ExprPtr callable = prelude_expr_allocateShared(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr desugarStaticExpr(StaticExprPtr x) { ExprPtr callable = prelude_expr_wrapStatic(); CallPtr call = new Call(callable, new ExprList()); call->args->add(x->expr); return call.ptr(); } ExprPtr updateOperatorExpr(int op) { switch (op) { case UPDATE_ADD : return prelude_expr_addAssign(); case UPDATE_SUBTRACT : return prelude_expr_subtractAssign(); case UPDATE_MULTIPLY : return prelude_expr_multiplyAssign(); case UPDATE_DIVIDE : return prelude_expr_divideAssign(); case UPDATE_REMAINDER : return prelude_expr_remainderAssign(); default : assert(false); return NULL; } } static vector<IdentifierPtr> identV(IdentifierPtr x) { vector<IdentifierPtr> v; v.push_back(x); return v; } StatementPtr desugarForStatement(ForPtr x) { IdentifierPtr exprVar = new Identifier("%expr"); IdentifierPtr iterVar = new Identifier("%iter"); BlockPtr block = new Block(); vector<StatementPtr> &bs = block->statements; bs.push_back(new Binding(REF, identV(exprVar), new ExprList(x->expr))); CallPtr iteratorCall = new Call(prelude_expr_iterator(), new ExprList()); iteratorCall->args->add(new NameRef(exprVar)); bs.push_back(new Binding(VAR, identV(iterVar), new ExprList(iteratorCall.ptr()))); CallPtr hasNextCall = new Call(prelude_expr_hasNextP(), new ExprList()); hasNextCall->args->add(new NameRef(iterVar)); CallPtr nextCall = new Call(prelude_expr_next(), new ExprList()); nextCall->args->add(new NameRef(iterVar)); ExprPtr unpackNext = new Unpack(nextCall.ptr()); BlockPtr whileBody = new Block(); vector<StatementPtr> &ws = whileBody->statements; ws.push_back(new Binding(REF, x->variables, new ExprList(unpackNext))); ws.push_back(x->body); bs.push_back(new While(hasNextCall.ptr(), whileBody.ptr())); return block.ptr(); } StatementPtr desugarCatchBlocks(const vector<CatchPtr> &catchBlocks) { bool lastWasAny = false; IfPtr lastIf; StatementPtr result; for (unsigned i = 0; i < catchBlocks.size(); ++i) { CatchPtr x = catchBlocks[i]; if (lastWasAny) error(x, "unreachable catch block"); if (x->exceptionType.ptr()) { ExprListPtr typeArg = new ExprList(x->exceptionType); CallPtr cond = new Call(prelude_expr_exceptionIsP(), typeArg); cond->location = x->exceptionType->location; BlockPtr block = new Block(); CallPtr getter = new Call(prelude_expr_exceptionAs(), typeArg); getter->location = x->exceptionVar->location; BindingPtr binding = new Binding(VAR, vector<IdentifierPtr>(1, x->exceptionVar), new ExprList(getter.ptr())); binding->location = x->exceptionVar->location; block->statements.push_back(binding.ptr()); block->statements.push_back(x->body); IfPtr ifStatement = new If(cond.ptr(), block.ptr()); ifStatement->location = x->location; if (!result) result = ifStatement.ptr(); if (lastIf.ptr()) lastIf->elsePart = ifStatement.ptr(); lastIf = ifStatement; } else { BlockPtr block = new Block(); block->location = x->location; CallPtr getter = new Call(prelude_expr_exceptionAsAny(), new ExprList()); getter->location = x->exceptionVar->location; BindingPtr binding = new Binding(VAR, vector<IdentifierPtr>(1, x->exceptionVar), new ExprList(getter.ptr())); binding->location = x->exceptionVar->location; block->statements.push_back(binding.ptr()); block->statements.push_back(x->body); if (!result) result = block.ptr(); if (lastIf.ptr()) lastIf->elsePart = block.ptr(); lastWasAny = true; lastIf = NULL; } } assert(result.ptr()); if (!lastWasAny) { assert(lastIf.ptr()); BlockPtr block = new Block(); CallPtr continueException = new Call(prelude_expr_continueException(), new ExprList()); StatementPtr stmt = new ExprStatement(continueException.ptr()); block->statements.push_back(stmt); block->statements.push_back(new Unreachable()); lastIf->elsePart = block.ptr(); } return result; } StatementPtr desugarSwitchStatement(SwitchPtr x) { BlockPtr block = new Block(); block->location = x->location; // %thing is the value being switched on IdentifierPtr thing = new Identifier("%thing"); thing->location = x->expr->location; NameRefPtr thingRef = new NameRef(thing); thingRef->location = x->expr->location; // initialize %thing { BindingPtr b = new Binding(REF, identV(thing), new ExprList(x->expr)); block->statements.push_back(b.ptr()); } StatementPtr root; StatementPtr *nextPtr = &root; // dispatch logic for (unsigned i = 0; i < x->caseBlocks.size(); ++i) { CaseBlockPtr y = x->caseBlocks[i]; ExprPtr condition; for (unsigned j = 0; j < y->caseLabels->size(); ++j) { ExprPtr caseValue = y->caseLabels->exprs[j]; ExprPtr compare = new BinaryOp(EQUALS, thingRef.ptr(), caseValue); compare->location = caseValue->location; if (!condition) { condition = compare; } else { condition = new Or(condition, compare); condition->location = y->location; } } assert(condition.ptr()); IfPtr ifStmt = new If(condition, y->body); ifStmt->location = y->location; *nextPtr = ifStmt.ptr(); nextPtr = &(ifStmt->elsePart); } if (x->defaultCase.ptr()) *nextPtr = x->defaultCase; else *nextPtr = new Break(); block->statements.push_back(root); return block.ptr(); } <|endoftext|>
<commit_before>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ASMITH_REFLECTION_FUNCTION_HPP #define ASMITH_REFLECTION_FUNCTION_HPP #include <string> namespace asmith { class reflection_class; class reflection_function { protected: virtual void call_(void*, void*, const void*) const = 0; public: virtual ~reflection_function() {} virtual const char* get_name() const = 0; virtual size_t get_parameter_count() const = 0; virtual const reflection_class& get_parameter(size_t) const = 0; virtual const reflection_class& get_return() const = 0; virtual size_t get_modifiers() const = 0; template<class R, class T> R call(T& aObject) const { //! \todo Check return type R tmp; call_(&aObject, &tmp, nullptr); return tmp; } template<class R, class T, class P1> R call(T& aObject, P1 p1) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2> R call(T& aObject, P1 p1, P2 p2) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3> R call(T& aObject, P1 p1, P2 p2, P3 p3) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3, class P4> R call(T& aObject, P1 p1, P2 p2, P3 p3, P4 p4) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3, class P4, class P5> R call(T& aObject, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } }; template<class CLASS, class RETURN, class... PARAMS> class auto_reflection_function : public reflection_function { public: typedef RETURN(CLASS::*ptr_t)(PARAMS...); private: const std::string mName; const ptr_t mPointer; const size_t mModifiers; //! \todo Implement for void return functions template<class R> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); ret = ((obj).*(mPointer))(); } template<class R, class P1> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); ret = ((obj).*(mPointer))(*p1); } template<class R, class P1, class P2> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); ret = ((obj).*(mPointer))(*p1, *p2); } template<class R, class P1, class P2, class P3> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); ret = ((obj).*(mPointer))(*p1, *p2, *p3); } template<class R, class P1, class P2, class P3, class P4> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); ret = ((obj).*(mPointer))(*p1, *p2, *p3, *p4); } template<class R, class P1, class P2, class P3, class P4, class P5> void call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); const P5* const p3 = reinterpret_cast<const P5*>(reinterpret_cast<const uint8_t*>(p4) + sizeof(P4)); ret = ((obj).*(mPointer))(*p1, *p2, *p3, *p4, *p5); } protected: // Inherited from reflection_function void call_(void* aObject, void* aReturn, const void* aParams) const override { call__<RETURN, PARAMS...>(aObject, aReturn, aParams); } public: auto_reflection_function(const std::string& aName, const ptr_t aPtr, const size_t aModifiers) : mName(aName), mModifiers(aModifiers), mPointer(aPtr) {} // Inherited from reflection_function const char* get_name() const override { return mName.c_str(); } size_t get_parameter_count() const override { return sizeof...(PARAMS); } const reflection_class& get_parameter(size_t aIndex) const override { //! \todo Implement throw 0; }; const reflection_class& get_return() const override { //! \todo Implement throw 0; }; size_t get_modifiers() const override { return mModifiers; }; }; } #endif<commit_msg>Void returing functions implemented<commit_after>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ASMITH_REFLECTION_FUNCTION_HPP #define ASMITH_REFLECTION_FUNCTION_HPP #include <string> namespace asmith { class reflection_class; class reflection_function { protected: virtual void call_(void*, void*, const void*) const = 0; public: virtual ~reflection_function() {} virtual const char* get_name() const = 0; virtual size_t get_parameter_count() const = 0; virtual const reflection_class& get_parameter(size_t) const = 0; virtual const reflection_class& get_return() const = 0; virtual size_t get_modifiers() const = 0; template<class R, class T> R call(T& aObject) const { //! \todo Check return type R tmp; call_(&aObject, &tmp, nullptr); return tmp; } template<class R, class T, class P1> R call(T& aObject, P1 p1) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2> R call(T& aObject, P1 p1, P2 p2) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3> R call(T& aObject, P1 p1, P2 p2, P3 p3) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3, class P4> R call(T& aObject, P1 p1, P2 p2, P3 p3, P4 p4) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } template<class R, class T, class P1, class P2, class P3, class P4, class P5> R call(T& aObject, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const { //! \todo Check return and parameter types R tmp; call_(&aObject, &tmp, &p1); return tmp; } }; template<class CLASS, class RETURN, class... PARAMS> class auto_reflection_function : public reflection_function { public: typedef RETURN(CLASS::*ptr_t)(PARAMS...); private: const std::string mName; const ptr_t mPointer; const size_t mModifiers; template<class R> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); ((obj).*(mPointer))(); } template<class R, class P1> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); const P1* const p1 = reinterpret_cast<const P1*>(aParams); ((obj).*(mPointer))(*p1); } template<class R, class P1, class P2> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); ((obj).*(mPointer))(*p1, *p2); } template<class R, class P1, class P2, class P3> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); ((obj).*(mPointer))(*p1, *p2, *p3); } template<class R, class P1, class P2, class P3, class P4> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); ((obj).*(mPointer))(*p1, *p2, *p3, *p4); } template<class R, class P1, class P2, class P3, class P4, class P5> typename std::enable_if<std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); const P5* const p3 = reinterpret_cast<const P5*>(reinterpret_cast<const uint8_t*>(p4) + sizeof(P4)); ((obj).*(mPointer))(*p1, *p2, *p3, *p4, *p5); } template<class R> typename std::enable_if<! std::is_same<R,void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); ret = ((obj).*(mPointer))(); } template<class R, class P1> typename std::enable_if<!std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); ret = ((obj).*(mPointer))(*p1); } template<class R, class P1, class P2> typename std::enable_if<!std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); ret = ((obj).*(mPointer))(*p1, *p2); } template<class R, class P1, class P2, class P3> typename std::enable_if<!std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); ret = ((obj).*(mPointer))(*p1, *p2, *p3); } template<class R, class P1, class P2, class P3, class P4> typename std::enable_if<!std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); ret = ((obj).*(mPointer))(*p1, *p2, *p3, *p4); } template<class R, class P1, class P2, class P3, class P4, class P5> typename std::enable_if<!std::is_same<R, void>::value, void>::type call__(void* aObject, void* aReturn, const void* aParams) const { CLASS& obj = *reinterpret_cast<CLASS*>(aObject); R& ret = *reinterpret_cast<RETURN*>(aReturn); const P1* const p1 = reinterpret_cast<const P1*>(aParams); const P2* const p2 = reinterpret_cast<const P2*>(reinterpret_cast<const uint8_t*>(p1) + sizeof(P1)); const P3* const p3 = reinterpret_cast<const P3*>(reinterpret_cast<const uint8_t*>(p2) + sizeof(P2)); const P4* const p3 = reinterpret_cast<const P4*>(reinterpret_cast<const uint8_t*>(p3) + sizeof(P3)); const P5* const p3 = reinterpret_cast<const P5*>(reinterpret_cast<const uint8_t*>(p4) + sizeof(P4)); ret = ((obj).*(mPointer))(*p1, *p2, *p3, *p4, *p5); } protected: // Inherited from reflection_function void call_(void* aObject, void* aReturn, const void* aParams) const override { call__<RETURN, PARAMS...>(aObject, aReturn, aParams); } public: auto_reflection_function(const std::string& aName, const ptr_t aPtr, const size_t aModifiers) : mName(aName), mModifiers(aModifiers), mPointer(aPtr) {} // Inherited from reflection_function const char* get_name() const override { return mName.c_str(); } size_t get_parameter_count() const override { return sizeof...(PARAMS); } const reflection_class& get_parameter(size_t aIndex) const override { //! \todo Implement throw 0; }; const reflection_class& get_return() const override { //! \todo Implement throw 0; }; size_t get_modifiers() const override { return mModifiers; }; }; } #endif<|endoftext|>
<commit_before>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name 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. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstdio> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> #define COPY_ISYNC int main(int argc, char* argv[]) { try { #if defined(_OPENMP) const int nthreads = std::min(std::max(1 < argc ? std::atoi(argv[1]) : 1, 1), omp_get_max_threads()); #else const int nthreads = std::min(std::max(1 < argc ? std::atoi(argv[1]) : 1, 1), 1); LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); libxstream_use_sink(&nthreads); #endif const int nstreams = std::min(std::max(2 < argc ? std::atoi(argv[2]) : 1, 1), LIBXSTREAM_MAX_NSTREAMS); const size_t maxsize = static_cast<size_t>(std::min(std::max(3 < argc ? std::atoi(argv[3]) : 2048, 1), 8192)) * (1 << 20), minsize = 8; int nrepeat = std::min(std::max(4 < argc ? std::atoi(argv[4]) : 7, 3), 100); size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { throw std::runtime_error("no device found!"); } const size_t stride = 2; for (size_t size = minsize, n = 1; size <= maxsize; size <<= 1, ++n) { if (0 == (n % stride)) { nrepeat <<= 1; } } void *buffer = 0; LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1, &buffer, maxsize, 0)); struct { libxstream_stream* stream; void* buffer; } copy[LIBXSTREAM_MAX_NSTREAMS]; for (int i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", i + 1); LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_create(&copy[i].stream, 0, 0, name)); LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(0/*device*/, &copy[i].buffer, maxsize, 0)); } int n = 1; double runavg = 0, runlns = 0; for (size_t size = minsize; size <= maxsize; size <<= 1, ++n) { if (0 == (n % stride)) { nrepeat >>= 1; } #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nrepeat; ++i) { const int j = i % nstreams; LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_h2d(buffer, copy[j].buffer, size, copy[j].stream)); #if defined(COPY_ISYNC) const int k = (j + 1) % nstreams; LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(copy[k].stream)); #endif } // sync all streams to complete any pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_sync(0)); #if defined(_OPENMP) const double duration = omp_get_wtime() - start; LIBXSTREAM_FLOCK(stdout); fprintf(stdout, "%lu Byte x %i: ", static_cast<unsigned long>(size), nrepeat); if (0 < duration) { const double bandwidth = (1.0 * size * nrepeat) / ((1ul << 20) * duration), factor = 1 < n ? 0.5 : 1.0; fprintf(stdout, "%.1f MB/s\n", bandwidth); runavg = (runavg + bandwidth) * factor; runlns = (runlns + std::log(bandwidth)) * factor; } else { fprintf(stdout, "-\n"); } LIBXSTREAM_FUNLOCK(stdout); #endif } if (1 < n) { fprintf(stdout, "runavg=%.0f rungeo=%.0f MB/s\n", runavg, std::exp(runlns)); } fprintf(stdout, "Finished\n"); } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Implemented copy-out benchmark and extended the command line interface accordingly.<commit_after>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name 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. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstdio> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> #define COPY_ISYNC int main(int argc, char* argv[]) { try { const bool copyin = 1 < argc ? ('i' == *argv[1]) : true; #if defined(_OPENMP) const int nthreads = std::min(std::max(2 < argc ? std::atoi(argv[2]) : 1, 1), omp_get_max_threads()); #else const int nthreads = std::min(std::max(2 < argc ? std::atoi(argv[2]) : 1, 1), 1); LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); libxstream_use_sink(&nthreads); #endif const int nstreams = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 1, 1), LIBXSTREAM_MAX_NSTREAMS); const size_t maxsize = static_cast<size_t>(std::min(std::max(4 < argc ? std::atoi(argv[4]) : 2048, 1), 8192)) * (1 << 20), minsize = 8; int nrepeat = std::min(std::max(5 < argc ? std::atoi(argv[5]) : 7, 3), 100); size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { throw std::runtime_error("no device found!"); } const size_t stride = 2; for (size_t size = minsize, n = 1; size <= maxsize; size <<= 1, ++n) { if (0 == (n % stride)) { nrepeat <<= 1; } } struct { libxstream_stream* stream; void *mem_hst, *mem_dev; } copy[LIBXSTREAM_MAX_NSTREAMS]; for (int i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", i + 1); LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_create(&copy[i].stream, 0, 0, name)); if (copyin) { if (0 == i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[i].mem_hst, maxsize, 0)); } else { copy[i].mem_hst = copy[0].mem_hst; } LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(0/*device*/, &copy[i].mem_dev, maxsize, 0)); } else { // copy-out LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[i].mem_hst, maxsize, 0)); if (0 == i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(0/*device*/, &copy[i].mem_dev, maxsize, 0)); } else { copy[i].mem_dev = copy[0].mem_dev; } } } int n = 1; double runavg = 0, runlns = 0; for (size_t size = minsize; size <= maxsize; size <<= 1, ++n) { if (0 == (n % stride)) { nrepeat >>= 1; } #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nrepeat; ++i) { const int j = i % nstreams; if (copyin) { LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_h2d(copy[j].mem_hst, copy[j].mem_dev, size, copy[j].stream)); } else { LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_d2h(copy[j].mem_dev, copy[j].mem_hst, size, copy[j].stream)); } #if defined(COPY_ISYNC) const int k = (j + 1) % nstreams; LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(copy[k].stream)); #endif } // sync all streams to complete any pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_sync(0)); #if defined(_OPENMP) const double duration = omp_get_wtime() - start; fprintf(stdout, "%lu Byte x %i: ", static_cast<unsigned long>(size), nrepeat); if (0 < duration) { const double bandwidth = (1.0 * size * nrepeat) / ((1ul << 20) * duration), factor = 1 < n ? 0.5 : 1.0; fprintf(stdout, "%.1f MB/s\n", bandwidth); runavg = (runavg + bandwidth) * factor; runlns = (runlns + std::log(bandwidth)) * factor; } else { fprintf(stdout, "-\n"); } fflush(stdout); #endif } if (1 < n) { fprintf(stdout, "runavg=%.0f rungeo=%.0f MB/s\n", runavg, std::exp(runlns)); } fprintf(stdout, "Finished\n"); } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <sksat/common.hpp> namespace sksat { using opt_func = int (*)(int, char**); class optparse { public: struct option { char s_opt; sksat::string l_opt, desc; opt_func func; }; optparse() : argc(0), argv(nullptr) {} void add_opt(optparse::option o){ opts.push_back(o); } void add_opt(char s_opt, sksat::string l_opt, sksat::string desc, opt_func func){ option o = { .s_opt = s_opt, .l_opt = l_opt, .desc = desc, .func = func }; add_opt(o); } void add_opt(char s_opt, sksat::string desc, opt_func func){ option o = { .s_opt = s_opt, .l_opt = "", .desc = desc, .func = func }; add_opt(o); } int search_short_opt(char c){ for(int i=0;i<opts.size();i++){ if(opts[i].s_opt == c) return i; } return -1; } int search_long_opt(sksat::string str){ if(str == "") return -1; for(int i=0;i<opts.size();i++){ if(opts[i].l_opt == str) return i; } return -1; } bool parse(int argc, char **argv){ this->argc = argc; this->argv = argv; if(argc == 1) return false; argc--; argv++; for(int i=0;i<argc;i++){ int opt_num = -1; if(argv[0][0] == '-'){ // option? if(argv[0][1] == '-'){ // long option opt_num = search_long_opt(argv[0]+2); }else{ // short option opt_num = search_short_opt(argv[0][1]); } } if(opt_num > -1){ // option found opt_func f = opts[opt_num].func; int ret = f(argc-i, argv); i += ret; argv+=ret; } argv++; } } private: int argc; char **argv; sksat::vector<option> opts; }; } <commit_msg>[FIX]<commit_after>#include <sksat/common.hpp> namespace sksat { using opt_func = int (*)(int, char**); class optparse { public: struct option { char s_opt; sksat::string l_opt, desc; opt_func func; }; optparse() : argc(0), argv(nullptr) {} void add_opt(optparse::option o){ opts.push_back(o); } void add_opt(char s_opt, sksat::string l_opt, sksat::string desc, opt_func func){ option o = { .s_opt = s_opt, .l_opt = l_opt, .desc = desc, .func = func }; add_opt(o); } void add_opt(char s_opt, sksat::string desc, opt_func func){ option o = { .s_opt = s_opt, .l_opt = "", .desc = desc, .func = func }; add_opt(o); } int search_short_opt(char c){ for(int i=0;i<opts.size();i++){ if(opts[i].s_opt == c) return i; } return -1; } int search_long_opt(sksat::string str){ if(str == "") return -1; for(int i=0;i<opts.size();i++){ if(opts[i].l_opt == str) return i; } return -1; } bool parse(int argc, char **argv){ this->argc = argc; this->argv = argv; if(argc == 1) return false; argc--; argv++; for(int i=0;i<argc;i++){ int opt_num = -1; if(argv[0][0] == '-'){ // option? if(argv[0][1] == '-'){ // long option opt_num = search_long_opt(argv[0]+2); }else{ // short option if(argv[0][1] != '\0'){ if(argv[0][2] == '\0') opt_num = search_short_opt(argv[0][1]); } } } if(opt_num > -1){ // option found opt_func f = opts[opt_num].func; int ret = f(argc-i, argv); i += ret; argv+=ret; } argv++; } } private: int argc; char **argv; sksat::vector<option> opts; }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-09-03 Martin Siggel <Martin.Siggel@dlr.de> * * 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 "CCPACSFarField.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CCPACSConfiguration.h" #include <string> #include <cmath> #include <gp_Ax2.hxx> #include <BRepPrimAPI_MakeSphere.hxx> #include <BRepPrimAPI_MakeBox.hxx> #include <TopExp_Explorer.hxx> #ifdef TIGL_USE_XCAF #include <XCAFDoc_ShapeTool.hxx> #include <XCAFApp_Application.hxx> #include <XCAFDoc_DocumentTool.hxx> #include <TDataStd_Name.hxx> #include <TDataXtd_Shape.hxx> #endif namespace tigl { CCPACSFarField::CCPACSFarField() { init(); } CCPACSFarField::~CCPACSFarField() {} void CCPACSFarField::init() { fieldType = NONE; fieldSize = 0.; loft.Nullify(); SetUID("FarField"); } TiglFarFieldType CCPACSFarField::GetFieldType() { return fieldType; } void CCPACSFarField::ReadCPACS(TixiDocumentHandle tixiHandle) { init(); std::string prefix = "/cpacs/toolspecific/cFD/farField"; if (tixiCheckElement(tixiHandle, prefix.c_str()) != SUCCESS) { LOG(INFO) << "No far-field defined."; fieldType = NONE; return; } // get field type std::string typePath = prefix + "/type"; char * tmpstr = NULL; if (tixiGetTextElement(tixiHandle, typePath.c_str(), &tmpstr) != SUCCESS) { fieldType = NONE; return; } else { if (strcmp(tmpstr, "halfSphere") == 0){ fieldType = HALF_SPHERE; } else if (strcmp(tmpstr, "fullSphere") == 0){ fieldType = FULL_SPHERE; } else if (strcmp(tmpstr, "halfCube") == 0){ fieldType = HALF_CUBE; } else if (strcmp(tmpstr, "fullCube") == 0){ fieldType = FULL_CUBE; } else { fieldType = NONE; return; } } // get reference length std::string refLenPath = prefix + "/referenceLength"; if (tixiGetDoubleElement(tixiHandle, refLenPath.c_str(), &fieldSize) != SUCCESS) { fieldSize = 0.; throw tigl::CTiglError("No reference length defined for far-field!"); } // get multiplier std::string multiplierPath = prefix + "/multiplier"; double multiplier = 1.; if (tixiGetDoubleElement(tixiHandle, multiplierPath.c_str(), &multiplier) != SUCCESS) { fieldSize = 0.; throw tigl::CTiglError("No multiplier defined for far-field!"); } else { fieldSize *= multiplier; } } TopoDS_Shape CCPACSFarField::BuildLoft(void) { TopoDS_Shape shape; shape.Nullify(); gp_Pnt center(0,0,0); switch(fieldType){ case NONE: return shape; case FULL_SPHERE: shape = BRepPrimAPI_MakeSphere(center, fieldSize).Shape(); break; case FULL_CUBE: shape = BRepPrimAPI_MakeBox(gp_Pnt(center.X()-fieldSize, center.Y()-fieldSize, center.Z()-fieldSize), fieldSize*2., fieldSize*2., fieldSize*2.).Shape(); break; case HALF_CUBE: shape = BRepPrimAPI_MakeBox(gp_Pnt(center.X()-fieldSize, center.Y(), center.Z()-fieldSize), fieldSize*2., fieldSize, fieldSize*2.).Shape(); break; case HALF_SPHERE: shape = BRepPrimAPI_MakeSphere(gp_Ax2(center, gp_Dir(0,1,0)), fieldSize, 0., M_PI_2).Shape(); break; default: shape.Nullify(); } return shape; } TiglGeometricComponentType CCPACSFarField::GetComponentType(void) { return TIGL_COMPONENT_LOGICAL; } #ifdef TIGL_USE_XCAF // builds data structure for a TDocStd_Application // mostly used for export TDF_Label CCPACSFarField::ExportDataStructure(CCPACSConfiguration&, Handle_XCAFDoc_ShapeTool &myAssembly, TDF_Label& label) { // add faces of current shape TopExp_Explorer faceExplorer; int iface = 1; for (faceExplorer.Init(GetLoft(), TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) { const TopoDS_Face& currentFace = TopoDS::Face(faceExplorer.Current()); TDF_Label aLabel = myAssembly->AddShape(currentFace, false); std::stringstream stream; stream << GetUID() << "_face" << iface++; TDataStd_Name::Set (aLabel, stream.str().c_str()); } return label; } #endif } // namespace tigl <commit_msg>Style fix<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-09-03 Martin Siggel <Martin.Siggel@dlr.de> * * 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 "CCPACSFarField.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CCPACSConfiguration.h" #include <string> #include <cmath> #include <gp_Ax2.hxx> #include <BRepPrimAPI_MakeSphere.hxx> #include <BRepPrimAPI_MakeBox.hxx> #include <TopExp_Explorer.hxx> #ifdef TIGL_USE_XCAF #include <XCAFDoc_ShapeTool.hxx> #include <XCAFApp_Application.hxx> #include <XCAFDoc_DocumentTool.hxx> #include <TDataStd_Name.hxx> #include <TDataXtd_Shape.hxx> #endif namespace tigl { CCPACSFarField::CCPACSFarField() { init(); } CCPACSFarField::~CCPACSFarField() {} void CCPACSFarField::init() { fieldType = NONE; fieldSize = 0.; loft.Nullify(); SetUID("FarField"); } TiglFarFieldType CCPACSFarField::GetFieldType() { return fieldType; } void CCPACSFarField::ReadCPACS(TixiDocumentHandle tixiHandle) { init(); std::string prefix = "/cpacs/toolspecific/cFD/farField"; if (tixiCheckElement(tixiHandle, prefix.c_str()) != SUCCESS) { LOG(INFO) << "No far-field defined."; fieldType = NONE; return; } // get field type std::string typePath = prefix + "/type"; char * tmpstr = NULL; if (tixiGetTextElement(tixiHandle, typePath.c_str(), &tmpstr) != SUCCESS) { fieldType = NONE; return; } else { if (strcmp(tmpstr, "halfSphere") == 0){ fieldType = HALF_SPHERE; } else if (strcmp(tmpstr, "fullSphere") == 0){ fieldType = FULL_SPHERE; } else if (strcmp(tmpstr, "halfCube") == 0){ fieldType = HALF_CUBE; } else if (strcmp(tmpstr, "fullCube") == 0){ fieldType = FULL_CUBE; } else { fieldType = NONE; return; } } // get reference length std::string refLenPath = prefix + "/referenceLength"; if (tixiGetDoubleElement(tixiHandle, refLenPath.c_str(), &fieldSize) != SUCCESS) { fieldSize = 0.; throw tigl::CTiglError("No reference length defined for far-field!"); } // get multiplier std::string multiplierPath = prefix + "/multiplier"; double multiplier = 1.; if (tixiGetDoubleElement(tixiHandle, multiplierPath.c_str(), &multiplier) != SUCCESS) { fieldSize = 0.; throw tigl::CTiglError("No multiplier defined for far-field!"); } else { fieldSize *= multiplier; } } TopoDS_Shape CCPACSFarField::BuildLoft(void) { TopoDS_Shape shape; shape.Nullify(); gp_Pnt center(0,0,0); switch (fieldType) { case NONE: return shape; case FULL_SPHERE: shape = BRepPrimAPI_MakeSphere(center, fieldSize).Shape(); break; case FULL_CUBE: shape = BRepPrimAPI_MakeBox(gp_Pnt(center.X()-fieldSize, center.Y()-fieldSize, center.Z()-fieldSize), fieldSize*2., fieldSize*2., fieldSize*2.).Shape(); break; case HALF_CUBE: shape = BRepPrimAPI_MakeBox(gp_Pnt(center.X()-fieldSize, center.Y(), center.Z()-fieldSize), fieldSize*2., fieldSize, fieldSize*2.).Shape(); break; case HALF_SPHERE: shape = BRepPrimAPI_MakeSphere(gp_Ax2(center, gp_Dir(0,1,0)), fieldSize, 0., M_PI_2).Shape(); break; default: shape.Nullify(); } return shape; } TiglGeometricComponentType CCPACSFarField::GetComponentType(void) { return TIGL_COMPONENT_LOGICAL; } #ifdef TIGL_USE_XCAF // builds data structure for a TDocStd_Application // mostly used for export TDF_Label CCPACSFarField::ExportDataStructure(CCPACSConfiguration&, Handle_XCAFDoc_ShapeTool &myAssembly, TDF_Label& label) { // add faces of current shape TopExp_Explorer faceExplorer; int iface = 1; for (faceExplorer.Init(GetLoft(), TopAbs_FACE); faceExplorer.More(); faceExplorer.Next()) { const TopoDS_Face& currentFace = TopoDS::Face(faceExplorer.Current()); TDF_Label aLabel = myAssembly->AddShape(currentFace, false); std::stringstream stream; stream << GetUID() << "_face" << iface++; TDataStd_Name::Set (aLabel, stream.str().c_str()); } return label; } #endif } // namespace tigl <|endoftext|>
<commit_before>#include "BoundingBox.hpp" namespace fast { void BoundingBox::createCorners(Float3 pos, Float3 size) { // Create corners float corners[8][3] = { {pos.x(),pos.y(),pos.z()}, {pos.x()+size.x(),pos.y(),pos.z()}, {pos.x()+size.x(),pos.y()+size.y(),pos.z()}, {pos.x()+size.x(),pos.y()+size.y(),pos.z()+size.z()}, {pos.x(),pos.y()+size.y(),pos.z()+size.z()}, {pos.x(),pos.y(),pos.z()+size.z()}, {pos.x()+size.x(),pos.y(),pos.z()+size.z()}, {pos.x(),pos.y()+size.y(),pos.z()} }; for(int c = 0; c < 8; c++) { for(int i = 0; i < 3; i++) { mCorners[c][i] = corners[c][i]; } } } BoundingBox::BoundingBox(Float3 pos, Float3 size) { mIsInitialized = true; createCorners(pos, size); } BoundingBox::BoundingBox(Float3 size) { mIsInitialized = true; Float3 pos; pos[0] = 0; pos[1] = 0; pos[2] = 0; createCorners(pos, size); } BoundingBox::BoundingBox(Vector<Float3, 8> corners) { mIsInitialized = true; mCorners = corners; // copy } BoundingBox::BoundingBox() { mIsInitialized = false; } Vector<Float3, 8> BoundingBox::getCorners() { if(!mIsInitialized) throw Exception("Cannot getCorners because bounding box was not initialized."); return mCorners; } BoundingBox::BoundingBox(std::vector<Float3> coordinates) { // Find min and max of all the coordinates Float3 minimum(coordinates[0].x(), coordinates[0].y(), coordinates[0].z()); Float3 maximum(coordinates[0].x(), coordinates[0].y(), coordinates[0].z()); for(uint i = 1; i < coordinates.size(); i++) { Float3 coordinate = coordinates[0]; for(uint j = 0; j < 4; j++) { if(coordinate[j] < minimum[j]) { minimum[j] = coordinate[j]; } if(coordinate[j] > maximum[j]) { maximum[j] = coordinate[j]; } } } // Make new bounding box Float3 size(maximum.x()-minimum.x(), maximum.y()-minimum.y(), maximum.z()-minimum.z()); BoundingBox(minimum, size); } BoundingBox BoundingBox::getTransformedBoundingBox( LinearTransformation transform) { if(!mIsInitialized) throw Exception("Cannot getTransformedBoundingBox because bounding box was not initialized."); Vector<Float3, 8> newCorners; for(uint i = 0; i < 8; i++) { Float3 vertex = mCorners[i]; Float3 transformedVertex = transform*vertex; newCorners[i] = transformedVertex; } return BoundingBox(newCorners); } std::ostream &operator<<(std::ostream &os, BoundingBox &object) { os << std::endl << "Bounding box" << std::endl; Vector<Float3, 8> corners = object.getCorners(); for(uint i = 0; i < 8; i++) { os << "Corner " << i << ": " << corners[i][0] << ", " << corners[i][1] << ", " << corners[i][2] << std::endl; } return os; } } // end namespace fast <commit_msg>fixed some bugs in the BoundingBox implementation<commit_after>#include "BoundingBox.hpp" namespace fast { void BoundingBox::createCorners(Float3 pos, Float3 size) { // Create corners float corners[8][3] = { {pos.x(),pos.y(),pos.z()}, {pos.x()+size.x(),pos.y(),pos.z()}, {pos.x()+size.x(),pos.y()+size.y(),pos.z()}, {pos.x()+size.x(),pos.y()+size.y(),pos.z()+size.z()}, {pos.x(),pos.y()+size.y(),pos.z()+size.z()}, {pos.x(),pos.y(),pos.z()+size.z()}, {pos.x()+size.x(),pos.y(),pos.z()+size.z()}, {pos.x(),pos.y()+size.y(),pos.z()} }; for(int c = 0; c < 8; c++) { for(int i = 0; i < 3; i++) { mCorners[c][i] = corners[c][i]; } } } BoundingBox::BoundingBox(Float3 pos, Float3 size) { mIsInitialized = true; createCorners(pos, size); } BoundingBox::BoundingBox(Float3 size) { mIsInitialized = true; Float3 pos; pos[0] = 0; pos[1] = 0; pos[2] = 0; createCorners(pos, size); } BoundingBox::BoundingBox(Vector<Float3, 8> corners) { mIsInitialized = true; mCorners = corners; // copy } BoundingBox::BoundingBox() { mIsInitialized = false; } Vector<Float3, 8> BoundingBox::getCorners() { if(!mIsInitialized) throw Exception("Cannot getCorners because bounding box was not initialized."); return mCorners; } BoundingBox::BoundingBox(std::vector<Float3> coordinates) { // Find min and max of all the coordinates Float3 minimum(coordinates[0].x(), coordinates[0].y(), coordinates[0].z()); Float3 maximum(coordinates[0].x(), coordinates[0].y(), coordinates[0].z()); for(uint i = 1; i < coordinates.size(); i++) { Float3 coordinate = coordinates[i]; for(uint j = 0; j < 4; j++) { if(coordinate[j] < minimum[j]) { minimum[j] = coordinate[j]; } if(coordinate[j] > maximum[j]) { maximum[j] = coordinate[j]; } } } // Make new bounding box Float3 size(maximum.x()-minimum.x(), maximum.y()-minimum.y(), maximum.z()-minimum.z()); mIsInitialized = true; std::cout << minimum[0] << " " << minimum[1] << std::endl; std::cout << maximum[0] << " " << maximum[1] << std::endl; std::cout << size[0] << " " << size[1] << std::endl; createCorners(minimum, size); } BoundingBox BoundingBox::getTransformedBoundingBox( LinearTransformation transform) { if(!mIsInitialized) throw Exception("Cannot getTransformedBoundingBox because bounding box was not initialized."); Vector<Float3, 8> newCorners; for(uint i = 0; i < 8; i++) { Float3 vertex = mCorners[i]; Float3 transformedVertex = transform*vertex; newCorners[i] = transformedVertex; } return BoundingBox(newCorners); } std::ostream &operator<<(std::ostream &os, BoundingBox &object) { os << std::endl << "Bounding box" << std::endl; Vector<Float3, 8> corners = object.getCorners(); for(uint i = 0; i < 8; i++) { os << "Corner " << i << ": " << corners[i][0] << ", " << corners[i][1] << ", " << corners[i][2] << std::endl; } return os; } } // end namespace fast <|endoftext|>
<commit_before>// RUN: %clang -target x86_64-unknown-nacl -ccc-echo %s -emit-llvm-only -c -o %t.o 2>&1 | FileCheck %s -check-prefix=ECHO // RUN: %clang -target x86_64-unknown-nacl %s -emit-llvm -S -c -o - | FileCheck %s // RUN: %clang -target x86_64-unknown-nacl %s -emit-llvm -S -c -pthread -o - | FileCheck %s -check-prefix=THREADS // ECHO: {{.*}} -cc1 {{.*}}x86_64-nacl-defines.c // Check platform defines // CHECK: __LITTLE_ENDIAN__defined #ifdef __LITTLE_ENDIAN__ void __LITTLE_ENDIAN__defined() {} #endif // CHECK: __native_client__defined #ifdef __native_client__ void __native_client__defined() {} #endif // CHECK: __x86_64__defined #ifdef __x86_64__ void __x86_64__defined() {} #endif // CHECK: unixdefined #ifdef unix void unixdefined() {} #endif // CHECK: __ELF__defined #ifdef __ELF__ void __ELF__defined() {} #endif // CHECK: _GNU_SOURCEdefined #ifdef _GNU_SOURCE void _GNU_SOURCEdefined() {} #endif // THREADS: _REENTRANTdefined // CHECK: _REENTRANTundefined #ifdef _REENTRANT void _REENTRANTdefined() {} #else void _REENTRANTundefined() {} #endif <commit_msg>Use -### instead of -ccc-echo.<commit_after>// RUN: %clang -target x86_64-unknown-nacl -### %s -emit-llvm-only -c -o %t.o 2>&1 | FileCheck %s -check-prefix=ECHO // RUN: %clang -target x86_64-unknown-nacl %s -emit-llvm -S -c -o - | FileCheck %s // RUN: %clang -target x86_64-unknown-nacl %s -emit-llvm -S -c -pthread -o - | FileCheck %s -check-prefix=THREADS // ECHO: {{.*}} -cc1 {{.*}}x86_64-nacl-defines.c // Check platform defines // CHECK: __LITTLE_ENDIAN__defined #ifdef __LITTLE_ENDIAN__ void __LITTLE_ENDIAN__defined() {} #endif // CHECK: __native_client__defined #ifdef __native_client__ void __native_client__defined() {} #endif // CHECK: __x86_64__defined #ifdef __x86_64__ void __x86_64__defined() {} #endif // CHECK: unixdefined #ifdef unix void unixdefined() {} #endif // CHECK: __ELF__defined #ifdef __ELF__ void __ELF__defined() {} #endif // CHECK: _GNU_SOURCEdefined #ifdef _GNU_SOURCE void _GNU_SOURCEdefined() {} #endif // THREADS: _REENTRANTdefined // CHECK: _REENTRANTundefined #ifdef _REENTRANT void _REENTRANTdefined() {} #else void _REENTRANTundefined() {} #endif <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Graphics.hpp> using namespace DO; struct Bresenham { template <typename Color> static inline void putColor(Image<Color>& image, int x, int y, const Color& color) { if (x < 0 || x >= image.width() || y < 0 || y >= image.height()) return; image(x,y) = color; } template <typename Color> static void drawLine(Image<Color>& image, int x0, int y0, int x1, int y1, const Color& color) { const int dx = abs(x1-x0); const int dy = abs(y1-y0); const int sx = x0 < x1 ? 1 : -1; const int sy = y0 < y1 ? 1 : -1; int err = dx-dy; while (true) { // Put color to image at current point $(x_0, y_0)$ putColor(image, x0, y0, color); // Stop drawing when we reach the end point $(x_1, y_1)$ if (x0 == x1 && y0 == y1) return; const int e2 = 2*err; if (e2 > -dy) { err -= dy; x0 += sx; } // Stop drawing when we reach the end point $(x_1, y_1)$ if (x0 == x1 && y0 == y1) { putColor(image, x0, y0, color); return; } if (e2 < dx) { err += dx; y0 += sy; } } } template <typename Color> static void drawCircle(Image<Color>& image, int x1, int y1, int r, const Color& color) { } template <typename Color> static void drawEllipse(Image<Color>& image, int x1, int y1, int r1, int r2, const Color& color) { } }; int main() { Image<Rgb8> img(300, 300); img.array().fill(White8); const float max_slope_value = 50.f; // Check line drawing when "start point < end point" for (float i = 0; i < max_slope_value; i += 0.2f) Bresenham::drawLine(img, 10, 10, 290, 290*i+10, Black8); // Check line drawing when "start point > end point" for (float i = 0.1f; i < max_slope_value; i += 0.2f) Bresenham::drawLine(img, 290, 290*i+10, 10, 10, Red8); viewImage(img); return 0; } struct Wu { template <typename T> void drawLine(Image<T>& image, int x1, int y1, int x2, int y2, const T& Color) { } template <typename T> void drawCircle(Image<T>& image, int x1, int y1, int r, const T& Color) { } template <typename T> void drawEllipse(Image<T>& image, int x1, int y1, int r1, int r2, const T& Color) { } }; <commit_msg>Development of image drawing in progress<commit_after>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Graphics.hpp> #include "ImageDrawing.hpp" using namespace DO; int main() { Image<Rgb8> img(300, 300); img.array().fill(White8); const float max_slope_value = 50.f; // Check line drawing when "start point < end point" for (float i = 0; i < max_slope_value; i += 0.2f) Bresenham::drawLine(img, 10, 10, 290, 290*i+10, Black8); // Check line drawing when "start point > end point" for (float i = 0.1f; i < max_slope_value; i += 0.2f) Bresenham::drawLine(img, 290, 290*i+10, 10, 10, Red8); viewImage(img); return 0; }<|endoftext|>
<commit_before>// // Copyright (c) 2008-2016 the Urho3D project. // // 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. // #ifdef URHO3D_ANGELSCRIPT #include <Urho3D/AngelScript/ScriptFile.h> #include <Urho3D/AngelScript/Script.h> #endif #include <Urho3D/Core/Main.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #ifdef URHO3D_LUA #include <Urho3D/LuaScript/LuaScript.h> #endif #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Resource/ResourceEvents.h> #include "Urho3DPlayer.h" #include <Urho3D/DebugNew.h> URHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer); Urho3DPlayer::Urho3DPlayer(Context* context) : Application(context) { } void Urho3DPlayer::Setup() { FileSystem* filesystem = GetSubsystem<FileSystem>(); // Web platform depends on the resource system to read any data files. Skip parsing the command line now // and try later when the resource system is live #ifndef EMSCRIPTEN // Read command line from a file if no arguments given. This is primarily intended for mobile platforms. // Note that the command file name uses a hardcoded path that does not utilize the resource system // properly (including resource path prefix), as the resource system is not yet initialized at this point const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt"; if (GetArguments().Empty() && filesystem->FileExists(commandFileName)) { SharedPtr<File> commandFile(new File(context_, commandFileName)); String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); // Reparse engine startup parameters now engineParameters_ = Engine::ParseParameters(GetArguments()); } // Check for script file name from the arguments GetScriptFileName(); // Show usage if not found if (scriptFileName_.Empty()) { ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x <res> Horizontal resolution\n" "-y <res> Vertical resolution\n" "-m <level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-hd Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b <length> Sound buffer length in milliseconds\n" "-r <freq> Sound mixing frequency in Hz\n" "-p <paths> Resource path(s) to use, separated by semicolons\n" "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n" "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-ds <file> Dump used shader variations to a file for precaching\n" "-mq <level> Material quality level, default 2 (high)\n" "-tq <level> Texture quality level, default 2 (high)\n" "-tf <level> Texture filter mode, default 2 (trilinear)\n" "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n" "-gl2 Force OpenGL 2 use even if OpenGL 3 is available\n" "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D\n" "-borderless Borderless window mode\n" "-headless Headless mode. No application window will be created\n" "-landscape Use landscape orientations (iOS only, default)\n" "-portrait Use portrait orientations (iOS only)\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-renderpath <name> Use the named renderpath (must enter full resource name)\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-touch Touch emulation on desktop platform\n" #endif ); } else { // Use the script file name as the base name for the log file engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log"; } #else // On Web platform setup a default windowed resolution similar to the executable samples engineParameters_["FullScreen"] = false; #endif // Construct a search path to find the resource prefix with two entries: // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location if (!engineParameters_.Contains("ResourcePrefixPaths")) engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources"; } void Urho3DPlayer::Start() { // Reattempt reading the command line now on Web platform #ifdef EMSCRIPTEN if (GetArguments().Empty()) { SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false); if (commandFile) { String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); GetScriptFileName(); } } if (scriptFileName_.Empty()) { ErrorExit("Script file name not specified; cannot proceed"); return; } #endif String extension = GetExtension(scriptFileName_); if (extension != ".lua" && extension != ".luc") { #ifdef URHO3D_ANGELSCRIPT // Instantiate and register the AngelScript subsystem context_->RegisterSubsystem(new Script(context_)); // Hold a shared pointer to the script file to make sure it is not unloaded during runtime scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_); /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances #ifdef URHO3D_LUA if (scriptFileName_.Contains("Editor.as", false)) context_->RegisterSubsystem(new LuaScript(context_)); #endif // If script loading is successful, proceed to main loop if (scriptFile_ && scriptFile_->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed)); return; } #else ErrorExit("AngelScript is not enabled!"); return; #endif } else { #ifdef URHO3D_LUA // Instantiate and register the Lua script subsystem LuaScript* luaScript = new LuaScript(context_); context_->RegisterSubsystem(luaScript); // If script loading is successful, proceed to main loop if (luaScript->ExecuteFile(scriptFileName_)) { luaScript->ExecuteFunction("Start"); return; } #else ErrorExit("Lua is not enabled!"); return; #endif } // The script was not successfully loaded. Show the last error message and do not run the main loop ErrorExit(); } void Urho3DPlayer::Stop() { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_) { // Execute the optional stop function if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); } #else if (false) { } #endif #ifdef URHO3D_LUA else { LuaScript* luaScript = GetSubsystem<LuaScript>(); if (luaScript && luaScript->GetFunction("Stop", true)) luaScript->ExecuteFunction("Stop"); } #endif } void Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); #endif } void Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT // Restart the script application after reload if (!scriptFile_->Execute("void Start()")) { scriptFile_.Reset(); ErrorExit(); } #endif } void Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT scriptFile_.Reset(); ErrorExit(); #endif } void Urho3DPlayer::GetScriptFileName() { const Vector<String>& arguments = GetArguments(); if (arguments.Size() && arguments[0][0] != '-') scriptFileName_ = GetInternalPath(arguments[0]); }<commit_msg>Fix logic for getting the script file name in web Urho3DPlayer in case arguments were already specified and the command line file is not used.<commit_after>// // Copyright (c) 2008-2016 the Urho3D project. // // 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. // #ifdef URHO3D_ANGELSCRIPT #include <Urho3D/AngelScript/ScriptFile.h> #include <Urho3D/AngelScript/Script.h> #endif #include <Urho3D/Core/Main.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #ifdef URHO3D_LUA #include <Urho3D/LuaScript/LuaScript.h> #endif #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Resource/ResourceEvents.h> #include "Urho3DPlayer.h" #include <Urho3D/DebugNew.h> URHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer); Urho3DPlayer::Urho3DPlayer(Context* context) : Application(context) { } void Urho3DPlayer::Setup() { // Web platform depends on the resource system to read any data files. Skip parsing the command line file now // and try later when the resource system is live #ifndef EMSCRIPTEN // Read command line from a file if no arguments given. This is primarily intended for mobile platforms. // Note that the command file name uses a hardcoded path that does not utilize the resource system // properly (including resource path prefix), as the resource system is not yet initialized at this point FileSystem* filesystem = GetSubsystem<FileSystem>(); const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt"; if (GetArguments().Empty() && filesystem->FileExists(commandFileName)) { SharedPtr<File> commandFile(new File(context_, commandFileName)); String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); // Reparse engine startup parameters now engineParameters_ = Engine::ParseParameters(GetArguments()); } // Check for script file name from the arguments GetScriptFileName(); // Show usage if not found if (scriptFileName_.Empty()) { ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x <res> Horizontal resolution\n" "-y <res> Vertical resolution\n" "-m <level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-hd Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b <length> Sound buffer length in milliseconds\n" "-r <freq> Sound mixing frequency in Hz\n" "-p <paths> Resource path(s) to use, separated by semicolons\n" "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n" "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-ds <file> Dump used shader variations to a file for precaching\n" "-mq <level> Material quality level, default 2 (high)\n" "-tq <level> Texture quality level, default 2 (high)\n" "-tf <level> Texture filter mode, default 2 (trilinear)\n" "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n" "-gl2 Force OpenGL 2 use even if OpenGL 3 is available\n" "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D\n" "-borderless Borderless window mode\n" "-headless Headless mode. No application window will be created\n" "-landscape Use landscape orientations (iOS only, default)\n" "-portrait Use portrait orientations (iOS only)\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-renderpath <name> Use the named renderpath (must enter full resource name)\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-touch Touch emulation on desktop platform\n" #endif ); } else { // Use the script file name as the base name for the log file engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log"; } #else // On Web platform setup a default windowed resolution similar to the executable samples engineParameters_["FullScreen"] = false; #endif // Construct a search path to find the resource prefix with two entries: // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location if (!engineParameters_.Contains("ResourcePrefixPaths")) engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources"; } void Urho3DPlayer::Start() { // Reattempt reading the command line now on Web platform #ifdef EMSCRIPTEN if (GetArguments().Empty()) { SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false); if (commandFile) { String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); } } GetScriptFileName(); if (scriptFileName_.Empty()) { ErrorExit("Script file name not specified; cannot proceed"); return; } #endif String extension = GetExtension(scriptFileName_); if (extension != ".lua" && extension != ".luc") { #ifdef URHO3D_ANGELSCRIPT // Instantiate and register the AngelScript subsystem context_->RegisterSubsystem(new Script(context_)); // Hold a shared pointer to the script file to make sure it is not unloaded during runtime scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_); /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances #ifdef URHO3D_LUA if (scriptFileName_.Contains("Editor.as", false)) context_->RegisterSubsystem(new LuaScript(context_)); #endif // If script loading is successful, proceed to main loop if (scriptFile_ && scriptFile_->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed)); return; } #else ErrorExit("AngelScript is not enabled!"); return; #endif } else { #ifdef URHO3D_LUA // Instantiate and register the Lua script subsystem LuaScript* luaScript = new LuaScript(context_); context_->RegisterSubsystem(luaScript); // If script loading is successful, proceed to main loop if (luaScript->ExecuteFile(scriptFileName_)) { luaScript->ExecuteFunction("Start"); return; } #else ErrorExit("Lua is not enabled!"); return; #endif } // The script was not successfully loaded. Show the last error message and do not run the main loop ErrorExit(); } void Urho3DPlayer::Stop() { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_) { // Execute the optional stop function if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); } #else if (false) { } #endif #ifdef URHO3D_LUA else { LuaScript* luaScript = GetSubsystem<LuaScript>(); if (luaScript && luaScript->GetFunction("Stop", true)) luaScript->ExecuteFunction("Stop"); } #endif } void Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); #endif } void Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT // Restart the script application after reload if (!scriptFile_->Execute("void Start()")) { scriptFile_.Reset(); ErrorExit(); } #endif } void Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData) { #ifdef URHO3D_ANGELSCRIPT scriptFile_.Reset(); ErrorExit(); #endif } void Urho3DPlayer::GetScriptFileName() { const Vector<String>& arguments = GetArguments(); if (arguments.Size() && arguments[0][0] != '-') scriptFileName_ = GetInternalPath(arguments[0]); }<|endoftext|>
<commit_before>#include <QTimer> #include <QsLog.h> #include "inverter_gateway.h" #include "abstract_detector.h" #include "settings.h" #include "fronius_udp_detector.h" static const int MaxSimultaneousRequests = 32; InverterGateway::InverterGateway(Settings *settings, QObject *parent) : QObject(parent), mSettings(settings), mTimer(new QTimer(this)), mUdpDetector(new FroniusUdpDetector(this)), mAutoDetect(false), mScanType(None) { Q_ASSERT(settings != 0); mAddressGenerator.setNetMaskLimit(QHostAddress(0xFFFFF000)); mTimer->setInterval(60000); connect(mTimer, SIGNAL(timeout()), this, SLOT(onTimer())); connect(mUdpDetector, SIGNAL(finished()), this, SLOT(continueScan())); } void InverterGateway::addDetector(AbstractDetector *detector) { mDetectors.append(detector); } bool InverterGateway::autoDetect() const { return mAutoDetect; } void InverterGateway::setAutoDetect(bool b) { if (mAutoDetect == b) return; mAutoDetect = b; emit autoDetectChanged(); } int InverterGateway::scanProgress() const { return mAutoDetect ? mAddressGenerator.progress(mActiveHosts.count()) : 100; } void InverterGateway::initializeSettings() { connect(mSettings, SIGNAL(portNumberChanged()), this, SLOT(onPortNumberChanged())); connect(mSettings, SIGNAL(ipAddressesChanged()), this, SLOT(onIpAddressesChanged())); } void InverterGateway::startDetection() { // startDetection is called as soon as localsettings comes up. So this // is a good spot to start our period re-scan timer. mTimer->start(); // Do a priorityScan, followed by a fullScan if not all hosts are found scan(TryPriority); } void InverterGateway::fullScan() { scan(Full); } void InverterGateway::scan(enum ScanType scanType) { mScanType = scanType; mDevicesFound.clear(); setAutoDetect(mScanType == Full); // Do a UDP scan mUdpDetector->start(); } void InverterGateway::continueScan() { // Start with any addresses found by the fast UDP scan. QList<QHostAddress> addresses = mUdpDetector->devicesFound(); // Initialise address generator with priority addresses foreach (QHostAddress a, mSettings->ipAddresses() + mSettings->knownIpAddresses()) { if (!addresses.contains(a)) { addresses.append(a); } } // If priority scan and no known PV-inverters, then we're done if (mScanType == Priority && addresses.isEmpty()) return; QLOG_TRACE() << "Starting IP scan (" << mScanType << ")"; mAddressGenerator.setPriorityAddresses(addresses); mAddressGenerator.setPriorityOnly(mScanType != Full); mAddressGenerator.reset(); while (mActiveHosts.size() < MaxSimultaneousRequests && mAddressGenerator.hasNext()) { QString host = mAddressGenerator.next().toString(); QLOG_TRACE() << "Starting scan for" << host; scanHost(host); } } void InverterGateway::scanHost(QString hostName) { HostScan *host = new HostScan(mDetectors, hostName); mActiveHosts.append(host); connect(host, SIGNAL(finished()), this, SLOT(onDetectionDone())); connect(host, SIGNAL(deviceFound(const DeviceInfo &)), this, SLOT(onInverterFound(const DeviceInfo &))); host->scan(); } void InverterGateway::onInverterFound(const DeviceInfo &deviceInfo) { QList<QHostAddress> addresses = mSettings->knownIpAddresses(); QHostAddress addr(deviceInfo.hostName); mDevicesFound.insert(addr); if (!addresses.contains(addr)) { addresses.append(addr); mSettings->setKnownIpAddresses(addresses); } emit inverterFound(deviceInfo); } void InverterGateway::onDetectionDone() { HostScan *host = static_cast<HostScan *>(sender()); QLOG_TRACE() << "Done scanning" << host->hostName(); mActiveHosts.removeOne(host); host->deleteLater(); updateScanProgress(); if (mScanType > None && mAddressGenerator.hasNext()) { // Scan the next available host scanHost(mAddressGenerator.next().toString()); } else if(mActiveHosts.size() == 0) { // Scan is complete enum ScanType scanType = mScanType; mScanType = None; // Did we get what we came for? For full and priority scans, this is it. // For TryPriority scans, we switch to a full scan if we're a few // piggies short, and if autoScan is enabled. if ((scanType == TryPriority) && mSettings->autoScan()) { // FIXME only check that we found all known ones, not all priority // ones. Otherwise we do a full scan whenever a manually defined one // is missing QSet<QHostAddress> addresses = QSet<QHostAddress>::fromList( mAddressGenerator.priorityAddresses()); // Do a full scan if not all devices were found if ((addresses - mDevicesFound).size()) { QLOG_INFO() << "Not all devices found, starting full IP scan"; mScanType = Full; setAutoDetect(true); continueScan(); return; } } setAutoDetect(false); QLOG_INFO() << "Auto IP scan completed. Detection finished"; } } void InverterGateway::onPortNumberChanged() { // If the port was changed, assume that the IP addresses did not, and // scan the priority addresses first, then fall back to a full scan. scan(TryPriority); } void InverterGateway::onIpAddressesChanged() { // If the IP addresses changed, do a priority scan. That will scan // the new addresses too, and avoid a full scan. scan(Priority); } void InverterGateway::onTimer() { // If we are in the middle of a sweep, don't start another one. if (mScanType > None) return; scan(TryPriority); } void InverterGateway::updateScanProgress() { emit scanProgressChanged(); } HostScan::HostScan(QList<AbstractDetector *> detectors, QString hostname, QObject *parent) : QObject(parent), mDetectors(detectors), mHostname(hostname) { } void HostScan::scan() { if (mDetectors.size()) { DetectorReply *reply = mDetectors.takeFirst()->start(mHostname); connect(reply, SIGNAL(deviceFound(const DeviceInfo &)), this, SLOT(onDeviceFound(const DeviceInfo &))); connect(reply, SIGNAL(finished()), this, SLOT(continueScan())); } else { emit finished(); } } void HostScan::continueScan() { DetectorReply *reply = static_cast<DetectorReply *>(sender()); reply->deleteLater(); scan(); // Try next detector } void HostScan::onDeviceFound(const DeviceInfo &deviceInfo) { mDetectors.clear(); // Found an inverter on this host, we're done. emit deviceFound(deviceInfo); } <commit_msg>Don't mix manually configured and autodetected ips<commit_after>#include <QTimer> #include <QsLog.h> #include "inverter_gateway.h" #include "abstract_detector.h" #include "settings.h" #include "fronius_udp_detector.h" static const int MaxSimultaneousRequests = 32; InverterGateway::InverterGateway(Settings *settings, QObject *parent) : QObject(parent), mSettings(settings), mTimer(new QTimer(this)), mUdpDetector(new FroniusUdpDetector(this)), mAutoDetect(false), mScanType(None) { Q_ASSERT(settings != 0); mAddressGenerator.setNetMaskLimit(QHostAddress(0xFFFFF000)); mTimer->setInterval(60000); connect(mTimer, SIGNAL(timeout()), this, SLOT(onTimer())); connect(mUdpDetector, SIGNAL(finished()), this, SLOT(continueScan())); } void InverterGateway::addDetector(AbstractDetector *detector) { mDetectors.append(detector); } bool InverterGateway::autoDetect() const { return mAutoDetect; } void InverterGateway::setAutoDetect(bool b) { if (mAutoDetect == b) return; mAutoDetect = b; emit autoDetectChanged(); } int InverterGateway::scanProgress() const { return mAutoDetect ? mAddressGenerator.progress(mActiveHosts.count()) : 100; } void InverterGateway::initializeSettings() { connect(mSettings, SIGNAL(portNumberChanged()), this, SLOT(onPortNumberChanged())); connect(mSettings, SIGNAL(ipAddressesChanged()), this, SLOT(onIpAddressesChanged())); } void InverterGateway::startDetection() { // startDetection is called as soon as localsettings comes up. So this // is a good spot to start our period re-scan timer. mTimer->start(); // Do a priorityScan, followed by a fullScan if not all hosts are found scan(TryPriority); } void InverterGateway::fullScan() { scan(Full); } void InverterGateway::scan(enum ScanType scanType) { mScanType = scanType; mDevicesFound.clear(); setAutoDetect(mScanType == Full); // Do a UDP scan mUdpDetector->start(); } void InverterGateway::continueScan() { // Start with any addresses found by the fast UDP scan. QList<QHostAddress> addresses = mUdpDetector->devicesFound(); // Initialise address generator with priority addresses foreach (QHostAddress a, mSettings->ipAddresses() + mSettings->knownIpAddresses()) { if (!addresses.contains(a)) { addresses.append(a); } } // If priority scan and no known PV-inverters, then we're done if (mScanType == Priority && addresses.isEmpty()) return; QLOG_TRACE() << "Starting IP scan (" << mScanType << ")"; mAddressGenerator.setPriorityAddresses(addresses); mAddressGenerator.setPriorityOnly(mScanType != Full); mAddressGenerator.reset(); while (mActiveHosts.size() < MaxSimultaneousRequests && mAddressGenerator.hasNext()) { QString host = mAddressGenerator.next().toString(); QLOG_TRACE() << "Starting scan for" << host; scanHost(host); } } void InverterGateway::scanHost(QString hostName) { HostScan *host = new HostScan(mDetectors, hostName); mActiveHosts.append(host); connect(host, SIGNAL(finished()), this, SLOT(onDetectionDone())); connect(host, SIGNAL(deviceFound(const DeviceInfo &)), this, SLOT(onInverterFound(const DeviceInfo &))); host->scan(); } void InverterGateway::onInverterFound(const DeviceInfo &deviceInfo) { QHostAddress addr(deviceInfo.hostName); mDevicesFound.insert(addr); // If the found address is already in the list of manually configured // addresses, do not append it to the list of discovered addresses. if (!mSettings->ipAddresses().contains(addr)) { QList<QHostAddress> addresses = mSettings->knownIpAddresses(); if (!addresses.contains(addr)) { addresses.append(addr); mSettings->setKnownIpAddresses(addresses); } } emit inverterFound(deviceInfo); } void InverterGateway::onDetectionDone() { HostScan *host = static_cast<HostScan *>(sender()); QLOG_TRACE() << "Done scanning" << host->hostName(); mActiveHosts.removeOne(host); host->deleteLater(); updateScanProgress(); if (mScanType > None && mAddressGenerator.hasNext()) { // Scan the next available host scanHost(mAddressGenerator.next().toString()); } else if(mActiveHosts.size() == 0) { // Scan is complete enum ScanType scanType = mScanType; mScanType = None; // Did we get what we came for? For full and priority scans, this is it. // For TryPriority scans, we switch to a full scan if we're a few // piggies short, and if autoScan is enabled. if ((scanType == TryPriority) && mSettings->autoScan()) { // FIXME only check that we found all known ones, not all priority // ones. Otherwise we do a full scan whenever a manually defined one // is missing QSet<QHostAddress> addresses = QSet<QHostAddress>::fromList( mAddressGenerator.priorityAddresses()); // Do a full scan if not all devices were found if ((addresses - mDevicesFound).size()) { QLOG_INFO() << "Not all devices found, starting full IP scan"; mScanType = Full; setAutoDetect(true); continueScan(); return; } } setAutoDetect(false); QLOG_INFO() << "Auto IP scan completed. Detection finished"; } } void InverterGateway::onPortNumberChanged() { // If the port was changed, assume that the IP addresses did not, and // scan the priority addresses first, then fall back to a full scan. scan(TryPriority); } void InverterGateway::onIpAddressesChanged() { // If the IP addresses changed, do a priority scan. That will scan // the new addresses too, and avoid a full scan. scan(Priority); } void InverterGateway::onTimer() { // If we are in the middle of a sweep, don't start another one. if (mScanType > None) return; scan(TryPriority); } void InverterGateway::updateScanProgress() { emit scanProgressChanged(); } HostScan::HostScan(QList<AbstractDetector *> detectors, QString hostname, QObject *parent) : QObject(parent), mDetectors(detectors), mHostname(hostname) { } void HostScan::scan() { if (mDetectors.size()) { DetectorReply *reply = mDetectors.takeFirst()->start(mHostname); connect(reply, SIGNAL(deviceFound(const DeviceInfo &)), this, SLOT(onDeviceFound(const DeviceInfo &))); connect(reply, SIGNAL(finished()), this, SLOT(continueScan())); } else { emit finished(); } } void HostScan::continueScan() { DetectorReply *reply = static_cast<DetectorReply *>(sender()); reply->deleteLater(); scan(); // Try next detector } void HostScan::onDeviceFound(const DeviceInfo &deviceInfo) { mDetectors.clear(); // Found an inverter on this host, we're done. emit deviceFound(deviceInfo); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** @file * Tests for SURGSIM_ASSERT() and SURGSIM_FAILURE(). */ #include <gtest/gtest.h> #include <SurgSim/Framework/Assert.h> class MockOutput : public SurgSim::Framework::LogOutput { public: MockOutput() {}; ~MockOutput() {}; bool writeMessage(const std::string& message) { logMessage = message; return true; } void reset() { logMessage = ""; } std::string logMessage; }; class AssertTest : public ::testing::Test { public: void SetUp() { logOutput = std::make_shared<MockOutput>(); testLogger = std::unique_ptr<SurgSim::Framework::Logger>(new SurgSim::Framework::Logger("test", logOutput)); // testLogger will be used for assertions in most tests, due to the definition of SURGSIM_ASSERT_LOGGER below. savedCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); } void TearDown() { SurgSim::Framework::AssertMessage::setFailureCallback(savedCallback); testLogger.reset(); logOutput.reset(); } std::shared_ptr<MockOutput> logOutput; std::unique_ptr<SurgSim::Framework::Logger> testLogger; SurgSim::Framework::AssertMessage::DeathCallback savedCallback; }; TEST_F(AssertTest, DefaultAssertLogger) { std::cout << "=== You should see an assertion message to cout/cerr:" << std::endl; EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); std::cout << "=== The test is now complete." << std::endl; } #undef SURGSIM_ASSERT_LOGGER // override the default definition #define SURGSIM_ASSERT_LOGGER testLogger // defined in the test fixture, above inline bool stringContains(const std::string& string, const std::string& fragment) { return string.find(fragment) != std::string::npos; } static int numIgnoredAssertions = 0; static void ignoreAssertionKeepGoing(const std::string& message) { ++numIgnoredAssertions; } TEST_F(AssertTest, Assertion) { logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "1 == 2")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "AssertTest.cpp")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "extra information")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_EQ("", logOutput->logMessage) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, Failure) { logOutput->reset(); EXPECT_THROW(SURGSIM_FAILURE() << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "AssertTest.cpp")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "extra information")) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, Manipulators) { logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "aAa" << std::endl << "bBb", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "aAa\nbBb") || stringContains(logOutput->logMessage, "aAa\r\n\bBb")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "[" << std::hex << std::setw(5) << std::setfill('0') << 0x1234 << "]", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "[01234]")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); // The next message should not show any evidence of previous manipulators. EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "[" << 987 << "]", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "[987]")) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, ExceptionBehavior) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_THROW(SURGSIM_FAILURE() << "extra information would go here", SurgSim::Framework::AssertionFailure); } TEST_F(AssertTest, Callback) { logOutput->reset(); typedef SurgSim::Framework::AssertMessage::DeathCallback CallbackType; const CallbackType defaultCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); const CallbackType throwCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); EXPECT_EQ(throwCallback, defaultCallback); SurgSim::Framework::AssertMessage::setFailureCallback(ignoreAssertionKeepGoing); EXPECT_EQ(static_cast<CallbackType>(ignoreAssertionKeepGoing), SurgSim::Framework::AssertMessage::getFailureCallback()); numIgnoredAssertions = 0; EXPECT_NO_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here"); EXPECT_EQ(1, numIgnoredAssertions); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_EQ(1, numIgnoredAssertions); EXPECT_NO_THROW(SURGSIM_FAILURE() << "extra information would go here"); EXPECT_EQ(2, numIgnoredAssertions); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); EXPECT_EQ(throwCallback, SurgSim::Framework::AssertMessage::getFailureCallback()); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_EQ(2, numIgnoredAssertions); } TEST_F(AssertTest, DebuggerBehaviorSuccess) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); } TEST_F(AssertTest, DebuggerBehaviorAssertFailedDeathTest) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); // The assertion should die with no output to stdout. ASSERT_DEATH_IF_SUPPORTED({SURGSIM_ASSERT(1 == 2) << "extra information would go here";}, "^$"); } TEST_F(AssertTest, DebuggerBehaviorFailureDeathTest) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); // The assertion should die with no output to stdout. ASSERT_DEATH_IF_SUPPORTED({SURGSIM_FAILURE() << "extra information would go here";}, "^$"); } <commit_msg>Follow instructions on death tests *correctly* this time.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** @file * Tests for SURGSIM_ASSERT() and SURGSIM_FAILURE(). */ #include <gtest/gtest.h> #include <SurgSim/Framework/Assert.h> class MockOutput : public SurgSim::Framework::LogOutput { public: MockOutput() {}; ~MockOutput() {}; bool writeMessage(const std::string& message) { logMessage = message; return true; } void reset() { logMessage = ""; } std::string logMessage; }; class AssertTest : public ::testing::Test { public: void SetUp() { logOutput = std::make_shared<MockOutput>(); testLogger = std::unique_ptr<SurgSim::Framework::Logger>(new SurgSim::Framework::Logger("test", logOutput)); // testLogger will be used for assertions in most tests, due to the definition of SURGSIM_ASSERT_LOGGER below. savedCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); } void TearDown() { SurgSim::Framework::AssertMessage::setFailureCallback(savedCallback); testLogger.reset(); logOutput.reset(); } std::shared_ptr<MockOutput> logOutput; std::unique_ptr<SurgSim::Framework::Logger> testLogger; SurgSim::Framework::AssertMessage::DeathCallback savedCallback; }; typedef AssertTest AssertDeathTest; TEST_F(AssertTest, DefaultAssertLogger) { std::cout << "=== You should see an assertion message to cout/cerr:" << std::endl; EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); std::cout << "=== The test is now complete." << std::endl; } #undef SURGSIM_ASSERT_LOGGER // override the default definition #define SURGSIM_ASSERT_LOGGER testLogger // defined in the test fixture, above inline bool stringContains(const std::string& string, const std::string& fragment) { return string.find(fragment) != std::string::npos; } static int numIgnoredAssertions = 0; static void ignoreAssertionKeepGoing(const std::string& message) { ++numIgnoredAssertions; } TEST_F(AssertTest, Assertion) { logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "1 == 2")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "AssertTest.cpp")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "extra information")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_EQ("", logOutput->logMessage) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, Failure) { logOutput->reset(); EXPECT_THROW(SURGSIM_FAILURE() << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "AssertTest.cpp")) << "message: '" << logOutput->logMessage << "'"; EXPECT_TRUE(stringContains(logOutput->logMessage, "extra information")) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, Manipulators) { logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "aAa" << std::endl << "bBb", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "aAa\nbBb") || stringContains(logOutput->logMessage, "aAa\r\n\bBb")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "[" << std::hex << std::setw(5) << std::setfill('0') << 0x1234 << "]", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "[01234]")) << "message: '" << logOutput->logMessage << "'"; logOutput->reset(); // The next message should not show any evidence of previous manipulators. EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "[" << 987 << "]", SurgSim::Framework::AssertionFailure); EXPECT_TRUE(stringContains(logOutput->logMessage, "[987]")) << "message: '" << logOutput->logMessage << "'"; } TEST_F(AssertTest, ExceptionBehavior) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_THROW(SURGSIM_FAILURE() << "extra information would go here", SurgSim::Framework::AssertionFailure); } TEST_F(AssertTest, Callback) { logOutput->reset(); typedef SurgSim::Framework::AssertMessage::DeathCallback CallbackType; const CallbackType defaultCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); const CallbackType throwCallback = SurgSim::Framework::AssertMessage::getFailureCallback(); EXPECT_EQ(throwCallback, defaultCallback); SurgSim::Framework::AssertMessage::setFailureCallback(ignoreAssertionKeepGoing); EXPECT_EQ(static_cast<CallbackType>(ignoreAssertionKeepGoing), SurgSim::Framework::AssertMessage::getFailureCallback()); numIgnoredAssertions = 0; EXPECT_NO_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here"); EXPECT_EQ(1, numIgnoredAssertions); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); EXPECT_EQ(1, numIgnoredAssertions); EXPECT_NO_THROW(SURGSIM_FAILURE() << "extra information would go here"); EXPECT_EQ(2, numIgnoredAssertions); SurgSim::Framework::AssertMessage::setFailureBehaviorToThrow(); EXPECT_EQ(throwCallback, SurgSim::Framework::AssertMessage::getFailureCallback()); EXPECT_THROW(SURGSIM_ASSERT(1 == 2) << "extra information would go here", SurgSim::Framework::AssertionFailure); EXPECT_EQ(2, numIgnoredAssertions); } TEST_F(AssertDeathTest, DebuggerBehaviorAssertFailed) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); // The assertion should die with no output to stdout. ASSERT_DEATH_IF_SUPPORTED({SURGSIM_ASSERT(1 == 2) << "extra information would go here";}, "^$"); } TEST_F(AssertDeathTest, DebuggerBehaviorAssertSucceded) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); EXPECT_NO_THROW({SURGSIM_ASSERT(3 == 3) << "extra information would go here";}); } TEST_F(AssertDeathTest, DebuggerBehaviorFailure) { logOutput->reset(); SurgSim::Framework::AssertMessage::setFailureBehaviorToDebugger(); // The assertion should die with no output to stdout. ASSERT_DEATH_IF_SUPPORTED({SURGSIM_FAILURE() << "extra information would go here";}, "^$"); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------- *//** * * @file linear.cpp * * @brief Linear-regression functions * *//* ----------------------------------------------------------------------- */ #include <dbconnector/dbconnector.hpp> #include <modules/shared/HandleTraits_proto.hpp> #include <modules/prob/prob.hpp> namespace madlib { namespace modules { // Import names from other MADlib modules using prob::studentT_CDF; namespace regress { #include "linear.hpp" /** * @brief Transition state for linear-regression functions * * TransitionState encapsulates the transition state during the * linear-regression aggregate functions. To the database, the state is exposed * as a single DOUBLE PRECISION array, to the C++ code it is a proper object * containing scalars, a vector, and a matrix. * * Note: We assume that the DOUBLE PRECISION array is initialized by the * database with length at least 5, and all elemenets are 0. */ template <class Handle, class LinAlgTypes = DefaultLinAlgTypes> class LinRegrTransitionState : public AbstractionLayer { // By §14.5.3/9: "Friend declarations shall not declare partial // specializations." We do access protected members in operator+=(). template <class OtherHandle, class OtherLinAlgTypes> friend class LinRegrTransitionState; public: LinRegrTransitionState(const AnyType &inArray) : mStorage(inArray.getAs<Handle>()) { rebind(mStorage[1]); } /** * @brief Convert to backend representation * * We define this function so that we can use TransitionState in the argument * list and as a return type. */ inline operator AnyType() const { return mStorage; } /** * @brief Initialize the transition state. Only called for first row. * * @param inAllocator Allocator for the memory transition state. Must fill * the memory block with zeros. * @param inWidthOfX Number of independent variables. The first row of data * determines the size of the transition state. This size is a quadratic * function of inWidthOfX. */ inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) { mStorage = inAllocator.allocateArray<double>(arraySize(inWidthOfX)); rebind(inWidthOfX); widthOfX = inWidthOfX; } /** * @brief Merge with another TransitionState object */ template <class OtherHandle> LinRegrTransitionState &operator+=( const LinRegrTransitionState<OtherHandle, LinAlgTypes> &inOtherState) { if (mStorage.size() != inOtherState.mStorage.size()) throw std::logic_error("Internal error: Incompatible transition states"); for (size_t i = 0; i < mStorage.size(); i++) mStorage[i] += inOtherState.mStorage[i]; // Undo the addition of widthOfX widthOfX = inOtherState.widthOfX; return *this; } private: static inline size_t arraySize(const uint16_t inWidthOfX) { return 4 + inWidthOfX + inWidthOfX % 2 + inWidthOfX * inWidthOfX; } /** * @brief Rebind to a new storage array * * @param inWidthOfX The number of independent variables. * * Array layout: * - 0: numRows (number of rows seen so far) * - 1: widthOfX (number of coefficients) * - 2: y_sum (sum of independent variables seen so far) * - 3: y_square_sum (sum of squares of independent variables seen so far) * - 4: X_transp_Y (X^T y, for that parts of X and y seen so far) * - 4 + widthOfX + widthOfX % 2: (X^T X, as seen so far) * * Note that we want 16-byte alignment for all vectors and matrices. We * therefore ensure that X_transp_Y and X_transp_X begin at even positions. */ void rebind(uint16_t inWidthOfX) { numRows.rebind(&mStorage[0]); widthOfX.rebind(&mStorage[1]); y_sum.rebind(&mStorage[2]); y_square_sum.rebind(&mStorage[3]); X_transp_Y.rebind(&mStorage[4], inWidthOfX); X_transp_X.rebind(&mStorage[4 + inWidthOfX + (inWidthOfX % 2)], inWidthOfX, inWidthOfX); } Handle mStorage; public: typename HandleTraits<Handle, LinAlgTypes>::ReferenceToUInt64 numRows; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToUInt16 widthOfX; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToDouble y_sum; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToDouble y_square_sum; typename HandleTraits<Handle, LinAlgTypes>::ColumnVectorTransparentHandleMap X_transp_Y; typename HandleTraits<Handle, LinAlgTypes>::MatrixTransparentHandleMap X_transp_X; }; /** * @brief Perform the linear-regression transition step * * We update: the number of rows \f$ n \f$, the partial sums * \f$ \sum_{i=1}^n y_i \f$ and \f$ \sum_{i=1}^n y_i^2 \f$, the matrix * \f$ X^T X \f$, and the vector \f$ X^T \boldsymbol y \f$. */ AnyType linregr_transition::run(AnyType &args) { // Arguments from SQL call. Immutable values passed by reference should be // instantiated from the respective <tt>_const</tt> class. Otherwise, the // abstraction layer will perform a deep copy (i.e., waste unnecessary // processor cycles). LinRegrTransitionState<MutableArrayHandle<double> > state = args[0]; double y = args[1].getAs<double>(); HandleMap<const ColumnVector> x = args[2].getAs<ArrayHandle<double> >(); // The following check was added with MADLIB-138. if (!std::isfinite(y)) throw std::invalid_argument("Dependent variables are not finite."); else if (!isfinite(x)) throw std::invalid_argument("Design matrix is not finite."); // Now do the transition step. if (state.numRows == 0) { if (x.size() > std::numeric_limits<uint16_t>::max()) throw std::domain_error("Number of independent variables cannot be " "larger than 65535."); state.initialize(*this, x.size()); } state.numRows++; state.y_sum += y; state.y_square_sum += y * y; state.X_transp_Y.noalias() += x * y; // FIXME: The following line is Eigen-specific // X^T X is symmetric, so it is sufficient to only fill a triangular part // of the matrix state.X_transp_X.triangularView<Eigen::Lower>() += x * trans(x); return state; } /** * @brief Perform the perliminary aggregation function: Merge transition states */ AnyType linregr_merge_states::run(AnyType &args) { LinRegrTransitionState<MutableArrayHandle<double> > stateLeft = args[0]; LinRegrTransitionState<ArrayHandle<double> > stateRight = args[1]; // We first handle the trivial case where this function is called with one // of the states being the initial state if (stateLeft.numRows == 0) return stateRight; else if (stateRight.numRows == 0) return stateLeft; // Merge states together and return stateLeft += stateRight; return stateLeft; } /** * @brief Perform the linear-regression final step */ AnyType linregr_final::run(AnyType &args) { LinRegrTransitionState<ArrayHandle<double> > state = args[0]; // See MADLIB-138. At least on certain platforms and with certain versions, // LAPACK will run into an infinite loop if pinv() is called for non-finite // matrices. We extend the check also to the dependent variables. if (!isfinite(state.X_transp_X) || !isfinite(state.X_transp_Y)) throw std::invalid_argument("Design matrix is not finite."); SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition( state.X_transp_X, EigenvaluesOnly, ComputePseudoInverse); // Precompute (X^T * X)^+ Matrix inverse_of_X_transp_X = decomposition.pseudoInverse(); // Vector of coefficients: For efficiency reasons, we want to return this // by reference, so we need to bind to db memory HandleMap<ColumnVector> coef(allocateArray<double>(state.widthOfX)); coef.noalias() = inverse_of_X_transp_X * state.X_transp_Y; // explained sum of squares (regression sum of squares) double ess = dot(state.X_transp_Y, coef) - ((state.y_sum * state.y_sum) / state.numRows); // total sum of squares double tss = state.y_square_sum - ((state.y_sum * state.y_sum) / state.numRows); // With infinite precision, the following checks are pointless. But due to // floating-point arithmetic, this need not hold at this point. // Without a formal proof convincing us of the contrary, we should // anticipate that numerical peculiarities might occur. if (tss < 0) tss = 0; if (ess < 0) ess = 0; // Since we know tss with greater accuracy than ess, we do the following // sanity adjustment to ess: if (ess > tss) ess = tss; // coefficient of determination // If tss == 0, then the regression perfectly fits the data, so the // coefficient of determination is 1. double r2 = (tss == 0 ? 1 : ess / tss); // In the case of linear regression: // residual sum of squares (rss) = total sum of squares (tss) - explained // sum of squares (ess) // Proof: http://en.wikipedia.org/wiki/Sum_of_squares double rss = tss - ess; // Variance is also called the mean square error double variance = rss / (state.numRows - state.widthOfX); // Vector of standard errors and t-statistics: For efficiency reasons, we // want to return these by reference, so we need to bind to db memory HandleMap<ColumnVector> stdErr(allocateArray<double>(state.widthOfX)); HandleMap<ColumnVector> tStats(allocateArray<double>(state.widthOfX)); for (int i = 0; i < state.widthOfX; i++) { // In an abundance of caution, we see a tiny possibility that numerical // instabilities in the pinv operation can lead to negative values on // the main diagonal of even a SPD matrix if (inverse_of_X_transp_X(i,i) < 0) { stdErr(i) = 0; } else { stdErr(i) = std::sqrt( variance * inverse_of_X_transp_X(i,i) ); } if (coef(i) == 0 && stdErr(i) == 0) { // In this special case, 0/0 should be interpreted as 0: // We know that 0 is the exact value for the coefficient, so // the t-value should be 0 (corresponding to a p-value of 1) tStats(i) = 0; } else { // If stdErr(i) == 0 then abs(tStats(i)) will be infinity, which is // what we need. tStats(i) = coef(i) / stdErr(i); } } // Vector of p-values: For efficiency reasons, we want to return this // by reference, so we need to bind to db memory HandleMap<ColumnVector> pValues(allocateArray<double>(state.widthOfX)); for (int i = 0; i < state.widthOfX; i++) pValues(i) = 2. * (1. - studentT_CDF( state.numRows - state.widthOfX, std::fabs( tStats(i) ))); // Return all coefficients, standard errors, etc. in a tuple AnyType tuple; tuple << coef << r2 << stdErr << tStats << pValues << decomposition.conditionNo(); return tuple; } } // namespace regress } // namespace modules } // namespace madlib <commit_msg>Linear regression: - Use abstraction for triangular view of matrix<commit_after>/* ----------------------------------------------------------------------- *//** * * @file linear.cpp * * @brief Linear-regression functions * *//* ----------------------------------------------------------------------- */ #include <dbconnector/dbconnector.hpp> #include <modules/shared/HandleTraits_proto.hpp> #include <modules/prob/prob.hpp> namespace madlib { namespace modules { // Import names from other MADlib modules using prob::studentT_CDF; namespace regress { #include "linear.hpp" /** * @brief Transition state for linear-regression functions * * TransitionState encapsulates the transition state during the * linear-regression aggregate functions. To the database, the state is exposed * as a single DOUBLE PRECISION array, to the C++ code it is a proper object * containing scalars, a vector, and a matrix. * * Note: We assume that the DOUBLE PRECISION array is initialized by the * database with length at least 5, and all elemenets are 0. */ template <class Handle, class LinAlgTypes = DefaultLinAlgTypes> class LinRegrTransitionState : public AbstractionLayer { // By §14.5.3/9: "Friend declarations shall not declare partial // specializations." We do access protected members in operator+=(). template <class OtherHandle, class OtherLinAlgTypes> friend class LinRegrTransitionState; public: LinRegrTransitionState(const AnyType &inArray) : mStorage(inArray.getAs<Handle>()) { rebind(mStorage[1]); } /** * @brief Convert to backend representation * * We define this function so that we can use TransitionState in the argument * list and as a return type. */ inline operator AnyType() const { return mStorage; } /** * @brief Initialize the transition state. Only called for first row. * * @param inAllocator Allocator for the memory transition state. Must fill * the memory block with zeros. * @param inWidthOfX Number of independent variables. The first row of data * determines the size of the transition state. This size is a quadratic * function of inWidthOfX. */ inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) { mStorage = inAllocator.allocateArray<double>(arraySize(inWidthOfX)); rebind(inWidthOfX); widthOfX = inWidthOfX; } /** * @brief Merge with another TransitionState object */ template <class OtherHandle> LinRegrTransitionState &operator+=( const LinRegrTransitionState<OtherHandle, LinAlgTypes> &inOtherState) { if (mStorage.size() != inOtherState.mStorage.size()) throw std::logic_error("Internal error: Incompatible transition states"); for (size_t i = 0; i < mStorage.size(); i++) mStorage[i] += inOtherState.mStorage[i]; // Undo the addition of widthOfX widthOfX = inOtherState.widthOfX; return *this; } private: static inline size_t arraySize(const uint16_t inWidthOfX) { return 4 + inWidthOfX + inWidthOfX % 2 + inWidthOfX * inWidthOfX; } /** * @brief Rebind to a new storage array * * @param inWidthOfX The number of independent variables. * * Array layout: * - 0: numRows (number of rows seen so far) * - 1: widthOfX (number of coefficients) * - 2: y_sum (sum of independent variables seen so far) * - 3: y_square_sum (sum of squares of independent variables seen so far) * - 4: X_transp_Y (X^T y, for that parts of X and y seen so far) * - 4 + widthOfX + widthOfX % 2: (X^T X, as seen so far) * * Note that we want 16-byte alignment for all vectors and matrices. We * therefore ensure that X_transp_Y and X_transp_X begin at even positions. */ void rebind(uint16_t inWidthOfX) { numRows.rebind(&mStorage[0]); widthOfX.rebind(&mStorage[1]); y_sum.rebind(&mStorage[2]); y_square_sum.rebind(&mStorage[3]); X_transp_Y.rebind(&mStorage[4], inWidthOfX); X_transp_X.rebind(&mStorage[4 + inWidthOfX + (inWidthOfX % 2)], inWidthOfX, inWidthOfX); } Handle mStorage; public: typename HandleTraits<Handle, LinAlgTypes>::ReferenceToUInt64 numRows; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToUInt16 widthOfX; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToDouble y_sum; typename HandleTraits<Handle, LinAlgTypes>::ReferenceToDouble y_square_sum; typename HandleTraits<Handle, LinAlgTypes>::ColumnVectorTransparentHandleMap X_transp_Y; typename HandleTraits<Handle, LinAlgTypes>::MatrixTransparentHandleMap X_transp_X; }; /** * @brief Perform the linear-regression transition step * * We update: the number of rows \f$ n \f$, the partial sums * \f$ \sum_{i=1}^n y_i \f$ and \f$ \sum_{i=1}^n y_i^2 \f$, the matrix * \f$ X^T X \f$, and the vector \f$ X^T \boldsymbol y \f$. */ AnyType linregr_transition::run(AnyType &args) { // Arguments from SQL call. Immutable values passed by reference should be // instantiated from the respective <tt>_const</tt> class. Otherwise, the // abstraction layer will perform a deep copy (i.e., waste unnecessary // processor cycles). LinRegrTransitionState<MutableArrayHandle<double> > state = args[0]; double y = args[1].getAs<double>(); HandleMap<const ColumnVector> x = args[2].getAs<ArrayHandle<double> >(); // The following check was added with MADLIB-138. if (!std::isfinite(y)) throw std::invalid_argument("Dependent variables are not finite."); else if (!isfinite(x)) throw std::invalid_argument("Design matrix is not finite."); // Now do the transition step. if (state.numRows == 0) { if (x.size() > std::numeric_limits<uint16_t>::max()) throw std::domain_error("Number of independent variables cannot be " "larger than 65535."); state.initialize(*this, x.size()); } state.numRows++; state.y_sum += y; state.y_square_sum += y * y; state.X_transp_Y.noalias() += x * y; // X^T X is symmetric, so it is sufficient to only fill a triangular part // of the matrix triangularView<Lower>(state.X_transp_X) += x * trans(x); return state; } /** * @brief Perform the perliminary aggregation function: Merge transition states */ AnyType linregr_merge_states::run(AnyType &args) { LinRegrTransitionState<MutableArrayHandle<double> > stateLeft = args[0]; LinRegrTransitionState<ArrayHandle<double> > stateRight = args[1]; // We first handle the trivial case where this function is called with one // of the states being the initial state if (stateLeft.numRows == 0) return stateRight; else if (stateRight.numRows == 0) return stateLeft; // Merge states together and return stateLeft += stateRight; return stateLeft; } /** * @brief Perform the linear-regression final step */ AnyType linregr_final::run(AnyType &args) { LinRegrTransitionState<ArrayHandle<double> > state = args[0]; // See MADLIB-138. At least on certain platforms and with certain versions, // LAPACK will run into an infinite loop if pinv() is called for non-finite // matrices. We extend the check also to the dependent variables. if (!isfinite(state.X_transp_X) || !isfinite(state.X_transp_Y)) throw std::invalid_argument("Design matrix is not finite."); SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition( state.X_transp_X, EigenvaluesOnly, ComputePseudoInverse); // Precompute (X^T * X)^+ Matrix inverse_of_X_transp_X = decomposition.pseudoInverse(); // Vector of coefficients: For efficiency reasons, we want to return this // by reference, so we need to bind to db memory HandleMap<ColumnVector> coef(allocateArray<double>(state.widthOfX)); coef.noalias() = inverse_of_X_transp_X * state.X_transp_Y; // explained sum of squares (regression sum of squares) double ess = dot(state.X_transp_Y, coef) - ((state.y_sum * state.y_sum) / state.numRows); // total sum of squares double tss = state.y_square_sum - ((state.y_sum * state.y_sum) / state.numRows); // With infinite precision, the following checks are pointless. But due to // floating-point arithmetic, this need not hold at this point. // Without a formal proof convincing us of the contrary, we should // anticipate that numerical peculiarities might occur. if (tss < 0) tss = 0; if (ess < 0) ess = 0; // Since we know tss with greater accuracy than ess, we do the following // sanity adjustment to ess: if (ess > tss) ess = tss; // coefficient of determination // If tss == 0, then the regression perfectly fits the data, so the // coefficient of determination is 1. double r2 = (tss == 0 ? 1 : ess / tss); // In the case of linear regression: // residual sum of squares (rss) = total sum of squares (tss) - explained // sum of squares (ess) // Proof: http://en.wikipedia.org/wiki/Sum_of_squares double rss = tss - ess; // Variance is also called the mean square error double variance = rss / (state.numRows - state.widthOfX); // Vector of standard errors and t-statistics: For efficiency reasons, we // want to return these by reference, so we need to bind to db memory HandleMap<ColumnVector> stdErr(allocateArray<double>(state.widthOfX)); HandleMap<ColumnVector> tStats(allocateArray<double>(state.widthOfX)); for (int i = 0; i < state.widthOfX; i++) { // In an abundance of caution, we see a tiny possibility that numerical // instabilities in the pinv operation can lead to negative values on // the main diagonal of even a SPD matrix if (inverse_of_X_transp_X(i,i) < 0) { stdErr(i) = 0; } else { stdErr(i) = std::sqrt( variance * inverse_of_X_transp_X(i,i) ); } if (coef(i) == 0 && stdErr(i) == 0) { // In this special case, 0/0 should be interpreted as 0: // We know that 0 is the exact value for the coefficient, so // the t-value should be 0 (corresponding to a p-value of 1) tStats(i) = 0; } else { // If stdErr(i) == 0 then abs(tStats(i)) will be infinity, which is // what we need. tStats(i) = coef(i) / stdErr(i); } } // Vector of p-values: For efficiency reasons, we want to return this // by reference, so we need to bind to db memory HandleMap<ColumnVector> pValues(allocateArray<double>(state.widthOfX)); for (int i = 0; i < state.widthOfX; i++) pValues(i) = 2. * (1. - studentT_CDF( state.numRows - state.widthOfX, std::fabs( tStats(i) ))); // Return all coefficients, standard errors, etc. in a tuple AnyType tuple; tuple << coef << r2 << stdErr << tStats << pValues << decomposition.conditionNo(); return tuple; } } // namespace regress } // namespace modules } // namespace madlib <|endoftext|>
<commit_before>#include "console.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" #include "cpp/ylikuutio/callback_system/callback_magic_numbers.hpp" #include "cpp/ylikuutio/common/any_value.hpp" // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include standard headers #include <vector> // std::vector #include <iostream> // std::cout, std::cin, std::cerr namespace console { // Keep these variable types as this is according to GLFW documentation! // So: `unsigned int codepoint`, `int mods`. void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods) { std::cout << "Hello from character_callback! codepoint: " << codepoint << "\n"; global_console_pointer->add_character(codepoint); } datatypes::AnyValue* exit_console( callback_system::CallbackEngine*, callback_system::CallbackObject* callback_object, std::vector<callback_system::CallbackParameter*>) { datatypes::AnyValue* any_value_console_pointer = callback_object->get_any_value("console_pointer"); if (any_value_console_pointer == nullptr) { return nullptr; } if (any_value_console_pointer->type != datatypes::CONSOLE_POINTER) { return nullptr; } console::Console* console_pointer = any_value_console_pointer->console_pointer; console_pointer->exit_console(); // Signal to caller that we have exited the console. uint32_t exit_console_magic_number = EXIT_CONSOLE_MAGIC_NUMBER; datatypes::AnyValue* any_value_magic_number = new datatypes::AnyValue(exit_console_magic_number); return any_value_magic_number; } datatypes::AnyValue* backspace( callback_system::CallbackEngine*, callback_system::CallbackObject* callback_object, std::vector<callback_system::CallbackParameter*>) { datatypes::AnyValue* any_value_console_pointer = callback_object->get_any_value("console_pointer"); if (any_value_console_pointer == nullptr) { return nullptr; } if (any_value_console_pointer->type != datatypes::CONSOLE_POINTER) { return nullptr; } console::Console* console = any_value_console_pointer->console_pointer; console->backspace(); return nullptr; } } <commit_msg>`void charmods_callback` prints also `mods` (for testing purposes).<commit_after>#include "console.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" #include "cpp/ylikuutio/callback_system/callback_magic_numbers.hpp" #include "cpp/ylikuutio/common/any_value.hpp" // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include standard headers #include <vector> // std::vector #include <iostream> // std::cout, std::cin, std::cerr namespace console { // Keep these variable types as this is according to GLFW documentation! // So: `unsigned int codepoint`, `int mods`. void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods) { // `int mods` values: // No modificators: 0x00 // Shift (left or right): 0x01 // Alt (not AltGr): 0x04 // Shift + Alt: 0x05 std::cout << "Hello from character_callback! codepoint: 0x" << std::hex << codepoint << ", mods: 0x" << mods << "\n"; global_console_pointer->add_character(codepoint); } datatypes::AnyValue* exit_console( callback_system::CallbackEngine*, callback_system::CallbackObject* callback_object, std::vector<callback_system::CallbackParameter*>) { datatypes::AnyValue* any_value_console_pointer = callback_object->get_any_value("console_pointer"); if (any_value_console_pointer == nullptr) { return nullptr; } if (any_value_console_pointer->type != datatypes::CONSOLE_POINTER) { return nullptr; } console::Console* console_pointer = any_value_console_pointer->console_pointer; console_pointer->exit_console(); // Signal to caller that we have exited the console. uint32_t exit_console_magic_number = EXIT_CONSOLE_MAGIC_NUMBER; datatypes::AnyValue* any_value_magic_number = new datatypes::AnyValue(exit_console_magic_number); return any_value_magic_number; } datatypes::AnyValue* backspace( callback_system::CallbackEngine*, callback_system::CallbackObject* callback_object, std::vector<callback_system::CallbackParameter*>) { datatypes::AnyValue* any_value_console_pointer = callback_object->get_any_value("console_pointer"); if (any_value_console_pointer == nullptr) { return nullptr; } if (any_value_console_pointer->type != datatypes::CONSOLE_POINTER) { return nullptr; } console::Console* console = any_value_console_pointer->console_pointer; console->backspace(); return nullptr; } } <|endoftext|>