commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
b1ea36bc47fefba9faac714e0cfc172221f9be58
src/plugins/texteditor/basetextdocument.cpp
src/plugins/texteditor/basetextdocument.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** **************************************************************************/ #include "basetextdocument.h" #include "basetexteditor.h" #include "storagesettings.h" #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QTextStream> #include <QtCore/QTextCodec> #include <QtGui/QMainWindow> #include <QtGui/QSyntaxHighlighter> #include <QtGui/QApplication> #ifndef TEXTEDITOR_STANDALONE #include <utils/reloadpromptutils.h> #include <coreplugin/icore.h> #endif #include <utils/qtcassert.h> using namespace TextEditor; extern Q_CORE_EXPORT int qt_ntfs_permission_lookup; #if defined (Q_OS_WIN) # define NATIVE_LINE_TERMINATOR CRLFLineTerminator #else # define NATIVE_LINE_TERMINATOR LFLineTerminator #endif DocumentMarker::DocumentMarker(QTextDocument *doc) : ITextMarkable(doc), document(doc) { } BaseTextDocument::BaseTextDocument() : m_document(new QTextDocument(this)), m_highlighter(0) { m_documentMarker = new DocumentMarker(m_document); m_lineTerminatorMode = NativeLineTerminator; m_isBinaryData = false; m_codec = QTextCodec::codecForLocale(); m_hasDecodingError = false; } BaseTextDocument::~BaseTextDocument() { QTextBlock block = m_document->begin(); while (block.isValid()) { if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) data->documentClosing(); block = block.next(); } delete m_document; m_document = 0; } QString BaseTextDocument::mimeType() const { return m_mimeType; } void BaseTextDocument::setMimeType(const QString &mt) { m_mimeType = mt; } bool BaseTextDocument::save(const QString &fileName) { QTextCursor cursor(m_document); cursor.beginEditBlock(); if (m_storageSettings.m_cleanWhitespace) cleanWhitespace(cursor, m_storageSettings.m_inEntireDocument); if (m_storageSettings.m_addFinalNewLine) ensureFinalNewLine(cursor); cursor.endEditBlock(); QString fName = m_fileName; if (!fileName.isEmpty()) fName = fileName; QFile file(fName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return false; QString plainText = m_document->toPlainText(); if (m_lineTerminatorMode == CRLFLineTerminator) plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n")); file.write(m_codec->fromUnicode(plainText)); if (!file.flush()) return false; file.close(); const QFileInfo fi(fName); m_fileName = fi.absoluteFilePath(); m_document->setModified(false); emit titleChanged(fi.fileName()); emit changed(); m_isBinaryData = false; m_hasDecodingError = false; m_decodingErrorSample.clear(); return true; } bool BaseTextDocument::isReadOnly() const { if (m_isBinaryData || m_hasDecodingError) return true; if (m_fileName.isEmpty()) //have no corresponding file, so editing is ok return false; const QFileInfo fi(m_fileName); #ifdef Q_OS_WIN32 // Check for permissions on NTFS file systems qt_ntfs_permission_lookup++; #endif const bool ro = !fi.isWritable(); #ifdef Q_OS_WIN32 qt_ntfs_permission_lookup--; #endif return ro; } bool BaseTextDocument::isModified() const { return m_document->isModified(); } bool BaseTextDocument::open(const QString &fileName) { QString title = tr("untitled"); if (!fileName.isEmpty()) { const QFileInfo fi(fileName); m_fileName = fi.absoluteFilePath(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return false; title = fi.fileName(); QByteArray buf = file.readAll(); int bytesRead = buf.size(); QTextCodec *codec = m_codec; // code taken from qtextstream if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0) || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) { codec = QTextCodec::codecForName("UTF-32"); } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe) || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) { codec = QTextCodec::codecForName("UTF-16"); } else if (!codec) { codec = QTextCodec::codecForLocale(); } // end code taken from qtextstream m_codec = codec; #if 0 // should work, but does not, Qt bug with "system" codec QTextDecoder *decoder = m_codec->makeDecoder(); QString text = decoder->toUnicode(buf); m_hasDecodingError = (decoder->hasFailure()); delete decoder; #else QString text = m_codec->toUnicode(buf); QByteArray verifyBuf = m_codec->fromUnicode(text); // slow // the minSize trick lets us ignore unicode headers int minSize = qMin(verifyBuf.size(), buf.size()); m_hasDecodingError = (minSize < buf.size()- 4 || memcmp(verifyBuf.constData() + verifyBuf.size() - minSize, buf.constData() + buf.size() - minSize, minSize)); #endif if (m_hasDecodingError) { int p = buf.indexOf('\n', 16384); if (p < 0) m_decodingErrorSample = buf; else m_decodingErrorSample = buf.left(p); } else { m_decodingErrorSample.clear(); } int lf = text.indexOf('\n'); if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) { m_lineTerminatorMode = CRLFLineTerminator; } else if (lf >= 0) { m_lineTerminatorMode = LFLineTerminator; } else { m_lineTerminatorMode = NativeLineTerminator; } m_document->setModified(false); m_document->setUndoRedoEnabled(false); if (m_isBinaryData) m_document->setHtml(tr("<em>Binary data</em>")); else m_document->setPlainText(text); m_document->setUndoRedoEnabled(true); TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout()); QTC_ASSERT(documentLayout, return true); documentLayout->lastSaveRevision = 0; m_document->setModified(false); emit titleChanged(title); emit changed(); } return true; } void BaseTextDocument::reload(QTextCodec *codec) { QTC_ASSERT(codec, return); m_codec = codec; reload(); } void BaseTextDocument::reload() { emit aboutToReload(); if (open(m_fileName)) emit reloaded(); } void BaseTextDocument::modified(Core::IFile::ReloadBehavior *behavior) { switch (*behavior) { case Core::IFile::ReloadNone: return; case Core::IFile::ReloadAll: reload(); return; case Core::IFile::ReloadPermissions: emit changed(); return; case Core::IFile::AskForReload: break; } #ifndef TEXTEDITOR_STANDALONE switch (Core::Utils::reloadPrompt(m_fileName, QApplication::activeWindow())) { case Core::Utils::ReloadCurrent: reload(); break; case Core::Utils::ReloadAll: reload(); *behavior = Core::IFile::ReloadAll; break; case Core::Utils::ReloadSkipCurrent: break; case Core::Utils::ReloadNone: *behavior = Core::IFile::ReloadNone; break; } #endif } void BaseTextDocument::setSyntaxHighlighter(QSyntaxHighlighter *highlighter) { if (m_highlighter) delete m_highlighter; m_highlighter = highlighter; m_highlighter->setParent(this); m_highlighter->setDocument(m_document); } void BaseTextDocument::cleanWhitespace() { QTextCursor cursor(m_document); cursor.beginEditBlock(); cleanWhitespace(cursor, true); if (m_storageSettings.m_addFinalNewLine) ensureFinalNewLine(cursor); cursor.endEditBlock(); } void BaseTextDocument::cleanWhitespace(QTextCursor& cursor, bool inEntireDocument) { TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout()); QTextBlock block = m_document->firstBlock(); while (block.isValid()) { if (inEntireDocument || block.revision() > documentLayout->lastSaveRevision) { QString blockText = block.text(); if (int trailing = m_tabSettings.trailingWhitespaces(blockText)) { cursor.setPosition(block.position() + block.length() - 1); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing); cursor.removeSelectedText(); } if (m_storageSettings.m_cleanIndentation && !m_tabSettings.isIndentationClean(blockText)) { cursor.setPosition(block.position()); int firstNonSpace = m_tabSettings.firstNonSpace(blockText); if (firstNonSpace == blockText.length()) { cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else { int column = m_tabSettings.columnAt(blockText, firstNonSpace); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace); QString indentationString = m_tabSettings.indentationString(0, column); cursor.insertText(indentationString); } } } block = block.next(); } } void BaseTextDocument::ensureFinalNewLine(QTextCursor& cursor) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); cursor.insertText(QLatin1String("\n")); } }
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** **************************************************************************/ #include "basetextdocument.h" #include "basetexteditor.h" #include "storagesettings.h" #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QTextStream> #include <QtCore/QTextCodec> #include <QtGui/QMainWindow> #include <QtGui/QSyntaxHighlighter> #include <QtGui/QApplication> #ifndef TEXTEDITOR_STANDALONE #include <utils/reloadpromptutils.h> #include <coreplugin/icore.h> #endif #include <utils/qtcassert.h> using namespace TextEditor; #if defined (Q_OS_WIN) QT_BEGIN_NAMESPACE extern Q_CORE_EXPORT int qt_ntfs_permission_lookup; QT_END_NAMESPACE #endif #if defined (Q_OS_WIN) # define NATIVE_LINE_TERMINATOR CRLFLineTerminator #else # define NATIVE_LINE_TERMINATOR LFLineTerminator #endif DocumentMarker::DocumentMarker(QTextDocument *doc) : ITextMarkable(doc), document(doc) { } BaseTextDocument::BaseTextDocument() : m_document(new QTextDocument(this)), m_highlighter(0) { m_documentMarker = new DocumentMarker(m_document); m_lineTerminatorMode = NativeLineTerminator; m_isBinaryData = false; m_codec = QTextCodec::codecForLocale(); m_hasDecodingError = false; } BaseTextDocument::~BaseTextDocument() { QTextBlock block = m_document->begin(); while (block.isValid()) { if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) data->documentClosing(); block = block.next(); } delete m_document; m_document = 0; } QString BaseTextDocument::mimeType() const { return m_mimeType; } void BaseTextDocument::setMimeType(const QString &mt) { m_mimeType = mt; } bool BaseTextDocument::save(const QString &fileName) { QTextCursor cursor(m_document); cursor.beginEditBlock(); if (m_storageSettings.m_cleanWhitespace) cleanWhitespace(cursor, m_storageSettings.m_inEntireDocument); if (m_storageSettings.m_addFinalNewLine) ensureFinalNewLine(cursor); cursor.endEditBlock(); QString fName = m_fileName; if (!fileName.isEmpty()) fName = fileName; QFile file(fName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return false; QString plainText = m_document->toPlainText(); if (m_lineTerminatorMode == CRLFLineTerminator) plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n")); file.write(m_codec->fromUnicode(plainText)); if (!file.flush()) return false; file.close(); const QFileInfo fi(fName); m_fileName = fi.absoluteFilePath(); m_document->setModified(false); emit titleChanged(fi.fileName()); emit changed(); m_isBinaryData = false; m_hasDecodingError = false; m_decodingErrorSample.clear(); return true; } bool BaseTextDocument::isReadOnly() const { if (m_isBinaryData || m_hasDecodingError) return true; if (m_fileName.isEmpty()) //have no corresponding file, so editing is ok return false; const QFileInfo fi(m_fileName); #ifdef Q_OS_WIN // Check for permissions on NTFS file systems qt_ntfs_permission_lookup++; #endif const bool ro = !fi.isWritable(); #ifdef Q_OS_WIN qt_ntfs_permission_lookup--; #endif return ro; } bool BaseTextDocument::isModified() const { return m_document->isModified(); } bool BaseTextDocument::open(const QString &fileName) { QString title = tr("untitled"); if (!fileName.isEmpty()) { const QFileInfo fi(fileName); m_fileName = fi.absoluteFilePath(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return false; title = fi.fileName(); QByteArray buf = file.readAll(); int bytesRead = buf.size(); QTextCodec *codec = m_codec; // code taken from qtextstream if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0) || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) { codec = QTextCodec::codecForName("UTF-32"); } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe) || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) { codec = QTextCodec::codecForName("UTF-16"); } else if (!codec) { codec = QTextCodec::codecForLocale(); } // end code taken from qtextstream m_codec = codec; #if 0 // should work, but does not, Qt bug with "system" codec QTextDecoder *decoder = m_codec->makeDecoder(); QString text = decoder->toUnicode(buf); m_hasDecodingError = (decoder->hasFailure()); delete decoder; #else QString text = m_codec->toUnicode(buf); QByteArray verifyBuf = m_codec->fromUnicode(text); // slow // the minSize trick lets us ignore unicode headers int minSize = qMin(verifyBuf.size(), buf.size()); m_hasDecodingError = (minSize < buf.size()- 4 || memcmp(verifyBuf.constData() + verifyBuf.size() - minSize, buf.constData() + buf.size() - minSize, minSize)); #endif if (m_hasDecodingError) { int p = buf.indexOf('\n', 16384); if (p < 0) m_decodingErrorSample = buf; else m_decodingErrorSample = buf.left(p); } else { m_decodingErrorSample.clear(); } int lf = text.indexOf('\n'); if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) { m_lineTerminatorMode = CRLFLineTerminator; } else if (lf >= 0) { m_lineTerminatorMode = LFLineTerminator; } else { m_lineTerminatorMode = NativeLineTerminator; } m_document->setModified(false); m_document->setUndoRedoEnabled(false); if (m_isBinaryData) m_document->setHtml(tr("<em>Binary data</em>")); else m_document->setPlainText(text); m_document->setUndoRedoEnabled(true); TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout()); QTC_ASSERT(documentLayout, return true); documentLayout->lastSaveRevision = 0; m_document->setModified(false); emit titleChanged(title); emit changed(); } return true; } void BaseTextDocument::reload(QTextCodec *codec) { QTC_ASSERT(codec, return); m_codec = codec; reload(); } void BaseTextDocument::reload() { emit aboutToReload(); if (open(m_fileName)) emit reloaded(); } void BaseTextDocument::modified(Core::IFile::ReloadBehavior *behavior) { switch (*behavior) { case Core::IFile::ReloadNone: return; case Core::IFile::ReloadAll: reload(); return; case Core::IFile::ReloadPermissions: emit changed(); return; case Core::IFile::AskForReload: break; } #ifndef TEXTEDITOR_STANDALONE switch (Core::Utils::reloadPrompt(m_fileName, QApplication::activeWindow())) { case Core::Utils::ReloadCurrent: reload(); break; case Core::Utils::ReloadAll: reload(); *behavior = Core::IFile::ReloadAll; break; case Core::Utils::ReloadSkipCurrent: break; case Core::Utils::ReloadNone: *behavior = Core::IFile::ReloadNone; break; } #endif } void BaseTextDocument::setSyntaxHighlighter(QSyntaxHighlighter *highlighter) { if (m_highlighter) delete m_highlighter; m_highlighter = highlighter; m_highlighter->setParent(this); m_highlighter->setDocument(m_document); } void BaseTextDocument::cleanWhitespace() { QTextCursor cursor(m_document); cursor.beginEditBlock(); cleanWhitespace(cursor, true); if (m_storageSettings.m_addFinalNewLine) ensureFinalNewLine(cursor); cursor.endEditBlock(); } void BaseTextDocument::cleanWhitespace(QTextCursor& cursor, bool inEntireDocument) { TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout()); QTextBlock block = m_document->firstBlock(); while (block.isValid()) { if (inEntireDocument || block.revision() > documentLayout->lastSaveRevision) { QString blockText = block.text(); if (int trailing = m_tabSettings.trailingWhitespaces(blockText)) { cursor.setPosition(block.position() + block.length() - 1); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing); cursor.removeSelectedText(); } if (m_storageSettings.m_cleanIndentation && !m_tabSettings.isIndentationClean(blockText)) { cursor.setPosition(block.position()); int firstNonSpace = m_tabSettings.firstNonSpace(blockText); if (firstNonSpace == blockText.length()) { cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else { int column = m_tabSettings.columnAt(blockText, firstNonSpace); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace); QString indentationString = m_tabSettings.indentationString(0, column); cursor.insertText(indentationString); } } } block = block.next(); } } void BaseTextDocument::ensureFinalNewLine(QTextCursor& cursor) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); cursor.insertText(QLatin1String("\n")); } }
Fix build with namespaced Qt
Fix build with namespaced Qt Reviewed-by: Thorbjorn Lindeijer
C++
lgpl-2.1
colede/qtcreator,enricoros/k-qt-creator-inspector,yinyunqiao/qtcreator,sandsmark/qtcreator-minimap,azat/qtcreator,KDAB/KDAB-Creator,KDAB/KDAB-Creator,kuba1/qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,omniacreator/qtcreator,azat/qtcreator,sandsmark/qtcreator-minimap,jonnor/qt-creator,darksylinc/qt-creator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,kuba1/qtcreator,enricoros/k-qt-creator-inspector,Distrotech/qtcreator,dmik/qt-creator-os2,xianian/qt-creator,kuba1/qtcreator,enricoros/k-qt-creator-inspector,renatofilho/QtCreator,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,richardmg/qtcreator,richardmg/qtcreator,xianian/qt-creator,yinyunqiao/qtcreator,malikcjm/qtcreator,KDE/android-qt-creator,syntheticpp/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,yinyunqiao/qtcreator,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,colede/qtcreator,omniacreator/qtcreator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,KDE/android-qt-creator,darksylinc/qt-creator,danimo/qt-creator,AltarBeastiful/qt-creator,pcacjr/qt-creator,KDAB/KDAB-Creator,amyvmiwei/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,Distrotech/qtcreator,danimo/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,renatofilho/QtCreator,darksylinc/qt-creator,farseerri/git_code,pcacjr/qt-creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,dmik/qt-creator-os2,farseerri/git_code,ostash/qt-creator-i18n-uk,hdweiss/qt-creator-visualizer,jonnor/qt-creator,colede/qtcreator,dmik/qt-creator-os2,enricoros/k-qt-creator-inspector,dmik/qt-creator-os2,enricoros/k-qt-creator-inspector,hdweiss/qt-creator-visualizer,richardmg/qtcreator,danimo/qt-creator,jonnor/qt-creator,sandsmark/qtcreator-minimap,ostash/qt-creator-i18n-uk,xianian/qt-creator,malikcjm/qtcreator,darksylinc/qt-creator,jonnor/qt-creator,omniacreator/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,malikcjm/qtcreator,duythanhphan/qt-creator,hdweiss/qt-creator-visualizer,yinyunqiao/qtcreator,omniacreator/qtcreator,Distrotech/qtcreator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,maui-packages/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,yinyunqiao/qtcreator,farseerri/git_code,xianian/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,danimo/qt-creator,malikcjm/qtcreator,enricoros/k-qt-creator-inspector,danimo/qt-creator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,syntheticpp/qt-creator,pcacjr/qt-creator,bakaiadam/collaborative_qt_creator,pcacjr/qt-creator,jonnor/qt-creator,sandsmark/qtcreator-minimap,syntheticpp/qt-creator,sandsmark/qtcreator-minimap,KDE/android-qt-creator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,sandsmark/qtcreator-minimap,martyone/sailfish-qtcreator,Distrotech/qtcreator,KDAB/KDAB-Creator,colede/qtcreator,renatofilho/QtCreator,omniacreator/qtcreator,maui-packages/qt-creator,maui-packages/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,KDE/android-qt-creator,danimo/qt-creator,KDE/android-qt-creator,renatofilho/QtCreator,amyvmiwei/qt-creator,bakaiadam/collaborative_qt_creator,KDAB/KDAB-Creator,hdweiss/qt-creator-visualizer,pcacjr/qt-creator,colede/qtcreator,azat/qtcreator,enricoros/k-qt-creator-inspector,darksylinc/qt-creator,duythanhphan/qt-creator,AltarBeastiful/qt-creator,ostash/qt-creator-i18n-uk,colede/qtcreator,omniacreator/qtcreator,syntheticpp/qt-creator,kuba1/qtcreator,renatofilho/QtCreator,dmik/qt-creator-os2,xianian/qt-creator,KDE/android-qt-creator,syntheticpp/qt-creator,maui-packages/qt-creator,pcacjr/qt-creator,KDAB/KDAB-Creator,azat/qtcreator,colede/qtcreator,martyone/sailfish-qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,malikcjm/qtcreator,bakaiadam/collaborative_qt_creator,dmik/qt-creator-os2,richardmg/qtcreator,duythanhphan/qt-creator,duythanhphan/qt-creator,xianian/qt-creator,kuba1/qtcreator,renatofilho/QtCreator,xianian/qt-creator,maui-packages/qt-creator,azat/qtcreator,danimo/qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,KDE/android-qt-creator,dmik/qt-creator-os2,syntheticpp/qt-creator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,hdweiss/qt-creator-visualizer,azat/qtcreator,pcacjr/qt-creator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,yinyunqiao/qtcreator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,richardmg/qtcreator,Distrotech/qtcreator,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,malikcjm/qtcreator
ea4b6a2096bc9ff55c9c8f2dda379f2b28a0023c
src/postgres/backend/postmaster/peloton.cpp
src/postgres/backend/postmaster/peloton.cpp
/*------------------------------------------------------------------------- * * peloton.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/peloton.c * *------------------------------------------------------------------------- */ #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/param.h> #include <sys/time.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #include <thread> #include <map> #include "backend/common/logger.h" #include "backend/common/message_queue.h" #include "backend/common/stack_trace.h" #include "backend/bridge/ddl/configuration.h" #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/bridge/ddl/tests/bridge_test.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/bridge/dml/mapper/mapper.h" #include "backend/common/stack_trace.h" #include "backend/logging/log_manager.h" #include "postgres.h" #include "c.h" #include "access/xact.h" #include "access/transam.h" #include "access/tupdesc.h" #include "catalog/pg_namespace.h" #include "executor/tuptable.h" #include "libpq/ip.h" #include "libpq/pqsignal.h" #include "miscadmin.h" #include "nodes/print.h" #include "nodes/params.h" #include "utils/guc.h" #include "utils/errcodes.h" #include "utils/ps_status.h" #include "utils/timeout.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/rel.h" #include "postmaster/fork_process.h" #include "postmaster/postmaster.h" #include "postmaster/peloton.h" #include "storage/latch.h" #include "storage/ipc.h" #include "storage/proc.h" #include "tcop/tcopprot.h" /* ---------- * Logging Flag * ---------- */ bool logging_on = true; bool syncronization_commit = false; static void peloton_process_status(const peloton_status& status); static void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest); static void __attribute__((unused)) peloton_test_config(); /* ---------- * peloton_bootstrap - * * Handle bootstrap requests in Peloton. * ---------- */ void peloton_bootstrap() { try { // Process the utility statement peloton::bridge::Bootstrap::BootstrapPeloton(); /* TODO: Handle logging if( logging_on){ // NOTE:: start logging since bootstrapPeloton is done auto& logManager = peloton::logging::LogManager::GetInstance(); if( logManager.IsReadyToLogging() == false){ logManager.StartLogging(); } } */ } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_ddl - * * Handle DDL requests in Peloton. * ---------- */ void peloton_ddl(Node *parsetree) { /* Ignore invalid parsetrees */ if(parsetree == NULL || nodeTag(parsetree) == T_Invalid) { return; } if(logging_on){ /* TODO: Handle logging // Launching a thread for logging auto& log_manager = peloton::logging::LogManager::GetInstance(); log_manager.SetDefaultLoggingType(peloton::LOGGING_TYPE_ARIES); log_manager.SetSyncCommit(syncronization_commit); std::thread(&peloton::logging::LogManager::StartStandbyMode, &log_manager, log_manager.GetDefaultLoggingType()).detach(); */ } auto txn_id = GetTopTransactionId(); try { /* Process the utility statement */ peloton::bridge::DDL::ProcessUtility(parsetree, txn_id); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_dml - * * Handle DML requests in Peloton. * ---------- */ void peloton_dml(PlanState *planstate, bool sendTuples, DestReceiver *dest, TupleDesc tuple_desc) { peloton_status status; // Get the parameter list assert(planstate != NULL); assert(planstate->state != NULL); auto param_list = planstate->state->es_param_list_info; // Create the raw planstate info auto plan_state = peloton::bridge::DMLUtils::peloton_prepare_data(planstate); // Get our plan auto plan = peloton::bridge::PlanTransformer::TransformPlan(plan_state); auto txn_id = GetTopTransactionId(); // Ignore empty plans if(plan == nullptr) { elog(WARNING, "Empty or unrecognized plan sent to Peloton"); return; } std::vector<peloton::oid_t> target_list; std::vector<peloton::oid_t> qual; // Analyze the plan peloton::bridge::PlanTransformer::AnalyzePlan(plan, target_list, qual); // Execute the plantree try { status = peloton::bridge::PlanExecutor::ExecutePlan(plan, param_list, tuple_desc, txn_id); // Clean up the plantree peloton::bridge::PlanTransformer::CleanPlan(plan); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } // Wait for the response and process it peloton_process_status(status); // Send output to dest peloton_send_output(status, sendTuples, dest); } /* ---------- * peloton_process_status() - * * Process status. * ---------- */ static void peloton_process_status(const peloton_status& status) { int code; // Process the status code code = status.m_result; switch(code) { case peloton::RESULT_SUCCESS: { // TODO: Update stats ? } break; case peloton::RESULT_INVALID: case peloton::RESULT_FAILURE: default: { ereport(ERROR, (errcode(status.m_result), errmsg("transaction failed"))); } break; } } /* ---------- * peloton_send_output() - * * Send the output to the receiver. * ---------- */ void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest) { TupleTableSlot *slot; // Go over any result slots if(status.m_result_slots != NULL) { ListCell *lc; foreach(lc, status.m_result_slots) { slot = (TupleTableSlot *) lfirst(lc); /* * if the tuple is null, then we assume there is nothing more to * process so we just end the loop... */ if (TupIsNull(slot)) break; /* * If we are supposed to send the tuple somewhere, do so. (In * practice, this is probably always the case at this point.) */ if (sendTuples) (*dest->receiveSlot) (slot, dest); /* * Free the underlying heap_tuple * and the TupleTableSlot itself. */ ExecDropSingleTupleTableSlot(slot); } // Clean up list list_free(status.m_result_slots); } } static void peloton_test_config() { auto val = GetConfigOption("peloton_mode", false, false); elog(LOG, "Before SetConfigOption : %s", val); SetConfigOption("peloton_mode", "peloton_mode_1", PGC_USERSET, PGC_S_USER); val = GetConfigOption("peloton_mode", false, false); elog(LOG, "After SetConfigOption : %s", val); // Build the configuration map peloton::bridge::ConfigManager::BuildConfigMap(); } /* ---------- * IsPelotonQuery - * * Does the query access peloton tables or not ? * ---------- */ bool IsPelotonQuery(List *relationOids) { bool peloton_query = false; // Check if we are in Postmaster environment */ if(IsPostmasterEnvironment == false && IsBackend == false) { return false; } if(relationOids != NULL) { ListCell *lc; // Go over each relation on which the plan depends foreach(lc, relationOids) { Oid relation_id = lfirst_oid(lc); // Check if relation in public namespace Relation target_table = relation_open(relation_id, AccessShareLock); Oid target_table_namespace = target_table->rd_rel->relnamespace; if(target_table_namespace == PG_PUBLIC_NAMESPACE) { peloton_query = true; } relation_close(target_table, AccessShareLock); if(peloton_query == true) break; } } return peloton_query; }
/*------------------------------------------------------------------------- * * peloton.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/peloton.c * *------------------------------------------------------------------------- */ #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/param.h> #include <sys/time.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #include <thread> #include <map> #include "backend/common/logger.h" #include "backend/common/message_queue.h" #include "backend/common/stack_trace.h" #include "backend/bridge/ddl/configuration.h" #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/bridge/ddl/tests/bridge_test.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/bridge/dml/mapper/mapper.h" #include "backend/common/stack_trace.h" #include "backend/logging/log_manager.h" #include "postgres.h" #include "c.h" #include "access/xact.h" #include "access/transam.h" #include "access/tupdesc.h" #include "catalog/pg_namespace.h" #include "executor/tuptable.h" #include "libpq/ip.h" #include "libpq/pqsignal.h" #include "miscadmin.h" #include "nodes/print.h" #include "nodes/params.h" #include "utils/guc.h" #include "utils/errcodes.h" #include "utils/ps_status.h" #include "utils/timeout.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/rel.h" #include "postmaster/fork_process.h" #include "postmaster/postmaster.h" #include "postmaster/peloton.h" #include "storage/latch.h" #include "storage/ipc.h" #include "storage/proc.h" #include "tcop/tcopprot.h" /* ---------- * Logging Flag * ---------- */ bool logging_on = true; bool syncronization_commit = false; static void peloton_process_status(const peloton_status& status, PlanState *planstate); static void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest); static void __attribute__((unused)) peloton_test_config(); /* ---------- * peloton_bootstrap - * * Handle bootstrap requests in Peloton. * ---------- */ void peloton_bootstrap() { try { // Process the utility statement peloton::bridge::Bootstrap::BootstrapPeloton(); /* TODO: Handle logging if( logging_on){ // NOTE:: start logging since bootstrapPeloton is done auto& logManager = peloton::logging::LogManager::GetInstance(); if( logManager.IsReadyToLogging() == false){ logManager.StartLogging(); } } */ } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_ddl - * * Handle DDL requests in Peloton. * ---------- */ void peloton_ddl(Node *parsetree) { /* Ignore invalid parsetrees */ if(parsetree == NULL || nodeTag(parsetree) == T_Invalid) { return; } if(logging_on){ /* TODO: Handle logging // Launching a thread for logging auto& log_manager = peloton::logging::LogManager::GetInstance(); log_manager.SetDefaultLoggingType(peloton::LOGGING_TYPE_ARIES); log_manager.SetSyncCommit(syncronization_commit); std::thread(&peloton::logging::LogManager::StartStandbyMode, &log_manager, log_manager.GetDefaultLoggingType()).detach(); */ } auto txn_id = GetTopTransactionId(); try { /* Process the utility statement */ peloton::bridge::DDL::ProcessUtility(parsetree, txn_id); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_dml - * * Handle DML requests in Peloton. * ---------- */ void peloton_dml(PlanState *planstate, bool sendTuples, DestReceiver *dest, TupleDesc tuple_desc) { peloton_status status; // Get the parameter list assert(planstate != NULL); assert(planstate->state != NULL); auto param_list = planstate->state->es_param_list_info; // Create the raw planstate info auto plan_state = peloton::bridge::DMLUtils::peloton_prepare_data(planstate); // Get our plan auto plan = peloton::bridge::PlanTransformer::TransformPlan(plan_state); auto txn_id = GetTopTransactionId(); // Ignore empty plans if(plan == nullptr) { elog(WARNING, "Empty or unrecognized plan sent to Peloton"); return; } std::vector<peloton::oid_t> target_list; std::vector<peloton::oid_t> qual; // Analyze the plan peloton::bridge::PlanTransformer::AnalyzePlan(plan, target_list, qual); // Execute the plantree try { status = peloton::bridge::PlanExecutor::ExecutePlan(plan, param_list, tuple_desc, txn_id); // Clean up the plantree peloton::bridge::PlanTransformer::CleanPlan(plan); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } // Wait for the response and process it peloton_process_status(status, planstate); // Send output to dest peloton_send_output(status, sendTuples, dest); } /* ---------- * peloton_process_status() - * * Process status. * ---------- */ static void peloton_process_status(const peloton_status& status, PlanState *planstate) { int code; // Process the status code code = status.m_result; switch(code) { case peloton::RESULT_SUCCESS: { // TODO: Update stats ? planstate->state->es_processed = status.m_processed; } break; case peloton::RESULT_INVALID: case peloton::RESULT_FAILURE: default: { ereport(ERROR, (errcode(status.m_result), errmsg("transaction failed"))); } break; } } /* ---------- * peloton_send_output() - * * Send the output to the receiver. * ---------- */ void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest) { TupleTableSlot *slot; // Go over any result slots if(status.m_result_slots != NULL) { ListCell *lc; foreach(lc, status.m_result_slots) { slot = (TupleTableSlot *) lfirst(lc); /* * if the tuple is null, then we assume there is nothing more to * process so we just end the loop... */ if (TupIsNull(slot)) break; /* * If we are supposed to send the tuple somewhere, do so. (In * practice, this is probably always the case at this point.) */ if (sendTuples) (*dest->receiveSlot) (slot, dest); /* * Free the underlying heap_tuple * and the TupleTableSlot itself. */ ExecDropSingleTupleTableSlot(slot); } // Clean up list list_free(status.m_result_slots); } } static void peloton_test_config() { auto val = GetConfigOption("peloton_mode", false, false); elog(LOG, "Before SetConfigOption : %s", val); SetConfigOption("peloton_mode", "peloton_mode_1", PGC_USERSET, PGC_S_USER); val = GetConfigOption("peloton_mode", false, false); elog(LOG, "After SetConfigOption : %s", val); // Build the configuration map peloton::bridge::ConfigManager::BuildConfigMap(); } /* ---------- * IsPelotonQuery - * * Does the query access peloton tables or not ? * ---------- */ bool IsPelotonQuery(List *relationOids) { bool peloton_query = false; // Check if we are in Postmaster environment */ if(IsPostmasterEnvironment == false && IsBackend == false) { return false; } if(relationOids != NULL) { ListCell *lc; // Go over each relation on which the plan depends foreach(lc, relationOids) { Oid relation_id = lfirst_oid(lc); // Check if relation in public namespace Relation target_table = relation_open(relation_id, AccessShareLock); Oid target_table_namespace = target_table->rd_rel->relnamespace; if(target_table_namespace == PG_PUBLIC_NAMESPACE) { peloton_query = true; } relation_close(target_table, AccessShareLock); if(peloton_query == true) break; } } return peloton_query; }
add back number of tuple processed
add back number of tuple processed Former-commit-id: c1ea065e718abf965f0c0beab913c3a9c4b33c5f
C++
apache-2.0
AngLi-Leon/peloton,vittvolt/15721-peloton,vittvolt/peloton,jessesleeping/iso_peloton,malin1993ml/peloton,cmu-db/peloton,wangziqi2016/peloton,eric-haibin-lin/peloton-1,yingjunwu/peloton,jessesleeping/iso_peloton,vittvolt/peloton,vittvolt/15721-peloton,jessesleeping/iso_peloton,vittvolt/peloton,cmu-db/peloton,jessesleeping/iso_peloton,ShuxinLin/peloton,prashasthip/peloton,AllisonWang/peloton,malin1993ml/peloton,ShuxinLin/peloton,seojungmin/peloton,haojin2/peloton,vittvolt/peloton,ShuxinLin/peloton,prashasthip/peloton,vittvolt/peloton,haojin2/peloton,seojungmin/peloton,haojin2/peloton,AngLi-Leon/peloton,AngLi-Leon/peloton,phisiart/peloton-p3,prashasthip/peloton,prashasthip/peloton,malin1993ml/peloton,yingjunwu/peloton,haojin2/peloton,cmu-db/peloton,phisiart/peloton-p3,yingjunwu/peloton,AngLi-Leon/peloton,apavlo/peloton,cmu-db/peloton,AngLi-Leon/peloton,wangziqi2016/peloton,wangziqi2016/peloton,malin1993ml/peloton,AllisonWang/peloton,yingjunwu/peloton,eric-haibin-lin/peloton-1,seojungmin/peloton,seojungmin/peloton,eric-haibin-lin/peloton-1,vittvolt/15721-peloton,haojin2/peloton,vittvolt/peloton,yingjunwu/peloton,seojungmin/peloton,PauloAmora/peloton,PauloAmora/peloton,phisiart/peloton-p3,ShuxinLin/peloton,jessesleeping/iso_peloton,apavlo/peloton,malin1993ml/peloton,apavlo/peloton,vittvolt/15721-peloton,jessesleeping/iso_peloton,apavlo/peloton,cmu-db/peloton,jessesleeping/iso_peloton,malin1993ml/peloton,AllisonWang/peloton,ShuxinLin/peloton,PauloAmora/peloton,eric-haibin-lin/peloton-1,prashasthip/peloton,PauloAmora/peloton,seojungmin/peloton,phisiart/peloton-p3,apavlo/peloton,AllisonWang/peloton,AllisonWang/peloton,wangziqi2016/peloton,vittvolt/15721-peloton,haojin2/peloton,prashasthip/peloton,cmu-db/peloton,wangziqi2016/peloton,AllisonWang/peloton,eric-haibin-lin/peloton-1,eric-haibin-lin/peloton-1,apavlo/peloton,yingjunwu/peloton,phisiart/peloton-p3,PauloAmora/peloton,PauloAmora/peloton,AngLi-Leon/peloton,phisiart/peloton-p3,vittvolt/15721-peloton,wangziqi2016/peloton,ShuxinLin/peloton
3cb862586ebb899ef33731528a1d002144721d10
src/postgres/backend/postmaster/peloton.cpp
src/postgres/backend/postmaster/peloton.cpp
/*------------------------------------------------------------------------- * * peloton.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/peloton.c * *------------------------------------------------------------------------- */ #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/param.h> #include <sys/time.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #include <thread> #include <map> #include "backend/common/logger.h" #include "backend/common/message_queue.h" #include "backend/common/stack_trace.h" #include "backend/bridge/ddl/configuration.h" #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/bridge/ddl/tests/bridge_test.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/bridge/dml/mapper/mapper.h" #include "backend/common/stack_trace.h" #include "backend/logging/log_manager.h" #include "postgres.h" #include "c.h" #include "access/xact.h" #include "access/transam.h" #include "access/tupdesc.h" #include "catalog/pg_namespace.h" #include "executor/tuptable.h" #include "libpq/ip.h" #include "libpq/pqsignal.h" #include "miscadmin.h" #include "nodes/print.h" #include "nodes/params.h" #include "utils/guc.h" #include "utils/errcodes.h" #include "utils/ps_status.h" #include "utils/timeout.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/rel.h" #include "postmaster/fork_process.h" #include "postmaster/postmaster.h" #include "postmaster/peloton.h" #include "storage/latch.h" #include "storage/ipc.h" #include "storage/proc.h" #include "tcop/tcopprot.h" /* ---------- * Logging Flag * ---------- */ bool logging_on = true; bool syncronization_commit = false; static void peloton_process_status(const peloton_status& status); static void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest); static void __attribute__((unused)) peloton_test_config(); /* ---------- * peloton_bootstrap - * * Handle bootstrap requests in Peloton. * ---------- */ void peloton_bootstrap() { try { // Process the utility statement peloton::bridge::Bootstrap::BootstrapPeloton(); /* TODO: Handle logging if( logging_on){ // NOTE:: start logging since bootstrapPeloton is done auto& logManager = peloton::logging::LogManager::GetInstance(); if( logManager.IsReadyToLogging() == false){ logManager.StartLogging(); } } */ } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_ddl - * * Handle DDL requests in Peloton. * ---------- */ void peloton_ddl(Node *parsetree) { /* Ignore invalid parsetrees */ if(parsetree == NULL || nodeTag(parsetree) == T_Invalid) { return; } if(logging_on){ /* TODO: Handle logging // Launching a thread for logging auto& log_manager = peloton::logging::LogManager::GetInstance(); log_manager.SetDefaultLoggingType(peloton::LOGGING_TYPE_ARIES); log_manager.SetSyncCommit(syncronization_commit); std::thread(&peloton::logging::LogManager::StartStandbyMode, &log_manager, log_manager.GetDefaultLoggingType()).detach(); */ } auto txn_id = GetTopTransactionId(); try { /* Process the utility statement */ peloton::bridge::DDL::ProcessUtility(parsetree, txn_id); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_dml - * * Handle DML requests in Peloton. * ---------- */ void peloton_dml(PlanState *planstate, bool sendTuples, DestReceiver *dest, TupleDesc tuple_desc) { peloton_status status; // Get the parameter list assert(planstate != NULL); assert(planstate->state != NULL); auto param_list = planstate->state->es_param_list_info; // Create the raw planstate info auto plan_state = peloton::bridge::DMLUtils::peloton_prepare_data(planstate); // Get our plan auto plan = peloton::bridge::PlanTransformer::TransformPlan(plan_state); auto txn_id = GetTopTransactionId(); // Ignore empty plans if(plan == nullptr) { elog(WARNING, "Empty or unrecognized plan sent to Peloton"); return; } std::vector<peloton::oid_t> target_list; std::vector<peloton::oid_t> qual; // Analyze the plan peloton::bridge::PlanTransformer::AnalyzePlan(plan, target_list, qual); // Execute the plantree try { status = peloton::bridge::PlanExecutor::ExecutePlan(plan, param_list, tuple_desc, txn_id); // Clean up the plantree peloton::bridge::PlanTransformer::CleanPlan(plan); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } // Wait for the response and process it peloton_process_status(status); // Send output to dest peloton_send_output(status, sendTuples, dest); } /* ---------- * peloton_process_status() - * * Process status. * ---------- */ static void peloton_process_status(const peloton_status& status) { int code; // Process the status code code = status.m_result; switch(code) { case peloton::RESULT_SUCCESS: { // TODO: Update stats ? } break; case peloton::RESULT_INVALID: case peloton::RESULT_FAILURE: default: { ereport(ERROR, (errcode(status.m_result), errmsg("transaction failed"))); } break; } } /* ---------- * peloton_send_output() - * * Send the output to the receiver. * ---------- */ void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest) { TupleTableSlot *slot; // Go over any result slots if(status.m_result_slots != NULL) { ListCell *lc; foreach(lc, status.m_result_slots) { slot = (TupleTableSlot *) lfirst(lc); /* * if the tuple is null, then we assume there is nothing more to * process so we just end the loop... */ if (TupIsNull(slot)) break; /* * If we are supposed to send the tuple somewhere, do so. (In * practice, this is probably always the case at this point.) */ if (sendTuples) (*dest->receiveSlot) (slot, dest); /* * Free the underlying heap_tuple * and the TupleTableSlot itself. */ ExecDropSingleTupleTableSlot(slot); } // Clean up list list_free(status.m_result_slots); } } static void peloton_test_config() { auto val = GetConfigOption("peloton_mode", false, false); elog(LOG, "Before SetConfigOption : %s", val); SetConfigOption("peloton_mode", "peloton_mode_1", PGC_USERSET, PGC_S_USER); val = GetConfigOption("peloton_mode", false, false); elog(LOG, "After SetConfigOption : %s", val); // Build the configuration map peloton::bridge::ConfigManager::BuildConfigMap(); } /* ---------- * IsPelotonQuery - * * Does the query access peloton tables or not ? * ---------- */ bool IsPelotonQuery(List *relationOids) { bool peloton_query = false; // Check if we are in Postmaster environment */ if(IsPostmasterEnvironment == false && IsBackend == false) { return false; } if(relationOids != NULL) { ListCell *lc; // Go over each relation on which the plan depends foreach(lc, relationOids) { Oid relation_id = lfirst_oid(lc); // Check if relation in public namespace Relation target_table = relation_open(relation_id, AccessShareLock); Oid target_table_namespace = target_table->rd_rel->relnamespace; if(target_table_namespace == PG_PUBLIC_NAMESPACE) { peloton_query = true; } relation_close(target_table, AccessShareLock); if(peloton_query == true) break; } } return peloton_query; }
/*------------------------------------------------------------------------- * * peloton.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/peloton.c * *------------------------------------------------------------------------- */ #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/param.h> #include <sys/time.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #include <thread> #include <map> #include "backend/common/logger.h" #include "backend/common/message_queue.h" #include "backend/common/stack_trace.h" #include "backend/bridge/ddl/configuration.h" #include "backend/bridge/ddl/ddl.h" #include "backend/bridge/ddl/ddl_utils.h" #include "backend/bridge/ddl/tests/bridge_test.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/bridge/dml/mapper/mapper.h" #include "backend/common/stack_trace.h" #include "backend/logging/log_manager.h" #include "postgres.h" #include "c.h" #include "access/xact.h" #include "access/transam.h" #include "access/tupdesc.h" #include "catalog/pg_namespace.h" #include "executor/tuptable.h" #include "libpq/ip.h" #include "libpq/pqsignal.h" #include "miscadmin.h" #include "nodes/print.h" #include "nodes/params.h" #include "utils/guc.h" #include "utils/errcodes.h" #include "utils/ps_status.h" #include "utils/timeout.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/rel.h" #include "postmaster/fork_process.h" #include "postmaster/postmaster.h" #include "postmaster/peloton.h" #include "storage/latch.h" #include "storage/ipc.h" #include "storage/proc.h" #include "tcop/tcopprot.h" /* ---------- * Logging Flag * ---------- */ bool logging_on = true; bool syncronization_commit = false; static void peloton_process_status(const peloton_status& status, PlanState *planstate); static void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest); static void __attribute__((unused)) peloton_test_config(); /* ---------- * peloton_bootstrap - * * Handle bootstrap requests in Peloton. * ---------- */ void peloton_bootstrap() { try { // Process the utility statement peloton::bridge::Bootstrap::BootstrapPeloton(); /* TODO: Handle logging if( logging_on){ // NOTE:: start logging since bootstrapPeloton is done auto& logManager = peloton::logging::LogManager::GetInstance(); if( logManager.IsReadyToLogging() == false){ logManager.StartLogging(); } } */ } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_ddl - * * Handle DDL requests in Peloton. * ---------- */ void peloton_ddl(Node *parsetree) { /* Ignore invalid parsetrees */ if(parsetree == NULL || nodeTag(parsetree) == T_Invalid) { return; } if(logging_on){ /* TODO: Handle logging // Launching a thread for logging auto& log_manager = peloton::logging::LogManager::GetInstance(); log_manager.SetDefaultLoggingType(peloton::LOGGING_TYPE_ARIES); log_manager.SetSyncCommit(syncronization_commit); std::thread(&peloton::logging::LogManager::StartStandbyMode, &log_manager, log_manager.GetDefaultLoggingType()).detach(); */ } auto txn_id = GetTopTransactionId(); try { /* Process the utility statement */ peloton::bridge::DDL::ProcessUtility(parsetree, txn_id); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } } /* ---------- * peloton_dml - * * Handle DML requests in Peloton. * ---------- */ void peloton_dml(PlanState *planstate, bool sendTuples, DestReceiver *dest, TupleDesc tuple_desc) { peloton_status status; // Get the parameter list assert(planstate != NULL); assert(planstate->state != NULL); auto param_list = planstate->state->es_param_list_info; // Create the raw planstate info auto plan_state = peloton::bridge::DMLUtils::peloton_prepare_data(planstate); // Get our plan auto plan = peloton::bridge::PlanTransformer::TransformPlan(plan_state); auto txn_id = GetTopTransactionId(); // Ignore empty plans if(plan == nullptr) { elog(WARNING, "Empty or unrecognized plan sent to Peloton"); return; } std::vector<peloton::oid_t> target_list; std::vector<peloton::oid_t> qual; // Analyze the plan peloton::bridge::PlanTransformer::AnalyzePlan(plan, target_list, qual); // Execute the plantree try { status = peloton::bridge::PlanExecutor::ExecutePlan(plan, param_list, tuple_desc, txn_id); // Clean up the plantree peloton::bridge::PlanTransformer::CleanPlan(plan); } catch(const std::exception &exception) { elog(ERROR, "Peloton exception :: %s", exception.what()); } // Wait for the response and process it peloton_process_status(status, planstate); // Send output to dest peloton_send_output(status, sendTuples, dest); } /* ---------- * peloton_process_status() - * * Process status. * ---------- */ static void peloton_process_status(const peloton_status& status, PlanState *planstate) { int code; // Process the status code code = status.m_result; switch(code) { case peloton::RESULT_SUCCESS: { // TODO: Update stats ? planstate->state->es_processed = status.m_processed; } break; case peloton::RESULT_INVALID: case peloton::RESULT_FAILURE: default: { ereport(ERROR, (errcode(status.m_result), errmsg("transaction failed"))); } break; } } /* ---------- * peloton_send_output() - * * Send the output to the receiver. * ---------- */ void peloton_send_output(const peloton_status& status, bool sendTuples, DestReceiver *dest) { TupleTableSlot *slot; // Go over any result slots if(status.m_result_slots != NULL) { ListCell *lc; foreach(lc, status.m_result_slots) { slot = (TupleTableSlot *) lfirst(lc); /* * if the tuple is null, then we assume there is nothing more to * process so we just end the loop... */ if (TupIsNull(slot)) break; /* * If we are supposed to send the tuple somewhere, do so. (In * practice, this is probably always the case at this point.) */ if (sendTuples) (*dest->receiveSlot) (slot, dest); /* * Free the underlying heap_tuple * and the TupleTableSlot itself. */ ExecDropSingleTupleTableSlot(slot); } // Clean up list list_free(status.m_result_slots); } } static void peloton_test_config() { auto val = GetConfigOption("peloton_mode", false, false); elog(LOG, "Before SetConfigOption : %s", val); SetConfigOption("peloton_mode", "peloton_mode_1", PGC_USERSET, PGC_S_USER); val = GetConfigOption("peloton_mode", false, false); elog(LOG, "After SetConfigOption : %s", val); // Build the configuration map peloton::bridge::ConfigManager::BuildConfigMap(); } /* ---------- * IsPelotonQuery - * * Does the query access peloton tables or not ? * ---------- */ bool IsPelotonQuery(List *relationOids) { bool peloton_query = false; // Check if we are in Postmaster environment */ if(IsPostmasterEnvironment == false && IsBackend == false) { return false; } if(relationOids != NULL) { ListCell *lc; // Go over each relation on which the plan depends foreach(lc, relationOids) { Oid relation_id = lfirst_oid(lc); // Check if relation in public namespace Relation target_table = relation_open(relation_id, AccessShareLock); Oid target_table_namespace = target_table->rd_rel->relnamespace; if(target_table_namespace == PG_PUBLIC_NAMESPACE) { peloton_query = true; } relation_close(target_table, AccessShareLock); if(peloton_query == true) break; } } return peloton_query; }
add back number of tuple processed
add back number of tuple processed Former-commit-id: c1ea065e718abf965f0c0beab913c3a9c4b33c5f
C++
apache-2.0
amaliujia/CMUDB-peloton,omegaga/peloton,ranxian/peloton,omegaga/peloton,amaliujia/CMUDB-peloton,ranxian/peloton,omegaga/peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,omegaga/peloton,larryxiao/peloton,omegaga/peloton,larryxiao/peloton,larryxiao/peloton-1,larryxiao/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,larryxiao/peloton,omegaga/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,larryxiao/peloton-1,amaliujia/CMUDB-peloton,larryxiao/peloton-1,larryxiao/peloton-1,ranxian/peloton,omegaga/peloton,ranxian/peloton,larryxiao/peloton-1,ranxian/peloton
8bbc2a4baffa94e55b1ffdaa84cb8e701e7ed6c9
src/server/implementation/ModuleManager.cpp
src/server/implementation/ModuleManager.cpp
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <config.h> #include "ModuleManager.hpp" #include <gst/gst.h> #include <KurentoException.hpp> #include <sstream> #define GST_CAT_DEFAULT kurento_media_set GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoModuleManager" namespace kurento { int ModuleManager::loadModule (std::string modulePath) { const kurento::FactoryRegistrar *registrar; void *registrarFactory; Glib::Module module (modulePath); if (!module) { GST_WARNING ("Module cannot be loaded: %s", Glib::Module::get_last_error().c_str() ); return -1; } module.make_resident(); if (!module.get_symbol ("getFactoryRegistrar", registrarFactory) ) { GST_WARNING ("Symbol not found"); return -1; } registrar = ( (RegistrarFactoryFunc) registrarFactory) (); const std::map <std::string, std::shared_ptr <kurento::Factory > > &factories = registrar->getFactories(); loadedFactories.insert (factories.begin(), factories.end() ); GST_INFO ("Module %s loaded", module.get_name().c_str() ); return 0; } std::list<std::string> split (const std::string &s, char delim) { std::list<std::string> elems; std::stringstream ss (s); std::string item; while (std::getline (ss, item, delim) ) { elems.push_back (item); } return elems; } void ModuleManager::loadModules (std::string dirPath) { DIR *dir; std::string name; struct dirent *ent; GST_INFO ("Looking for modules in %s", dirPath.c_str() ); dir = opendir (dirPath.c_str() ); if (dir == NULL) { GST_WARNING ("Unable to load modules from: %s", dirPath.c_str() ); return; } /* print all the files and directories within directory */ while ( (ent = readdir (dir) ) != NULL) { name = ent->d_name; if (ent->d_type == DT_REG) { std::string ext = name.substr (name.size() - 3); if ( ext == ".so" ) { std::string name = dirPath + "/" + ent->d_name; loadModule (name); } } else if (ent->d_type == DT_DIR && "." != name && ".." != name) { std::string dirName = dirPath + "/" + ent->d_name; this->loadModules (dirName); } } closedir (dir); } void ModuleManager::loadModulesFromDirectories (std::string path) { std::list <std::string> locations; locations = split (path, ':'); for (std::string location : locations) { this->loadModules (location); } //try to load modules from the default path this->loadModules (KURENTO_MODULES_DIR); return; } const std::map <std::string, std::shared_ptr <kurento::Factory > > ModuleManager::getLoadedFactories () { return loadedFactories; } std::shared_ptr<kurento::Factory> ModuleManager::getFactory (std::string symbolName) { try { return loadedFactories.at (symbolName); } catch (std::exception &e) { GST_ERROR ("Factory not found: %s", e.what() ); throw kurento::KurentoException (MEDIA_OBJECT_NOT_AVAILABLE, "Factory not found"); } } ModuleManager::StaticConstructor ModuleManager::staticConstructor; ModuleManager::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <config.h> #include "ModuleManager.hpp" #include <gst/gst.h> #include <KurentoException.hpp> #include <sstream> #define GST_CAT_DEFAULT kurento_media_set GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoModuleManager" namespace kurento { int ModuleManager::loadModule (std::string modulePath) { const kurento::FactoryRegistrar *registrar; void *registrarFactory; Glib::Module module (modulePath); if (!module) { GST_WARNING ("Module cannot be loaded: %s", Glib::Module::get_last_error().c_str() ); return -1; } module.make_resident(); if (!module.get_symbol ("getFactoryRegistrar", registrarFactory) ) { GST_WARNING ("Symbol not found"); return -1; } registrar = ( (RegistrarFactoryFunc) registrarFactory) (); const std::map <std::string, std::shared_ptr <kurento::Factory > > &factories = registrar->getFactories(); loadedFactories.insert (factories.begin(), factories.end() ); GST_INFO ("Module %s loaded", module.get_name().c_str() ); return 0; } std::list<std::string> split (const std::string &s, char delim) { std::list<std::string> elems; std::stringstream ss (s); std::string item; while (std::getline (ss, item, delim) ) { elems.push_back (item); } return elems; } void ModuleManager::loadModules (std::string dirPath) { DIR *dir; std::string name; struct dirent *ent; GST_INFO ("Looking for modules in %s", dirPath.c_str() ); dir = opendir (dirPath.c_str() ); if (dir == NULL) { GST_WARNING ("Unable to load modules from: %s", dirPath.c_str() ); return; } /* print all the files and directories within directory */ while ( (ent = readdir (dir) ) != NULL) { name = ent->d_name; if (ent->d_type == DT_REG) { if (name.size () > 3) { std::string ext = name.substr (name.size() - 3); if ( ext == ".so" ) { std::string name = dirPath + "/" + ent->d_name; loadModule (name); } } } else if (ent->d_type == DT_DIR && "." != name && ".." != name) { std::string dirName = dirPath + "/" + ent->d_name; this->loadModules (dirName); } } closedir (dir); } void ModuleManager::loadModulesFromDirectories (std::string path) { std::list <std::string> locations; locations = split (path, ':'); for (std::string location : locations) { this->loadModules (location); } //try to load modules from the default path this->loadModules (KURENTO_MODULES_DIR); return; } const std::map <std::string, std::shared_ptr <kurento::Factory > > ModuleManager::getLoadedFactories () { return loadedFactories; } std::shared_ptr<kurento::Factory> ModuleManager::getFactory (std::string symbolName) { try { return loadedFactories.at (symbolName); } catch (std::exception &e) { GST_ERROR ("Factory not found: %s", e.what() ); throw kurento::KurentoException (MEDIA_OBJECT_NOT_AVAILABLE, "Factory not found"); } } ModuleManager::StaticConstructor ModuleManager::staticConstructor; ModuleManager::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento
Fix problem while reading files with short names
ModuleManager: Fix problem while reading files with short names Change-Id: Ib42287d75e82495ac83565fa588d393742679c28
C++
apache-2.0
TribeMedia/kms-core,ESTOS/kms-core,shelsonjava/kms-core,shelsonjava/kms-core,ESTOS/kms-core,ESTOS/kms-core,shelsonjava/kms-core,Kurento/kms-core,TribeMedia/kms-core,Kurento/kms-core,shelsonjava/kms-core,TribeMedia/kms-core,ESTOS/kms-core,Kurento/kms-core,TribeMedia/kms-core,Kurento/kms-core
b8b1739a7380ada61f0bae6d8f0d1ae0eb1c3f02
src/programs/robotDevastation/RobotDevastation.cpp
src/programs/robotDevastation/RobotDevastation.cpp
// Authors: see AUTHORS.md at project root. // CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root. // URL: https://github.com/asrob-uc3m/robotDevastation #include "RobotDevastation.hpp" #include <cstdio> #include <yarp/os/LogComponent.h> #include <yarp/os/LogStream.h> #include <yarp/os/Property.h> YARP_LOG_COMPONENT(RD, "asrob.rd.RobotDevastation") bool rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf) { //-- Get player data //----------------------------------------------------------------------------- //-- Request player/robot info if( ! initPlayerInfo(rf) ) return false; //-- Init screen manager if( ! SDLScreenManager::RegisterManager() ) return false; screenManager = ScreenManager::getScreenManager(SDLScreenManager::id); if (screenManager==NULL) { yCError(RD) << "Could not create ScreenManager"; return false; } if( rf.check("fullscreen") ) screenManager->configure(SDLScreenManager::PARAM_FULLSCREEN, "enabled"); screenManager->start(); //-- Init input manager if( ! SDLInputManager::RegisterManager() ) return false; inputManager = InputManager::getInputManager("SDL"); //-- Init sound if( ! initSound(rf) ) return false; //-- Configure robot device yarp::os::Property robotOptions; if( rf.check("fakeRobotManager") ) robotOptions.put("device", "FakeMotorController"); else robotOptions.put("device", "RobotClient"); robotOptions.put("name", "/" + robotName); //-- Start robot device if( ! robotDevice.open(robotOptions) ) { yCError(RD) << "Found no robot motors with robotName" << robotName << "(try running with --fakeRobotManager if no robot)"; return false; } //-- Acquire robot interface if( ! robotDevice.view(robotManager) ) { yCError(RD) << "Could not acquire robot interface"; return false; } //-- Init image manager if( rf.check("fakeImageManager") ) { if( ! MockImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(MockImageManager::id); } else if( rf.check("yarpLocalImageManager") ) { if( ! YarpLocalImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(YarpLocalImageManager::id); if (imageManager == NULL) { yCError(RD) << "Could not create yarpLocalImageManager"; return false; } if(rf.check("camera_id")) { std::stringstream camera_id_ss; camera_id_ss << rf.find("camera_id").asInt32(); yCInfo(RD) << "YarpLocalImageManager is using camera with index" << camera_id_ss.str(); imageManager->configure("camera_id", camera_id_ss.str()); } } else { if( ! YarpImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(YarpImageManager::id); } //-- Configure the camera port std::ostringstream remoteCameraPortName; //-- Default looks like "/rd1/img:o" remoteCameraPortName << "/"; remoteCameraPortName << robotName; remoteCameraPortName << "/img:o"; imageManager->configure("remote_img_port", remoteCameraPortName.str() ); std::ostringstream localCameraPortName; //-- Default should look like "/robotDevastation/rd1/img:i" localCameraPortName << "/robotDevastation/"; localCameraPortName << robotName; localCameraPortName << "/img:i"; imageManager->configure("local_img_port", localCameraPortName.str() ); //-- Name given by me //-- Init mentalMap mentalMap = MentalMap::getMentalMap(); mentalMap->configure(id); std::vector<Player> players; players.push_back(Player(id,name,100,100,team,0)); mentalMap->updatePlayers(players); mentalMap->addWeapon(Weapon("Default gun", 10, 5)); //-- Init network manager if( ! YarpNetworkManager::RegisterManager() ) return false; networkManager = NetworkManager::getNetworkManager(YarpNetworkManager::id); networkManager->configure("player", players[0]); //-- Get game FSM and start game if( ! initGameFSM() ) return false; if( ! gameFSM->start() ) return false; return true; } double rd::RobotDevastation::getPeriod() { return 1; // Fixed, in seconds, the slow thread that calls updateModule below } bool rd::RobotDevastation::updateModule() { //-- Check if FSM has arrived the end-state if (gameFSM->getCurrentState() == -1) { stopModule(); return true; } if (mentalMap != NULL) { std::printf("===robotDevastation===\n"); std::printf("Number of players: %zd\n",mentalMap->getPlayers().size()); for(size_t i=0;i<mentalMap->getPlayers().size();i++) { std::printf("----------------------\n%s\n",mentalMap->getPlayers().at(i).str().c_str()); } //std::printf("======================\n"); return true; } yCDebug(RD) << "Current state id:" << gameFSM->getCurrentState(); return true; } bool rd::RobotDevastation::initPlayerInfo(yarp::os::ResourceFinder &rf) { if(rf.check("id")) { id = rf.find("id").asInt32(); std::stringstream question; question << "Insert player id [" << id << "]"; getInfoFromUser(question.str(), id); } else { id = -1; getInfoFromUser("Insert player id []", id, true); } if(rf.check("name")) { name = rf.find("name").asString(); std::stringstream question; question << "Insert name [" << name << "]"; getInfoFromUser(question.str(), name); } else { name = ""; getInfoFromUser("Insert name []", name, true); } if(rf.check("team")) { team = rf.find("team").asInt32(); std::stringstream question; question << "Insert team [" << team << "]"; getInfoFromUser(question.str(), team); } else { team = -1; getInfoFromUser("Insert team []", team, true); } if(rf.check("robotName")) { robotName = rf.find("robotName").asString(); std::stringstream question; question << "Insert robotName [" << robotName << "]"; getInfoFromUser(question.str(), robotName); } else { robotName = ""; getInfoFromUser("Insert robotName []", robotName, true); } std::printf("\n\n"); std::printf("Player information:\n"); std::printf("\t-id: %d\n", id); std::printf("\t-name: %s\n", name.c_str()); std::printf("\t-team: %d\n", team); std::printf("\t-robotName: %s\n", robotName.c_str()); return true; } bool rd::RobotDevastation::initSound(yarp::os::ResourceFinder &rf) { if( ! SDLAudioManager::RegisterManager() ) return false; audioManager = AudioManager::getAudioManager("SDL"); std::string bsoStr( rf.findFileByName("../sounds/RobotDevastationBSO.mp3") ); if ( ! audioManager->load(bsoStr, "RD_THEME", 0) ) return false; std::string shootStr( rf.findFileByName("../sounds/01_milshot.wav") ); if ( ! audioManager->load(shootStr, "shoot", 1) ) return false; std::string explosionStr( rf.findFileByName("../sounds/15_explosion.wav") ); if ( ! audioManager->load(explosionStr, "explosion", 1) ) return false; std::string noAmmoStr( rf.findFileByName("../sounds/03_clip.wav") ); if ( ! audioManager->load(noAmmoStr, "noAmmo", 1) ) return false; std::string reloadStr( rf.findFileByName("../sounds/04_milaction.wav") ); if ( ! audioManager->load(reloadStr, "reload", 1) ) return false; return true; } bool rd::RobotDevastation::initGameFSM() { StateMachineBuilder builder; builder.setDirectorType("YARP"); //-- Create states int init_state_id = builder.addState(new InitState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int game_state_id = builder.addState(new GameState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int dead_state_id = builder.addState(new DeadState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int end_state_id = builder.addState(State::getEndState()); //-- Add transitions to other states builder.addTransition(init_state_id, game_state_id, InitState::LOGIN_SUCCESSFUL); builder.addTransition(init_state_id, end_state_id, InitState::EXIT_REQUESTED); builder.addTransition(game_state_id, dead_state_id, GameState::KILLED); builder.addTransition(game_state_id, end_state_id, GameState::EXIT_REQUESTED); builder.addTransition(dead_state_id, game_state_id, DeadState::RESPAWN_SELECTED); builder.addTransition(dead_state_id, end_state_id, DeadState::EXIT_SELECTED); //-- Set initial state builder.setInitialState(init_state_id); gameFSM = builder.buildStateMachine(); return gameFSM != NULL; } bool rd::RobotDevastation::cleanup() { InputManager::destroyInputManager(); inputManager = NULL; NetworkManager::destroyNetworkManager(); networkManager = NULL; //-- Closing audio system: AudioManager::destroyAudioManager(); audioManager = NULL; //-- Closing mental map: MentalMap::destroyMentalMap(); mentalMap = NULL; //-- Close img related ports: ImageManager::destroyImageManager(); imageManager = NULL; //-- Close robot: robotDevice.close(); //-- Delete FSM: delete gameFSM; gameFSM = NULL; //-- Close SDL / GUI screenManager->stop(); ScreenManager::destroyScreenManager(); screenManager = NULL; return true; } bool rd::RobotDevastation::interruptModule() { yCInfo(RD) << "Closing program..."; return cleanup(); }
// Authors: see AUTHORS.md at project root. // CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root. // URL: https://github.com/asrob-uc3m/robotDevastation #include "RobotDevastation.hpp" #include <cstdio> #include <yarp/os/LogComponent.h> #include <yarp/os/LogStream.h> #include <yarp/os/Property.h> namespace { YARP_LOG_COMPONENT(RD, "asrob.rd.RobotDevastation") } bool rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf) { //-- Get player data //----------------------------------------------------------------------------- //-- Request player/robot info if( ! initPlayerInfo(rf) ) return false; //-- Init screen manager if( ! SDLScreenManager::RegisterManager() ) return false; screenManager = ScreenManager::getScreenManager(SDLScreenManager::id); if (screenManager==NULL) { yCError(RD) << "Could not create ScreenManager"; return false; } if( rf.check("fullscreen") ) screenManager->configure(SDLScreenManager::PARAM_FULLSCREEN, "enabled"); screenManager->start(); //-- Init input manager if( ! SDLInputManager::RegisterManager() ) return false; inputManager = InputManager::getInputManager("SDL"); //-- Init sound if( ! initSound(rf) ) return false; //-- Configure robot device yarp::os::Property robotOptions; if( rf.check("fakeRobotManager") ) robotOptions.put("device", "FakeMotorController"); else robotOptions.put("device", "RobotClient"); robotOptions.put("name", "/" + robotName); //-- Start robot device if( ! robotDevice.open(robotOptions) ) { yCError(RD) << "Found no robot motors with robotName" << robotName << "(try running with --fakeRobotManager if no robot)"; return false; } //-- Acquire robot interface if( ! robotDevice.view(robotManager) ) { yCError(RD) << "Could not acquire robot interface"; return false; } //-- Init image manager if( rf.check("fakeImageManager") ) { if( ! MockImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(MockImageManager::id); } else if( rf.check("yarpLocalImageManager") ) { if( ! YarpLocalImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(YarpLocalImageManager::id); if (imageManager == NULL) { yCError(RD) << "Could not create yarpLocalImageManager"; return false; } if(rf.check("camera_id")) { std::stringstream camera_id_ss; camera_id_ss << rf.find("camera_id").asInt32(); yCInfo(RD) << "YarpLocalImageManager is using camera with index" << camera_id_ss.str(); imageManager->configure("camera_id", camera_id_ss.str()); } } else { if( ! YarpImageManager::RegisterManager() ) return false; imageManager = ImageManager::getImageManager(YarpImageManager::id); } //-- Configure the camera port std::ostringstream remoteCameraPortName; //-- Default looks like "/rd1/img:o" remoteCameraPortName << "/"; remoteCameraPortName << robotName; remoteCameraPortName << "/img:o"; imageManager->configure("remote_img_port", remoteCameraPortName.str() ); std::ostringstream localCameraPortName; //-- Default should look like "/robotDevastation/rd1/img:i" localCameraPortName << "/robotDevastation/"; localCameraPortName << robotName; localCameraPortName << "/img:i"; imageManager->configure("local_img_port", localCameraPortName.str() ); //-- Name given by me //-- Init mentalMap mentalMap = MentalMap::getMentalMap(); mentalMap->configure(id); std::vector<Player> players; players.push_back(Player(id,name,100,100,team,0)); mentalMap->updatePlayers(players); mentalMap->addWeapon(Weapon("Default gun", 10, 5)); //-- Init network manager if( ! YarpNetworkManager::RegisterManager() ) return false; networkManager = NetworkManager::getNetworkManager(YarpNetworkManager::id); networkManager->configure("player", players[0]); //-- Get game FSM and start game if( ! initGameFSM() ) return false; if( ! gameFSM->start() ) return false; return true; } double rd::RobotDevastation::getPeriod() { return 1; // Fixed, in seconds, the slow thread that calls updateModule below } bool rd::RobotDevastation::updateModule() { //-- Check if FSM has arrived the end-state if (gameFSM->getCurrentState() == -1) { stopModule(); return true; } if (mentalMap != NULL) { std::printf("===robotDevastation===\n"); std::printf("Number of players: %zd\n",mentalMap->getPlayers().size()); for(size_t i=0;i<mentalMap->getPlayers().size();i++) { std::printf("----------------------\n%s\n",mentalMap->getPlayers().at(i).str().c_str()); } //std::printf("======================\n"); return true; } yCDebug(RD) << "Current state id:" << gameFSM->getCurrentState(); return true; } bool rd::RobotDevastation::initPlayerInfo(yarp::os::ResourceFinder &rf) { if(rf.check("id")) { id = rf.find("id").asInt32(); std::stringstream question; question << "Insert player id [" << id << "]"; getInfoFromUser(question.str(), id); } else { id = -1; getInfoFromUser("Insert player id []", id, true); } if(rf.check("name")) { name = rf.find("name").asString(); std::stringstream question; question << "Insert name [" << name << "]"; getInfoFromUser(question.str(), name); } else { name = ""; getInfoFromUser("Insert name []", name, true); } if(rf.check("team")) { team = rf.find("team").asInt32(); std::stringstream question; question << "Insert team [" << team << "]"; getInfoFromUser(question.str(), team); } else { team = -1; getInfoFromUser("Insert team []", team, true); } if(rf.check("robotName")) { robotName = rf.find("robotName").asString(); std::stringstream question; question << "Insert robotName [" << robotName << "]"; getInfoFromUser(question.str(), robotName); } else { robotName = ""; getInfoFromUser("Insert robotName []", robotName, true); } std::printf("\n\n"); std::printf("Player information:\n"); std::printf("\t-id: %d\n", id); std::printf("\t-name: %s\n", name.c_str()); std::printf("\t-team: %d\n", team); std::printf("\t-robotName: %s\n", robotName.c_str()); return true; } bool rd::RobotDevastation::initSound(yarp::os::ResourceFinder &rf) { if( ! SDLAudioManager::RegisterManager() ) return false; audioManager = AudioManager::getAudioManager("SDL"); std::string bsoStr( rf.findFileByName("../sounds/RobotDevastationBSO.mp3") ); if ( ! audioManager->load(bsoStr, "RD_THEME", 0) ) return false; std::string shootStr( rf.findFileByName("../sounds/01_milshot.wav") ); if ( ! audioManager->load(shootStr, "shoot", 1) ) return false; std::string explosionStr( rf.findFileByName("../sounds/15_explosion.wav") ); if ( ! audioManager->load(explosionStr, "explosion", 1) ) return false; std::string noAmmoStr( rf.findFileByName("../sounds/03_clip.wav") ); if ( ! audioManager->load(noAmmoStr, "noAmmo", 1) ) return false; std::string reloadStr( rf.findFileByName("../sounds/04_milaction.wav") ); if ( ! audioManager->load(reloadStr, "reload", 1) ) return false; return true; } bool rd::RobotDevastation::initGameFSM() { StateMachineBuilder builder; builder.setDirectorType("YARP"); //-- Create states int init_state_id = builder.addState(new InitState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int game_state_id = builder.addState(new GameState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int dead_state_id = builder.addState(new DeadState(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager, screenManager)); int end_state_id = builder.addState(State::getEndState()); //-- Add transitions to other states builder.addTransition(init_state_id, game_state_id, InitState::LOGIN_SUCCESSFUL); builder.addTransition(init_state_id, end_state_id, InitState::EXIT_REQUESTED); builder.addTransition(game_state_id, dead_state_id, GameState::KILLED); builder.addTransition(game_state_id, end_state_id, GameState::EXIT_REQUESTED); builder.addTransition(dead_state_id, game_state_id, DeadState::RESPAWN_SELECTED); builder.addTransition(dead_state_id, end_state_id, DeadState::EXIT_SELECTED); //-- Set initial state builder.setInitialState(init_state_id); gameFSM = builder.buildStateMachine(); return gameFSM != NULL; } bool rd::RobotDevastation::cleanup() { InputManager::destroyInputManager(); inputManager = NULL; NetworkManager::destroyNetworkManager(); networkManager = NULL; //-- Closing audio system: AudioManager::destroyAudioManager(); audioManager = NULL; //-- Closing mental map: MentalMap::destroyMentalMap(); mentalMap = NULL; //-- Close img related ports: ImageManager::destroyImageManager(); imageManager = NULL; //-- Close robot: robotDevice.close(); //-- Delete FSM: delete gameFSM; gameFSM = NULL; //-- Close SDL / GUI screenManager->stop(); ScreenManager::destroyScreenManager(); screenManager = NULL; return true; } bool rd::RobotDevastation::interruptModule() { yCInfo(RD) << "Closing program..."; return cleanup(); }
Apply internal static linkage to logging component
Apply internal static linkage to logging component
C++
lgpl-2.1
asrob-uc3m/robotDevastation,asrob-uc3m/robotDevastation
87e4cee02d7450740d1d3ab78a9e40459e97577b
src/test/syscoin_asset_allocation_tests.cpp
src/test/syscoin_asset_allocation_tests.cpp
// Copyright (c) 2016-2017 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "test/test_syscoin_services.h" #include "utiltime.h" #include "util.h" #include "rpc/server.h" #include "alias.h" #include "cert.h" #include "asset.h" #include "base58.h" #include "chainparams.h" #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <iterator> #include <chrono> #include "ranges.h" using namespace boost::chrono; using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_send) { UniValue r; printf("Running generate_asset_allocation_send...\n"); GenerateBlocks(5); AliasNew("node1", "jagassetallocationsend1", "data"); AliasNew("node2", "jagassetallocationsend2", "data"); string guid = AssetNew("node1", "usd", "jagassetallocationsend1", "data", "8", "false", "1", "-1"); AssetSend("node1", guid, "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend1\\\",\\\"amount\\\":1}]\"", "assetallocationsend"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend1 false")); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.11}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false),0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.12}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.13}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // first ones now OK because it was found explicitely BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_througput) { UniValue r; printf("Running generate_asset_allocation_througput...\n"); GenerateBlocks(5); map<string, string> assetMap; // create 1000 aliases and assets for each asset printf("creating 1000 aliases/asset...\n"); for (int i = 0; i < 1000; i++) { string aliasname = "jagthroughput-" + boost::lexical_cast<string>(i); string aliasnameto = "jagthroughput3-" + boost::lexical_cast<string>(i); AliasNew("node1",aliasname, "data"); AliasNew("node3", aliasnameto, "data"); string guid = AssetNew("node1", "usd", aliasname, "data", "8", "false", "1", "-1"); assetMap[guid] = aliasnameto; if (i % 100 == 0) printf("%d percentage done\n", 100 / (1000 / i)); } printf("Creating assetsend transactions to node3 alias...\n"); vector<string> assetSendTxVec; int count = 0; for (auto& assetTuple : assetMap) { count++; string hex_str = AssetSend("node1", assetTuple.first, "\"[{\\\"aliasto\\\":\\\"" + assetTuple.second + "\\\",\\\"amount\\\":1}]\"", "assetallocationsend", "''", false); assetSendTxVec.push_back(hex_str); if (count % 100 == 0) printf("%d percentage done\n", 100 / (1000 / count)); } printf("Sending assetsend transactions to network...\n"); map<string, int64_t> sendTimes; count = 0; for (auto& hex_str : assetSendTxVec) { count++; BOOST_CHECK_NO_THROW(r = CallRPC("node1", "syscoinsendrawtransaction " + hex_str)); string txid = find_value(r.get_obj(), "txid").get_str(); sendTimes[txid] = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); if (count % 100 == 0) printf("%d percentage done\n", 100 / (1000 / count)); } printf("Gathering results...\n"); float totalTime = 0; // wait 10 seconds MilliSleep(10000); BOOST_CHECK_NO_THROW(r = CallRPC("node3", "tpstestinfo")); UniValue tpsresponse = r.get_array(); for (int i = 0; i < tpsresponse.size();i++) { UniValue responesObj = tpsresponse[i].get_obj(); string txid = find_value(responesObj, "txid").get_str(); int64_t timeRecv = find_value(responesObj, "time").get_int64(); if (sendTimes.find(txid) == sendTimes.end()) continue; totalTime += timeRecv - sendTimes[txid]; } totalTime /= tpsresponse.size(); printf("totalTime %.2f, num responses %d\n", totalTime, tpsresponse.size()); } BOOST_AUTO_TEST_SUITE_END ()
// Copyright (c) 2016-2017 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "test/test_syscoin_services.h" #include "utiltime.h" #include "util.h" #include "rpc/server.h" #include "alias.h" #include "cert.h" #include "asset.h" #include "base58.h" #include "chainparams.h" #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <iterator> #include <chrono> #include "ranges.h" using namespace boost::chrono; using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_send) { UniValue r; printf("Running generate_asset_allocation_send...\n"); GenerateBlocks(5); AliasNew("node1", "jagassetallocationsend1", "data"); AliasNew("node2", "jagassetallocationsend2", "data"); string guid = AssetNew("node1", "usd", "jagassetallocationsend1", "data", "8", "false", "1", "-1"); AssetSend("node1", guid, "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend1\\\",\\\"amount\\\":1}]\"", "assetallocationsend"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend1 false")); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.11}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false),0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.12}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, "jagassetallocationsend1", "\"[{\\\"aliasto\\\":\\\"jagassetallocationsend2\\\",\\\"amount\\\":0.13}]\"", "allocationsendmemo"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " jagassetallocationsend2 false")); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8, false), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // first ones now OK because it was found explicitely BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT_OK); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " jagassetallocationsend1 ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_througput) { UniValue r; printf("Running generate_asset_allocation_througput...\n"); GenerateBlocks(5); map<string, string> assetMap; // create 1000 aliases and assets for each asset printf("creating 1000 aliases/asset...\n"); for (int i = 0; i < 1000; i++) { string aliasname = "jagthroughput-" + boost::lexical_cast<string>(i); string aliasnameto = "jagthroughput3-" + boost::lexical_cast<string>(i); AliasNew("node1",aliasname, "data"); AliasNew("node3", aliasnameto, "data"); string guid = AssetNew("node1", "usd", aliasname, "data", "8", "false", "1", "-1"); assetMap[guid] = aliasnameto; if (i % 100 == 0) printf("%d percentage done\n", 100 / (1000 / (i+1))); } printf("Creating assetsend transactions to node3 alias...\n"); vector<string> assetSendTxVec; int count = 0; for (auto& assetTuple : assetMap) { count++; string hex_str = AssetSend("node1", assetTuple.first, "\"[{\\\"aliasto\\\":\\\"" + assetTuple.second + "\\\",\\\"amount\\\":1}]\"", "assetallocationsend", "''", false); assetSendTxVec.push_back(hex_str); if (count % 100 == 0) printf("%d percentage done\n", 100 / (1000 / count)); } printf("Sending assetsend transactions to network...\n"); map<string, int64_t> sendTimes; count = 0; for (auto& hex_str : assetSendTxVec) { count++; BOOST_CHECK_NO_THROW(r = CallRPC("node1", "syscoinsendrawtransaction " + hex_str)); string txid = find_value(r.get_obj(), "txid").get_str(); sendTimes[txid] = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); if (count % 100 == 0) printf("%d percentage done\n", 100 / (1000 / count)); } printf("Gathering results...\n"); float totalTime = 0; // wait 10 seconds MilliSleep(10000); BOOST_CHECK_NO_THROW(r = CallRPC("node3", "tpstestinfo")); UniValue tpsresponse = r.get_array(); for (int i = 0; i < tpsresponse.size();i++) { UniValue responesObj = tpsresponse[i].get_obj(); string txid = find_value(responesObj, "txid").get_str(); int64_t timeRecv = find_value(responesObj, "time").get_int64(); if (sendTimes.find(txid) == sendTimes.end()) continue; totalTime += timeRecv - sendTimes[txid]; } totalTime /= tpsresponse.size(); printf("totalTime %.2f, num responses %d\n", totalTime, tpsresponse.size()); } BOOST_AUTO_TEST_SUITE_END ()
fix div by 0
fix div by 0 Former-commit-id: 8be3ab74dd21763d356dc139bb46e11385727606
C++
mit
syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin
9edee2fe5a1ef796c351bfc5f960c28aac7ee13d
src/qt/bitcoinamountfield.cpp
src/qt/bitcoinamountfield.cpp
#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QComboBox> #include <QApplication> #include <qmath.h> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); qApp->sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); }
#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QComboBox> #include <QApplication> #include <qmath.h> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); amount->setSingleStep(0.001); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); qApp->sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); }
Change up/down increment in UI to 0.001 BTC (issue #760)
Change up/down increment in UI to 0.001 BTC (issue #760)
C++
mit
bmp02050/ReddcoinUpdates,coinkeeper/2015-06-22_19-10_cannacoin,reddink/reddcoin,joroob/reddcoin,Cannacoin-Project/Cannacoin,Cannacoin-Project/Cannacoin,coinkeeper/2015-06-22_19-10_cannacoin,reddink/reddcoin,bmp02050/ReddcoinUpdates,reddink/reddcoin,bmp02050/ReddcoinUpdates,reddcoin-project/reddcoin,joroob/reddcoin,reddcoin-project/reddcoin,joroob/reddcoin,reddcoin-project/reddcoin,ahmedbodi/poscoin,joroob/reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,ahmedbodi/poscoin,reddcoin-project/reddcoin,reddcoin-project/reddcoin,coinkeeper/2015-06-22_19-10_cannacoin,coinkeeper/2015-06-22_19-10_cannacoin,coinkeeper/2015-06-22_18-46_reddcoin,bmp02050/ReddcoinUpdates,bmp02050/ReddcoinUpdates,Cannacoin-Project/Cannacoin,coinkeeper/2015-06-22_18-46_reddcoin,reddink/reddcoin,ahmedbodi/poscoin,coinkeeper/2015-06-22_18-46_reddcoin,coinkeeper/2015-06-22_19-10_cannacoin,ahmedbodi/poscoin,reddcoin-project/reddcoin,Cannacoin-Project/Cannacoin,joroob/reddcoin,Cannacoin-Project/Cannacoin,ahmedbodi/poscoin,reddink/reddcoin
37f7e3e18c81b7ca4b8ee3f3edd22b57e64e82bc
src/share/complex_modifications_assets_manager.hpp
src/share/complex_modifications_assets_manager.hpp
#pragma once #include "core_configuration.hpp" #include <dirent.h> namespace krbn { class complex_modifications_assets_manager final { public: class file final { public: file(const std::string& file_path) : file_path_(file_path) { std::ifstream stream(file_path); if (!stream) { throw std::runtime_error(std::string("Failed to open ") + file_path); } else { auto json = nlohmann::json::parse(stream); { const std::string key = "title"; if (json.find(key) != json.end() && json[key].is_string()) { title_ = json[key]; } } { const std::string key = "rules"; if (json.find(key) != json.end() && json[key].is_array()) { core_configuration::profile::complex_modifications::parameters parameters; for (const auto& j : json[key]) { rules_.emplace_back(j, parameters); } } } } } const std::string& get_file_path(void) const { return file_path_; } const std::string& get_title(void) const { return title_; } const std::vector<core_configuration::profile::complex_modifications::rule>& get_rules(void) const { return rules_; } private: std::string file_path_; std::string title_; std::vector<core_configuration::profile::complex_modifications::rule> rules_; }; void reload(const std::string& directory) { files_.clear(); DIR* dir = opendir(directory.c_str()); if (dir) { while (auto entry = readdir(dir)) { if (entry->d_type == DT_REG || entry->d_type == DT_LNK) { auto file_path = directory + "/" + entry->d_name; try { files_.emplace_back(file_path); } catch (std::exception& e) { logger::get_logger().error("Error in {0}: {1}", file_path, e.what()); } } } closedir(dir); } // Sort by title_ std::sort(std::begin(files_), std::end(files_), [](auto& a, auto& b) { return a.get_title() < b.get_title(); }); } const std::vector<file>& get_files(void) const { return files_; } private: std::vector<file> files_; }; } // namespace krbn
#pragma once #include "core_configuration.hpp" #include <dirent.h> #include <unistd.h> namespace krbn { class complex_modifications_assets_manager final { public: class file final { public: file(const std::string& file_path) : file_path_(file_path) { std::ifstream stream(file_path); if (!stream) { throw std::runtime_error(std::string("Failed to open ") + file_path); } else { auto json = nlohmann::json::parse(stream); { const std::string key = "title"; if (json.find(key) != json.end() && json[key].is_string()) { title_ = json[key]; } } { const std::string key = "rules"; if (json.find(key) != json.end() && json[key].is_array()) { core_configuration::profile::complex_modifications::parameters parameters; for (const auto& j : json[key]) { rules_.emplace_back(j, parameters); } } } } } const std::string& get_file_path(void) const { return file_path_; } const std::string& get_title(void) const { return title_; } const std::vector<core_configuration::profile::complex_modifications::rule>& get_rules(void) const { return rules_; } void unlink_file(void) const { unlink(file_path_.c_str()); } private: std::string file_path_; std::string title_; std::vector<core_configuration::profile::complex_modifications::rule> rules_; }; void reload(const std::string& directory) { files_.clear(); DIR* dir = opendir(directory.c_str()); if (dir) { while (auto entry = readdir(dir)) { if (entry->d_type == DT_REG || entry->d_type == DT_LNK) { auto file_path = directory + "/" + entry->d_name; try { files_.emplace_back(file_path); } catch (std::exception& e) { logger::get_logger().error("Error in {0}: {1}", file_path, e.what()); } } } closedir(dir); } // Sort by title_ std::sort(std::begin(files_), std::end(files_), [](auto& a, auto& b) { return a.get_title() < b.get_title(); }); } const std::vector<file>& get_files(void) const { return files_; } private: std::vector<file> files_; }; } // namespace krbn
add unlink_file
add unlink_file
C++
unlicense
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
c1929ee9f3cc330cd4b15980d5ef5b907c7541e0
include/vsmc/utility/rng_set.hpp
include/vsmc/utility/rng_set.hpp
#ifndef VSMC_UTILITY_RNG_SET_HPP #define VSMC_UTILITY_RNG_SET_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/seed.hpp> #if VSMC_USE_RANDOM123 #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4521) #endif // _MSC_VER #define R123_USE_U01_DOUBLE 1 #include <Random123/threefry.h> #include <Random123/conventional/Engine.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // VSMC_USE_RANDOM123 namespace vsmc { /// \brief Scalar RNG set /// \ingroup Utility template <typename RngType> class RngSet<RngType, ScalarRng> { public : typedef RngType rng_type; typedef std::size_t size_type; explicit RngSet (size_type) : rng_(static_cast< typename rng_type::result_type>(Seed::instance().get())) {} rng_type &rng (size_type id) {return rng_;} private : rng_type rng_; }; // class RngSet /// \brief Vector RNG set /// \ingroup Utility template <typename RngType> class RngSet<RngType, VectorRng> { public : typedef RngType rng_type; typedef typename std::vector<rng_type>::size_type size_type; explicit RngSet (size_type N) { Seed &seed = Seed::instance(); for (size_type i = 0; i != N; ++i) { rng_.push_back(rng_type(static_cast< typename rng_type::result_type>(seed.get()))); } } rng_type &rng (size_type id) {return rng_[id];} private : std::vector<rng_type> rng_; }; // class RngSet } // namespace vsmc #if VSMC_USE_RANDOM123 #define VSMC_DEFAULT_RNG_SET_TYPE \ RngSet<r123::Engine<r123::Threefry4x64>, VectorRng> #else #define VSMC_DEFAULT_RNG_SET_TYPE \ RngSet<vsmc::cxx11::mt19937, VectorRng> #endif VSMC_DEFINE_TYPE_DISPATCH_TRAIT(RngSetType, rng_set_type, VSMC_DEFAULT_RNG_SET_TYPE) #endif // VSMC_UTILITY_RNG_SET_HPP
#ifndef VSMC_UTILITY_RNG_SET_HPP #define VSMC_UTILITY_RNG_SET_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/seed.hpp> #if VSMC_USE_RANDOM123 #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4521) #endif // _MSC_VER #define R123_USE_U01_DOUBLE 1 #include <Random123/threefry.h> #include <Random123/conventional/Engine.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // VSMC_USE_RANDOM123 #if VSMC_USE_RANDOM123 #define VSMC_DEFAULT_RNG_SET_TYPE \ RngSet<r123::Engine<r123::Threefry4x64>, VectorRng> #else #define VSMC_DEFAULT_RNG_SET_TYPE \ RngSet<vsmc::cxx11::mt19937, VectorRng> #endif VSMC_DEFINE_TYPE_DISPATCH_TRAIT(RngSetType, rng_set_type, VSMC_DEFAULT_RNG_SET_TYPE) namespace vsmc { /// \brief Scalar RNG set /// \ingroup Utility template <typename RngType> class RngSet<RngType, ScalarRng> { public : typedef RngType rng_type; typedef std::size_t size_type; explicit RngSet (size_type) : rng_(static_cast< typename rng_type::result_type>(Seed::instance().get())) {} rng_type &rng (size_type id) {return rng_;} private : rng_type rng_; }; // class RngSet /// \brief Vector RNG set /// \ingroup Utility template <typename RngType> class RngSet<RngType, VectorRng> { public : typedef RngType rng_type; typedef typename std::vector<rng_type>::size_type size_type; explicit RngSet (size_type N) { Seed &seed = Seed::instance(); for (size_type i = 0; i != N; ++i) { rng_.push_back(rng_type(static_cast< typename rng_type::result_type>(seed.get()))); } } rng_type &rng (size_type id) {return rng_[id];} private : std::vector<rng_type> rng_; }; // class RngSet } // namespace vsmc #endif // VSMC_UTILITY_RNG_SET_HPP
move type traits to the head of rng_set.hpp
move type traits to the head of rng_set.hpp
C++
bsd-2-clause
zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC
1d1d22ac5fff9520762c3d5968cfc252c9db0d00
src/random_torque_applier.cpp
src/random_torque_applier.cpp
#include <ros/ros.h> #include <gazebo_msgs/ApplyBodyWrench.h> #include <geometry_msgs/PoseStamped.h> #include <boost/random.hpp> #define USE_FIXED_SEED 1 namespace { using namespace std; using namespace ros; static const double DURATION_DEFAULT = 0.001; static const unsigned int FIXED_SEED = 0; class RandomTorqueApplier { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Gazebo client ros::ServiceClient gazeboClient; //! Notifier ros::Publisher notifier; //! X torque double x; //! Y torque double y; //! Z torque double z; //! Torque Duration double duration; //! Set random values for x-y bool random; //! Wait for a specific topic bool waitForTopic; //! Topic to wait for string topic; //! rng boost::mt19937 rng; public: RandomTorqueApplier() : pnh("~") { gazeboClient = nh.serviceClient<gazebo_msgs::ApplyBodyWrench>("/gazebo/apply_body_wrench", true /* persistent */); notifier = nh.advertise<std_msgs::Header>("/human/fall", 1, true); pnh.param("x", x, 0.0); pnh.param("y", y, 0.0); pnh.param("z", z, 0.0); pnh.param("duration", duration, DURATION_DEFAULT); pnh.param("waitForTopic", waitForTopic, true); pnh.param("random", random, true); pnh.param<string>("topic", topic, "/balancer/torques"); if (waitForTopic) { ros::service::waitForService(topic); } if (random) { unsigned int seed = 0; #if(!USE_FIXED_SEED) seed = static_cast<unsigned int>(std::time(NULL)); #else const char* scenarioNumberStr = std::getenv("i"); unsigned int scenarioNumber = 0; if(scenarioNumberStr != NULL) { scenarioNumber = boost::lexical_cast<unsigned int>(scenarioNumberStr); seed = scenarioNumber + 1000; } else { cout << "No scenario number set. Using 0" << endl; seed = FIXED_SEED; } #endif rng.seed(seed); bool found = false; while (!found) { // X generator boost::uniform_real<double> xRange(-250, 250); boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > genX(rng, xRange); x = genX(); // Y generator boost::uniform_real<double> yRange(250, 0); boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > genY(rng, yRange); y = genY(); if (fabs(x) >= 150 || fabs(y) >= 150) { found = true; } } } } void apply() { ROS_INFO("Applying forces [%f, %f, %f]", x, y, z); gazebo_msgs::ApplyBodyWrench wrench; wrench.request.body_name = "human::link"; wrench.request.wrench.torque.x = x; wrench.request.wrench.torque.y = y; wrench.request.wrench.torque.z = z; wrench.request.duration = ros::Duration(duration); if (!gazeboClient.call(wrench)) { ROS_ERROR("Failed to apply wrench"); return; } ROS_DEBUG("Notifying"); std_msgs::Header header; header.stamp = ros::Time::now(); notifier.publish(header); ROS_DEBUG("Torque application complete"); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "random_torque_applier"); RandomTorqueApplier rta; rta.apply(); ros::Duration(3.0).sleep(); }
#include <ros/ros.h> #include <gazebo_msgs/ApplyBodyWrench.h> #include <geometry_msgs/PoseStamped.h> #include <boost/random.hpp> #define USE_FIXED_SEED 1 namespace { using namespace std; using namespace ros; static const double DURATION_DEFAULT = 0.001; static const unsigned int FIXED_SEED = 0; class RandomTorqueApplier { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Gazebo client ros::ServiceClient gazeboClient; //! Notifier ros::Publisher notifier; //! X torque double x; //! Y torque double y; //! Z torque double z; //! Torque Duration double duration; //! Set random values for x-y bool random; //! Wait for a specific topic bool waitForTopic; //! Topic to wait for string topic; //! rng boost::mt19937 rng; public: RandomTorqueApplier() : pnh("~") { gazeboClient = nh.serviceClient<gazebo_msgs::ApplyBodyWrench>("/gazebo/apply_body_wrench", true /* persistent */); notifier = nh.advertise<std_msgs::Header>("/human/fall", 1, true); pnh.param("x", x, 0.0); pnh.param("y", y, 0.0); pnh.param("z", z, 0.0); pnh.param("duration", duration, DURATION_DEFAULT); pnh.param("waitForTopic", waitForTopic, true); pnh.param("random", random, true); pnh.param<string>("topic", topic, "/balancer/torques"); if (waitForTopic) { ros::service::waitForService(topic); } if (random) { unsigned int seed = 0; #if(!USE_FIXED_SEED) seed = static_cast<unsigned int>(std::time(NULL)); #else const char* scenarioNumberStr = std::getenv("i"); unsigned int scenarioNumber = 0; if(scenarioNumberStr != NULL) { scenarioNumber = boost::lexical_cast<unsigned int>(scenarioNumberStr); seed = scenarioNumber + 1000; } else { cout << "No scenario number set. Using 0" << endl; seed = FIXED_SEED; } #endif rng.seed(seed); bool found = false; while (!found) { // X generator boost::uniform_real<double> xRange(-250, 250); boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > genX(rng, xRange); x = genX(); // Y generator boost::uniform_real<double> yRange(0, 250); boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > genY(rng, yRange); y = genY(); if (fabs(x) >= 150 || fabs(y) >= 150) { found = true; } } } } void apply() { ROS_INFO("Applying forces [%f, %f, %f]", x, y, z); gazebo_msgs::ApplyBodyWrench wrench; wrench.request.body_name = "human::link"; wrench.request.wrench.torque.x = x; wrench.request.wrench.torque.y = y; wrench.request.wrench.torque.z = z; wrench.request.duration = ros::Duration(duration); if (!gazeboClient.call(wrench)) { ROS_ERROR("Failed to apply wrench"); return; } ROS_DEBUG("Notifying"); std_msgs::Header header; header.stamp = ros::Time::now(); notifier.publish(header); ROS_DEBUG("Torque application complete"); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "random_torque_applier"); RandomTorqueApplier rta; rta.apply(); ros::Duration(3.0).sleep(); }
Fix torque applier
Fix torque applier
C++
apache-2.0
jlurz24/gazebo_utils
1750215c6730654d7a0df73eccd7eef040fed209
ouzel/gui/BMFont.hpp
ouzel/gui/BMFont.hpp
// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GUI_BMFONT_HPP #define OUZEL_GUI_BMFONT_HPP #include "Font.hpp" namespace ouzel { namespace gui { class BMFont final: public Font { public: BMFont() = default; explicit BMFont(const std::vector<uint8_t>& data); void getVertices(const std::string& text, Color color, float fontSize, const Vector2F& anchor, std::vector<uint16_t>& indices, std::vector<graphics::Vertex>& vertices, std::shared_ptr<graphics::Texture>& texture) override; float getStringWidth(const std::string& text); private: int16_t getKerningPair(uint32_t, uint32_t); class CharDescriptor { public: int16_t x = 0; int16_t y = 0; int16_t width = 0; int16_t height = 0; int16_t xOffset = 0; int16_t yOffset = 0; int16_t xAdvance = 0; int16_t page = 0; }; uint16_t lineHeight = 0; uint16_t base = 0; uint16_t width = 0; uint16_t height = 0; uint16_t pages = 0; uint16_t outline = 0; uint16_t kernCount = 0; std::unordered_map<uint32_t, CharDescriptor> chars; std::map<std::pair<uint32_t, uint32_t>, int16_t> kern; std::shared_ptr<graphics::Texture> fontTexture; }; } // namespace gui } // namespace ouzel #endif // OUZEL_GUI_BMFONT_HPP
// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GUI_BMFONT_HPP #define OUZEL_GUI_BMFONT_HPP #include "Font.hpp" namespace ouzel { namespace gui { class BMFont final: public Font { public: BMFont() = default; explicit BMFont(const std::vector<uint8_t>& data); void getVertices(const std::string& text, Color color, float fontSize, const Vector2F& anchor, std::vector<uint16_t>& indices, std::vector<graphics::Vertex>& vertices, std::shared_ptr<graphics::Texture>& texture) override; float getStringWidth(const std::string& text); private: int16_t getKerningPair(uint32_t, uint32_t); struct CharDescriptor final { int16_t x = 0; int16_t y = 0; int16_t width = 0; int16_t height = 0; int16_t xOffset = 0; int16_t yOffset = 0; int16_t xAdvance = 0; int16_t page = 0; }; uint16_t lineHeight = 0; uint16_t base = 0; uint16_t width = 0; uint16_t height = 0; uint16_t pages = 0; uint16_t outline = 0; uint16_t kernCount = 0; std::unordered_map<uint32_t, CharDescriptor> chars; std::map<std::pair<uint32_t, uint32_t>, int16_t> kern; std::shared_ptr<graphics::Texture> fontTexture; }; } // namespace gui } // namespace ouzel #endif // OUZEL_GUI_BMFONT_HPP
Make the CharDescriptor a struct and make it final
Make the CharDescriptor a struct and make it final
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
b2db7182fa909fefca35e3cc99dc987ecfdbcf68
src/firmware/database/Database.cpp
src/firmware/database/Database.cpp
/* OpenDeck MIDI platform firmware Copyright (C) 2015-2018 Igor Petrovic This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Database.h" #include "../interface/display/Config.h" /// /// \brief Default constructor. /// Database::Database() { } /// /// \brief Initializes database. /// void Database::init() { createLayout(); if (!signatureValid()) { DBMS::initData(initFull); } } /// /// \brief Performs factory reset of data in database. /// @param [in] type Factory reset type. See initType_t enumeration. /// void Database::factoryReset(initType_t type) { DBMS::initData(type); writeCustomValues(); } /// /// \brief Checks if database has been already initialized by checking DB_BLOCK_ID. /// \returns True if valid, false otherwise. /// bool Database::signatureValid() { //check if all bytes up to START_OFFSET address match unique id for (int i=0; i<ID_BYTES; i++) { if (DBMS::read(DB_BLOCK_ID, 0, i) != UNIQUE_ID) return false; } return true; } void Database::writeCustomValues() { //used to init custom data for display database.update(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime, MIN_MESSAGE_RETENTION_TIME); } Database database;
/* OpenDeck MIDI platform firmware Copyright (C) 2015-2018 Igor Petrovic This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Database.h" #include "../interface/display/Config.h" #include <avr/eeprom.h> bool memoryRead(uint32_t address, sectionParameterType_t type, int32_t &value) { switch(type) { case BIT_PARAMETER: case BYTE_PARAMETER: case HALFBYTE_PARAMETER: value = eeprom_read_byte((uint8_t*)address); break; case WORD_PARAMETER: value = eeprom_read_word((uint16_t*)address); break; default: // case DWORD_PARAMETER: value = eeprom_read_dword((uint32_t*)address); break; } return true; } bool memoryWrite(uint32_t address, int32_t value, sectionParameterType_t type) { switch(type) { case BIT_PARAMETER: case BYTE_PARAMETER: case HALFBYTE_PARAMETER: eeprom_update_byte((uint8_t*)address, value); break; case WORD_PARAMETER: if (address >= (EEPROM_SIZE-2)) eeprom_update_word((uint16_t*)address, value); break; default: // case DWORD_PARAMETER: eeprom_update_dword((uint32_t*)address, value); break; } return true; } /// /// \brief Default constructor. /// Database::Database() { } /// /// \brief Initializes database. /// void Database::init() { DBMS::init(); DBMS::setHandleRead(memoryRead); DBMS::setHandleWrite(memoryWrite); createLayout(); if (!signatureValid()) { DBMS::initData(initFull); } } /// /// \brief Performs factory reset of data in database. /// @param [in] type Factory reset type. See initType_t enumeration. /// void Database::factoryReset(initType_t type) { DBMS::initData(type); writeCustomValues(); } /// /// \brief Checks if database has been already initialized by checking DB_BLOCK_ID. /// \returns True if valid, false otherwise. /// bool Database::signatureValid() { //check if all bytes up to START_OFFSET address match unique id for (int i=0; i<ID_BYTES; i++) { if (DBMS::read(DB_BLOCK_ID, 0, i) != UNIQUE_ID) return false; } return true; } void Database::writeCustomValues() { //used to init custom data for display database.update(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime, MIN_MESSAGE_RETENTION_TIME); } Database database;
add handling for database, init db
add handling for database, init db
C++
apache-2.0
paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck
e5f201a54ea6b76f1026505e8d60676a0207701b
Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx
Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkGaussianDerivativeImageFunction_hxx #define __itkGaussianDerivativeImageFunction_hxx #include "itkGaussianDerivativeImageFunction.h" #include "itkCompensatedSummation.h" namespace itk { /** Set the Input Image */ template< typename TInputImage, typename TOutput > GaussianDerivativeImageFunction< TInputImage, TOutput > ::GaussianDerivativeImageFunction() { typename GaussianFunctionType::ArrayType mean; mean[0] = 0.0; for ( unsigned int i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = 1.0; m_Extent[i] = 1.0; } m_UseImageSpacing = true; m_GaussianDerivativeFunction = GaussianDerivativeFunctionType::New(); m_GaussianFunction = GaussianFunctionType::New(); m_OperatorImageFunction = OperatorImageFunctionType::New(); m_GaussianFunction->SetMean(mean); m_GaussianFunction->SetNormalized(false); // faster m_GaussianDerivativeFunction->SetNormalized(false); // faster this->RecomputeGaussianKernel(); } /** Print self method */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::PrintSelf(std::ostream & os, Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Extent: " << m_Extent << std::endl; os << indent << "OperatorArray: " << m_OperatorArray << std::endl; os << indent << "ContinuousOperatorArray: " << m_ContinuousOperatorArray << std::endl; os << indent << "OperatorImageFunction: " << m_OperatorImageFunction << std::endl; os << indent << "GaussianDerivativeFunction: " << m_GaussianDerivativeFunction << std::endl; os << indent << "GaussianFunction: " << m_GaussianFunction << std::endl; } /** Set the input image */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetInputImage(const InputImageType *ptr) { Superclass::SetInputImage(ptr); m_OperatorImageFunction->SetInputImage(ptr); } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double *sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma[i] != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma[i]; } this->RecomputeGaussianKernel(); } } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double *extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent[i] != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent[i]; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent; } this->RecomputeGaussianKernel(); } } /** Recompute the gaussian kernel used to evaluate indexes * This should use a fastest Derivative Gaussian operator */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeGaussianKernel() { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename NeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int i = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++i; ++it; } m_OperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); i = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++i; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_OperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed index */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtIndex(const IndexType & index) const { OutputType gradient; for ( unsigned int ii = 0; ii < itkGetStaticConstMacro(ImageDimension2); ++ii ) { // Apply each gaussian kernel to a subset of the image InputPixelType value = static_cast< double >( this->GetInputImage()->GetPixel(index) ); // gaussian blurring first for ( unsigned int direction = 0; direction < itkGetStaticConstMacro(ImageDimension2); ++direction ) { if ( ii != direction ) { const unsigned int idx = 2 * direction + 1; // select only gaussian kernel; const unsigned int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[direction] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; } } // then derivative in the direction const unsigned int idx = 2 * ii; const signed int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[ii] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; gradient[ii] = value; } return gradient; } /** Recompute the gaussian kernel used to evaluate indexes * The variance should be uniform */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeContinuousGaussianKernel( const double *offset) const { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename OperatorNeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int ii = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++ii; ++it; } m_ContinuousOperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); ii = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++ii; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_ContinuousOperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed point */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::Evaluate(const PointType & point) const { IndexType index; this->ConvertPointToNearestIndex(point, index); return this->EvaluateAtIndex (index); } /** Evaluate the function at specified ContinousIndex position.*/ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtContinuousIndex(const ContinuousIndexType & cindex) const { IndexType index; this->ConvertContinuousIndexToNearestIndex(cindex, index); return this->EvaluateAtIndex(index); } } // end namespace itk #endif
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkGaussianDerivativeImageFunction_hxx #define __itkGaussianDerivativeImageFunction_hxx #include "itkGaussianDerivativeImageFunction.h" #include "itkCompensatedSummation.h" namespace itk { /** Set the Input Image */ template< typename TInputImage, typename TOutput > GaussianDerivativeImageFunction< TInputImage, TOutput > ::GaussianDerivativeImageFunction() { typename GaussianFunctionType::ArrayType mean; mean[0] = 0.0; for ( unsigned int i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = 1.0; m_Extent[i] = 1.0; } m_UseImageSpacing = true; m_GaussianDerivativeFunction = GaussianDerivativeFunctionType::New(); m_GaussianFunction = GaussianFunctionType::New(); m_OperatorImageFunction = OperatorImageFunctionType::New(); m_GaussianFunction->SetMean(mean); m_GaussianFunction->SetNormalized(false); // faster m_GaussianDerivativeFunction->SetNormalized(false); // faster this->RecomputeGaussianKernel(); } /** Print self method */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::PrintSelf(std::ostream & os, Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Extent: " << m_Extent << std::endl; os << indent << "OperatorArray: " << m_OperatorArray << std::endl; os << indent << "ContinuousOperatorArray: " << m_ContinuousOperatorArray << std::endl; os << indent << "OperatorImageFunction: " << m_OperatorImageFunction << std::endl; os << indent << "GaussianDerivativeFunction: " << m_GaussianDerivativeFunction << std::endl; os << indent << "GaussianFunction: " << m_GaussianFunction << std::endl; } /** Set the input image */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetInputImage(const InputImageType *ptr) { Superclass::SetInputImage(ptr); m_OperatorImageFunction->SetInputImage(ptr); } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double *sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma[i] != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma[i]; } this->RecomputeGaussianKernel(); } } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double *extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent[i] != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent[i]; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent; } this->RecomputeGaussianKernel(); } } /** Recompute the gaussian kernel used to evaluate indexes * This should use a fastest Derivative Gaussian operator */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeGaussianKernel() { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename NeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int i = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++i; ++it; } m_OperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); i = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++i; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_OperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed index */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtIndex(const IndexType & index) const { OutputType gradient; for ( unsigned int ii = 0; ii < itkGetStaticConstMacro(ImageDimension2); ++ii ) { // Apply each gaussian kernel to a subset of the image typedef typename OutputType::RealValueType OutputRealValueType; OutputRealValueType value = static_cast< OutputRealValueType >( this->GetInputImage()->GetPixel(index) ); // gaussian blurring first for ( unsigned int direction = 0; direction < itkGetStaticConstMacro(ImageDimension2); ++direction ) { if ( ii != direction ) { const unsigned int idx = 2 * direction + 1; // select only gaussian kernel; const unsigned int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[direction] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; } } // then derivative in the direction const unsigned int idx = 2 * ii; const signed int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[ii] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; gradient[ii] = static_cast< typename OutputType::ComponentType >( value ); } return gradient; } /** Recompute the gaussian kernel used to evaluate indexes * The variance should be uniform */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeContinuousGaussianKernel( const double *offset) const { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename OperatorNeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int ii = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++ii; ++it; } m_ContinuousOperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); ii = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++ii; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_ContinuousOperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed point */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::Evaluate(const PointType & point) const { IndexType index; this->ConvertPointToNearestIndex(point, index); return this->EvaluateAtIndex (index); } /** Evaluate the function at specified ContinousIndex position.*/ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtContinuousIndex(const ContinuousIndexType & cindex) const { IndexType index; this->ConvertContinuousIndexToNearestIndex(cindex, index); return this->EvaluateAtIndex(index); } } // end namespace itk #endif
Fix implicit conversion warning
COMP: Fix implicit conversion warning This was caused by commit 7b5fbefbc9f802f53a8c961c6c6ba3f872b49cbf . Also remove use of explicit double types. Change-Id: I1d60fcf31b27d0f08077f373056ac6c6367d2df3
C++
apache-2.0
LucHermitte/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,jmerkow/ITK,richardbeare/ITK,BRAINSia/ITK,richardbeare/ITK,spinicist/ITK,blowekamp/ITK,ajjl/ITK,ajjl/ITK,fedral/ITK,hjmjohnson/ITK,eile/ITK,hjmjohnson/ITK,jcfr/ITK,atsnyder/ITK,jcfr/ITK,stnava/ITK,jcfr/ITK,jmerkow/ITK,heimdali/ITK,LucHermitte/ITK,malaterre/ITK,ajjl/ITK,malaterre/ITK,spinicist/ITK,LucasGandel/ITK,eile/ITK,msmolens/ITK,hendradarwin/ITK,BlueBrain/ITK,vfonov/ITK,PlutoniumHeart/ITK,malaterre/ITK,richardbeare/ITK,fbudin69500/ITK,LucasGandel/ITK,richardbeare/ITK,msmolens/ITK,atsnyder/ITK,blowekamp/ITK,LucHermitte/ITK,BlueBrain/ITK,stnava/ITK,atsnyder/ITK,hendradarwin/ITK,BRAINSia/ITK,biotrump/ITK,hendradarwin/ITK,heimdali/ITK,BRAINSia/ITK,thewtex/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,LucHermitte/ITK,BlueBrain/ITK,ajjl/ITK,LucHermitte/ITK,blowekamp/ITK,msmolens/ITK,thewtex/ITK,Kitware/ITK,eile/ITK,malaterre/ITK,fbudin69500/ITK,thewtex/ITK,blowekamp/ITK,LucHermitte/ITK,LucHermitte/ITK,fbudin69500/ITK,msmolens/ITK,hendradarwin/ITK,richardbeare/ITK,stnava/ITK,atsnyder/ITK,biotrump/ITK,heimdali/ITK,jmerkow/ITK,vfonov/ITK,malaterre/ITK,vfonov/ITK,fedral/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,msmolens/ITK,hendradarwin/ITK,biotrump/ITK,Kitware/ITK,stnava/ITK,eile/ITK,spinicist/ITK,PlutoniumHeart/ITK,spinicist/ITK,malaterre/ITK,heimdali/ITK,jmerkow/ITK,stnava/ITK,biotrump/ITK,BRAINSia/ITK,hendradarwin/ITK,msmolens/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,zachary-williamson/ITK,richardbeare/ITK,jmerkow/ITK,ajjl/ITK,biotrump/ITK,fedral/ITK,Kitware/ITK,richardbeare/ITK,thewtex/ITK,PlutoniumHeart/ITK,blowekamp/ITK,spinicist/ITK,fedral/ITK,vfonov/ITK,fbudin69500/ITK,spinicist/ITK,vfonov/ITK,spinicist/ITK,biotrump/ITK,PlutoniumHeart/ITK,atsnyder/ITK,biotrump/ITK,hjmjohnson/ITK,atsnyder/ITK,eile/ITK,LucasGandel/ITK,LucasGandel/ITK,msmolens/ITK,zachary-williamson/ITK,hendradarwin/ITK,BRAINSia/ITK,spinicist/ITK,heimdali/ITK,InsightSoftwareConsortium/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,jcfr/ITK,atsnyder/ITK,jcfr/ITK,LucHermitte/ITK,PlutoniumHeart/ITK,ajjl/ITK,thewtex/ITK,hjmjohnson/ITK,msmolens/ITK,zachary-williamson/ITK,jcfr/ITK,jcfr/ITK,BlueBrain/ITK,zachary-williamson/ITK,blowekamp/ITK,fedral/ITK,heimdali/ITK,heimdali/ITK,fbudin69500/ITK,stnava/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,thewtex/ITK,blowekamp/ITK,fedral/ITK,hjmjohnson/ITK,atsnyder/ITK,hjmjohnson/ITK,zachary-williamson/ITK,BRAINSia/ITK,Kitware/ITK,fbudin69500/ITK,LucasGandel/ITK,LucasGandel/ITK,hendradarwin/ITK,jmerkow/ITK,jmerkow/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,malaterre/ITK,thewtex/ITK,PlutoniumHeart/ITK,eile/ITK,malaterre/ITK,jmerkow/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,eile/ITK,heimdali/ITK,ajjl/ITK,Kitware/ITK,eile/ITK,spinicist/ITK,fedral/ITK,fedral/ITK,biotrump/ITK,vfonov/ITK,BlueBrain/ITK,malaterre/ITK,vfonov/ITK,eile/ITK,vfonov/ITK,blowekamp/ITK,atsnyder/ITK,jcfr/ITK,zachary-williamson/ITK,LucasGandel/ITK,stnava/ITK,LucasGandel/ITK,Kitware/ITK,fbudin69500/ITK,ajjl/ITK,BRAINSia/ITK
78e1d93f768270bc7b02fd20e908c287df4153ba
src/Homie.cpp
src/Homie.cpp
#include "Homie.hpp" using namespace HomieInternals; SendingPromise::SendingPromise(HomieClass* homie) : _homie(homie) , _node(nullptr) , _property(nullptr) , _qos(0) , _retained(false) { } SendingPromise& SendingPromise::setQos(uint8_t qos) { _qos = qos; } SendingPromise& SendingPromise::setRetained(bool retained) { _retained = retained; } SendingPromise& SendingPromise::setRange(HomieRange range) { _range = range; } SendingPromise& SendingPromise::setRange(uint16_t rangeIndex) { HomieRange range; range.isRange = true; range.index = rangeIndex; _range = range; } uint16_t SendingPromise::send(const String& value) { if (!_homie->isConnected()) { _homie->_logger.logln(F("✖ setNodeProperty(): impossible now")); return; } char* topic = new char[strlen(_homie->getConfiguration().mqtt.baseTopic) + strlen(_homie->getConfiguration().deviceId) + 1 + strlen(_node->getId()) + 1 + strlen(_property->c_str()) + 6 + 1]; // last + 6 for range _65536 strcpy(topic, _homie->getConfiguration().mqtt.baseTopic); strcat(topic, _homie->getConfiguration().deviceId); strcat_P(topic, PSTR("/")); strcat(topic, _node->getId()); strcat_P(topic, PSTR("/")); strcat(topic, _property->c_str()); if (_range.isRange) { char rangeStr[5 + 1]; // max 65536 itoa(_range.index, rangeStr, 10); strcat_P(topic, PSTR("_")); strcat(topic, rangeStr); } uint16_t packetId = _homie->getMqttClient().publish(topic, _qos, _retained, value.c_str()); delete[] topic; return packetId; } SendingPromise& SendingPromise::setNode(const HomieNode& node) { _node = &node; } SendingPromise& SendingPromise::setProperty(const String& property) { _property = &property; } const HomieNode* SendingPromise::getNode() const { return _node; } const String* SendingPromise::getProperty() const { return _property; } uint8_t SendingPromise::getQos() const { return _qos; } HomieRange SendingPromise::getRange() const { return _range; } bool SendingPromise::isRetained() const { return _retained; } HomieClass::HomieClass() : _setupCalled(false) , _sendingPromise(this) , __HOMIE_SIGNATURE("\x25\x48\x4f\x4d\x49\x45\x5f\x45\x53\x50\x38\x32\x36\x36\x5f\x46\x57\x25") { strcpy(_interface.brand, DEFAULT_BRAND); _interface.standalone = false; strcpy(_interface.firmware.name, DEFAULT_FW_NAME); strcpy(_interface.firmware.version, DEFAULT_FW_VERSION); _interface.led.enabled = true; _interface.led.pin = BUILTIN_LED; _interface.led.on = LOW; _interface.reset.able = true; _interface.reset.enabled = true; _interface.reset.triggerPin = DEFAULT_RESET_PIN; _interface.reset.triggerState = DEFAULT_RESET_STATE; _interface.reset.triggerTime = DEFAULT_RESET_TIME; _interface.reset.userFunction = []() { return false; }; _interface.globalInputHandler = [](String node, String property, HomieRange range, String value) { return false; }; _interface.setupFunction = []() {}; _interface.loopFunction = []() {}; _interface.eventHandler = [](const HomieEvent& event) {}; _interface.connected = false; _interface.logger = &_logger; _interface.blinker = &_blinker; _interface.config = &_config; _interface.mqttClient = &_mqttClient; Helpers::generateDeviceId(); _config.attachInterface(&_interface); _blinker.attachInterface(&_interface); _bootStandalone.attachInterface(&_interface); _bootNormal.attachInterface(&_interface); _bootConfig.attachInterface(&_interface); } HomieClass::~HomieClass() { } void HomieClass::_checkBeforeSetup(const __FlashStringHelper* functionName) const { if (_setupCalled) { _logger.log(F("✖ ")); _logger.log(functionName); _logger.logln(F("(): has to be called before setup()")); _logger.flush(); abort(); } } void HomieClass::setup() { _setupCalled = true; if (!_config.load()) { if (_interface.standalone && !_config.canBypassStandalone()) { _boot = &_bootStandalone; _logger.logln(F("Triggering STANDALONE_MODE event...")); _interface.event.type = HomieEventType::STANDALONE_MODE; _interface.eventHandler(_interface.event); } else { _boot = &_bootConfig; _logger.logln(F("Triggering CONFIGURATION_MODE event...")); _interface.event.type = HomieEventType::CONFIGURATION_MODE; _interface.eventHandler(_interface.event); } } else { switch (_config.getBootMode()) { case BOOT_NORMAL: _boot = &_bootNormal; _logger.logln(F("Triggering NORMAL_MODE event...")); _interface.event.type = HomieEventType::NORMAL_MODE; _interface.eventHandler(_interface.event); break; default: _logger.logln(F("✖ The boot mode is invalid")); _logger.flush(); abort(); break; } } _boot->setup(); } void HomieClass::loop() { _boot->loop(); } HomieClass& HomieClass::disableLogging() { _checkBeforeSetup(F("disableLogging")); _logger.setLogging(false); return *this; } HomieClass& HomieClass::setLoggingPrinter(Print* printer) { _checkBeforeSetup(F("setLoggingPrinter")); _logger.setPrinter(printer); return *this; } HomieClass& HomieClass::disableLedFeedback() { _checkBeforeSetup(F("disableLedFeedback")); _interface.led.enabled = false; return *this; } HomieClass& HomieClass::setLedPin(uint8_t pin, uint8_t on) { _checkBeforeSetup(F("setLedPin")); _interface.led.pin = pin; _interface.led.on = on; return *this; } void HomieClass::__setFirmware(const char* name, const char* version) { _checkBeforeSetup(F("setFirmware")); if (strlen(name) + 1 - 10 > MAX_FIRMWARE_NAME_LENGTH || strlen(version) + 1 - 10 > MAX_FIRMWARE_VERSION_LENGTH) { _logger.logln(F("✖ setFirmware(): either the name or version string is too long")); _logger.flush(); abort(); } strncpy(_interface.firmware.name, name + 5, strlen(name) - 10); _interface.firmware.name[strlen(name) - 10] = '\0'; strncpy(_interface.firmware.version, version + 5, strlen(version) - 10); _interface.firmware.version[strlen(version) - 10] = '\0'; } void HomieClass::__setBrand(const char* brand) { _checkBeforeSetup(F("setBrand")); if (strlen(brand) + 1 - 10 > MAX_BRAND_LENGTH) { _logger.logln(F("✖ setBrand(): the brand string is too long")); _logger.flush(); abort(); } strncpy(_interface.brand, brand + 5, strlen(brand) - 10); _interface.brand[strlen(brand) - 10] = '\0'; } void HomieClass::setIdle(bool idle) { _interface.reset.able = idle; } HomieClass& HomieClass::setGlobalInputHandler(GlobalInputHandler inputHandler) { _checkBeforeSetup(F("setGlobalInputHandler")); _interface.globalInputHandler = inputHandler; return *this; } HomieClass& HomieClass::setResetFunction(ResetFunction function) { _checkBeforeSetup(F("setResetFunction")); _interface.reset.userFunction = function; return *this; } HomieClass& HomieClass::setSetupFunction(OperationFunction function) { _checkBeforeSetup(F("setSetupFunction")); _interface.setupFunction = function; return *this; } HomieClass& HomieClass::setLoopFunction(OperationFunction function) { _checkBeforeSetup(F("setLoopFunction")); _interface.loopFunction = function; return *this; } HomieClass& HomieClass::setStandalone() { _checkBeforeSetup(F("setStandalone")); _interface.standalone = true; return *this; } bool HomieClass::isConfigured() const { return _config.getBootMode() == BOOT_NORMAL; } bool HomieClass::isConnected() const { return _interface.connected; } HomieClass& HomieClass::onEvent(EventHandler handler) { _checkBeforeSetup(F("onEvent")); _interface.eventHandler = handler; return *this; } HomieClass& HomieClass::setResetTrigger(uint8_t pin, uint8_t state, uint16_t time) { _checkBeforeSetup(F("setResetTrigger")); _interface.reset.enabled = true; _interface.reset.triggerPin = pin; _interface.reset.triggerState = state; _interface.reset.triggerTime = time; return *this; } HomieClass& HomieClass::disableResetTrigger() { _checkBeforeSetup(F("disableResetTrigger")); _interface.reset.enabled = false; return *this; } void HomieClass::eraseConfiguration() { _config.erase(); } const ConfigStruct& HomieClass::getConfiguration() const { return _config.get(); } AsyncMqttClient& HomieClass::getMqttClient() { return _mqttClient; } void HomieClass::prepareForSleep() { _boot->prepareForSleep(); } HomieClass Homie;
#include "Homie.hpp" using namespace HomieInternals; SendingPromise::SendingPromise(HomieClass* homie) : _homie(homie) , _node(nullptr) , _property(nullptr) , _qos(0) , _retained(false) { } SendingPromise& SendingPromise::setQos(uint8_t qos) { _qos = qos; } SendingPromise& SendingPromise::setRetained(bool retained) { _retained = retained; } SendingPromise& SendingPromise::setRange(HomieRange range) { _range = range; } SendingPromise& SendingPromise::setRange(uint16_t rangeIndex) { HomieRange range; range.isRange = true; range.index = rangeIndex; _range = range; } uint16_t SendingPromise::send(const String& value) { if (!_homie->isConnected()) { _homie->_logger.logln(F("✖ setNodeProperty(): impossible now")); return 0; } char* topic = new char[strlen(_homie->getConfiguration().mqtt.baseTopic) + strlen(_homie->getConfiguration().deviceId) + 1 + strlen(_node->getId()) + 1 + strlen(_property->c_str()) + 6 + 1]; // last + 6 for range _65536 strcpy(topic, _homie->getConfiguration().mqtt.baseTopic); strcat(topic, _homie->getConfiguration().deviceId); strcat_P(topic, PSTR("/")); strcat(topic, _node->getId()); strcat_P(topic, PSTR("/")); strcat(topic, _property->c_str()); if (_range.isRange) { char rangeStr[5 + 1]; // max 65536 itoa(_range.index, rangeStr, 10); strcat_P(topic, PSTR("_")); strcat(topic, rangeStr); } uint16_t packetId = _homie->getMqttClient().publish(topic, _qos, _retained, value.c_str()); delete[] topic; return packetId; } SendingPromise& SendingPromise::setNode(const HomieNode& node) { _node = &node; } SendingPromise& SendingPromise::setProperty(const String& property) { _property = &property; } const HomieNode* SendingPromise::getNode() const { return _node; } const String* SendingPromise::getProperty() const { return _property; } uint8_t SendingPromise::getQos() const { return _qos; } HomieRange SendingPromise::getRange() const { return _range; } bool SendingPromise::isRetained() const { return _retained; } HomieClass::HomieClass() : _setupCalled(false) , _sendingPromise(this) , __HOMIE_SIGNATURE("\x25\x48\x4f\x4d\x49\x45\x5f\x45\x53\x50\x38\x32\x36\x36\x5f\x46\x57\x25") { strcpy(_interface.brand, DEFAULT_BRAND); _interface.standalone = false; strcpy(_interface.firmware.name, DEFAULT_FW_NAME); strcpy(_interface.firmware.version, DEFAULT_FW_VERSION); _interface.led.enabled = true; _interface.led.pin = BUILTIN_LED; _interface.led.on = LOW; _interface.reset.able = true; _interface.reset.enabled = true; _interface.reset.triggerPin = DEFAULT_RESET_PIN; _interface.reset.triggerState = DEFAULT_RESET_STATE; _interface.reset.triggerTime = DEFAULT_RESET_TIME; _interface.reset.userFunction = []() { return false; }; _interface.globalInputHandler = [](String node, String property, HomieRange range, String value) { return false; }; _interface.setupFunction = []() {}; _interface.loopFunction = []() {}; _interface.eventHandler = [](const HomieEvent& event) {}; _interface.connected = false; _interface.logger = &_logger; _interface.blinker = &_blinker; _interface.config = &_config; _interface.mqttClient = &_mqttClient; Helpers::generateDeviceId(); _config.attachInterface(&_interface); _blinker.attachInterface(&_interface); _bootStandalone.attachInterface(&_interface); _bootNormal.attachInterface(&_interface); _bootConfig.attachInterface(&_interface); } HomieClass::~HomieClass() { } void HomieClass::_checkBeforeSetup(const __FlashStringHelper* functionName) const { if (_setupCalled) { _logger.log(F("✖ ")); _logger.log(functionName); _logger.logln(F("(): has to be called before setup()")); _logger.flush(); abort(); } } void HomieClass::setup() { _setupCalled = true; if (!_config.load()) { if (_interface.standalone && !_config.canBypassStandalone()) { _boot = &_bootStandalone; _logger.logln(F("Triggering STANDALONE_MODE event...")); _interface.event.type = HomieEventType::STANDALONE_MODE; _interface.eventHandler(_interface.event); } else { _boot = &_bootConfig; _logger.logln(F("Triggering CONFIGURATION_MODE event...")); _interface.event.type = HomieEventType::CONFIGURATION_MODE; _interface.eventHandler(_interface.event); } } else { switch (_config.getBootMode()) { case BOOT_NORMAL: _boot = &_bootNormal; _logger.logln(F("Triggering NORMAL_MODE event...")); _interface.event.type = HomieEventType::NORMAL_MODE; _interface.eventHandler(_interface.event); break; default: _logger.logln(F("✖ The boot mode is invalid")); _logger.flush(); abort(); break; } } _boot->setup(); } void HomieClass::loop() { _boot->loop(); } HomieClass& HomieClass::disableLogging() { _checkBeforeSetup(F("disableLogging")); _logger.setLogging(false); return *this; } HomieClass& HomieClass::setLoggingPrinter(Print* printer) { _checkBeforeSetup(F("setLoggingPrinter")); _logger.setPrinter(printer); return *this; } HomieClass& HomieClass::disableLedFeedback() { _checkBeforeSetup(F("disableLedFeedback")); _interface.led.enabled = false; return *this; } HomieClass& HomieClass::setLedPin(uint8_t pin, uint8_t on) { _checkBeforeSetup(F("setLedPin")); _interface.led.pin = pin; _interface.led.on = on; return *this; } void HomieClass::__setFirmware(const char* name, const char* version) { _checkBeforeSetup(F("setFirmware")); if (strlen(name) + 1 - 10 > MAX_FIRMWARE_NAME_LENGTH || strlen(version) + 1 - 10 > MAX_FIRMWARE_VERSION_LENGTH) { _logger.logln(F("✖ setFirmware(): either the name or version string is too long")); _logger.flush(); abort(); } strncpy(_interface.firmware.name, name + 5, strlen(name) - 10); _interface.firmware.name[strlen(name) - 10] = '\0'; strncpy(_interface.firmware.version, version + 5, strlen(version) - 10); _interface.firmware.version[strlen(version) - 10] = '\0'; } void HomieClass::__setBrand(const char* brand) { _checkBeforeSetup(F("setBrand")); if (strlen(brand) + 1 - 10 > MAX_BRAND_LENGTH) { _logger.logln(F("✖ setBrand(): the brand string is too long")); _logger.flush(); abort(); } strncpy(_interface.brand, brand + 5, strlen(brand) - 10); _interface.brand[strlen(brand) - 10] = '\0'; } void HomieClass::setIdle(bool idle) { _interface.reset.able = idle; } HomieClass& HomieClass::setGlobalInputHandler(GlobalInputHandler inputHandler) { _checkBeforeSetup(F("setGlobalInputHandler")); _interface.globalInputHandler = inputHandler; return *this; } HomieClass& HomieClass::setResetFunction(ResetFunction function) { _checkBeforeSetup(F("setResetFunction")); _interface.reset.userFunction = function; return *this; } HomieClass& HomieClass::setSetupFunction(OperationFunction function) { _checkBeforeSetup(F("setSetupFunction")); _interface.setupFunction = function; return *this; } HomieClass& HomieClass::setLoopFunction(OperationFunction function) { _checkBeforeSetup(F("setLoopFunction")); _interface.loopFunction = function; return *this; } HomieClass& HomieClass::setStandalone() { _checkBeforeSetup(F("setStandalone")); _interface.standalone = true; return *this; } bool HomieClass::isConfigured() const { return _config.getBootMode() == BOOT_NORMAL; } bool HomieClass::isConnected() const { return _interface.connected; } HomieClass& HomieClass::onEvent(EventHandler handler) { _checkBeforeSetup(F("onEvent")); _interface.eventHandler = handler; return *this; } HomieClass& HomieClass::setResetTrigger(uint8_t pin, uint8_t state, uint16_t time) { _checkBeforeSetup(F("setResetTrigger")); _interface.reset.enabled = true; _interface.reset.triggerPin = pin; _interface.reset.triggerState = state; _interface.reset.triggerTime = time; return *this; } HomieClass& HomieClass::disableResetTrigger() { _checkBeforeSetup(F("disableResetTrigger")); _interface.reset.enabled = false; return *this; } void HomieClass::eraseConfiguration() { _config.erase(); } const ConfigStruct& HomieClass::getConfiguration() const { return _config.get(); } AsyncMqttClient& HomieClass::getMqttClient() { return _mqttClient; } void HomieClass::prepareForSleep() { _boot->prepareForSleep(); } HomieClass Homie;
Fix build error
Fix build error
C++
mit
marvinroger/homie-esp8266,euphi/homie-esp8266,marvinroger/homie-esp8266,euphi/homie-esp8266,marvinroger/homie-esp8266,marvinroger/homie-esp8266,euphi/homie-esp8266,euphi/homie-esp8266
8a3a964a9f9c9e662597f62b293011e0943600b8
chrome/browser/ui/views/sad_tab_view.cc
chrome/browser/ui/views/sad_tab_view.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/sad_tab_view.h" #include <string> #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/feedback/feedback_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/url_constants.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/widget/widget.h" using content::OpenURLParams; using content::WebContents; namespace { const int kPadding = 20; const float kMessageSize = 0.65f; const SkColor kTextColor = SK_ColorWHITE; const SkColor kCrashColor = SkColorSetRGB(35, 48, 64); const SkColor kKillColor = SkColorSetRGB(57, 48, 88); const char kCategoryTagCrash[] = "Crash"; } // namespace SadTabView::SadTabView(WebContents* web_contents, chrome::SadTabKind kind) : web_contents_(web_contents), kind_(kind), painted_(false), message_(NULL), help_link_(NULL), feedback_link_(NULL), reload_button_(NULL) { DCHECK(web_contents); // Sometimes the user will never see this tab, so keep track of the total // number of creation events to compare to display events. // TODO(jamescook): Remove this after R20 stable. Keep it for now so we can // compare R20 to earlier versions. UMA_HISTOGRAM_COUNTS("SadTab.Created", kind_); // These stats should use the same counting approach and bucket size used for // tab discard events in chromeos::OomPriorityManager so they can be // directly compared. // TODO(jamescook): Maybe track time between sad tabs? switch (kind_) { case chrome::SAD_TAB_KIND_CRASHED: { static int crashed = 0; crashed++; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.CrashCreated", crashed, 1, 1000, 50); break; } case chrome::SAD_TAB_KIND_KILLED: { static int killed = 0; killed++; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.KillCreated", killed, 1, 1000, 50); break; } default: NOTREACHED(); } // Set the background color. set_background(views::Background::CreateSolidBackground( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? kCrashColor : kKillColor)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int column_set_id = 0; views::ColumnSet* columns = layout->AddColumnSet(column_set_id); columns->AddPaddingColumn(1, kPadding); columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); columns->AddPaddingColumn(1, kPadding); views::ImageView* image = new views::ImageView(); image->SetImage(ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDR_SAD_TAB : IDR_KILLED_TAB)); layout->StartRowWithPadding(0, column_set_id, 1, kPadding); layout->AddView(image); views::Label* title = CreateLabel(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_TITLE : IDS_KILLED_TAB_TITLE)); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); title->SetFontList(rb.GetFontList(ui::ResourceBundle::MediumFont)); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(title); message_ = CreateLabel(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_MESSAGE : IDS_KILLED_TAB_MESSAGE)); message_->SetMultiLine(true); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(message_); if (web_contents_) { layout->StartRowWithPadding(0, column_set_id, 0, kPadding); reload_button_ = new views::LabelButton( this, l10n_util::GetStringUTF16(IDS_SAD_TAB_RELOAD_LABEL)); reload_button_->SetStyle(views::Button::STYLE_BUTTON); layout->AddView(reload_button_); help_link_ = CreateLink(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_HELP_LINK : IDS_LEARN_MORE)); if (kind_ == chrome::SAD_TAB_KIND_CRASHED) { size_t offset = 0; base::string16 help_text( l10n_util::GetStringFUTF16(IDS_SAD_TAB_HELP_MESSAGE, base::string16(), &offset)); views::Label* help_prefix = CreateLabel(help_text.substr(0, offset)); views::Label* help_suffix = CreateLabel(help_text.substr(offset)); const int help_column_set_id = 1; views::ColumnSet* help_columns = layout->AddColumnSet(help_column_set_id); help_columns->AddPaddingColumn(1, kPadding); // Center three middle columns for the help's [prefix][link][suffix]. for (size_t column = 0; column < 3; column++) help_columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); help_columns->AddPaddingColumn(1, kPadding); layout->StartRowWithPadding(0, help_column_set_id, 0, kPadding); layout->AddView(help_prefix); layout->AddView(help_link_); layout->AddView(help_suffix); } else { layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(help_link_); feedback_link_ = CreateLink( l10n_util::GetStringUTF16(IDS_KILLED_TAB_FEEDBACK_LINK)); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(feedback_link_); } } layout->AddPaddingRow(1, kPadding); } SadTabView::~SadTabView() {} void SadTabView::LinkClicked(views::Link* source, int event_flags) { DCHECK(web_contents_); if (source == help_link_) { GURL help_url((kind_ == chrome::SAD_TAB_KIND_CRASHED) ? chrome::kCrashReasonURL : chrome::kKillReasonURL); OpenURLParams params( help_url, content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); } else if (source == feedback_link_) { chrome::ShowFeedbackPage( chrome::FindBrowserWithWebContents(web_contents_), l10n_util::GetStringUTF8(IDS_KILLED_TAB_FEEDBACK_MESSAGE), std::string(kCategoryTagCrash)); } } void SadTabView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(web_contents_); DCHECK_EQ(reload_button_, sender); web_contents_->GetController().Reload(true); } void SadTabView::Layout() { // Specify the maximum message width explicitly. message_->SizeToFit(static_cast<int>(width() * kMessageSize)); View::Layout(); } void SadTabView::OnPaint(gfx::Canvas* canvas) { if (!painted_) { // User actually saw the error, keep track for user experience stats. // TODO(jamescook): Remove this after R20 stable. Keep it for now so we can // compare R20 to earlier versions. UMA_HISTOGRAM_COUNTS("SadTab.Displayed", kind_); // These stats should use the same counting approach and bucket size used // for tab discard events in chromeos::OomPriorityManager so they // can be directly compared. switch (kind_) { case chrome::SAD_TAB_KIND_CRASHED: { static int crashed = 0; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.CrashDisplayed", ++crashed, 1, 1000, 50); break; } case chrome::SAD_TAB_KIND_KILLED: { static int killed = 0; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.KillDisplayed", ++killed, 1, 1000, 50); break; } default: NOTREACHED(); } painted_ = true; } View::OnPaint(canvas); } void SadTabView::Show() { views::Widget::InitParams sad_tab_params( views::Widget::InitParams::TYPE_CONTROL); // It is not possible to create a native_widget_win that has no parent in // and later re-parent it. // TODO(avi): This is a cheat. Can this be made cleaner? sad_tab_params.parent = web_contents_->GetView()->GetNativeView(); set_owned_by_client(); views::Widget* sad_tab = new views::Widget; sad_tab->Init(sad_tab_params); sad_tab->SetContentsView(this); views::Widget::ReparentNativeView(sad_tab->GetNativeView(), web_contents_->GetView()->GetNativeView()); gfx::Rect bounds; web_contents_->GetView()->GetContainerBounds(&bounds); sad_tab->SetBounds(gfx::Rect(bounds.size())); } void SadTabView::Close() { if (GetWidget()) GetWidget()->Close(); } views::Label* SadTabView::CreateLabel(const base::string16& text) { views::Label* label = new views::Label(text); label->SetBackgroundColor(background()->get_color()); label->SetEnabledColor(kTextColor); return label; } views::Link* SadTabView::CreateLink(const base::string16& text) { views::Link* link = new views::Link(text); link->SetBackgroundColor(background()->get_color()); link->SetEnabledColor(kTextColor); link->set_listener(this); return link; } namespace chrome { SadTab* SadTab::Create(content::WebContents* web_contents, SadTabKind kind) { return new SadTabView(web_contents, kind); } } // namespace chrome
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/sad_tab_view.h" #include <string> #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/feedback/feedback_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/url_constants.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/widget/widget.h" using content::OpenURLParams; using content::WebContents; namespace { const int kPadding = 20; const float kMessageSize = 0.65f; const SkColor kTextColor = SK_ColorWHITE; const SkColor kCrashColor = SkColorSetRGB(35, 48, 64); const SkColor kKillColor = SkColorSetRGB(57, 48, 88); const char kCategoryTagCrash[] = "Crash"; } // namespace SadTabView::SadTabView(WebContents* web_contents, chrome::SadTabKind kind) : web_contents_(web_contents), kind_(kind), painted_(false), message_(NULL), help_link_(NULL), feedback_link_(NULL), reload_button_(NULL) { DCHECK(web_contents); // Sometimes the user will never see this tab, so keep track of the total // number of creation events to compare to display events. // TODO(jamescook): Remove this after R20 stable. Keep it for now so we can // compare R20 to earlier versions. UMA_HISTOGRAM_COUNTS("SadTab.Created", kind_); // These stats should use the same counting approach and bucket size used for // tab discard events in chromeos::OomPriorityManager so they can be // directly compared. // TODO(jamescook): Maybe track time between sad tabs? switch (kind_) { case chrome::SAD_TAB_KIND_CRASHED: { static int crashed = 0; crashed++; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.CrashCreated", crashed, 1, 1000, 50); break; } case chrome::SAD_TAB_KIND_KILLED: { static int killed = 0; killed++; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.KillCreated", killed, 1, 1000, 50); break; } default: NOTREACHED(); } // Set the background color. set_background(views::Background::CreateSolidBackground( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? kCrashColor : kKillColor)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int column_set_id = 0; views::ColumnSet* columns = layout->AddColumnSet(column_set_id); columns->AddPaddingColumn(1, kPadding); columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); columns->AddPaddingColumn(1, kPadding); views::ImageView* image = new views::ImageView(); image->SetImage(ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDR_SAD_TAB : IDR_KILLED_TAB)); layout->StartRowWithPadding(0, column_set_id, 1, kPadding); layout->AddView(image); views::Label* title = CreateLabel(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_TITLE : IDS_KILLED_TAB_TITLE)); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); title->SetFontList(rb.GetFontList(ui::ResourceBundle::MediumFont)); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(title); message_ = CreateLabel(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_MESSAGE : IDS_KILLED_TAB_MESSAGE)); message_->SetMultiLine(true); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(message_); if (web_contents_) { layout->StartRowWithPadding(0, column_set_id, 0, kPadding); reload_button_ = new views::LabelButton( this, l10n_util::GetStringUTF16(IDS_SAD_TAB_RELOAD_LABEL)); reload_button_->SetStyle(views::Button::STYLE_BUTTON); // Always render the reload button with chrome style borders; never rely on // native styles. reload_button_->SetBorder(scoped_ptr<views::Border>( new views::LabelButtonBorder(reload_button_->style()))); layout->AddView(reload_button_); help_link_ = CreateLink(l10n_util::GetStringUTF16( (kind_ == chrome::SAD_TAB_KIND_CRASHED) ? IDS_SAD_TAB_HELP_LINK : IDS_LEARN_MORE)); if (kind_ == chrome::SAD_TAB_KIND_CRASHED) { size_t offset = 0; base::string16 help_text( l10n_util::GetStringFUTF16(IDS_SAD_TAB_HELP_MESSAGE, base::string16(), &offset)); views::Label* help_prefix = CreateLabel(help_text.substr(0, offset)); views::Label* help_suffix = CreateLabel(help_text.substr(offset)); const int help_column_set_id = 1; views::ColumnSet* help_columns = layout->AddColumnSet(help_column_set_id); help_columns->AddPaddingColumn(1, kPadding); // Center three middle columns for the help's [prefix][link][suffix]. for (size_t column = 0; column < 3; column++) help_columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); help_columns->AddPaddingColumn(1, kPadding); layout->StartRowWithPadding(0, help_column_set_id, 0, kPadding); layout->AddView(help_prefix); layout->AddView(help_link_); layout->AddView(help_suffix); } else { layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(help_link_); feedback_link_ = CreateLink( l10n_util::GetStringUTF16(IDS_KILLED_TAB_FEEDBACK_LINK)); layout->StartRowWithPadding(0, column_set_id, 0, kPadding); layout->AddView(feedback_link_); } } layout->AddPaddingRow(1, kPadding); } SadTabView::~SadTabView() {} void SadTabView::LinkClicked(views::Link* source, int event_flags) { DCHECK(web_contents_); if (source == help_link_) { GURL help_url((kind_ == chrome::SAD_TAB_KIND_CRASHED) ? chrome::kCrashReasonURL : chrome::kKillReasonURL); OpenURLParams params( help_url, content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); } else if (source == feedback_link_) { chrome::ShowFeedbackPage( chrome::FindBrowserWithWebContents(web_contents_), l10n_util::GetStringUTF8(IDS_KILLED_TAB_FEEDBACK_MESSAGE), std::string(kCategoryTagCrash)); } } void SadTabView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(web_contents_); DCHECK_EQ(reload_button_, sender); web_contents_->GetController().Reload(true); } void SadTabView::Layout() { // Specify the maximum message width explicitly. message_->SizeToFit(static_cast<int>(width() * kMessageSize)); View::Layout(); } void SadTabView::OnPaint(gfx::Canvas* canvas) { if (!painted_) { // User actually saw the error, keep track for user experience stats. // TODO(jamescook): Remove this after R20 stable. Keep it for now so we can // compare R20 to earlier versions. UMA_HISTOGRAM_COUNTS("SadTab.Displayed", kind_); // These stats should use the same counting approach and bucket size used // for tab discard events in chromeos::OomPriorityManager so they // can be directly compared. switch (kind_) { case chrome::SAD_TAB_KIND_CRASHED: { static int crashed = 0; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.CrashDisplayed", ++crashed, 1, 1000, 50); break; } case chrome::SAD_TAB_KIND_KILLED: { static int killed = 0; UMA_HISTOGRAM_CUSTOM_COUNTS( "Tabs.SadTab.KillDisplayed", ++killed, 1, 1000, 50); break; } default: NOTREACHED(); } painted_ = true; } View::OnPaint(canvas); } void SadTabView::Show() { views::Widget::InitParams sad_tab_params( views::Widget::InitParams::TYPE_CONTROL); // It is not possible to create a native_widget_win that has no parent in // and later re-parent it. // TODO(avi): This is a cheat. Can this be made cleaner? sad_tab_params.parent = web_contents_->GetView()->GetNativeView(); set_owned_by_client(); views::Widget* sad_tab = new views::Widget; sad_tab->Init(sad_tab_params); sad_tab->SetContentsView(this); views::Widget::ReparentNativeView(sad_tab->GetNativeView(), web_contents_->GetView()->GetNativeView()); gfx::Rect bounds; web_contents_->GetView()->GetContainerBounds(&bounds); sad_tab->SetBounds(gfx::Rect(bounds.size())); } void SadTabView::Close() { if (GetWidget()) GetWidget()->Close(); } views::Label* SadTabView::CreateLabel(const base::string16& text) { views::Label* label = new views::Label(text); label->SetBackgroundColor(background()->get_color()); label->SetEnabledColor(kTextColor); return label; } views::Link* SadTabView::CreateLink(const base::string16& text) { views::Link* link = new views::Link(text); link->SetBackgroundColor(background()->get_color()); link->SetEnabledColor(kTextColor); link->set_listener(this); return link; } namespace chrome { SadTab* SadTab::Create(content::WebContents* web_contents, SadTabKind kind) { return new SadTabView(web_contents, kind); } } // namespace chrome
Fix the button on the chrome://kill page.
linux_aura: Fix the button on the chrome://kill page. Provide an escape valve for buttons that really shouldn't be rendered by GTK. BUG=337081 [email protected] Review URL: https://codereview.chromium.org/146193002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@247043 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,ltilve/chromium,Chilledheart/chromium,littlstar/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,anirudhSK/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,anirudhSK/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,dushu1203/chromium.src,dednal/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,Chilledheart/chromium,M4sse/chromium.src,M4sse/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,ltilve/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src
d570c046353d93cfb05fb93d539a9eaad327829a
chrome/common/pepper_plugin_registry.cc
chrome/common/pepper_plugin_registry.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/pepper_plugin_registry.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/native_library.h" #include "base/path_service.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "remoting/client/plugin/pepper_entrypoints.h" namespace { const char* kPDFPluginMimeType = "application/pdf"; const char* kPDFPluginExtension = "pdf"; const char* kPDFPluginDescription = "Portable Document Format"; const char* kNaClPluginName = "Chrome NaCl"; const char* kNaClPluginMimeType = "application/x-nacl"; const char* kNaClPluginExtension = "nexe"; const char* kNaClPluginDescription = "Native Client Executable"; #if defined(ENABLE_REMOTING) const char* kRemotingPluginMimeType = "pepper-application/x-chromoting"; #endif // Appends the known built-in plugins to the given vector. Some built-in // plugins are "internal" which means they are compiled into the Chrome binary, // and some are extra shared libraries distributed with the browser (these are // not marked internal, aside from being automatically registered, they're just // regular plugins). void ComputeBuiltInPlugins(std::vector<PepperPluginInfo>* plugins) { // PDF. // // Once we're sandboxed, we can't know if the PDF plugin is available or not; // but (on Linux) this function is always called once before we're sandboxed. // So the first time through test if the file is available and then skip the // check on subsequent calls if yes. static bool skip_pdf_file_check = false; FilePath path; if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) { if (skip_pdf_file_check || file_util::PathExists(path)) { PepperPluginInfo pdf; pdf.path = path; pdf.name = PepperPluginRegistry::kPDFPluginName; pdf.mime_types.push_back(kPDFPluginMimeType); pdf.file_extensions = kPDFPluginExtension; pdf.type_descriptions = kPDFPluginDescription; plugins->push_back(pdf); skip_pdf_file_check = true; } } // Native client. // // Verify that we enable nacl on the command line. The name of the switch // varies between the browser and renderer process. if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path) && file_util::PathExists(path)) { PepperPluginInfo nacl; nacl.path = path; nacl.name = kNaClPluginName; nacl.mime_types.push_back(kNaClPluginMimeType); // TODO(bbudge) Remove this mime type after NaCl tree has been updated. const char* kNaClPluginOldMimeType = "application/x-ppapi-nacl-srpc"; nacl.mime_types.push_back(kNaClPluginOldMimeType); nacl.file_extensions = kNaClPluginExtension; nacl.type_descriptions = kNaClPluginDescription; plugins->push_back(nacl); } // Remoting. #if defined(ENABLE_REMOTING) if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableRemoting)) { PepperPluginInfo info; info.is_internal = true; info.path = FilePath(FILE_PATH_LITERAL("internal-chromoting")); info.mime_types.push_back(kRemotingPluginMimeType); info.internal_entry_points.get_interface = remoting::PPP_GetInterface; info.internal_entry_points.initialize_module = remoting::PPP_InitializeModule; info.internal_entry_points.shutdown_module = remoting::PPP_ShutdownModule; plugins->push_back(info); } #endif } } // namespace const char* PepperPluginRegistry::kPDFPluginName = "Chrome PDF Viewer"; PepperPluginInfo::PepperPluginInfo() : is_internal(false), is_out_of_process(false) { } PepperPluginInfo::~PepperPluginInfo() {} // static PepperPluginRegistry* PepperPluginRegistry::GetInstance() { static PepperPluginRegistry* registry = NULL; // This object leaks. It is a temporary hack to work around a crash. // http://code.google.com/p/chromium/issues/detail?id=63234 if (!registry) registry = new PepperPluginRegistry; return registry; } // static void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) { ComputeBuiltInPlugins(plugins); GetPluginInfoFromSwitch(plugins); } // static void PepperPluginRegistry::PreloadModules() { std::vector<PepperPluginInfo> plugins; GetList(&plugins); for (size_t i = 0; i < plugins.size(); ++i) { if (!plugins[i].is_internal && !plugins[i].is_out_of_process) { base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path); LOG_IF(WARNING, !library) << "Unable to load plugin " << plugins[i].path.value(); } } } // static void PepperPluginRegistry::GetPluginInfoFromSwitch( std::vector<PepperPluginInfo>* plugins) { const std::string value = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kRegisterPepperPlugins); if (value.empty()) return; bool out_of_process = CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess); // FORMAT: // command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> ) // plugin-entry = <file-path> + ["#" + <name> + ["#" + <description>]] + // *1( LWS + ";" + LWS + <mime-type> ) std::vector<std::string> modules; base::SplitString(value, ',', &modules); for (size_t i = 0; i < modules.size(); ++i) { std::vector<std::string> parts; base::SplitString(modules[i], ';', &parts); if (parts.size() < 2) { DLOG(ERROR) << "Required mime-type not found"; continue; } std::vector<std::string> name_parts; base::SplitString(parts[0], '#', &name_parts); PepperPluginInfo plugin; plugin.is_out_of_process = out_of_process; #if defined(OS_WIN) // This means we can't provide plugins from non-ASCII paths, but // since this switch is only for development I don't think that's // too awful. plugin.path = FilePath(ASCIIToUTF16(name_parts[0])); #else plugin.path = FilePath(name_parts[0]); #endif if (name_parts.size() > 1) plugin.name = name_parts[1]; if (name_parts.size() > 2) { plugin.description = name_parts[2]; plugin.type_descriptions = name_parts[2]; } for (size_t j = 1; j < parts.size(); ++j) plugin.mime_types.push_back(parts[j]); plugins->push_back(plugin); } } PepperPluginInfo* PepperPluginRegistry::GetInfoForPlugin( const FilePath& path) const { // TODO(brettw) don't recompute this every time. But since this Pepper // switch is only for development, it's OK for now. std::vector<PepperPluginInfo> plugins; GetList(&plugins); for (size_t i = 0; i < plugins.size(); ++i) { if (path == plugins[i].path) return new PepperPluginInfo(plugins[i]); } return NULL; } webkit::ppapi::PluginModule* PepperPluginRegistry::GetModule( const FilePath& path) { NonOwningModuleMap::iterator it = live_modules_.find(path); if (it == live_modules_.end()) return NULL; return it->second; } void PepperPluginRegistry::AddLiveModule(const FilePath& path, webkit::ppapi::PluginModule* module) { DCHECK(live_modules_.find(path) == live_modules_.end()); live_modules_[path] = module; } void PepperPluginRegistry::PluginModuleDestroyed( webkit::ppapi::PluginModule* destroyed_module) { // Modules aren't destroyed very often and there are normally at most a // couple of them. So for now we just do a brute-force search. for (NonOwningModuleMap::iterator i = live_modules_.begin(); i != live_modules_.end(); ++i) { if (i->second == destroyed_module) { live_modules_.erase(i); return; } } NOTREACHED(); // Should have always found the module above. } PepperPluginRegistry::~PepperPluginRegistry() { // Explicitly clear all preloaded modules first. This will cause callbacks // to erase these modules from the live_modules_ list, and we don't want // that to happen implicitly out-of-order. preloaded_modules_.clear(); DCHECK(live_modules_.empty()); } PepperPluginRegistry::PepperPluginRegistry() { std::vector<PepperPluginInfo> plugin_info; ComputeBuiltInPlugins(&plugin_info); GetPluginInfoFromSwitch(&plugin_info); // Register modules for these suckers. for (std::vector<PepperPluginInfo>::const_iterator it = plugin_info.begin(); it != plugin_info.end(); ++it) { if (!it->is_internal) continue; const FilePath& path = it->path; scoped_refptr<webkit::ppapi::PluginModule> module( new webkit::ppapi::PluginModule(it->name, this)); if (!module->InitAsInternalPlugin(it->internal_entry_points)) { DLOG(ERROR) << "Failed to load pepper module: " << path.value(); continue; } preloaded_modules_[path] = module; AddLiveModule(path, module); } // Add the modules specified on the command line last so that they can // override the internal plugins. for (size_t i = 0; i < plugin_info.size(); ++i) { if (plugin_info[i].is_internal) continue; if (plugin_info[i].is_out_of_process) continue; // Only preload in-process plugins. const FilePath& path = plugin_info[i].path; scoped_refptr<webkit::ppapi::PluginModule> module( new webkit::ppapi::PluginModule(plugin_info[i].name, this)); // Must call this before bailing out later since the PluginModule's // destructor will call the corresponding Remove in the "continue" case. AddLiveModule(path, module); if (!module->InitAsLibrary(path)) { DLOG(ERROR) << "Failed to load pepper module: " << path.value(); continue; } preloaded_modules_[path] = module; } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/pepper_plugin_registry.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/native_library.h" #include "base/path_service.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "remoting/client/plugin/pepper_entrypoints.h" namespace { const char* kPDFPluginMimeType = "application/pdf"; const char* kPDFPluginExtension = "pdf"; const char* kPDFPluginDescription = "Portable Document Format"; const char* kNaClPluginName = "Chrome NaCl"; const char* kNaClPluginMimeType = "application/x-nacl"; const char* kNaClPluginExtension = "nexe"; const char* kNaClPluginDescription = "Native Client Executable"; #if defined(ENABLE_REMOTING) const char* kRemotingPluginMimeType = "pepper-application/x-chromoting"; #endif // Appends the known built-in plugins to the given vector. Some built-in // plugins are "internal" which means they are compiled into the Chrome binary, // and some are extra shared libraries distributed with the browser (these are // not marked internal, aside from being automatically registered, they're just // regular plugins). void ComputeBuiltInPlugins(std::vector<PepperPluginInfo>* plugins) { // PDF. // // Once we're sandboxed, we can't know if the PDF plugin is available or not; // but (on Linux) this function is always called once before we're sandboxed. // So the first time through test if the file is available and then skip the // check on subsequent calls if yes. static bool skip_pdf_file_check = false; FilePath path; if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) { if (skip_pdf_file_check || file_util::PathExists(path)) { PepperPluginInfo pdf; pdf.path = path; pdf.name = PepperPluginRegistry::kPDFPluginName; pdf.mime_types.push_back(kPDFPluginMimeType); pdf.file_extensions = kPDFPluginExtension; pdf.type_descriptions = kPDFPluginDescription; plugins->push_back(pdf); skip_pdf_file_check = true; } } // Native client. // // Verify that we enable nacl on the command line. The name of the switch // varies between the browser and renderer process. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaCl) && PathService::Get(chrome::FILE_NACL_PLUGIN, &path) && file_util::PathExists(path)) { PepperPluginInfo nacl; nacl.path = path; nacl.name = kNaClPluginName; nacl.mime_types.push_back(kNaClPluginMimeType); // TODO(bbudge) Remove this mime type after NaCl tree has been updated. const char* kNaClPluginOldMimeType = "application/x-ppapi-nacl-srpc"; nacl.mime_types.push_back(kNaClPluginOldMimeType); nacl.file_extensions = kNaClPluginExtension; nacl.type_descriptions = kNaClPluginDescription; plugins->push_back(nacl); } // Remoting. #if defined(ENABLE_REMOTING) if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableRemoting)) { PepperPluginInfo info; info.is_internal = true; info.path = FilePath(FILE_PATH_LITERAL("internal-chromoting")); info.mime_types.push_back(kRemotingPluginMimeType); info.internal_entry_points.get_interface = remoting::PPP_GetInterface; info.internal_entry_points.initialize_module = remoting::PPP_InitializeModule; info.internal_entry_points.shutdown_module = remoting::PPP_ShutdownModule; plugins->push_back(info); } #endif } } // namespace const char* PepperPluginRegistry::kPDFPluginName = "Chrome PDF Viewer"; PepperPluginInfo::PepperPluginInfo() : is_internal(false), is_out_of_process(false) { } PepperPluginInfo::~PepperPluginInfo() {} // static PepperPluginRegistry* PepperPluginRegistry::GetInstance() { static PepperPluginRegistry* registry = NULL; // This object leaks. It is a temporary hack to work around a crash. // http://code.google.com/p/chromium/issues/detail?id=63234 if (!registry) registry = new PepperPluginRegistry; return registry; } // static void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) { ComputeBuiltInPlugins(plugins); GetPluginInfoFromSwitch(plugins); } // static void PepperPluginRegistry::PreloadModules() { std::vector<PepperPluginInfo> plugins; GetList(&plugins); for (size_t i = 0; i < plugins.size(); ++i) { if (!plugins[i].is_internal && !plugins[i].is_out_of_process) { base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path); LOG_IF(WARNING, !library) << "Unable to load plugin " << plugins[i].path.value(); } } } // static void PepperPluginRegistry::GetPluginInfoFromSwitch( std::vector<PepperPluginInfo>* plugins) { const std::string value = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kRegisterPepperPlugins); if (value.empty()) return; bool out_of_process = CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess); // FORMAT: // command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> ) // plugin-entry = <file-path> + ["#" + <name> + ["#" + <description>]] + // *1( LWS + ";" + LWS + <mime-type> ) std::vector<std::string> modules; base::SplitString(value, ',', &modules); for (size_t i = 0; i < modules.size(); ++i) { std::vector<std::string> parts; base::SplitString(modules[i], ';', &parts); if (parts.size() < 2) { DLOG(ERROR) << "Required mime-type not found"; continue; } std::vector<std::string> name_parts; base::SplitString(parts[0], '#', &name_parts); PepperPluginInfo plugin; plugin.is_out_of_process = out_of_process; #if defined(OS_WIN) // This means we can't provide plugins from non-ASCII paths, but // since this switch is only for development I don't think that's // too awful. plugin.path = FilePath(ASCIIToUTF16(name_parts[0])); #else plugin.path = FilePath(name_parts[0]); #endif if (name_parts.size() > 1) plugin.name = name_parts[1]; if (name_parts.size() > 2) { plugin.description = name_parts[2]; plugin.type_descriptions = name_parts[2]; } for (size_t j = 1; j < parts.size(); ++j) plugin.mime_types.push_back(parts[j]); plugins->push_back(plugin); } } PepperPluginInfo* PepperPluginRegistry::GetInfoForPlugin( const FilePath& path) const { // TODO(brettw) don't recompute this every time. But since this Pepper // switch is only for development, it's OK for now. std::vector<PepperPluginInfo> plugins; GetList(&plugins); for (size_t i = 0; i < plugins.size(); ++i) { if (path == plugins[i].path) return new PepperPluginInfo(plugins[i]); } return NULL; } webkit::ppapi::PluginModule* PepperPluginRegistry::GetModule( const FilePath& path) { NonOwningModuleMap::iterator it = live_modules_.find(path); if (it == live_modules_.end()) return NULL; return it->second; } void PepperPluginRegistry::AddLiveModule(const FilePath& path, webkit::ppapi::PluginModule* module) { DCHECK(live_modules_.find(path) == live_modules_.end()); live_modules_[path] = module; } void PepperPluginRegistry::PluginModuleDestroyed( webkit::ppapi::PluginModule* destroyed_module) { // Modules aren't destroyed very often and there are normally at most a // couple of them. So for now we just do a brute-force search. for (NonOwningModuleMap::iterator i = live_modules_.begin(); i != live_modules_.end(); ++i) { if (i->second == destroyed_module) { live_modules_.erase(i); return; } } NOTREACHED(); // Should have always found the module above. } PepperPluginRegistry::~PepperPluginRegistry() { // Explicitly clear all preloaded modules first. This will cause callbacks // to erase these modules from the live_modules_ list, and we don't want // that to happen implicitly out-of-order. preloaded_modules_.clear(); DCHECK(live_modules_.empty()); } PepperPluginRegistry::PepperPluginRegistry() { std::vector<PepperPluginInfo> plugin_info; ComputeBuiltInPlugins(&plugin_info); GetPluginInfoFromSwitch(&plugin_info); // Register modules for these suckers. for (std::vector<PepperPluginInfo>::const_iterator it = plugin_info.begin(); it != plugin_info.end(); ++it) { if (!it->is_internal) continue; const FilePath& path = it->path; scoped_refptr<webkit::ppapi::PluginModule> module( new webkit::ppapi::PluginModule(it->name, this)); if (!module->InitAsInternalPlugin(it->internal_entry_points)) { DLOG(ERROR) << "Failed to load pepper module: " << path.value(); continue; } preloaded_modules_[path] = module; AddLiveModule(path, module); } // Add the modules specified on the command line last so that they can // override the internal plugins. for (size_t i = 0; i < plugin_info.size(); ++i) { if (plugin_info[i].is_internal) continue; if (plugin_info[i].is_out_of_process) continue; // Only preload in-process plugins. const FilePath& path = plugin_info[i].path; scoped_refptr<webkit::ppapi::PluginModule> module( new webkit::ppapi::PluginModule(plugin_info[i].name, this)); // Must call this before bailing out later since the PluginModule's // destructor will call the corresponding Remove in the "continue" case. AddLiveModule(path, module); if (!module->InitAsLibrary(path)) { DLOG(ERROR) << "Failed to load pepper module: " << path.value(); continue; } preloaded_modules_[path] = module; } }
Add check for NaCl being enabled which got lost in my refactoring of the PluginRegistry and is likely the cause of the startup regressions.
Add check for NaCl being enabled which got lost in my refactoring of the PluginRegistry and is likely the cause of the startup regressions. Review URL: http://codereview.chromium.org/6413011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@73944 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium
12b650b1c28cf9fd87011187c875dd153498487f
src/zmqpp/compatibility.hpp
src/zmqpp/compatibility.hpp
/* * 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 is part of zmqpp. * Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file. */ /** * \file * * \date 10 Sep 2011 * \author ron * \author Ben Gray (\@benjamg) * * A fair number of C++0x (or more accurately C++11) features are used in this * library and as this project is used where I work on older compilers this * file was created to help. * * C++ features and their workaround where not supported: * \li lambda functions - disabled, these are only used in the test anyway. * \li typesafe enums - replaced with enum where comparisons needed. * \li nullptr - defined to null. * * As of the port to version 3.1 (libzmqpp version 1.1.0) this file will also * be used to maintain compatablity with multiple versions of 0mq */ #ifndef ZMQPP_COMPATIBILITY_HPP_ #define ZMQPP_COMPATIBILITY_HPP_ #include <zmq.h> // Include export file if on windows, generated by cmake only #if _WIN32 #include "zmqpp_export.h" #else #define ZMQPP_EXPORT #endif // Currently we require at least 0mq version 2.2.x #define ZMQPP_REQUIRED_ZMQ_MAJOR 2 #define ZMQPP_REQUIRED_ZMQ_MINOR 2 #if (ZMQ_VERSION_MAJOR < ZMQPP_REQUIRED_ZMQ_MAJOR) || ((ZMQ_VERSION_MAJOR == ZMQPP_REQUIRED_ZMQ_MAJOR) && (ZMQ_VERSION_MINOR < ZMQPP_REQUIRED_ZMQ_MINOR)) #error zmqpp requires a later version of 0mq #endif // Experimental feature support #if (ZMQ_VERSION_MAJOR == 3) && (ZMQ_VERSION_MINOR == 0) #define ZMQ_EXPERIMENTAL_LABELS #endif // Deal with older versions of gcc #if defined(__GNUC__) && !defined(__clang__) #if __GNUC__ == 4 // Deal with older gcc not supporting C++0x typesafe enum class name {} comparison #if __GNUC_MINOR__ < 4 #define ZMQPP_COMPARABLE_ENUM enum #endif #if __GNUC_MINOR__ == 4 #if __GNUC_PATCHLEVEL__ < 1 #undef ZMQPP_COMPARABLE_ENUM #define ZMQPP_COMPARABLE_ENUM enum #endif // if __GNUC_PATCHLEVEL__ < 1 #endif // if __GNUC_MINOR__ == 4 // Deal with older gcc not supporting C++0x lambda function #if __GNUC_MINOR__ < 5 #define ZMQPP_IGNORE_LAMBDA_FUNCTION_TESTS #define ZMQPP_EXPLICITLY_DELETED #endif // if __GNUC_MINOR__ < 5 // Deal with older gcc not supporting C++0x nullptr #if __GNUC_MINOR__ < 6 #define nullptr NULL #define NOEXCEPT #endif // if __GNUC_MINOR__ < 6 #endif // if __GNUC_ == 4 #endif // if defined(__GNUC__) && !defined(__clang__) #if defined(_MSC_VER) #define NOEXCEPT throw() #if _MSC_VER < 1900 # define ZMQPP_NO_CONSTEXPR #endif #if _MSC_VER < 1800 #define ZMQPP_EXPLICITLY_DELETED #endif // if _MSC_VER < 1800 #if _MSC_VER < 1600 #define nullptr NULL #define ZMQPP_IGNORE_LAMBDA_FUNCTION_TESTS #define ZMQPP_COMPARABLE_ENUM enum #endif // if _MSC_VER < 1600 #endif // if defined(_MSC_VER) // Generic state, assume a modern compiler #ifndef ZMQPP_COMPARABLE_ENUM #define ZMQPP_COMPARABLE_ENUM enum class #endif #ifndef ZMQPP_EXPLICITLY_DELETED #define ZMQPP_EXPLICITLY_DELETED = delete #endif #if __cplusplus >= 201300 // c++14 version. This number worked // on g++ 4.9 when compiling with -std=c++14 #define ZMQPP_DEPRECATED(reason) [[deprecated(#reason)]] #elif __GNUC__ #define ZMQPP_DEPRECATED(reason) __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define ZMQPP_DEPRECATED(reason) __declspec(deprecated(#reason)) #else #define ZMQPP_DEPRECATED(reason) #endif #ifndef NOEXCEPT #define NOEXCEPT noexcept #endif // There are a couple of methods that take a raw socket in form of a 'file descriptor'. Under POSIX // this is simply an int. But under Windows this type must be a SOCKET. In order to hide this // platform detail we create a raw_socket_t which is a SOCKET under Windows and an int on all the // other platforms. This is practically the same as libzmq does with its zmq_pollitem_t struct. namespace zmqpp { #ifdef _WIN32 #if defined _WIN64 typedef unsigned __int64 raw_socket_t; #else typedef unsigned int raw_socket_t; #endif #else typedef int raw_socket_t; #endif } #endif /* ZMQPP_COMPATIBILITY_HPP_ */
/* * 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 is part of zmqpp. * Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file. */ /** * \file * * \date 10 Sep 2011 * \author ron * \author Ben Gray (\@benjamg) * * A fair number of C++0x (or more accurately C++11) features are used in this * library and as this project is used where I work on older compilers this * file was created to help. * * C++ features and their workaround where not supported: * \li lambda functions - disabled, these are only used in the test anyway. * \li typesafe enums - replaced with enum where comparisons needed. * \li nullptr - defined to null. * * As of the port to version 3.1 (libzmqpp version 1.1.0) this file will also * be used to maintain compatablity with multiple versions of 0mq */ #ifndef ZMQPP_COMPATIBILITY_HPP_ #define ZMQPP_COMPATIBILITY_HPP_ #include <zmq.h> // Include export file if on windows, generated by cmake only #ifdef _WIN32 #include "zmqpp_export.h" #else #define ZMQPP_EXPORT #endif // Currently we require at least 0mq version 2.2.x #define ZMQPP_REQUIRED_ZMQ_MAJOR 2 #define ZMQPP_REQUIRED_ZMQ_MINOR 2 #if (ZMQ_VERSION_MAJOR < ZMQPP_REQUIRED_ZMQ_MAJOR) || ((ZMQ_VERSION_MAJOR == ZMQPP_REQUIRED_ZMQ_MAJOR) && (ZMQ_VERSION_MINOR < ZMQPP_REQUIRED_ZMQ_MINOR)) #error zmqpp requires a later version of 0mq #endif // Experimental feature support #if (ZMQ_VERSION_MAJOR == 3) && (ZMQ_VERSION_MINOR == 0) #define ZMQ_EXPERIMENTAL_LABELS #endif // Deal with older versions of gcc #if defined(__GNUC__) && !defined(__clang__) #if __GNUC__ == 4 // Deal with older gcc not supporting C++0x typesafe enum class name {} comparison #if __GNUC_MINOR__ < 4 #define ZMQPP_COMPARABLE_ENUM enum #endif #if __GNUC_MINOR__ == 4 #if __GNUC_PATCHLEVEL__ < 1 #undef ZMQPP_COMPARABLE_ENUM #define ZMQPP_COMPARABLE_ENUM enum #endif // if __GNUC_PATCHLEVEL__ < 1 #endif // if __GNUC_MINOR__ == 4 // Deal with older gcc not supporting C++0x lambda function #if __GNUC_MINOR__ < 5 #define ZMQPP_IGNORE_LAMBDA_FUNCTION_TESTS #define ZMQPP_EXPLICITLY_DELETED #endif // if __GNUC_MINOR__ < 5 // Deal with older gcc not supporting C++0x nullptr #if __GNUC_MINOR__ < 6 #define nullptr NULL #define NOEXCEPT #endif // if __GNUC_MINOR__ < 6 #endif // if __GNUC_ == 4 #endif // if defined(__GNUC__) && !defined(__clang__) #if defined(_MSC_VER) #define NOEXCEPT throw() #if _MSC_VER < 1900 # define ZMQPP_NO_CONSTEXPR #endif #if _MSC_VER < 1800 #define ZMQPP_EXPLICITLY_DELETED #endif // if _MSC_VER < 1800 #if _MSC_VER < 1600 #define nullptr NULL #define ZMQPP_IGNORE_LAMBDA_FUNCTION_TESTS #define ZMQPP_COMPARABLE_ENUM enum #endif // if _MSC_VER < 1600 #endif // if defined(_MSC_VER) // Generic state, assume a modern compiler #ifndef ZMQPP_COMPARABLE_ENUM #define ZMQPP_COMPARABLE_ENUM enum class #endif #ifndef ZMQPP_EXPLICITLY_DELETED #define ZMQPP_EXPLICITLY_DELETED = delete #endif #if __cplusplus >= 201300 // c++14 version. This number worked // on g++ 4.9 when compiling with -std=c++14 #define ZMQPP_DEPRECATED(reason) [[deprecated(#reason)]] #elif __GNUC__ #define ZMQPP_DEPRECATED(reason) __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define ZMQPP_DEPRECATED(reason) __declspec(deprecated(#reason)) #else #define ZMQPP_DEPRECATED(reason) #endif #ifndef NOEXCEPT #define NOEXCEPT noexcept #endif // There are a couple of methods that take a raw socket in form of a 'file descriptor'. Under POSIX // this is simply an int. But under Windows this type must be a SOCKET. In order to hide this // platform detail we create a raw_socket_t which is a SOCKET under Windows and an int on all the // other platforms. This is practically the same as libzmq does with its zmq_pollitem_t struct. namespace zmqpp { #ifdef _WIN32 #if defined _WIN64 typedef unsigned __int64 raw_socket_t; #else typedef unsigned int raw_socket_t; #endif #else typedef int raw_socket_t; #endif } #endif /* ZMQPP_COMPATIBILITY_HPP_ */
Allow building with `-Werror=undef`
Allow building with `-Werror=undef` `#if` will create an error when building with `-Werror=undef`. The same test is done with `#ifdef` in other places in the code.
C++
mpl-2.0
zeromq/zmqpp,zeromq/zmqpp
a520d6cc38dd13c68bf7fac24a919ec8b0bfcdfe
mediapipe/gpu/gpu_buffer_multi_pool.cc
mediapipe/gpu/gpu_buffer_multi_pool.cc
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/gpu/gpu_buffer_multi_pool.h" #include <tuple> #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/gpu/gpu_shared_data_internal.h" #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER #include "CoreFoundation/CFBase.h" #include "mediapipe/objc/CFHolder.h" #include "mediapipe/objc/util.h" #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER namespace mediapipe { // Keep this many buffers allocated for a given frame size. static constexpr int kKeepCount = 2; // The maximum size of the GpuBufferMultiPool. When the limit is reached, the // oldest BufferSpec will be dropped. static constexpr int kMaxPoolCount = 10; // Time in seconds after which an inactive buffer can be dropped from the pool. // Currently only used with CVPixelBufferPool. static constexpr float kMaxInactiveBufferAge = 0.25; // Skip allocating a buffer pool until at least this many requests have been // made for a given BufferSpec. static constexpr int kMinRequestsBeforePool = 2; // Do a deeper flush every this many requests. static constexpr int kRequestCountScrubInterval = 50; #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER CvPixelBufferPoolWrapper::CvPixelBufferPoolWrapper( const GpuBufferMultiPool::BufferSpec& spec, CFTimeInterval maxAge) { OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); CHECK_NE(cv_format, -1) << "unsupported pixel format"; pool_ = MakeCFHolderAdopting( /* keep count is 0 because the age param keeps buffers around anyway */ CreateCVPixelBufferPool(spec.width, spec.height, cv_format, 0, maxAge)); } GpuBuffer CvPixelBufferPoolWrapper::GetBuffer(std::function<void(void)> flush) { CVPixelBufferRef buffer; int threshold = 1; NSMutableDictionary* auxAttributes = [NSMutableDictionary dictionaryWithCapacity:1]; CVReturn err; bool tried_flushing = false; while (1) { auxAttributes[(id)kCVPixelBufferPoolAllocationThresholdKey] = @(threshold); err = CVPixelBufferPoolCreatePixelBufferWithAuxAttributes( kCFAllocatorDefault, *pool_, (__bridge CFDictionaryRef)auxAttributes, &buffer); if (err != kCVReturnWouldExceedAllocationThreshold) break; if (flush && !tried_flushing) { // Call the flush function to potentially release old holds on buffers // and try again to create a pixel buffer. // This is used to flush CV texture caches, which may retain buffers until // flushed. flush(); tried_flushing = true; } else { ++threshold; } } CHECK(!err) << "Error creating pixel buffer: " << err; count_ = threshold; return GpuBuffer(MakeCFHolderAdopting(buffer)); } std::string CvPixelBufferPoolWrapper::GetDebugString() const { auto description = MakeCFHolderAdopting(CFCopyDescription(*pool_)); return [(__bridge NSString*)*description UTF8String]; } void CvPixelBufferPoolWrapper::Flush() { CVPixelBufferPoolFlush(*pool_, 0); } std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::MakeSimplePool(const GpuBufferMultiPool::BufferSpec& spec) { return std::make_shared<CvPixelBufferPoolWrapper>(spec, kMaxInactiveBufferAge); } GpuBuffer GpuBufferMultiPool::GetBufferWithoutPool(const BufferSpec& spec) { OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); CHECK_NE(cv_format, -1) << "unsupported pixel format"; CVPixelBufferRef buffer; CVReturn err = CreateCVPixelBufferWithoutPool(spec.width, spec.height, cv_format, &buffer); CHECK(!err) << "Error creating pixel buffer: " << err; return GpuBuffer(MakeCFHolderAdopting(buffer)); } void GpuBufferMultiPool::FlushTextureCaches() { absl::MutexLock lock(&mutex_); for (const auto& cache : texture_caches_) { #if TARGET_OS_OSX CVOpenGLTextureCacheFlush(*cache, 0); #else CVOpenGLESTextureCacheFlush(*cache, 0); #endif // TARGET_OS_OSX } } // Turning this on disables the pixel buffer pools when using the simulator. // It is no longer necessary, since the helper code now supports non-contiguous // buffers. We leave the code in for now for the sake of documentation. #define FORCE_CONTIGUOUS_PIXEL_BUFFER_ON_IPHONE_SIMULATOR 0 GpuBuffer GpuBufferMultiPool::GetBufferFromSimplePool( BufferSpec spec, GpuBufferMultiPool::SimplePool& pool) { #if TARGET_IPHONE_SIMULATOR && FORCE_CONTIGUOUS_PIXEL_BUFFER_ON_IPHONE_SIMULATOR // On the simulator, syncing the texture with the pixelbuffer does not work, // and we have to use glReadPixels. Since GL_UNPACK_ROW_LENGTH is not // available in OpenGL ES 2, we should create the buffer so the pixels are // contiguous. // // TODO: verify if we can use kIOSurfaceBytesPerRow to force the // pool to give us contiguous data. return GetBufferWithoutPool(spec); #else return pool.GetBuffer([this]() { FlushTextureCaches(); }); #endif // TARGET_IPHONE_SIMULATOR } #else std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::MakeSimplePool(const BufferSpec& spec) { return GlTextureBufferPool::Create(spec.width, spec.height, spec.format, kKeepCount); } GpuBuffer GpuBufferMultiPool::GetBufferWithoutPool(const BufferSpec& spec) { return GpuBuffer( GlTextureBuffer::Create(spec.width, spec.height, spec.format)); } GpuBuffer GpuBufferMultiPool::GetBufferFromSimplePool( BufferSpec spec, GpuBufferMultiPool::SimplePool& pool) { return GpuBuffer(pool.GetBuffer()); } #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::RequestPool( const BufferSpec& spec) { std::shared_ptr<SimplePool> pool; std::vector<std::shared_ptr<SimplePool>> evicted; { absl::MutexLock lock(&mutex_); pool = cache_.Lookup(spec, [this](const BufferSpec& spec, int request_count) { return (request_count >= kMinRequestsBeforePool) ? MakeSimplePool(spec) : nullptr; }); evicted = cache_.Evict(kMaxPoolCount, kRequestCountScrubInterval); } // Evicted pools, and their buffers, will be released without holding the // lock. return pool; } GpuBuffer GpuBufferMultiPool::GetBuffer(int width, int height, GpuBufferFormat format) { BufferSpec key(width, height, format); std::shared_ptr<SimplePool> pool = RequestPool(key); if (pool) { // Note: we release our multipool lock before accessing the simple pool. return GetBufferFromSimplePool(key, *pool); } else { return GetBufferWithoutPool(key); } } GpuBufferMultiPool::~GpuBufferMultiPool() { #ifdef __APPLE__ CHECK_EQ(texture_caches_.size(), 0) << "Failed to unregister texture caches before deleting pool"; #endif // defined(__APPLE__) } #ifdef __APPLE__ void GpuBufferMultiPool::RegisterTextureCache(CVTextureCacheType cache) { absl::MutexLock lock(&mutex_); CHECK(std::find(texture_caches_.begin(), texture_caches_.end(), cache) == texture_caches_.end()) << "Attempting to register a texture cache twice"; texture_caches_.emplace_back(cache); } void GpuBufferMultiPool::UnregisterTextureCache(CVTextureCacheType cache) { absl::MutexLock lock(&mutex_); auto it = std::find(texture_caches_.begin(), texture_caches_.end(), cache); CHECK(it != texture_caches_.end()) << "Attempting to unregister an unknown texture cache"; texture_caches_.erase(it); } #endif // defined(__APPLE__) } // namespace mediapipe
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/gpu/gpu_buffer_multi_pool.h" #include <tuple> #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/gpu/gpu_shared_data_internal.h" #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER #include "CoreFoundation/CFBase.h" #include "mediapipe/objc/CFHolder.h" #include "mediapipe/objc/util.h" #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER namespace mediapipe { // Keep this many buffers allocated for a given frame size. static constexpr int kKeepCount = 2; // The maximum size of the GpuBufferMultiPool. When the limit is reached, the // oldest BufferSpec will be dropped. static constexpr int kMaxPoolCount = 10; // Time in seconds after which an inactive buffer can be dropped from the pool. // Currently only used with CVPixelBufferPool. static constexpr float kMaxInactiveBufferAge = 0.25; // Skip allocating a buffer pool until at least this many requests have been // made for a given BufferSpec. static constexpr int kMinRequestsBeforePool = 2; // Do a deeper flush every this many requests. static constexpr int kRequestCountScrubInterval = 50; #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER CvPixelBufferPoolWrapper::CvPixelBufferPoolWrapper( const GpuBufferMultiPool::BufferSpec& spec, CFTimeInterval maxAge) { OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); CHECK_NE(cv_format, -1) << "unsupported pixel format"; pool_ = MakeCFHolderAdopting( /* keep count is 0 because the age param keeps buffers around anyway */ CreateCVPixelBufferPool(spec.width, spec.height, cv_format, 0, maxAge)); } GpuBuffer CvPixelBufferPoolWrapper::GetBuffer(std::function<void(void)> flush) { CVPixelBufferRef buffer; int threshold = 1; NSMutableDictionary* auxAttributes = [NSMutableDictionary dictionaryWithCapacity:1]; CVReturn err; bool tried_flushing = false; while (1) { auxAttributes[(id)kCVPixelBufferPoolAllocationThresholdKey] = @(threshold); err = CVPixelBufferPoolCreatePixelBufferWithAuxAttributes( kCFAllocatorDefault, *pool_, (__bridge CFDictionaryRef)auxAttributes, &buffer); if (err != kCVReturnWouldExceedAllocationThreshold) break; if (flush && !tried_flushing) { // Call the flush function to potentially release old holds on buffers // and try again to create a pixel buffer. // This is used to flush CV texture caches, which may retain buffers until // flushed. flush(); tried_flushing = true; } else { ++threshold; } } CHECK(!err) << "Error creating pixel buffer: " << err; count_ = threshold; return GpuBuffer(MakeCFHolderAdopting(buffer)); } std::string CvPixelBufferPoolWrapper::GetDebugString() const { auto description = MakeCFHolderAdopting(CFCopyDescription(*pool_)); return [(__bridge NSString*)*description UTF8String]; } void CvPixelBufferPoolWrapper::Flush() { CVPixelBufferPoolFlush(*pool_, 0); } std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::MakeSimplePool(const GpuBufferMultiPool::BufferSpec& spec) { return std::make_shared<CvPixelBufferPoolWrapper>(spec, kMaxInactiveBufferAge); } GpuBuffer GpuBufferMultiPool::GetBufferWithoutPool(const BufferSpec& spec) { OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); CHECK_NE(cv_format, -1) << "unsupported pixel format"; CVPixelBufferRef buffer; CVReturn err = CreateCVPixelBufferWithoutPool(spec.width, spec.height, cv_format, &buffer); CHECK(!err) << "Error creating pixel buffer: " << err; return GpuBuffer(MakeCFHolderAdopting(buffer)); } void GpuBufferMultiPool::FlushTextureCaches() { absl::MutexLock lock(&mutex_); for (const auto& cache : texture_caches_) { #if TARGET_OS_OSX CVOpenGLTextureCacheFlush(*cache, 0); #else CVOpenGLESTextureCacheFlush(*cache, 0); #endif // TARGET_OS_OSX } } GpuBuffer GpuBufferMultiPool::GetBufferFromSimplePool( BufferSpec spec, GpuBufferMultiPool::SimplePool& pool) { return pool.GetBuffer([this]() { FlushTextureCaches(); }); } #else std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::MakeSimplePool(const BufferSpec& spec) { return GlTextureBufferPool::Create(spec.width, spec.height, spec.format, kKeepCount); } GpuBuffer GpuBufferMultiPool::GetBufferWithoutPool(const BufferSpec& spec) { return GpuBuffer( GlTextureBuffer::Create(spec.width, spec.height, spec.format)); } GpuBuffer GpuBufferMultiPool::GetBufferFromSimplePool( BufferSpec spec, GpuBufferMultiPool::SimplePool& pool) { return GpuBuffer(pool.GetBuffer()); } #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER std::shared_ptr<GpuBufferMultiPool::SimplePool> GpuBufferMultiPool::RequestPool( const BufferSpec& spec) { std::shared_ptr<SimplePool> pool; std::vector<std::shared_ptr<SimplePool>> evicted; { absl::MutexLock lock(&mutex_); pool = cache_.Lookup(spec, [this](const BufferSpec& spec, int request_count) { return (request_count >= kMinRequestsBeforePool) ? MakeSimplePool(spec) : nullptr; }); evicted = cache_.Evict(kMaxPoolCount, kRequestCountScrubInterval); } // Evicted pools, and their buffers, will be released without holding the // lock. return pool; } GpuBuffer GpuBufferMultiPool::GetBuffer(int width, int height, GpuBufferFormat format) { BufferSpec key(width, height, format); std::shared_ptr<SimplePool> pool = RequestPool(key); if (pool) { // Note: we release our multipool lock before accessing the simple pool. return GetBufferFromSimplePool(key, *pool); } else { return GetBufferWithoutPool(key); } } GpuBufferMultiPool::~GpuBufferMultiPool() { #ifdef __APPLE__ CHECK_EQ(texture_caches_.size(), 0) << "Failed to unregister texture caches before deleting pool"; #endif // defined(__APPLE__) } #ifdef __APPLE__ void GpuBufferMultiPool::RegisterTextureCache(CVTextureCacheType cache) { absl::MutexLock lock(&mutex_); CHECK(std::find(texture_caches_.begin(), texture_caches_.end(), cache) == texture_caches_.end()) << "Attempting to register a texture cache twice"; texture_caches_.emplace_back(cache); } void GpuBufferMultiPool::UnregisterTextureCache(CVTextureCacheType cache) { absl::MutexLock lock(&mutex_); auto it = std::find(texture_caches_.begin(), texture_caches_.end(), cache); CHECK(it != texture_caches_.end()) << "Attempting to unregister an unknown texture cache"; texture_caches_.erase(it); } #endif // defined(__APPLE__) } // namespace mediapipe
Remove FORCE_CONTIGUOUS_PIXEL_BUFFER_ON_IPHONE_SIMULATOR
Remove FORCE_CONTIGUOUS_PIXEL_BUFFER_ON_IPHONE_SIMULATOR This workaround code is no longer necessary, as per the comment. PiperOrigin-RevId: 488777606
C++
apache-2.0
google/mediapipe,google/mediapipe,google/mediapipe,google/mediapipe,google/mediapipe,google/mediapipe,google/mediapipe,google/mediapipe
9a857cd78ea3ea001d0bc56b0e709905b6661c6e
src/bindings.cc
src/bindings.cc
// Copyright 2015, Camilo Aguilar #include "bindings.h" /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) namespace NodeInotify { void Inotify::Initialize(Handle<Object> exports) { Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); t->SetClassName(Nan::New<String>("Inotify").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "addWatch", Inotify::AddWatch); Nan::SetPrototypeMethod(t, "removeWatch", Inotify::RemoveWatch); Nan::SetPrototypeMethod(t, "close", Inotify::Close); Local<ObjectTemplate> object_tmpl = t->InstanceTemplate(); Nan::SetAccessor(object_tmpl, Nan::New<String>("persistent").ToLocalChecked(), Inotify::GetPersistent); Local<Function> fn = t->GetFunction(); exports->Set(Nan::New<String>("Inotify").ToLocalChecked(), fn); // Constants initialization NODE_DEFINE_CONSTANT(fn, IN_ACCESS); //File was accessed (read) NODE_DEFINE_CONSTANT(fn, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps, //extended attributes, link count (since Linux 2.6.25), //UID, GID, etc. NODE_DEFINE_CONSTANT(fn, IN_CLOSE_WRITE); //File opened for writing was closed NODE_DEFINE_CONSTANT(fn, IN_CLOSE_NOWRITE); //File not opened for writing was closed NODE_DEFINE_CONSTANT(fn, IN_CREATE); //File/directory created in watched directory NODE_DEFINE_CONSTANT(fn, IN_DELETE); //File/directory deleted from watched directory NODE_DEFINE_CONSTANT(fn, IN_DELETE_SELF); //Watched file/directory was itself deleted NODE_DEFINE_CONSTANT(fn, IN_MODIFY); //File was modified NODE_DEFINE_CONSTANT(fn, IN_MOVE_SELF); //Watched file/directory was itself moved NODE_DEFINE_CONSTANT(fn, IN_MOVED_FROM); //File moved out of watched directory NODE_DEFINE_CONSTANT(fn, IN_MOVED_TO); //File moved into watched directory NODE_DEFINE_CONSTANT(fn, IN_OPEN); //File was opened NODE_DEFINE_CONSTANT(fn, IN_IGNORED);// Watch was removed explicitly (inotify.watch.rm) or // automatically (file was deleted, or file system was // unmounted) NODE_DEFINE_CONSTANT(fn, IN_ISDIR); //Subject of this event is a directory NODE_DEFINE_CONSTANT(fn, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event) NODE_DEFINE_CONSTANT(fn, IN_UNMOUNT); //File system containing watched object was unmounted NODE_DEFINE_CONSTANT(fn, IN_ALL_EVENTS); NODE_DEFINE_CONSTANT(fn, IN_ONLYDIR); // Only watch the path if it is a directory. NODE_DEFINE_CONSTANT(fn, IN_DONT_FOLLOW); // Do not follow a sym link NODE_DEFINE_CONSTANT(fn, IN_ONESHOT); // Only send event once NODE_DEFINE_CONSTANT(fn, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it // already exists (instead of replacing mask). NODE_DEFINE_CONSTANT(fn, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close NODE_DEFINE_CONSTANT(fn, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves } Inotify::Inotify() : Nan::ObjectWrap() { //ev_init(&read_watcher, Inotify::Callback); read_watcher = new uv_poll_t; read_watcher->data = this; //preserving my reference to use it inside Inotify::Callback //uv_poll_init(uv_default_loop(), &read_watcher, Inotify::Callback); persistent = true; poll_stopped = 0; } Inotify::Inotify(bool nonpersistent) : Nan::ObjectWrap() { read_watcher = new uv_poll_t; read_watcher->data = this; //preserving my reference so that we can use it inside Inotify::Callback //ev_init(&read_watcher, Inotify::Callback); persistent = nonpersistent; poll_stopped = 0; } Inotify::~Inotify() { if(!persistent) { //ev_ref(EV_DEFAULT_UC); uv_ref((uv_handle_t *) read_watcher); } //ev_io_stop(EV_DEFAULT_UC_ &read_watcher); // if Inotify::Close() was already called we do not need to // stop polling again thus it causes fail of assertion test StopPolling(); //assert(!uv_is_pending(&read_watcher)); } NAN_METHOD(Inotify::New) { Nan::HandleScope scope; Inotify *inotify = NULL; if(info.Length() == 1 && info[0]->IsBoolean()) { inotify = new Inotify(info[0]->IsTrue()); } else { inotify = new Inotify(); } inotify->fd = inotify_init(); if(inotify->fd == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::Null()); } int flags = fcntl(inotify->fd, F_GETFL); if(flags == -1) { flags = 0; } fcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK); //ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ); //ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher); uv_poll_init(uv_default_loop(), inotify->read_watcher, inotify->fd); uv_poll_start(inotify->read_watcher, UV_READABLE, Inotify::Callback); Local<Object> obj = info.This(); inotify->Wrap(obj); if(!inotify->persistent) { //ev_unref(EV_DEFAULT_UC); uv_unref((uv_handle_t *) inotify->read_watcher); } /** * Increment object references to avoid be GCed while * we are waiting for events in the inotify file descriptor. * Also, the object is not weak anymore. */ inotify->Ref(); info.GetReturnValue().Set(obj); } NAN_METHOD(Inotify::AddWatch) { Nan::HandleScope scope; uint32_t mask = 0; int watch_descriptor = 0; if(info.Length() < 1 || !info[0]->IsObject()) { return Nan::ThrowTypeError("You must specify an object as first argument"); } Local<Object> args_ = info[0]->ToObject(); Local<String> path_sym = Nan::New<String>("path").ToLocalChecked(); if (!args_->Has(path_sym)) { return Nan::ThrowTypeError("You must specify a path to watch for events"); } Local<String> callback_sym = Nan::New<String>("callback").ToLocalChecked(); if (!args_->Has(callback_sym) || !args_->Get(callback_sym)->IsFunction()) { return Nan::ThrowTypeError("You must specify a callback function"); } Local<String> watch_for_sym = Nan::New<String>("watch_for").ToLocalChecked(); if (!args_->Has(watch_for_sym)) { mask |= IN_ALL_EVENTS; } else { if (!args_->Get(watch_for_sym)->IsInt32()) { return Nan::ThrowTypeError("You must specify OR'ed set of events"); } mask |= args_->Get(watch_for_sym)->Int32Value(); if (mask == 0) { return Nan::ThrowTypeError("You must specify OR'ed set of events"); } } String::Utf8Value path(args_->Get(path_sym)); Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); /* add watch */ watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask); Local<Integer> descriptor = Nan::New<Integer>(watch_descriptor); //Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym)); inotify->handle()->Set(descriptor, args_->Get(callback_sym)); info.GetReturnValue().Set(descriptor); } NAN_METHOD(Inotify::RemoveWatch) { Nan::HandleScope scope; uint32_t watch = 0; int ret = -1; if(info.Length() == 0 || !info[0]->IsInt32()) { return Nan::ThrowTypeError("You must specify a valid watcher descriptor as argument"); } watch = info[0]->Int32Value(); Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); ret = inotify_rm_watch(inotify->fd, watch); if(ret == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::False()); } info.GetReturnValue().Set(Nan::True()); } void Inotify::on_handle_close(uv_handle_t* handle) { assert(!uv_is_active(handle)); delete handle; } NAN_METHOD(Inotify::Close) { Nan::HandleScope scope; int ret = -1; Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); ret = close(inotify->fd); if (ret == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::False()); } if (!inotify->persistent) { //ev_ref(EV_DEFAULT_UC); uv_ref((uv_handle_t *) inotify->read_watcher); } //ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher); inotify->StopPolling(); /*Eliminating reference created inside of Inotify::New. The object is also weak again. Now v8 can do its stuff and GC the object. */ inotify->Unref(); info.GetReturnValue().Set(Nan::True()); } void Inotify::Callback(uv_poll_t *watcher, int status, int revents) { Nan::HandleScope scope; Inotify *inotify = static_cast<Inotify*>(watcher->data); assert(watcher == inotify->read_watcher); char buffer[BUF_LEN]; //int length = read(inotify->fd, buffer, BUF_LEN); Local<Value> argv[1]; Nan::TryCatch try_catch; int sz = 0; while ((sz = read(inotify->fd, buffer, BUF_LEN)) > 0) { struct inotify_event *event; for (unsigned int i = 0; i <= (sz-EVENT_SIZE); i += (EVENT_SIZE + event->len)) { event = (struct inotify_event *) &buffer[i]; Local<Object> obj = Nan::New<Object>(); obj->Set(Nan::New<String>("watch").ToLocalChecked(), Nan::New<Integer>(event->wd)); obj->Set(Nan::New<String>("mask").ToLocalChecked(), Nan::New<Integer>(event->mask)); obj->Set(Nan::New<String>("cookie").ToLocalChecked(), Nan::New<Integer>(event->cookie)); if(event->len) { obj->Set(Nan::New<String>("name").ToLocalChecked(), Nan::New<String>(event->name).ToLocalChecked()); } argv[0] = obj; inotify->Ref(); Local<Object> handle = inotify->handle(); Local<Value> callback_ = handle->Get(Nan::New<Integer>(event->wd)); Local<Function> callback = Local<Function>::Cast(callback_); callback->Call(handle, 1, argv); inotify->Unref(); if(event->mask & IN_IGNORED) { //deleting callback because the watch was removed Local<Value> wd = Nan::New<Integer>(event->wd); handle->Delete(wd->ToString()); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } // for } // while } NAN_GETTER(Inotify::GetPersistent) { Nan::HandleScope scope; Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); if (inotify->persistent) { info.GetReturnValue().Set(Nan::True()); } info.GetReturnValue().Set(Nan::False()); } void Inotify::StopPolling() { if (!poll_stopped) { uv_poll_stop(read_watcher); uv_close((uv_handle_t *) read_watcher, Inotify::on_handle_close); poll_stopped = 1; } } }//namespace NodeInotify
// Copyright 2015, Camilo Aguilar #include "bindings.h" /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) namespace NodeInotify { void Inotify::Initialize(Handle<Object> exports) { Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); t->SetClassName(Nan::New<String>("Inotify").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "addWatch", Inotify::AddWatch); Nan::SetPrototypeMethod(t, "removeWatch", Inotify::RemoveWatch); Nan::SetPrototypeMethod(t, "close", Inotify::Close); Local<ObjectTemplate> object_tmpl = t->InstanceTemplate(); Nan::SetAccessor(object_tmpl, Nan::New<String>("persistent").ToLocalChecked(), Inotify::GetPersistent); Local<Function> fn = t->GetFunction(); exports->Set(Nan::New<String>("Inotify").ToLocalChecked(), fn); // Constants initialization NODE_DEFINE_CONSTANT(fn, IN_ACCESS); //File was accessed (read) NODE_DEFINE_CONSTANT(fn, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps, //extended attributes, link count (since Linux 2.6.25), //UID, GID, etc. NODE_DEFINE_CONSTANT(fn, IN_CLOSE_WRITE); //File opened for writing was closed NODE_DEFINE_CONSTANT(fn, IN_CLOSE_NOWRITE); //File not opened for writing was closed NODE_DEFINE_CONSTANT(fn, IN_CREATE); //File/directory created in watched directory NODE_DEFINE_CONSTANT(fn, IN_DELETE); //File/directory deleted from watched directory NODE_DEFINE_CONSTANT(fn, IN_DELETE_SELF); //Watched file/directory was itself deleted NODE_DEFINE_CONSTANT(fn, IN_MODIFY); //File was modified NODE_DEFINE_CONSTANT(fn, IN_MOVE_SELF); //Watched file/directory was itself moved NODE_DEFINE_CONSTANT(fn, IN_MOVED_FROM); //File moved out of watched directory NODE_DEFINE_CONSTANT(fn, IN_MOVED_TO); //File moved into watched directory NODE_DEFINE_CONSTANT(fn, IN_OPEN); //File was opened NODE_DEFINE_CONSTANT(fn, IN_IGNORED);// Watch was removed explicitly (inotify.watch.rm) or // automatically (file was deleted, or file system was // unmounted) NODE_DEFINE_CONSTANT(fn, IN_ISDIR); //Subject of this event is a directory NODE_DEFINE_CONSTANT(fn, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event) NODE_DEFINE_CONSTANT(fn, IN_UNMOUNT); //File system containing watched object was unmounted NODE_DEFINE_CONSTANT(fn, IN_ALL_EVENTS); NODE_DEFINE_CONSTANT(fn, IN_ONLYDIR); // Only watch the path if it is a directory. NODE_DEFINE_CONSTANT(fn, IN_DONT_FOLLOW); // Do not follow a sym link NODE_DEFINE_CONSTANT(fn, IN_ONESHOT); // Only send event once NODE_DEFINE_CONSTANT(fn, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it // already exists (instead of replacing mask). NODE_DEFINE_CONSTANT(fn, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close NODE_DEFINE_CONSTANT(fn, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves } Inotify::Inotify() : Nan::ObjectWrap() { //ev_init(&read_watcher, Inotify::Callback); read_watcher = new uv_poll_t; read_watcher->data = this; //preserving my reference to use it inside Inotify::Callback //uv_poll_init(uv_default_loop(), &read_watcher, Inotify::Callback); persistent = true; poll_stopped = 0; } Inotify::Inotify(bool nonpersistent) : Nan::ObjectWrap() { read_watcher = new uv_poll_t; read_watcher->data = this; //preserving my reference so that we can use it inside Inotify::Callback //ev_init(&read_watcher, Inotify::Callback); persistent = nonpersistent; poll_stopped = 0; } Inotify::~Inotify() { if(!persistent) { //ev_ref(EV_DEFAULT_UC); uv_ref((uv_handle_t *) read_watcher); } //ev_io_stop(EV_DEFAULT_UC_ &read_watcher); // if Inotify::Close() was already called we do not need to // stop polling again thus it causes fail of assertion test StopPolling(); //assert(!uv_is_pending(&read_watcher)); } NAN_METHOD(Inotify::New) { Nan::HandleScope scope; Inotify *inotify = NULL; if(info.Length() == 1 && info[0]->IsBoolean()) { inotify = new Inotify(info[0]->IsTrue()); } else { inotify = new Inotify(); } inotify->fd = inotify_init(); if(inotify->fd == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::Null()); } int flags = fcntl(inotify->fd, F_GETFL); if(flags == -1) { flags = 0; } fcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK); //ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ); //ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher); uv_poll_init(uv_default_loop(), inotify->read_watcher, inotify->fd); uv_poll_start(inotify->read_watcher, UV_READABLE, Inotify::Callback); Local<Object> obj = info.This(); inotify->Wrap(obj); if(!inotify->persistent) { //ev_unref(EV_DEFAULT_UC); uv_unref((uv_handle_t *) inotify->read_watcher); } /** * Increment object references to avoid be GCed while * we are waiting for events in the inotify file descriptor. * Also, the object is not weak anymore. */ inotify->Ref(); info.GetReturnValue().Set(obj); } NAN_METHOD(Inotify::AddWatch) { Nan::HandleScope scope; uint32_t mask = 0; int watch_descriptor = 0; if(info.Length() < 1 || !info[0]->IsObject()) { return Nan::ThrowTypeError("You must specify an object as first argument"); } Local<Object> args_ = info[0]->ToObject(); Local<String> path_sym = Nan::New<String>("path").ToLocalChecked(); if (!args_->Has(path_sym)) { return Nan::ThrowTypeError("You must specify a path to watch for events"); } Local<String> callback_sym = Nan::New<String>("callback").ToLocalChecked(); if (!args_->Has(callback_sym) || !args_->Get(callback_sym)->IsFunction()) { return Nan::ThrowTypeError("You must specify a callback function"); } Local<String> watch_for_sym = Nan::New<String>("watch_for").ToLocalChecked(); if (!args_->Has(watch_for_sym)) { mask |= IN_ALL_EVENTS; } else { if (!args_->Get(watch_for_sym)->IsInt32()) { return Nan::ThrowTypeError("You must specify OR'ed set of events"); } mask |= args_->Get(watch_for_sym)->Int32Value(); if (mask == 0) { return Nan::ThrowTypeError("You must specify OR'ed set of events"); } } String::Utf8Value path(args_->Get(path_sym)); Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); /* add watch */ watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask); Local<Integer> descriptor = Nan::New<Integer>(watch_descriptor); //Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym)); inotify->handle()->Set(descriptor, args_->Get(callback_sym)); info.GetReturnValue().Set(descriptor); } NAN_METHOD(Inotify::RemoveWatch) { Nan::HandleScope scope; uint32_t watch = 0; int ret = -1; if(info.Length() == 0 || !info[0]->IsInt32()) { return Nan::ThrowTypeError("You must specify a valid watcher descriptor as argument"); } watch = info[0]->Int32Value(); Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); ret = inotify_rm_watch(inotify->fd, watch); if(ret == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::False()); } info.GetReturnValue().Set(Nan::True()); } void Inotify::on_handle_close(uv_handle_t* handle) { assert(!uv_is_active(handle)); delete handle; } NAN_METHOD(Inotify::Close) { Nan::HandleScope scope; int ret = -1; Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); ret = close(inotify->fd); if (ret == -1) { Nan::ThrowError(Nan::New<String>(strerror(errno)).ToLocalChecked()); info.GetReturnValue().Set(Nan::False()); } if (!inotify->persistent) { //ev_ref(EV_DEFAULT_UC); uv_ref((uv_handle_t *) inotify->read_watcher); } //ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher); inotify->StopPolling(); /*Eliminating reference created inside of Inotify::New. The object is also weak again. Now v8 can do its stuff and GC the object. */ inotify->Unref(); info.GetReturnValue().Set(Nan::True()); } void Inotify::Callback(uv_poll_t *watcher, int status, int revents) { Nan::HandleScope scope; Inotify *inotify = static_cast<Inotify*>(watcher->data); assert(watcher == inotify->read_watcher); char buffer[BUF_LEN]; //int length = read(inotify->fd, buffer, BUF_LEN); Local<Value> argv[1]; Nan::TryCatch try_catch; int sz = 0; while ((sz = read(inotify->fd, buffer, BUF_LEN)) > 0) { struct inotify_event *event; for (unsigned int i = 0; i <= (sz-EVENT_SIZE); i += (EVENT_SIZE + event->len)) { event = (struct inotify_event *) &buffer[i]; Local<Object> obj = Nan::New<Object>(); obj->Set(Nan::New<String>("watch").ToLocalChecked(), Nan::New<Integer>(event->wd)); obj->Set(Nan::New<String>("mask").ToLocalChecked(), Nan::New<Integer>(event->mask)); obj->Set(Nan::New<String>("cookie").ToLocalChecked(), Nan::New<Integer>(event->cookie)); if(event->len) { obj->Set(Nan::New<String>("name").ToLocalChecked(), Nan::New<String>(event->name).ToLocalChecked()); } argv[0] = obj; inotify->Ref(); Local<Object> handle = inotify->handle(); Local<Value> value = handle->Get(Nan::New<Integer>(event->wd)); Local<Function> func = Local<Function>::Cast(value); Nan::Callback callback(func); callback.Call(handle, 1, argv); inotify->Unref(); if(event->mask & IN_IGNORED) { //deleting callback because the watch was removed Local<Value> wd = Nan::New<Integer>(event->wd); handle->Delete(wd->ToString()); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } // for } // while } NAN_GETTER(Inotify::GetPersistent) { Nan::HandleScope scope; Inotify *inotify = Nan::ObjectWrap::Unwrap<Inotify>(info.This()); if (inotify->persistent) { info.GetReturnValue().Set(Nan::True()); } info.GetReturnValue().Set(Nan::False()); } void Inotify::StopPolling() { if (!poll_stopped) { uv_poll_stop(read_watcher); uv_close((uv_handle_t *) read_watcher, Inotify::on_handle_close); poll_stopped = 1; } } }//namespace NodeInotify
Fix #67
Fix #67 By making sure any JS land Promises are resolved and queued callbacks called.
C++
mit
c4milo/node-inotify,c4milo/node-inotify,c4milo/node-inotify
da9c0b9386eaab45999a62d4a90d07db793b6a4b
audio/audio_engine/yas_audio_route_node.cpp
audio/audio_engine/yas_audio_route_node.cpp
// // yas_audio_route_node.cpp // #include "yas_audio_route_node.h" #include "yas_stl_utils.h" using namespace yas; #pragma mark - kernel struct audio::route_node::kernel : node::kernel { ~kernel() = default; route_set_t routes; }; #pragma mark - impl struct audio::route_node::impl : node::impl { struct core { route_set_t routes; void erase_route_if_either_matched(route const &route) { erase_route_if([&route](audio::route const &route_of_set) { return route_of_set.source == route.source || route_of_set.destination == route.destination; }); } void erase_route_if(std::function<bool(route const &)> pred) { erase_if(routes, pred); } }; impl() : node::impl(), _core(std::make_unique<core>()) { } ~impl() = default; virtual void reset() override { _core->routes.clear(); node::impl::reset(); } virtual UInt32 input_bus_count() const override { return std::numeric_limits<UInt32>::max(); } virtual UInt32 output_bus_count() const override { return std::numeric_limits<UInt32>::max(); } virtual std::shared_ptr<node::kernel> make_kernel() override { return std::shared_ptr<node::kernel>(new route_node::kernel()); } virtual void prepare_kernel(std::shared_ptr<node::kernel> const &kernel) override { node::impl::prepare_kernel(kernel); auto route_kernel = std::static_pointer_cast<route_node::kernel>(kernel); route_kernel->routes = _core->routes; } virtual void render(pcm_buffer &dst_buffer, UInt32 const dst_bus_idx, time const &when) override { node::impl::render(dst_buffer, dst_bus_idx, when); if (auto kernel = kernel_cast<route_node::kernel>()) { auto &routes = kernel->routes; auto output_connection = kernel->output_connection(dst_bus_idx); auto input_connections = kernel->input_connections(); UInt32 const dst_ch_count = dst_buffer.format().channel_count(); for (auto const &pair : input_connections) { if (auto const &input_connection = pair.second) { if (auto node = input_connection.source_node()) { auto const &src_format = input_connection.format(); auto const &src_bus_idx = pair.first; UInt32 const src_ch_count = src_format.channel_count(); if (auto const result = channel_map_from_routes(routes, src_bus_idx, src_ch_count, dst_bus_idx, dst_ch_count)) { pcm_buffer src_buffer(src_format, dst_buffer, result.value()); node.render(src_buffer, src_bus_idx, when); } } } } } } #pragma mark - audio::route_set_t const &routes() const { return _core->routes; } void add_route(route &&route) { _core->erase_route_if_either_matched(route); _core->routes.insert(std::move(route)); update_kernel(); } void remove_route(route const &route) { _core->routes.erase(route); update_kernel(); } void remove_route_for_source(route::point const &src_pt) { _core->erase_route_if([&src_pt](route const &route_of_set) { return route_of_set.source == src_pt; }); update_kernel(); } void remove_route_for_destination(route::point const &dst_pt) { _core->erase_route_if([&dst_pt](route const &route_of_set) { return route_of_set.destination == dst_pt; }); update_kernel(); } void set_routes(route_set_t &&routes) { _core->routes.clear(); _core->routes = std::move(routes); update_kernel(); } void clear_routes() { _core->routes.clear(); update_kernel(); } private: std::unique_ptr<core> _core; }; #pragma mark - main audio::route_node::route_node() : node(std::make_unique<impl>()) { } audio::route_node::route_node(std::nullptr_t) : node(nullptr) { } audio::route_set_t const &audio::route_node::routes() const { return impl_ptr<impl>()->routes(); } void audio::route_node::add_route(route route) { impl_ptr<impl>()->add_route(std::move(route)); } void audio::route_node::remove_route(route const &route) { impl_ptr<impl>()->remove_route(route); } void audio::route_node::remove_route_for_source(route::point const &src_pt) { impl_ptr<impl>()->remove_route_for_source(src_pt); } void audio::route_node::remove_route_for_destination(route::point const &dst_pt) { impl_ptr<impl>()->remove_route_for_destination(dst_pt); } void audio::route_node::set_routes(route_set_t routes) { impl_ptr<impl>()->set_routes(std::move(routes)); } void audio::route_node::clear_routes() { impl_ptr<impl>()->clear_routes(); }
// // yas_audio_route_node.cpp // #include "yas_audio_route_node.h" #include "yas_stl_utils.h" using namespace yas; #pragma mark - kernel struct audio::route_node::kernel : node::kernel { ~kernel() = default; route_set_t routes; }; #pragma mark - impl struct audio::route_node::impl : node::impl { struct core { route_set_t routes; void erase_route_if_either_matched(route const &route) { erase_route_if([&route](audio::route const &route_of_set) { return route_of_set.source == route.source || route_of_set.destination == route.destination; }); } void erase_route_if(std::function<bool(route const &)> pred) { erase_if(routes, pred); } }; impl() : node::impl(), _core(std::make_unique<core>()) { } ~impl() = default; virtual void reset() override { _core->routes.clear(); node::impl::reset(); } virtual uint32_t input_bus_count() const override { return std::numeric_limits<uint32_t>::max(); } virtual uint32_t output_bus_count() const override { return std::numeric_limits<uint32_t>::max(); } virtual std::shared_ptr<node::kernel> make_kernel() override { return std::shared_ptr<node::kernel>(new route_node::kernel()); } virtual void prepare_kernel(std::shared_ptr<node::kernel> const &kernel) override { node::impl::prepare_kernel(kernel); auto route_kernel = std::static_pointer_cast<route_node::kernel>(kernel); route_kernel->routes = _core->routes; } virtual void render(pcm_buffer &dst_buffer, uint32_t const dst_bus_idx, time const &when) override { node::impl::render(dst_buffer, dst_bus_idx, when); if (auto kernel = kernel_cast<route_node::kernel>()) { auto &routes = kernel->routes; auto output_connection = kernel->output_connection(dst_bus_idx); auto input_connections = kernel->input_connections(); uint32_t const dst_ch_count = dst_buffer.format().channel_count(); for (auto const &pair : input_connections) { if (auto const &input_connection = pair.second) { if (auto node = input_connection.source_node()) { auto const &src_format = input_connection.format(); auto const &src_bus_idx = pair.first; uint32_t const src_ch_count = src_format.channel_count(); if (auto const result = channel_map_from_routes(routes, src_bus_idx, src_ch_count, dst_bus_idx, dst_ch_count)) { pcm_buffer src_buffer(src_format, dst_buffer, result.value()); node.render(src_buffer, src_bus_idx, when); } } } } } } #pragma mark - audio::route_set_t const &routes() const { return _core->routes; } void add_route(route &&route) { _core->erase_route_if_either_matched(route); _core->routes.insert(std::move(route)); update_kernel(); } void remove_route(route const &route) { _core->routes.erase(route); update_kernel(); } void remove_route_for_source(route::point const &src_pt) { _core->erase_route_if([&src_pt](route const &route_of_set) { return route_of_set.source == src_pt; }); update_kernel(); } void remove_route_for_destination(route::point const &dst_pt) { _core->erase_route_if([&dst_pt](route const &route_of_set) { return route_of_set.destination == dst_pt; }); update_kernel(); } void set_routes(route_set_t &&routes) { _core->routes.clear(); _core->routes = std::move(routes); update_kernel(); } void clear_routes() { _core->routes.clear(); update_kernel(); } private: std::unique_ptr<core> _core; }; #pragma mark - main audio::route_node::route_node() : node(std::make_unique<impl>()) { } audio::route_node::route_node(std::nullptr_t) : node(nullptr) { } audio::route_set_t const &audio::route_node::routes() const { return impl_ptr<impl>()->routes(); } void audio::route_node::add_route(route route) { impl_ptr<impl>()->add_route(std::move(route)); } void audio::route_node::remove_route(route const &route) { impl_ptr<impl>()->remove_route(route); } void audio::route_node::remove_route_for_source(route::point const &src_pt) { impl_ptr<impl>()->remove_route_for_source(src_pt); } void audio::route_node::remove_route_for_destination(route::point const &dst_pt) { impl_ptr<impl>()->remove_route_for_destination(dst_pt); } void audio::route_node::set_routes(route_set_t routes) { impl_ptr<impl>()->set_routes(std::move(routes)); } void audio::route_node::clear_routes() { impl_ptr<impl>()->clear_routes(); }
replace type in audio_route_node
replace type in audio_route_node
C++
mit
objective-audio/audio_engine,objective-audio/audio_engine,objective-audio/YASAudio,objective-audio/YASAudio,objective-audio/audio_engine
b0ce7c3070327b61adea46ea063c687f9b2e0e01
test/core/test_read_dihedral_angle_interaction.cpp
test/core/test_read_dihedral_angle_interaction.cpp
#define BOOST_TEST_MODULE "test_read_dihedral_angle_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_local_interaction.hpp> BOOST_AUTO_TEST_CASE(read_dihedral_angle_harmonic) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "Harmonic" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::HarmonicPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_go_contact) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "ClementiDihedral" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::ClementiDihedralPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_gaussian) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "Gaussian" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::PeriodicGaussianPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_periodic_gaussian) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "PeriodicGaussian" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::PeriodicGaussianPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_flexible_local) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "FlexibleLocalDihedral" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::FlexibleLocalDihedralPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } }
#define BOOST_TEST_MODULE "test_read_dihedral_angle_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_local_interaction.hpp> BOOST_AUTO_TEST_CASE(read_dihedral_angle_harmonic) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "Harmonic" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::HarmonicPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_go_contact) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "ClementiDihedral" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::ClementiDihedralPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_gaussian) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "Gaussian" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::PeriodicGaussianPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_periodic_gaussian) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "PeriodicGaussian" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::PeriodicGaussianPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_flexible_local) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "FlexibleLocalDihedral" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::FlexibleLocalDihedralPotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } } BOOST_AUTO_TEST_CASE(read_dihedral_angle_cosine) { mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; { using namespace toml::literals; const toml::value v = u8R"( interaction = "DihedralAngle" potential = "Cosine" topology = "none" parameters = [] )"_toml; const auto base = mjolnir::read_local_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction< traits_type, mjolnir::CosinePotential<real_type>>* >(base.get()); // check the expected type is contained BOOST_TEST(static_cast<bool>(derv)); } }
add test code for Cosine Dihedral
test: add test code for Cosine Dihedral
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
2146a89b9f5bd779fc1a969063bf794e96156c8f
benchmark/isa_arithmetic/isa_arithmetic.cpp
benchmark/isa_arithmetic/isa_arithmetic.cpp
// Copyright Steinwurf ApS 2011-2012. // Distributed under the "STEINWURF RESEARCH LICENSE 1.0". // See accompanying file LICENSE.rst or // http://www.steinwurf.com/licensing #include <ctime> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> // for memset, memcmp #include <vector> #include <set> #include <sak/aligned_allocator.hpp> #include <gauge/gauge.hpp> extern "C" { #include "erasure_code.h" #include "test.h" } #define TEST_SOURCES 250 #define MMAX TEST_SOURCES #define KMAX TEST_SOURCES /// Benchmark fixture for the arithmetic benchmark class arithmetic_setup : public gauge::time_benchmark { public: /// The value type of a field element typedef uint8_t value_type; public: double measurement() { // Get the time spent per iteration double time = gauge::time_benchmark::measurement(); gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); // The number of bytes processed per iteration uint64_t bytes = size * vectors; return bytes / time; // MB/s for each iteration } void store_run(tables::table& results) { if(!results.has_column("throughput")) results.add_column("throughput"); results.set_value("throughput", measurement()); } std::string unit_text() const { return "MB/s"; } void get_options(gauge::po::variables_map& options) { auto sizes = options["size"].as<std::vector<uint32_t>>(); auto vectors = options["vectors"].as<std::vector<uint32_t>>(); assert(sizes.size() > 0); assert(vectors.size() > 0); for (const auto& s : sizes) { for (const auto& v : vectors) { gauge::config_set cs; cs.set_value<uint32_t>("size", s); cs.set_value<uint32_t>("vectors", v); add_configuration(cs); } } } /// Prepares the data structures between each run void setup() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); // Prepare the continuous data blocks m_data_one.resize(vectors * size); m_data_two.resize(vectors * size); for (uint32_t i = 0; i < size; ++i) { m_data_one[i] = rand() % 256; m_data_two[i] = rand() % 256; } // Prepare the symbol pointers m_symbols_one.resize(vectors); m_symbols_two.resize(vectors); for (uint32_t i = 0; i < vectors; ++i) { m_symbols_one[i] = &m_data_one[i * size]; m_symbols_two[i] = &m_data_two[i * size]; } gf_gen_rs_matrix(a, vectors, vectors); } void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); for (uint32_t i = 0; i < vectors; ++i) { gf_vect_dot_prod(size, vectors, g_tbls, m_symbols_two.data(), m_symbols_one[i]); } } } protected: uint8_t a[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; /// Type of the aligned vector typedef std::vector<value_type, sak::aligned_allocator<value_type>> aligned_vector; /// The first buffer of vectors std::vector<value_type*> m_symbols_one; /// The second buffer of vectors std::vector<value_type*> m_symbols_two; /// Random data for the first data buffer aligned_vector m_data_one; /// Random data for the second data buffer aligned_vector m_data_two; }; class arithmetic2_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint32_t dest_vectors = vectors; uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; while (dest_vectors >= 2) { gf_2vect_dot_prod_avx2(size, vectors, table, data, coding); table += 2 * vectors * 32; coding += 2; dest_vectors -= 2; } if (dest_vectors > 0) { gf_vect_dot_prod_avx2(size, vectors, table, data, *coding); } } } }; class arithmetic4_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint32_t dest_vectors = vectors; uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; while (dest_vectors >= 4) { gf_4vect_dot_prod_avx2(size, vectors, table, data, coding); table += 4 * vectors * 32; coding += 4; dest_vectors -= 4; } switch (dest_vectors) { case 3: gf_3vect_dot_prod_avx2(size, vectors, table, data, coding); break; case 2: gf_2vect_dot_prod_avx2(size, vectors, table, data, coding); break; case 1: gf_vect_dot_prod_avx2(size, vectors, table, data, *coding); break; case 0: break; } } } }; class arithmetic_encode_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; ec_encode_data(size, vectors, vectors, table, data, coding); } } }; /// Using this macro we may specify options. For specifying options /// we use the boost program options library. So you may additional /// details on how to do it in the manual for that library. BENCHMARK_OPTION(arithmetic_options) { gauge::po::options_description options; options.add_options() ("size", gauge::po::value<std::vector<uint32_t>>()->default_value( {1000000}, "")->multitoken(), "Set the size of a vector in bytes"); options.add_options() ("vectors", gauge::po::value<std::vector<uint32_t>>()-> default_value({8,16,32}, "")->multitoken(), "Set the number of vectors to perform the operations on"); gauge::runner::instance().register_options(options); } //------------------------------------------------------------------ // ISA Arithmetic //------------------------------------------------------------------ BENCHMARK_F_INLINE(arithmetic_setup, ISA, dot_product1, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic2_setup, ISA, dot_product2, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic4_setup, ISA, dot_product4, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic_encode_setup, ISA, dot_product_encode, 1) { run_benchmark(); } int main(int argc, const char* argv[]) { srand(static_cast<uint32_t>(time(0))); gauge::runner::add_default_printers(); gauge::runner::run_benchmarks(argc, argv); return 0; }
// Copyright Steinwurf ApS 2011-2012. // Distributed under the "STEINWURF RESEARCH LICENSE 1.0". // See accompanying file LICENSE.rst or // http://www.steinwurf.com/licensing #include <ctime> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> // for memset, memcmp #include <vector> #include <set> #include <sak/aligned_allocator.hpp> #include <gauge/gauge.hpp> extern "C" { #include "erasure_code.h" #include "test.h" } #define TEST_SOURCES 250 #define MMAX TEST_SOURCES #define KMAX TEST_SOURCES /// Benchmark fixture for the arithmetic benchmark class arithmetic_setup : public gauge::time_benchmark { public: /// The value type of a field element typedef uint8_t value_type; public: double measurement() { // Get the time spent per iteration double time = gauge::time_benchmark::measurement(); gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); // The number of bytes processed per iteration uint64_t bytes = size * vectors; return bytes / time; // MB/s for each iteration } void store_run(tables::table& results) { if(!results.has_column("throughput")) results.add_column("throughput"); results.set_value("throughput", measurement()); } std::string unit_text() const { return "MB/s"; } void get_options(gauge::po::variables_map& options) { auto sizes = options["size"].as<std::vector<uint32_t>>(); auto vectors = options["vectors"].as<std::vector<uint32_t>>(); assert(sizes.size() > 0); assert(vectors.size() > 0); for (const auto& s : sizes) { for (const auto& v : vectors) { gauge::config_set cs; cs.set_value<uint32_t>("size", s); cs.set_value<uint32_t>("vectors", v); add_configuration(cs); } } } /// Prepares the data structures between each run void setup() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); // Prepare the continuous data blocks m_data_one.resize(vectors * size); m_data_two.resize(vectors * size); for (uint32_t i = 0; i < size; ++i) { m_data_one[i] = rand() % 256; m_data_two[i] = rand() % 256; } // Prepare the symbol pointers m_symbols_one.resize(vectors); m_symbols_two.resize(vectors); for (uint32_t i = 0; i < vectors; ++i) { m_symbols_one[i] = &m_data_one[i * size]; m_symbols_two[i] = &m_data_two[i * size]; } gf_gen_rs_matrix(a, vectors, vectors); } void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); for (uint32_t i = 0; i < vectors; ++i) { gf_vect_dot_prod(size, vectors, g_tbls, m_symbols_two.data(), m_symbols_one[i]); } } } protected: uint8_t a[MMAX*KMAX]; uint8_t g_tbls[KMAX*TEST_SOURCES*32]; /// Type of the aligned vector typedef std::vector<value_type, sak::aligned_allocator<value_type>> aligned_vector; /// The first buffer of vectors std::vector<value_type*> m_symbols_one; /// The second buffer of vectors std::vector<value_type*> m_symbols_two; /// Random data for the first data buffer aligned_vector m_data_one; /// Random data for the second data buffer aligned_vector m_data_two; }; class arithmetic2_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint32_t dest_vectors = vectors; uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; while (dest_vectors >= 2) { gf_2vect_dot_prod_avx2(size, vectors, table, data, coding); table += 2 * vectors * 32; coding += 2; dest_vectors -= 2; } if (dest_vectors > 0) { gf_vect_dot_prod_avx2(size, vectors, table, data, *coding); } } } }; class arithmetic4_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint32_t dest_vectors = vectors; uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; while (dest_vectors >= 4) { gf_4vect_dot_prod_avx2(size, vectors, table, data, coding); table += 4 * vectors * 32; coding += 4; dest_vectors -= 4; } switch (dest_vectors) { case 3: gf_3vect_dot_prod_avx2(size, vectors, table, data, coding); break; case 2: gf_2vect_dot_prod_avx2(size, vectors, table, data, coding); break; case 1: gf_vect_dot_prod_avx2(size, vectors, table, data, *coding); break; case 0: break; } } } }; class arithmetic_encode_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; ec_encode_data(size, vectors, vectors, table, data, coding); } } }; class arithmetic_encode_sse_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; ec_encode_data_sse(size, vectors, vectors, table, data, coding); } } }; class arithmetic_encode_avx_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; ec_encode_data_avx(size, vectors, vectors, table, data, coding); } } }; class arithmetic_encode_avx2_setup : public arithmetic_setup { public: using base = arithmetic_setup; using base::m_symbols_one; using base::m_symbols_two; using base::g_tbls; using base::a; public: void run_benchmark() { gauge::config_set cs = get_current_configuration(); uint32_t size = cs.get_value<uint32_t>("size"); uint32_t vectors = cs.get_value<uint32_t>("vectors"); RUN { // Make parity vects ec_init_tables(vectors, vectors, &a[vectors * vectors], g_tbls); uint8_t** data = m_symbols_two.data(); uint8_t** coding = m_symbols_one.data(); uint8_t* table = base::g_tbls; ec_encode_data_avx2(size, vectors, vectors, table, data, coding); } } }; /// Using this macro we may specify options. For specifying options /// we use the boost program options library. So you may additional /// details on how to do it in the manual for that library. BENCHMARK_OPTION(arithmetic_options) { gauge::po::options_description options; options.add_options() ("size", gauge::po::value<std::vector<uint32_t>>()->default_value( {1000000}, "")->multitoken(), "Set the size of a vector in bytes"); options.add_options() ("vectors", gauge::po::value<std::vector<uint32_t>>()-> default_value({8,16,32}, "")->multitoken(), "Set the number of vectors to perform the operations on"); gauge::runner::instance().register_options(options); } //------------------------------------------------------------------ // ISA Arithmetic //------------------------------------------------------------------ BENCHMARK_F_INLINE(arithmetic_setup, ISA, dot_product1, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic2_setup, ISA, dot_product2, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic4_setup, ISA, dot_product4, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic_encode_setup, ISA, dot_product_encode, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic_encode_sse_setup, ISA, dot_product_encode_sse, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic_encode_avx_setup, ISA, dot_product_encode_avx, 1) { run_benchmark(); } BENCHMARK_F_INLINE(arithmetic_encode_avx2_setup, ISA, dot_product_encode_avx2, 1) { run_benchmark(); } int main(int argc, const char* argv[]) { srand(static_cast<uint32_t>(time(0))); gauge::runner::add_default_printers(); gauge::runner::run_benchmarks(argc, argv); return 0; }
Add separate benchmarks for ec_encode_data sse, avx and avx2 versions
Add separate benchmarks for ec_encode_data sse, avx and avx2 versions
C++
bsd-3-clause
steinwurf/storage-benchmarks,steinwurf/storage-benchmarks,steinwurf/storage-benchmarks,steinwurf/storage-benchmarks,steinwurf/storage-benchmarks,steinwurf/storage-benchmarks
b6d24c6b35e6734d6009e9b841a66f81bc3d0423
src/box2d.cpp
src/box2d.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/box2d.hpp> #include <mapnik/util/trim.hpp> // stl #include <stdexcept> // boost // fusion #include <boost/fusion/include/adapt_adt.hpp> // spirit #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_adapt_adt_attributes.hpp> // agg #include "agg_trans_affine.h" BOOST_FUSION_ADAPT_TPL_ADT( (T), (mapnik::box2d)(T), (T, T, obj.minx(), obj.set_minx(val)) (T, T, obj.miny(), obj.set_miny(val)) (T, T, obj.maxx(), obj.set_maxx(val)) (T, T, obj.maxy(), obj.set_maxy(val))) namespace mapnik { template <typename T> box2d<T>::box2d() :minx_(0),miny_(0),maxx_(-1),maxy_(-1) {} template <typename T> box2d<T>::box2d(T minx,T miny,T maxx,T maxy) { init(minx,miny,maxx,maxy); } template <typename T> box2d<T>::box2d(const coord<T,2> &c0,const coord<T,2> &c1) { init(c0.x,c0.y,c1.x,c1.y); } template <typename T> box2d<T>::box2d(const box2d &rhs) : minx_(rhs.minx_), miny_(rhs.miny_), maxx_(rhs.maxx_), maxy_(rhs.maxy_) {} template <typename T> box2d<T>::box2d(box2d_type const& rhs, const agg::trans_affine& tr) { double x0 = rhs.minx_, y0 = rhs.miny_; double x1 = rhs.maxx_, y1 = rhs.miny_; double x2 = rhs.maxx_, y2 = rhs.maxy_; double x3 = rhs.minx_, y3 = rhs.maxy_; tr.transform(&x0, &y0); tr.transform(&x1, &y1); tr.transform(&x2, &y2); tr.transform(&x3, &y3); init(static_cast<T>(x0), static_cast<T>(y0), static_cast<T>(x2), static_cast<T>(y2)); expand_to_include(static_cast<T>(x1), static_cast<T>(y1)); expand_to_include(static_cast<T>(x3), static_cast<T>(y3)); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::operator==(const box2d<T>& other) const { return minx_==other.minx_ && miny_==other.miny_ && maxx_==other.maxx_ && maxy_==other.maxy_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::minx() const { return minx_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::maxx() const { return maxx_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::miny() const { return miny_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::maxy() const { return maxy_; } template<typename T> void box2d<T>::set_minx(T v) { minx_ = v; } template<typename T> void box2d<T>::set_miny(T v) { miny_ = v; } template<typename T> void box2d<T>::set_maxx(T v) { maxx_ = v; } template<typename T> void box2d<T>::set_maxy(T v) { maxy_ = v; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::width() const { return maxx_-minx_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif T box2d<T>::height() const { return maxy_-miny_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::width(T w) { T cx=center().x; minx_=static_cast<T>(cx-w*0.5); maxx_=static_cast<T>(cx+w*0.5); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::height(T h) { T cy=center().y; miny_=static_cast<T>(cy-h*0.5); maxy_=static_cast<T>(cy+h*0.5); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif coord<T,2> box2d<T>::center() const { return coord<T,2>(static_cast<T>(0.5*(minx_+maxx_)), static_cast<T>(0.5*(miny_+maxy_))); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::expand_to_include(const coord<T,2>& c) { expand_to_include(c.x,c.y); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::expand_to_include(T x,T y) { if (x<minx_) minx_=x; if (x>maxx_) maxx_=x; if (y<miny_) miny_=y; if (y>maxy_) maxy_=y; } template <typename T> void box2d<T>::expand_to_include(const box2d<T> &other) { if (other.minx_<minx_) minx_=other.minx_; if (other.maxx_>maxx_) maxx_=other.maxx_; if (other.miny_<miny_) miny_=other.miny_; if (other.maxy_>maxy_) maxy_=other.maxy_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::contains(const coord<T,2> &c) const { return contains(c.x,c.y); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::contains(T x,T y) const { return x>=minx_ && x<=maxx_ && y>=miny_ && y<=maxy_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::contains(const box2d<T> &other) const { return other.minx_>=minx_ && other.maxx_<=maxx_ && other.miny_>=miny_ && other.maxy_<=maxy_; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::intersects(const coord<T,2> &c) const { return intersects(c.x,c.y); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::intersects(T x,T y) const { return !(x>maxx_ || x<minx_ || y>maxy_ || y<miny_); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::intersects(const box2d<T> &other) const { return !(other.minx_>maxx_ || other.maxx_<minx_ || other.miny_>maxy_ || other.maxy_<miny_); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif box2d<T> box2d<T>::intersect(const box2d_type& other) const { if (intersects(other)) { T x0=std::max(minx_,other.minx_); T y0=std::max(miny_,other.miny_); T x1=std::min(maxx_,other.maxx_); T y1=std::min(maxy_,other.maxy_); return box2d<T>(x0,y0,x1,y1); } else { return box2d<T>(); } } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::re_center(T cx,T cy) { T dx=cx-center().x; T dy=cy-center().y; minx_+=dx; miny_+=dy; maxx_+=dx; maxy_+=dy; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::re_center(const coord<T,2> &c) { re_center(c.x,c.y); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::init(T x0,T y0,T x1,T y1) { if (x0<x1) { minx_=x0;maxx_=x1; } else { minx_=x1;maxx_=x0; } if (y0<y1) { miny_=y0;maxy_=y1; } else { miny_=y1;maxy_=y0; } } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::clip(const box2d_type& other) { minx_ = std::max(minx_,other.minx()); miny_ = std::max(miny_,other.miny()); maxx_ = std::min(maxx_,other.maxx()); maxy_ = std::min(maxy_,other.maxy()); } template <typename T> #if !defined(__SUNPRO_CC) inline #endif void box2d<T>::pad(T padding) { minx_ -= padding; miny_ -= padding; maxx_ += padding; maxy_ += padding; } template <typename T> inline bool box2d<T>::from_string(std::string const& str) { using boost::spirit::qi::double_; using boost::spirit::ascii::space; bool r = boost::spirit::qi::phrase_parse(str.begin(), str.end(), double_ >> ',' >> double_ >> ',' >> double_ >> ',' >> double_, space, *this); return r; } template <typename T> #if !defined(__SUNPRO_CC) inline #endif bool box2d<T>::valid() const { return (minx_ <= maxx_ && miny_ <= maxy_) ; } template <typename T> box2d<T>& box2d<T>::operator+=(box2d<T> const& other) { expand_to_include(other); return *this; } template <typename T> box2d<T>& box2d<T>::operator*=(T t) { coord<T,2> c = center(); T sx = static_cast<T>(0.5 * width() * t); T sy = static_cast<T>(0.5 * height() * t); minx_ = c.x - sx; maxx_ = c.x + sx; miny_ = c.y - sy; maxy_ = c.y + sy; return *this; } template <typename T> box2d<T>& box2d<T>::operator/=(T t) { coord<T,2> c = center(); T sx = static_cast<T>(0.5 * width() / t); T sy = static_cast<T>(0.5 * height() / t); minx_ = c.x - sx; maxx_ = c.x + sx; miny_ = c.y - sy; maxy_ = c.y + sy; return *this; } template <typename T> T box2d<T>::operator[] (int index) const { switch(index) { case 0: return minx_; case 1: return miny_; case 2: return maxx_; case 3: return maxy_; case -4: return minx_; case -3: return miny_; case -2: return maxx_; case -1: return maxy_; default: throw std::out_of_range("index out of range, max value is 3, min value is -4 "); } } template <typename T> box2d<T> box2d<T>::operator*(agg::trans_affine const& tr) const { return box2d<T>(*this, tr); } template <typename T> box2d<T>& box2d<T>::operator*=(agg::trans_affine const& tr) { double x0 = minx_, y0 = miny_; double x1 = maxx_, y1 = miny_; double x2 = maxx_, y2 = maxy_; double x3 = minx_, y3 = maxy_; tr.transform(&x0, &y0); tr.transform(&x1, &y1); tr.transform(&x2, &y2); tr.transform(&x3, &y3); init(static_cast<T>(x0), static_cast<T>(y0), static_cast<T>(x2), static_cast<T>(y2)); expand_to_include(static_cast<T>(x1), static_cast<T>(y1)); expand_to_include(static_cast<T>(x3), static_cast<T>(y3)); return *this; } template class box2d<int>; template class box2d<double>; }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/box2d.hpp> #include <mapnik/util/trim.hpp> // stl #include <stdexcept> // boost // fusion #include <boost/fusion/include/adapt_adt.hpp> // spirit #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_adapt_adt_attributes.hpp> // agg #include "agg_trans_affine.h" BOOST_FUSION_ADAPT_TPL_ADT( (T), (mapnik::box2d)(T), (T, T, obj.minx(), obj.set_minx(val)) (T, T, obj.miny(), obj.set_miny(val)) (T, T, obj.maxx(), obj.set_maxx(val)) (T, T, obj.maxy(), obj.set_maxy(val))) namespace mapnik { template <typename T> box2d<T>::box2d() :minx_(0),miny_(0),maxx_(-1),maxy_(-1) {} template <typename T> box2d<T>::box2d(T minx,T miny,T maxx,T maxy) { init(minx,miny,maxx,maxy); } template <typename T> box2d<T>::box2d(const coord<T,2> &c0,const coord<T,2> &c1) { init(c0.x,c0.y,c1.x,c1.y); } template <typename T> box2d<T>::box2d(const box2d &rhs) : minx_(rhs.minx_), miny_(rhs.miny_), maxx_(rhs.maxx_), maxy_(rhs.maxy_) {} template <typename T> box2d<T>::box2d(box2d_type const& rhs, const agg::trans_affine& tr) { double x0 = rhs.minx_, y0 = rhs.miny_; double x1 = rhs.maxx_, y1 = rhs.miny_; double x2 = rhs.maxx_, y2 = rhs.maxy_; double x3 = rhs.minx_, y3 = rhs.maxy_; tr.transform(&x0, &y0); tr.transform(&x1, &y1); tr.transform(&x2, &y2); tr.transform(&x3, &y3); init(static_cast<T>(x0), static_cast<T>(y0), static_cast<T>(x2), static_cast<T>(y2)); expand_to_include(static_cast<T>(x1), static_cast<T>(y1)); expand_to_include(static_cast<T>(x3), static_cast<T>(y3)); } template <typename T> bool box2d<T>::operator==(const box2d<T>& other) const { return minx_==other.minx_ && miny_==other.miny_ && maxx_==other.maxx_ && maxy_==other.maxy_; } template <typename T> T box2d<T>::minx() const { return minx_; } template <typename T> T box2d<T>::maxx() const { return maxx_; } template <typename T> T box2d<T>::miny() const { return miny_; } template <typename T> T box2d<T>::maxy() const { return maxy_; } template<typename T> void box2d<T>::set_minx(T v) { minx_ = v; } template<typename T> void box2d<T>::set_miny(T v) { miny_ = v; } template<typename T> void box2d<T>::set_maxx(T v) { maxx_ = v; } template<typename T> void box2d<T>::set_maxy(T v) { maxy_ = v; } template <typename T> T box2d<T>::width() const { return maxx_-minx_; } template <typename T> T box2d<T>::height() const { return maxy_-miny_; } template <typename T> void box2d<T>::width(T w) { T cx=center().x; minx_=static_cast<T>(cx-w*0.5); maxx_=static_cast<T>(cx+w*0.5); } template <typename T> void box2d<T>::height(T h) { T cy=center().y; miny_=static_cast<T>(cy-h*0.5); maxy_=static_cast<T>(cy+h*0.5); } template <typename T> coord<T,2> box2d<T>::center() const { return coord<T,2>(static_cast<T>(0.5*(minx_+maxx_)), static_cast<T>(0.5*(miny_+maxy_))); } template <typename T> void box2d<T>::expand_to_include(const coord<T,2>& c) { expand_to_include(c.x,c.y); } template <typename T> void box2d<T>::expand_to_include(T x,T y) { if (x<minx_) minx_=x; if (x>maxx_) maxx_=x; if (y<miny_) miny_=y; if (y>maxy_) maxy_=y; } template <typename T> void box2d<T>::expand_to_include(const box2d<T> &other) { if (other.minx_<minx_) minx_=other.minx_; if (other.maxx_>maxx_) maxx_=other.maxx_; if (other.miny_<miny_) miny_=other.miny_; if (other.maxy_>maxy_) maxy_=other.maxy_; } template <typename T> bool box2d<T>::contains(const coord<T,2> &c) const { return contains(c.x,c.y); } template <typename T> bool box2d<T>::contains(T x,T y) const { return x>=minx_ && x<=maxx_ && y>=miny_ && y<=maxy_; } template <typename T> bool box2d<T>::contains(const box2d<T> &other) const { return other.minx_>=minx_ && other.maxx_<=maxx_ && other.miny_>=miny_ && other.maxy_<=maxy_; } template <typename T> bool box2d<T>::intersects(const coord<T,2> &c) const { return intersects(c.x,c.y); } template <typename T> bool box2d<T>::intersects(T x,T y) const { return !(x>maxx_ || x<minx_ || y>maxy_ || y<miny_); } template <typename T> bool box2d<T>::intersects(const box2d<T> &other) const { return !(other.minx_>maxx_ || other.maxx_<minx_ || other.miny_>maxy_ || other.maxy_<miny_); } template <typename T> box2d<T> box2d<T>::intersect(const box2d_type& other) const { if (intersects(other)) { T x0=std::max(minx_,other.minx_); T y0=std::max(miny_,other.miny_); T x1=std::min(maxx_,other.maxx_); T y1=std::min(maxy_,other.maxy_); return box2d<T>(x0,y0,x1,y1); } else { return box2d<T>(); } } template <typename T> void box2d<T>::re_center(T cx,T cy) { T dx=cx-center().x; T dy=cy-center().y; minx_+=dx; miny_+=dy; maxx_+=dx; maxy_+=dy; } template <typename T> void box2d<T>::re_center(const coord<T,2> &c) { re_center(c.x,c.y); } template <typename T> void box2d<T>::init(T x0,T y0,T x1,T y1) { if (x0<x1) { minx_=x0;maxx_=x1; } else { minx_=x1;maxx_=x0; } if (y0<y1) { miny_=y0;maxy_=y1; } else { miny_=y1;maxy_=y0; } } template <typename T> void box2d<T>::clip(const box2d_type& other) { minx_ = std::max(minx_,other.minx()); miny_ = std::max(miny_,other.miny()); maxx_ = std::min(maxx_,other.maxx()); maxy_ = std::min(maxy_,other.maxy()); } template <typename T> void box2d<T>::pad(T padding) { minx_ -= padding; miny_ -= padding; maxx_ += padding; maxy_ += padding; } template <typename T> inline bool box2d<T>::from_string(std::string const& str) { using boost::spirit::qi::double_; using boost::spirit::ascii::space; bool r = boost::spirit::qi::phrase_parse(str.begin(), str.end(), double_ >> ',' >> double_ >> ',' >> double_ >> ',' >> double_, space, *this); return r; } template <typename T> bool box2d<T>::valid() const { return (minx_ <= maxx_ && miny_ <= maxy_) ; } template <typename T> box2d<T>& box2d<T>::operator+=(box2d<T> const& other) { expand_to_include(other); return *this; } template <typename T> box2d<T>& box2d<T>::operator*=(T t) { coord<T,2> c = center(); T sx = static_cast<T>(0.5 * width() * t); T sy = static_cast<T>(0.5 * height() * t); minx_ = c.x - sx; maxx_ = c.x + sx; miny_ = c.y - sy; maxy_ = c.y + sy; return *this; } template <typename T> box2d<T>& box2d<T>::operator/=(T t) { coord<T,2> c = center(); T sx = static_cast<T>(0.5 * width() / t); T sy = static_cast<T>(0.5 * height() / t); minx_ = c.x - sx; maxx_ = c.x + sx; miny_ = c.y - sy; maxy_ = c.y + sy; return *this; } template <typename T> T box2d<T>::operator[] (int index) const { switch(index) { case 0: return minx_; case 1: return miny_; case 2: return maxx_; case 3: return maxy_; case -4: return minx_; case -3: return miny_; case -2: return maxx_; case -1: return maxy_; default: throw std::out_of_range("index out of range, max value is 3, min value is -4 "); } } template <typename T> box2d<T> box2d<T>::operator*(agg::trans_affine const& tr) const { return box2d<T>(*this, tr); } template <typename T> box2d<T>& box2d<T>::operator*=(agg::trans_affine const& tr) { double x0 = minx_, y0 = miny_; double x1 = maxx_, y1 = miny_; double x2 = maxx_, y2 = maxy_; double x3 = minx_, y3 = maxy_; tr.transform(&x0, &y0); tr.transform(&x1, &y1); tr.transform(&x2, &y2); tr.transform(&x3, &y3); init(static_cast<T>(x0), static_cast<T>(y0), static_cast<T>(x2), static_cast<T>(y2)); expand_to_include(static_cast<T>(x1), static_cast<T>(y1)); expand_to_include(static_cast<T>(x3), static_cast<T>(y3)); return *this; } template class box2d<int>; template class box2d<double>; }
remove cruft
remove cruft
C++
lgpl-2.1
mapycz/python-mapnik,rouault/mapnik,CartoDB/mapnik,jwomeara/mapnik,Mappy/mapnik,yohanboniface/python-mapnik,yohanboniface/python-mapnik,yohanboniface/python-mapnik,qianwenming/mapnik,manz/python-mapnik,garnertb/python-mapnik,Airphrame/mapnik,tomhughes/mapnik,pnorman/mapnik,mapycz/mapnik,Uli1/mapnik,lightmare/mapnik,tomhughes/python-mapnik,mapnik/mapnik,naturalatlas/mapnik,jwomeara/mapnik,qianwenming/mapnik,tomhughes/mapnik,whuaegeanse/mapnik,CartoDB/mapnik,mapycz/python-mapnik,yiqingj/work,zerebubuth/mapnik,Uli1/mapnik,rouault/mapnik,Airphrame/mapnik,Mappy/mapnik,mbrukman/mapnik,jwomeara/mapnik,Mappy/mapnik,pnorman/mapnik,mapnik/python-mapnik,mbrukman/mapnik,qianwenming/mapnik,sebastic/python-mapnik,yiqingj/work,mapnik/python-mapnik,sebastic/python-mapnik,pramsey/mapnik,stefanklug/mapnik,Airphrame/mapnik,pramsey/mapnik,davenquinn/python-mapnik,mapnik/python-mapnik,naturalatlas/mapnik,pnorman/mapnik,sebastic/python-mapnik,tomhughes/python-mapnik,pnorman/mapnik,Mappy/mapnik,whuaegeanse/mapnik,mapycz/mapnik,qianwenming/mapnik,rouault/mapnik,cjmayo/mapnik,Airphrame/mapnik,Uli1/mapnik,lightmare/mapnik,garnertb/python-mapnik,mapnik/mapnik,whuaegeanse/mapnik,cjmayo/mapnik,lightmare/mapnik,stefanklug/mapnik,davenquinn/python-mapnik,yiqingj/work,davenquinn/python-mapnik,whuaegeanse/mapnik,yiqingj/work,pramsey/mapnik,qianwenming/mapnik,mapycz/mapnik,naturalatlas/mapnik,zerebubuth/mapnik,garnertb/python-mapnik,stefanklug/mapnik,manz/python-mapnik,tomhughes/mapnik,tomhughes/mapnik,naturalatlas/mapnik,pramsey/mapnik,zerebubuth/mapnik,Uli1/mapnik,stefanklug/mapnik,mapnik/mapnik,jwomeara/mapnik,lightmare/mapnik,tomhughes/python-mapnik,cjmayo/mapnik,cjmayo/mapnik,CartoDB/mapnik,rouault/mapnik,mapnik/mapnik,mbrukman/mapnik,manz/python-mapnik,mbrukman/mapnik
06325798f007b571f1cfdb073995874de9d5aa29
chrome/test/mini_installer_test/test.cc
chrome/test/mini_installer_test/test.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/win_util.h" #include "chrome/installer/util/install_util.h" #include "chrome/test/mini_installer_test/mini_installer_test_constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "chrome_mini_installer.h" namespace { class MiniInstallTest : public testing::Test { protected: virtual void SetUp() { ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall); userinstall.UnInstall(); if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller systeminstall( mini_installer_constants::kSystemInstall); systeminstall.UnInstall(); } } virtual void TearDown() { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.CloseProcesses(installer_util::kChromeExe); } }; }; TEST_F(MiniInstallTest, MiniInstallerOverChromeMetaInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.OverInstall(); } TEST_F(MiniInstallTest, MiniInstallerSystemInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall); installer.InstallMiniInstaller(); } } TEST_F(MiniInstallTest, MiniInstallerUserInstallTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallMiniInstaller(); }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/win_util.h" #include "chrome/installer/util/install_util.h" #include "chrome/test/mini_installer_test/mini_installer_test_constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "chrome_mini_installer.h" namespace { class MiniInstallTest : public testing::Test { protected: virtual void SetUp() { ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall); userinstall.UnInstall(); if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller systeminstall( mini_installer_constants::kSystemInstall); systeminstall.UnInstall(); } } virtual void TearDown() { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.CloseProcesses(installer_util::kChromeExe); } }; }; TEST_F(MiniInstallTest, MiniInstallerOverChromeMetaInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.OverInstall(); } TEST_F(MiniInstallTest, MiniInstallerSystemInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall); installer.InstallMiniInstaller(); } } TEST_F(MiniInstallTest, MiniInstallerUserInstallTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallMiniInstaller(); } TEST(InstallUtilTests, MiniInstallTestValidWindowsVersion) { // We run the tests on all supported OSes. // Make sure the code agrees. EXPECT_TRUE(InstallUtil::IsOSSupported()); }
Add a test case to be sure that InstallerUtil::IsOSSupported returns true for all the versions we support (or test on)
Add a test case to be sure that InstallerUtil::IsOSSupported returns true for all the versions we support (or test on) bug: 7735 Review URL: http://codereview.chromium.org/27171 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@10444 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium
2cec34808f8743131b483233bee5e7772d2761ce
tests/integrationtests/inviwo-integrationtests.cpp
tests/integrationtests/inviwo-integrationtests.cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * *********************************************************************************/ #ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:CONSOLE") #endif #ifdef WIN32 #include <windows.h> #endif #include <modules/opengl/inviwoopengl.h> #include <modules/glfw/canvasglfw.h> #include <inviwo/core/common/defaulttohighperformancegpu.h> #include <inviwo/core/common/inviwo.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/network/workspacemanager.h> #include <inviwo/core/network/processornetwork.h> #include <inviwo/core/util/logcentral.h> #include <inviwo/core/util/utilities.h> #include <inviwo/core/util/raiiutils.h> #include <inviwo/core/util/logerrorcounter.h> #include <inviwo/core/util/settings/systemsettings.h> #include <inviwo/core/moduleregistration.h> #include <inviwo/core/util/commandlineparser.h> #include <inviwo/core/util/rendercontext.h> #include <inviwo/testutil/configurablegtesteventlistener.h> #include <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> using namespace inviwo; int main(int argc, char** argv) { int ret = -1; { // scope for ivw app LogCentral::init(); util::OnScopeExit deleteLogcentral([]() { LogCentral::deleteInstance(); }); auto logCounter = std::make_shared<LogErrorCounter>(); LogCentral::getPtr()->registerLogger(logCounter); InviwoApplication inviwoApp(argc, argv, "Inviwo-IntegrationTests"); inviwoApp.getSystemSettings().stackTraceInException_.set(true); inviwoApp.setPostEnqueueFront([]() { glfwPostEmptyEvent(); }); inviwoApp.setProgressCallback([](std::string m) { LogCentral::getPtr()->log("InviwoApplication", LogLevel::Info, LogAudience::User, "", "", 0, m); }); // Initialize all modules inviwoApp.registerModules(inviwo::getModuleList()); inviwoApp.resizePool(0); inviwoApp.printApplicationInfo(); RenderContext::getPtr()->activateDefaultRenderContext(); auto& cmdparser = inviwoApp.getCommandLineParser(); cmdparser.processCallbacks(); // run any command line callbacks from modules. size_t warnCount = logCounter->getWarnCount(); size_t errCount = logCounter->getErrorCount(); ::testing::InitGoogleTest(&argc, argv); ConfigurableGTestEventListener::setup(); ret = RUN_ALL_TESTS(); if (ret) { LogErrorCustom("UnitTestsModule::runAllTests", "Some unit tests did not pass, see console output for details"); } size_t warnCountAfter = logCounter->getWarnCount(); size_t errCountAfter = logCounter->getErrorCount(); if (warnCount != warnCountAfter) { LogWarnCustom("UnitTestsModule::runAllTest", "The integration test runs generated " << (warnCountAfter - warnCount) << " warnings"); } if (errCount != errCountAfter) { LogWarnCustom("UnitTestsModule::runAllTest", "The integration test runs generated " << (errCountAfter - errCount) << " errors"); } } glfwTerminate(); return ret; }
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * *********************************************************************************/ #ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:CONSOLE") #endif #ifdef WIN32 #include <windows.h> #endif #include <modules/opengl/inviwoopengl.h> #include <modules/glfw/canvasglfw.h> #include <inviwo/core/common/defaulttohighperformancegpu.h> #include <inviwo/core/common/inviwo.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/network/workspacemanager.h> #include <inviwo/core/network/processornetwork.h> #include <inviwo/core/util/logcentral.h> #include <inviwo/core/util/utilities.h> #include <inviwo/core/util/raiiutils.h> #include <inviwo/core/util/logerrorcounter.h> #include <inviwo/core/util/settings/systemsettings.h> #include <inviwo/core/moduleregistration.h> #include <inviwo/core/util/commandlineparser.h> #include <inviwo/core/util/rendercontext.h> #include <inviwo/testutil/configurablegtesteventlistener.h> #include <modules/opengl/openglmodule.h> #include <modules/opengl/openglsettings.h> #include <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> using namespace inviwo; int main(int argc, char** argv) { int ret = -1; { // scope for ivw app LogCentral::init(); util::OnScopeExit deleteLogcentral([]() { LogCentral::deleteInstance(); }); auto logCounter = std::make_shared<LogErrorCounter>(); LogCentral::getPtr()->registerLogger(logCounter); InviwoApplication inviwoApp(argc, argv, "Inviwo-IntegrationTests"); inviwoApp.getSystemSettings().stackTraceInException_.set(true); inviwoApp.setPostEnqueueFront([]() { glfwPostEmptyEvent(); }); inviwoApp.setProgressCallback([](std::string m) { LogCentral::getPtr()->log("InviwoApplication", LogLevel::Info, LogAudience::User, "", "", 0, m); }); // Initialize all modules inviwoApp.registerModules(inviwo::getModuleList()); inviwoApp.resizePool(0); inviwoApp.printApplicationInfo(); RenderContext::getPtr()->activateDefaultRenderContext(); for (auto* settings : inviwoApp.getModuleByType<OpenGLModule>()->getSettings()) { if (auto glSettings = dynamic_cast<OpenGLSettings*>(settings)) { glSettings->debugMessages_.set(utilgl::debug::Mode::DebugSynchronous); glSettings->debugSeverity_.set(utilgl::debug::Severity::Medium); } } auto& cmdparser = inviwoApp.getCommandLineParser(); cmdparser.processCallbacks(); // run any command line callbacks from modules. size_t warnCount = logCounter->getWarnCount(); size_t errCount = logCounter->getErrorCount(); ::testing::InitGoogleTest(&argc, argv); ConfigurableGTestEventListener::setup(); ret = RUN_ALL_TESTS(); if (ret) { LogErrorCustom("UnitTestsModule::runAllTests", "Some unit tests did not pass, see console output for details"); } size_t warnCountAfter = logCounter->getWarnCount(); size_t errCountAfter = logCounter->getErrorCount(); if (warnCount != warnCountAfter) { LogWarnCustom("UnitTestsModule::runAllTest", "The integration test runs generated " << (warnCountAfter - warnCount) << " warnings"); } if (errCount != errCountAfter) { LogWarnCustom("UnitTestsModule::runAllTest", "The integration test runs generated " << (errCountAfter - errCount) << " errors"); } } glfwTerminate(); return ret; }
Enable OpenGL debugging
IntegrationTests: Enable OpenGL debugging
C++
bsd-2-clause
inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo
655474f4d2f6df8e5cefc18a8385a0b25ff4adb6
src/Robot.cpp
src/Robot.cpp
#include "WPILib.h" #include "../ADBLib/src/ADBLib.h" #include "auton/AutoBot.h" #include <unistd.h> using namespace ADBLib; #define CAM_FOV 57.0 #define CAM_XSIZE 1280.0 #define CAM_YSIZE 720.0 #define CAM_ANGRESO (CAM_FOV / CAM_XSIZE) class Robot: public IterativeRobot { private: TractionDrive* drivebase; CANTalon* motors[5]; Joystick* jys; ADBLib::Controller gpd; Compressor* compressor; Preferences* prefs; AHRS* ahrs; MultiVision mv; SimplePneumatic* shooterPiston; SimplePneumatic* liftArm; SimplePneumatic* extendArm; SimplePneumatic* tail; SimplePneumatic* intakeArms; CANTalon* fan; AutoBot* autobot; void RobotInit() { prefs = Preferences::GetInstance(); compressor = new Compressor(1); jys = new Joystick(0); gpd.setJoystick(jys); gpd.parseConfig("/ControlConfig.xml"); for (int i = 1; i < 5; i++) { motors[i] = new CANTalon(i); motors[i]->SetControlMode(CANTalon::kPercentVbus); motors[i]->SetVoltageRampRate(0.5); } motors[2]->SetInverted(true); motors[1]->SetInverted(true); drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]); ahrs = new AHRS(SPI::Port::kMXP); liftArm = new SimplePneumatic(new DoubleSolenoid(1, 0, 1)); shooterPiston = new SimplePneumatic(new Solenoid(1, 2)); extendArm = new SimplePneumatic(new DoubleSolenoid(1, 3, 4)); // bfdtail = new SimplePneumatic(new DoubleSolenoid(1, 5, 6)); intakeArms = new SimplePneumatic(new DoubleSolenoid(1, 5, 6)); fan = new CANTalon(5); mv.switchCamera("cam0"); autobot = new AutoBot; autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs); if (fork() == 0) system("/home/lvuser/grip &"); } void AutonomousInit() { autobot->switchMode(AutoBot::DRIVE); compressor->Start(); } void AutonomousPeriodic() { if (prefs->GetBoolean("fan-on", true)) fan->Set(1); else fan->Set(0); auto grip = NetworkTable::GetTable("grip"); auto areas = grip->GetNumberArray("targetsCam0/area", llvm::ArrayRef<double>()); const int size = sizeof(areas) / sizeof(double); double bestTarget = 0; for (int i = 0; i < size; i++) if (areas[i] > areas[bestTarget]) bestTarget = i; double diff = 640.0 - grip->GetNumberArray("targetsCam0/centerX", llvm::ArrayRef<double>())[bestTarget]; diff *= CAM_ANGRESO; drivebase->drive(0, 0.15, diff / 18.0); //autobot->update(); mv.postImage(); } void TeleopInit() { compressor->Start(); } void TeleopPeriodic() { shooterPiston->set(gpd["shooter"]); liftArm->set(gpd["liftArm"]); extendArm->set(gpd["extendArm"] != 0 ? 1 : -1); intakeArms->set(gpd["intakeArms"] != 0 ? 1 : -1); drivebase->drive(0, -gpd["transY"], gpd["rot"]); if (jys->GetRawButton(7)) mv.switchCamera("cam0"); if (jys->GetRawButton(8)) mv.switchCamera("cam1"); mv.postImage(); if (prefs->GetBoolean("fan-on", true)) fan->Set(1); else fan->Set(0); } void DisabledInit() { Logger::flushLogBuffers(); fan->Set(0); } void TestInit() { } void TestPeriodic() { } }; START_ROBOT_CLASS(Robot);
#include "WPILib.h" #include "../ADBLib/src/ADBLib.h" #include "auton/AutoBot.h" #include <unistd.h> using namespace ADBLib; #define CAM_FOV 57.0 #define CAM_XSIZE 1280.0 #define CAM_YSIZE 720.0 #define CAM_ANGRESO (CAM_FOV / CAM_XSIZE) class Robot: public IterativeRobot { private: TractionDrive* drivebase; CANTalon* motors[5]; Joystick* jys; ADBLib::Controller gpd; Compressor* compressor; Preferences* prefs; AHRS* ahrs; MultiVision mv; SimplePneumatic* shooterPiston; SimplePneumatic* liftArm; SimplePneumatic* extendArm; SimplePneumatic* tail; SimplePneumatic* intakeArms; CANTalon* fan; AutoBot* autobot; void RobotInit() { prefs = Preferences::GetInstance(); compressor = new Compressor(1); jys = new Joystick(0); gpd.setJoystick(jys); gpd.parseConfig("/ControlConfig.xml"); for (int i = 1; i < 5; i++) { motors[i] = new CANTalon(i); motors[i]->SetControlMode(CANTalon::kPercentVbus); motors[i]->SetVoltageRampRate(0.5); } motors[2]->SetInverted(true); motors[1]->SetInverted(true); drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]); ahrs = new AHRS(SPI::Port::kMXP); liftArm = new SimplePneumatic(new DoubleSolenoid(1, 0, 1)); shooterPiston = new SimplePneumatic(new Solenoid(1, 2)); extendArm = new SimplePneumatic(new DoubleSolenoid(1, 3, 4)); // bfdtail = new SimplePneumatic(new DoubleSolenoid(1, 5, 6)); intakeArms = new SimplePneumatic(new DoubleSolenoid(1, 5, 6)); fan = new CANTalon(5); mv.switchCamera("cam0"); autobot = new AutoBot; autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs); if (fork() == 0) system("/home/lvuser/grip &"); } void AutonomousInit() { autobot->switchMode(AutoBot::DRIVE); compressor->Start(); } void AutonomousPeriodic() { if (prefs->GetBoolean("fan-on", true)) fan->Set(1); else fan->Set(0); auto grip = NetworkTable::GetTable("grip"); auto areas = grip->GetNumberArray("targetsCam0/area", llvm::ArrayRef<double>()); unsigned int bestTarget = 0; for (unsigned int i = 0; i < areas.size(); i++) if (areas[i] > areas[bestTarget]) bestTarget = i; double diff = 640.0 - grip->GetNumberArray("targetsCam0/centerX", llvm::ArrayRef<double>())[bestTarget]; diff *= CAM_ANGRESO; drivebase->drive(0, 0.15, diff / 18.0); //autobot->update(); mv.postImage(); } void TeleopInit() { compressor->Start(); } void TeleopPeriodic() { shooterPiston->set(gpd["shooter"]); liftArm->set(gpd["liftArm"]); extendArm->set(gpd["extendArm"] != 0 ? 1 : -1); intakeArms->set(gpd["intakeArms"] != 0 ? 1 : -1); drivebase->drive(0, -gpd["transY"], gpd["rot"]); if (jys->GetRawButton(7)) mv.switchCamera("cam0"); if (jys->GetRawButton(8)) mv.switchCamera("cam1"); mv.postImage(); if (prefs->GetBoolean("fan-on", true)) fan->Set(1); else fan->Set(0); } void DisabledInit() { Logger::flushLogBuffers(); fan->Set(0); } void TestInit() { } void TestPeriodic() { } }; START_ROBOT_CLASS(Robot);
Fix vision-based autorotate code.
Fix vision-based autorotate code. Turns out that, despite the name of "GetNumberArray", GetNumberArray() *actually* returns an std::vector, so sizeof(container)/sizeof(element) doesn't work. Thanks to Mr. King for finding this!
C++
mit
Dreadbot/Dreadbot-VI
d4c9161eb9e275489b8be906f3afd5b28bf7135f
tests/unit/operation/polygonize/PolygonizeTest.cpp
tests/unit/operation/polygonize/PolygonizeTest.cpp
// $Id$ // // Test Suite for geos::operation::polygonize::Polygonizer class. // // Port of junit/operation/polygonize/PolygonizeTest.java // // tut #include <tut.hpp> // geos #include <geos/operation/polygonize/Polygonizer.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/Point.h> #include <geos/io/WKTReader.h> #include <geos/io/WKTWriter.h> // std #include <memory> #include <string> #include <vector> #include <iostream> namespace tut { // // Test Group // // Common data used by tests struct test_polygonizetest_data { geos::geom::GeometryFactory gf; geos::io::WKTReader wktreader; geos::io::WKTWriter wktwriter; typedef geos::geom::Geometry::AutoPtr GeomPtr; typedef geos::geom::Geometry Geom; typedef geos::geom::Polygon Poly; typedef geos::operation::polygonize::Polygonizer Polygonizer; test_polygonizetest_data() : gf(), wktreader(&gf) { wktwriter.setTrim(true); } template <class T> void delAll(T& cnt) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { delete *i; } } template <class T> void printAll(std::ostream& os, T& cnt) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { os << **i; } } GeomPtr readWKT(const std::string& inputWKT) { return GeomPtr(wktreader.read(inputWKT)); } void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms) { for (const char* const* ptr=inputWKT; *ptr; ++ptr) { geoms.push_back(readWKT(*ptr).release()); } } template <class T> bool contains( T& cnt, const Geom* g) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { const Geom* element = *i; if (element->equalsExact(g)) { return true; } } return false; } template <class T, class S> bool compare( T& ex, S& ob) { using std::cout; using std::endl; if ( ex.size() != ob.size() ) { cout << "Expected " << ex.size() << " polygons, obtained " << ob.size() << endl; return false; } for (typename T::iterator i=ex.begin(), e=ex.end(); i!=e; ++i) { if ( ! contains(ob, *i) ) { cout << "Expected " << wktwriter.write(*i) << " not found" << endl; return false; } } return true; } bool doTest(const char* const* inputWKT, const char* const* expectWKT) { using std::cout; using std::endl; std::vector<Geom*> inputGeoms, expectGeoms; readWKT(inputWKT, inputGeoms); readWKT(expectWKT, expectGeoms); Polygonizer polygonizer; polygonizer.add(&inputGeoms); std::auto_ptr< std::vector<Poly*> > retGeoms; retGeoms.reset( polygonizer.getPolygons() ); delAll(inputGeoms); bool ok = compare(expectGeoms, *retGeoms); if ( ! ok ) { cout << "OBTAINED(" << retGeoms->size() << "): "; printAll(cout, *retGeoms); cout << endl; ensure( "not all expected geometries in the obtained set", 0 ); } delAll(expectGeoms); delAll(*retGeoms); return ok; } }; typedef test_group<test_polygonizetest_data> group; typedef group::object object; group test_polygonizetest_group("geos::operation::polygonize::Polygonizer"); template<> template<> void object::test<1>() { static char const* const inp[] = { "LINESTRING EMPTY", "LINESTRING EMPTY", NULL }; static char const* const exp[] = { NULL }; doTest(inp, exp); } template<> template<> void object::test<2>() { static char const* const inp[] = { "LINESTRING (100 180, 20 20, 160 20, 100 180)", "LINESTRING (100 180, 80 60, 120 60, 100 180)", NULL }; static char const* const exp[] = { "POLYGON ((100 180, 120 60, 80 60, 100 180))", "POLYGON ((100 180, 160 20, 20 20, 100 180), (100 180, 80 60, 120 60, 100 180))", NULL }; doTest(inp, exp); } } // namespace tut
// $Id$ // // Test Suite for geos::operation::polygonize::Polygonizer class. // // Port of junit/operation/polygonize/PolygonizeTest.java // // tut #include <tut.hpp> // geos #include <geos/operation/polygonize/Polygonizer.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/Point.h> #include <geos/io/WKTReader.h> #include <geos/io/WKTWriter.h> // std #include <memory> #include <string> #include <vector> #include <iostream> namespace tut { // // Test Group // // Common data used by tests struct test_polygonizetest_data { geos::geom::GeometryFactory gf; geos::io::WKTReader wktreader; geos::io::WKTWriter wktwriter; typedef geos::geom::Geometry::AutoPtr GeomPtr; typedef geos::geom::Geometry Geom; typedef geos::geom::Polygon Poly; typedef geos::operation::polygonize::Polygonizer Polygonizer; test_polygonizetest_data() : gf(), wktreader(&gf) { wktwriter.setTrim(true); } template <class T> void delAll(T& cnt) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { delete *i; } } template <class T> void printAll(std::ostream& os, T& cnt) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { os << **i; } } GeomPtr readWKT(const std::string& inputWKT) { return GeomPtr(wktreader.read(inputWKT)); } void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms) { for (const char* const* ptr=inputWKT; *ptr; ++ptr) { geoms.push_back(readWKT(*ptr).release()); } } template <class T> bool contains( T& cnt, const Geom* g) { for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) { const Geom* element = *i; if (element->equalsExact(g)) { return true; } } return false; } template <class T, class S> bool compare( T& ex, S& ob) { using std::cout; using std::endl; if ( ex.size() != ob.size() ) { cout << "Expected " << ex.size() << " polygons, obtained " << ob.size() << endl; return false; } for (typename T::iterator i=ex.begin(), e=ex.end(); i!=e; ++i) { if ( ! contains(ob, *i) ) { cout << "Expected " << wktwriter.write(*i) << " not found" << endl; return false; } } return true; } bool doTest(const char* const* inputWKT, const char* const* expectWKT) { using std::cout; using std::endl; std::vector<Geom*> inputGeoms, expectGeoms; readWKT(inputWKT, inputGeoms); readWKT(expectWKT, expectGeoms); Polygonizer polygonizer; polygonizer.add(&inputGeoms); std::auto_ptr< std::vector<Poly*> > retGeoms; retGeoms.reset( polygonizer.getPolygons() ); delAll(inputGeoms); bool ok = compare(expectGeoms, *retGeoms); if ( ! ok ) { cout << "OBTAINED(" << retGeoms->size() << "): "; printAll(cout, *retGeoms); cout << endl; ensure( "not all expected geometries in the obtained set", 0 ); } delAll(expectGeoms); delAll(*retGeoms); return ok; } }; typedef test_group<test_polygonizetest_data> group; typedef group::object object; group test_polygonizetest_group("geos::operation::polygonize::Polygonizer"); // test1() in JTS template<> template<> void object::test<1>() { static char const* const inp[] = { "LINESTRING EMPTY", "LINESTRING EMPTY", NULL }; static char const* const exp[] = { NULL }; doTest(inp, exp); } // test2() in JTS template<> template<> void object::test<2>() { static char const* const inp[] = { "LINESTRING (100 180, 20 20, 160 20, 100 180)", "LINESTRING (100 180, 80 60, 120 60, 100 180)", NULL }; static char const* const exp[] = { "POLYGON ((100 180, 120 60, 80 60, 100 180))", "POLYGON ((100 180, 160 20, 20 20, 100 180), (100 180, 80 60, 120 60, 100 180))", NULL }; doTest(inp, exp); } } // namespace tut
Add port info
Add port info git-svn-id: 6c2b1bd10c324c49ea9d9e6e31006a80e70507cb@3434 5242fede-7e19-0410-aef8-94bd7d2200fb
C++
lgpl-2.1
CartoDB/libgeos,gtourkas/libgeos,manisandro/libgeos,CartoDB/libgeos,rkanavath/libgeos,mwtoews/libgeos,CartoDB/libgeos,WillieMaddox/libgeos,libgeos/libgeos,manisandro/libgeos,rkanavath/libgeos,CartoDB/libgeos,WillieMaddox/libgeos,mwtoews/libgeos,rkanavath/libgeos,libgeos/libgeos,kyroskoh/libgeos,mwtoews/libgeos,kyroskoh/libgeos,WillieMaddox/libgeos,gtourkas/libgeos,rkanavath/libgeos,rkanavath/libgeos,kyroskoh/libgeos,gtourkas/libgeos,WillieMaddox/libgeos,WillieMaddox/libgeos,kyroskoh/libgeos,manisandro/libgeos,kyroskoh/libgeos,CartoDB/libgeos,kyroskoh/libgeos,strk/libgeos,libgeos/libgeos,strk/libgeos,strk/libgeos,gtourkas/libgeos,manisandro/libgeos,strk/libgeos,libgeos/libgeos,mwtoews/libgeos,gtourkas/libgeos,WillieMaddox/libgeos,mwtoews/libgeos,mwtoews/libgeos,manisandro/libgeos,WillieMaddox/libgeos,libgeos/libgeos,manisandro/libgeos,kyroskoh/libgeos,manisandro/libgeos,strk/libgeos,CartoDB/libgeos,mwtoews/libgeos
166087c8f3fca8763a7a7e894034fcd45c13ffce
thrift/conformance/data/CompatibilityGenerator.cpp
thrift/conformance/data/CompatibilityGenerator.cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/conformance/data/CompatibilityGenerator.h> #include <cstdio> #include <optional> #include <random> #include <set> #include <stdexcept> #include <string_view> #include <vector> #include <boost/mp11.hpp> #include <fmt/core.h> #include <folly/container/Foreach.h> #include <folly/io/IOBufQueue.h> #include <thrift/conformance/cpp2/AnyRegistry.h> #include <thrift/conformance/cpp2/Object.h> #include <thrift/conformance/cpp2/Protocol.h> #include <thrift/conformance/data/ValueGenerator.h> #include <thrift/conformance/data/internal/TestGenerator.h> #include <thrift/conformance/if/gen-cpp2/test_suite_types.h> #include <thrift/lib/cpp/util/EnumUtils.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/type/Name.h> #include <thrift/test/testset/Testset.h> #include <thrift/test/testset/gen-cpp2/Enum_types.h> #include <thrift/test/testset/gen-cpp2/testset_types_custom_protocol.h> // TODO: use FieldQualifier using apache::thrift::test::testset::FieldModifier; using apache::thrift::test::testset::detail::mod_set; using apache::thrift::test::testset::detail::struct_ByFieldType; namespace mp11 = boost::mp11; namespace apache::thrift::conformance::data { namespace { [[nodiscard]] std::unique_ptr<folly::IOBuf> serialize( const Object& a, const Protocol& protocol) { switch (auto p = protocol.standard()) { case StandardProtocol::Compact: return serializeObject<apache::thrift::CompactProtocolWriter>(a); case StandardProtocol::Binary: return serializeObject<apache::thrift::BinaryProtocolWriter>(a); default: throw std::invalid_argument( "Unsupported protocol: " + util::enumNameSafe(p)); } } template <class TT> [[nodiscard]] TestCase addFieldTestCase(const Protocol& protocol) { const typename struct_ByFieldType<TT, mod_set<>>::type def; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize({}, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); TestCase testCase; testCase.name() = fmt::format("testset.{}/AddField", type::getName<TT>()); testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } template <class T> [[nodiscard]] Object toObject(const T& t) { Value v; ::apache::thrift::protocol::detail::ObjectWriter writer{&v}; t.write(&writer); return std::move(*v.objectValue_ref()); } template <class TT> [[nodiscard]] std::vector<TestCase> removeFieldTestCase( const Protocol& protocol) { const typename struct_ByFieldType<TT, mod_set<>>::type def; std::vector<TestCase> ret; for (const auto& value : ValueGenerator<TT>::getInterestingValues()) { typename struct_ByFieldType<TT, mod_set<>>::type data; data.field_1() = value.value; Object obj = toObject(def); Object dataObj = toObject(data); for (auto&& i : *dataObj.members()) { // Add new field with non-existing field id obj.members()[obj.members()->rbegin()->first + 1] = i.second; } RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize(obj, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}/RemoveField/{}", type::getName<TT>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } template <class ThriftStruct> [[nodiscard]] std::unique_ptr<folly::IOBuf> serializeThriftStruct( const ThriftStruct& s, const Protocol& protocol) { static_assert(is_thrift_class_v<ThriftStruct>); switch (auto p = protocol.standard()) { case StandardProtocol::Compact: return apache::thrift::CompactSerializer::serialize<folly::IOBufQueue>(s) .move(); case StandardProtocol::Binary: return apache::thrift::BinarySerializer::serialize<folly::IOBufQueue>(s) .move(); default: throw std::invalid_argument( "Unsupported protocol: " + util::enumNameSafe(p)); } } constexpr auto alwaysReturnTrue = [](auto&&) { return true; }; template < class Old, class New, bool compatible, class ShouldTest = decltype(alwaysReturnTrue)> [[nodiscard]] std::vector<TestCase> changeFieldTypeTestCase( const Protocol& protocol, ShouldTest shouldTest = alwaysReturnTrue) { static_assert(!std::is_same_v<Old, New>); std::vector<TestCase> ret; for (const auto& value : ValueGenerator<Old>::getInterestingValues()) { if (!shouldTest(value)) { continue; } typename struct_ByFieldType<Old, mod_set<FieldModifier::Optional>>::type old_data; typename struct_ByFieldType<New, mod_set<FieldModifier::Optional>>::type new_data; old_data.field_1() = value.value; if constexpr (compatible) { // If type change is compatible, new data will be deserialized as old data new_data.field_1() = static_cast<type::native_type<New>>(value.value); } RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(new_data, protocol); roundTrip.request()->value()->data() = *serializeThriftStruct(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}.{}/ChangeFieldType/{}", type::getName<Old>(), type::getName<New>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } template <class T> [[nodiscard]] const char* getQualifierName() { if (std::is_same_v<T, mod_set<>>) { return "Unqualified"; } // TODO(ytj): use std::is_same_v<T, mod_set<type::FieldQualifier::Optional>> if (std::is_same_v<T, mod_set<FieldModifier::Optional>>) { return "Optional"; } if (std::is_same_v<T, mod_set<FieldModifier::Required>>) { return "Required"; } throw std::runtime_error("Unknown ModSet"); } template <class Old, class New> [[nodiscard]] std::vector<TestCase> changeQualifierTestCase( const Protocol& protocol) { using TypeTag = type::list<type::i32_t>; std::vector<TestCase> ret; for (const auto& value : ValueGenerator<TypeTag>::getInterestingValues()) { typename struct_ByFieldType<TypeTag, Old>::type old_data; typename struct_ByFieldType<TypeTag, New>::type new_data; old_data.field_1() = value.value; new_data.field_1() = value.value; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}.{}/ChangeQualifier/{}", getQualifierName<Old>(), getQualifierName<New>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } using test::testset::DifferentNameEnumStruct; using test::testset::DifferentValueEnumStruct; using test::testset::LessFieldEnumStruct; using test::testset::NoZeroEnumStruct; using test::testset::StandardEnumStruct; template <class EnumStruct> std::string getEnumStructName() { if constexpr (std::is_same_v<EnumStruct, StandardEnumStruct>) { return "Standard"; } else if constexpr (std::is_same_v<EnumStruct, NoZeroEnumStruct>) { return "NoZero"; } else if constexpr (std::is_same_v<EnumStruct, LessFieldEnumStruct>) { return "MissingField"; } else if constexpr (std::is_same_v<EnumStruct, DifferentNameEnumStruct>) { return "NameMismatch"; } else if constexpr (std::is_same_v<EnumStruct, DifferentValueEnumStruct>) { return "ValueMismatch"; } else { static_assert(sizeof(EnumStruct) == 0); } return ""; } template <class E> void setEnum(E& e, std::underlying_type_t<E> i) { e = E(i); } template <class Old, class New> [[nodiscard]] TestCase changeEnumValueTestCase( const Protocol& protocol, Old old_data, int32_t old_value, New new_data, int32_t new_value) { setEnum(old_data.field().ensure(), old_value); setEnum(new_data.field().ensure(), new_value); RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(new_data, protocol); roundTrip.request()->value()->data() = *serializeThriftStruct(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset/ChangeEnumType/{}.{}.{}.{}", getEnumStructName<decltype(old_data)>(), old_value, getEnumStructName<decltype(new_data)>(), new_value); for (char& c : *testCase.name()) { if (c == '-') { c = '_'; } } testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } [[nodiscard]] std::vector<TestCase> changeEnumValueTestCases( const Protocol& protocol) { std::vector<TestCase> ret; using Enums = std::tuple< StandardEnumStruct, NoZeroEnumStruct, LessFieldEnumStruct, DifferentNameEnumStruct, DifferentValueEnumStruct>; folly::for_each(Enums{}, [&](auto old_data) { folly::for_each(Enums{}, [&](auto new_data) { ret.push_back( changeEnumValueTestCase(protocol, old_data, 0, new_data, 0)); ret.push_back( changeEnumValueTestCase(protocol, old_data, 1, new_data, 1)); }); }); // Remove field 0 ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 0, NoZeroEnumStruct{}, 0)); // Remove field ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, LessFieldEnumStruct{}, -1)); // Rename field ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, DifferentNameEnumStruct{}, 2)); // Change value ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, DifferentValueEnumStruct{}, -1)); return ret; } template <typename TT> Test createCompatibilityTest(const Protocol& protocol) { Test test; test.name() = protocol.name(); auto addToTest = [&](std::vector<TestCase>&& tests) { for (auto& t : tests) { test.testCases()->push_back(std::move(t)); } }; addToTest({addFieldTestCase<TT>(protocol)}); addToTest(removeFieldTestCase<TT>(protocol)); addToTest(changeFieldTypeTestCase<type::i32_t, type::i16_t, false>(protocol)); addToTest(changeFieldTypeTestCase<type::i32_t, type::i64_t, false>(protocol)); addToTest( changeFieldTypeTestCase<type::string_t, type::binary_t, true>(protocol)); addToTest(changeFieldTypeTestCase<type::binary_t, type::string_t, true>( protocol, [](auto&& value) { return value.name != "bad_utf8"; })); addToTest(changeFieldTypeTestCase<type::binary_t, type::string_t, false>( protocol, [](auto&& value) { return value.name == "bad_utf8"; })); addToTest(changeFieldTypeTestCase< type::set<type::i64_t>, type::list<type::i64_t>, false>(protocol)); addToTest(changeFieldTypeTestCase< type::list<type::i64_t>, type::set<type::i64_t>, false>(protocol)); // TODO: Test change between enum and integer. addToTest( changeQualifierTestCase<mod_set<>, mod_set<FieldModifier::Optional>>( protocol)); addToTest( changeQualifierTestCase<mod_set<>, mod_set<FieldModifier::Required>>( protocol)); addToTest( changeQualifierTestCase<mod_set<FieldModifier::Optional>, mod_set<>>( protocol)); addToTest(changeQualifierTestCase< mod_set<FieldModifier::Optional>, mod_set<FieldModifier::Required>>(protocol)); addToTest( changeQualifierTestCase<mod_set<FieldModifier::Required>, mod_set<>>( protocol)); addToTest(changeQualifierTestCase< mod_set<FieldModifier::Required>, mod_set<FieldModifier::Optional>>(protocol)); addToTest(changeEnumValueTestCases(protocol)); return test; } } // namespace TestSuite createCompatibilitySuite() { TestSuite suite; suite.name() = "CompatibilityTest"; for (const auto& protocol : detail::toProtocols(detail::kDefaultProtocols)) { mp11::mp_for_each<detail::PrimaryTypeTags>([&](auto t) { suite.tests()->emplace_back( createCompatibilityTest<decltype(t)>(protocol)); }); } return suite; } } // namespace apache::thrift::conformance::data
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/conformance/data/CompatibilityGenerator.h> #include <cstdio> #include <optional> #include <random> #include <set> #include <stdexcept> #include <string_view> #include <vector> #include <boost/mp11.hpp> #include <fmt/core.h> #include <folly/container/Foreach.h> #include <folly/io/IOBufQueue.h> #include <thrift/conformance/cpp2/AnyRegistry.h> #include <thrift/conformance/cpp2/Object.h> #include <thrift/conformance/cpp2/Protocol.h> #include <thrift/conformance/data/ValueGenerator.h> #include <thrift/conformance/data/internal/TestGenerator.h> #include <thrift/conformance/if/gen-cpp2/test_suite_types.h> #include <thrift/lib/cpp/util/EnumUtils.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/type/Name.h> #include <thrift/test/testset/Testset.h> #include <thrift/test/testset/gen-cpp2/Enum_types.h> #include <thrift/test/testset/gen-cpp2/testset_types_custom_protocol.h> // TODO: use FieldQualifier using apache::thrift::test::testset::FieldModifier; using apache::thrift::test::testset::detail::mod_set; using apache::thrift::test::testset::detail::struct_ByFieldType; namespace mp11 = boost::mp11; namespace apache::thrift::conformance::data { namespace { [[nodiscard]] std::unique_ptr<folly::IOBuf> serialize( const Object& a, const Protocol& protocol) { switch (auto p = protocol.standard()) { case StandardProtocol::Compact: return serializeObject<apache::thrift::CompactProtocolWriter>(a); case StandardProtocol::Binary: return serializeObject<apache::thrift::BinaryProtocolWriter>(a); default: throw std::invalid_argument( "Unsupported protocol: " + util::enumNameSafe(p)); } } template <class TT> [[nodiscard]] TestCase addFieldTestCase(const Protocol& protocol) { const typename struct_ByFieldType<TT, mod_set<>>::type def; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize({}, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); TestCase testCase; testCase.name() = fmt::format("testset.{}/AddField", type::getName<TT>()); testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } template <class TT> [[nodiscard]] TestCase addFieldWithCustomDefaultTestCase( const Protocol& protocol) { const typename struct_ByFieldType<TT, mod_set<FieldModifier::CustomDefault>>:: type def; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize({}, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); TestCase testCase; testCase.name() = fmt::format("testset.{}/AddFieldWithCustomDefault", type::getName<TT>()); testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } template <class TT> [[nodiscard]] TestCase addOptionalFieldWithCustomDefaultTestCase( const Protocol& protocol) { const typename struct_ByFieldType< TT, mod_set<FieldModifier::Optional, FieldModifier::CustomDefault>>::type def; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize({}, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); roundTrip.expectedResponse().emplace().value()->data() = *serialize({}, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}/AddOptionalFieldWithCustomDefault", type::getName<TT>()); testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } template <class T> [[nodiscard]] Object toObject(const T& t) { Value v; ::apache::thrift::protocol::detail::ObjectWriter writer{&v}; t.write(&writer); return std::move(*v.objectValue_ref()); } template <class TT> [[nodiscard]] std::vector<TestCase> removeFieldTestCase( const Protocol& protocol) { const typename struct_ByFieldType<TT, mod_set<>>::type def; std::vector<TestCase> ret; for (const auto& value : ValueGenerator<TT>::getInterestingValues()) { typename struct_ByFieldType<TT, mod_set<>>::type data; data.field_1() = value.value; Object obj = toObject(def); Object dataObj = toObject(data); for (auto&& i : *dataObj.members()) { // Add new field with non-existing field id obj.members()[obj.members()->rbegin()->first + 1] = i.second; } RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(def, protocol); roundTrip.request()->value()->data() = *serialize(obj, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(def, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}/RemoveField/{}", type::getName<TT>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } template <class ThriftStruct> [[nodiscard]] std::unique_ptr<folly::IOBuf> serializeThriftStruct( const ThriftStruct& s, const Protocol& protocol) { static_assert(is_thrift_class_v<ThriftStruct>); switch (auto p = protocol.standard()) { case StandardProtocol::Compact: return apache::thrift::CompactSerializer::serialize<folly::IOBufQueue>(s) .move(); case StandardProtocol::Binary: return apache::thrift::BinarySerializer::serialize<folly::IOBufQueue>(s) .move(); default: throw std::invalid_argument( "Unsupported protocol: " + util::enumNameSafe(p)); } } constexpr auto alwaysReturnTrue = [](auto&&) { return true; }; template < class Old, class New, bool compatible, class ShouldTest = decltype(alwaysReturnTrue)> [[nodiscard]] std::vector<TestCase> changeFieldTypeTestCase( const Protocol& protocol, ShouldTest shouldTest = alwaysReturnTrue) { static_assert(!std::is_same_v<Old, New>); std::vector<TestCase> ret; for (const auto& value : ValueGenerator<Old>::getInterestingValues()) { if (!shouldTest(value)) { continue; } typename struct_ByFieldType<Old, mod_set<FieldModifier::Optional>>::type old_data; typename struct_ByFieldType<New, mod_set<FieldModifier::Optional>>::type new_data; old_data.field_1() = value.value; if constexpr (compatible) { // If type change is compatible, new data will be deserialized as old data new_data.field_1() = static_cast<type::native_type<New>>(value.value); } RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(new_data, protocol); roundTrip.request()->value()->data() = *serializeThriftStruct(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}.{}/ChangeFieldType/{}", type::getName<Old>(), type::getName<New>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } template <class T> [[nodiscard]] const char* getQualifierName() { if (std::is_same_v<T, mod_set<>>) { return "Unqualified"; } // TODO(ytj): use std::is_same_v<T, mod_set<type::FieldQualifier::Optional>> if (std::is_same_v<T, mod_set<FieldModifier::Optional>>) { return "Optional"; } if (std::is_same_v<T, mod_set<FieldModifier::Required>>) { return "Required"; } throw std::runtime_error("Unknown ModSet"); } template <class Old, class New> [[nodiscard]] std::vector<TestCase> changeQualifierTestCase( const Protocol& protocol) { using TypeTag = type::list<type::i32_t>; std::vector<TestCase> ret; for (const auto& value : ValueGenerator<TypeTag>::getInterestingValues()) { typename struct_ByFieldType<TypeTag, Old>::type old_data; typename struct_ByFieldType<TypeTag, New>::type new_data; old_data.field_1() = value.value; new_data.field_1() = value.value; RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset.{}.{}/ChangeQualifier/{}", getQualifierName<Old>(), getQualifierName<New>(), value.name); testCase.test()->roundTrip_ref() = std::move(roundTrip); ret.push_back(std::move(testCase)); } return ret; } using test::testset::DifferentNameEnumStruct; using test::testset::DifferentValueEnumStruct; using test::testset::LessFieldEnumStruct; using test::testset::NoZeroEnumStruct; using test::testset::StandardEnumStruct; template <class EnumStruct> std::string getEnumStructName() { if constexpr (std::is_same_v<EnumStruct, StandardEnumStruct>) { return "Standard"; } else if constexpr (std::is_same_v<EnumStruct, NoZeroEnumStruct>) { return "NoZero"; } else if constexpr (std::is_same_v<EnumStruct, LessFieldEnumStruct>) { return "MissingField"; } else if constexpr (std::is_same_v<EnumStruct, DifferentNameEnumStruct>) { return "NameMismatch"; } else if constexpr (std::is_same_v<EnumStruct, DifferentValueEnumStruct>) { return "ValueMismatch"; } else { static_assert(sizeof(EnumStruct) == 0); } return ""; } template <class E> void setEnum(E& e, std::underlying_type_t<E> i) { e = E(i); } template <class Old, class New> [[nodiscard]] TestCase changeEnumValueTestCase( const Protocol& protocol, Old old_data, int32_t old_value, New new_data, int32_t new_value) { setEnum(old_data.field().ensure(), old_value); setEnum(new_data.field().ensure(), new_value); RoundTripTestCase roundTrip; roundTrip.request()->value() = AnyRegistry::generated().store(new_data, protocol); roundTrip.request()->value()->data() = *serializeThriftStruct(old_data, protocol); roundTrip.expectedResponse().emplace().value() = AnyRegistry::generated().store(new_data, protocol); TestCase testCase; testCase.name() = fmt::format( "testset/ChangeEnumType/{}.{}.{}.{}", getEnumStructName<decltype(old_data)>(), old_value, getEnumStructName<decltype(new_data)>(), new_value); for (char& c : *testCase.name()) { if (c == '-') { c = '_'; } } testCase.test()->roundTrip_ref() = std::move(roundTrip); return testCase; } [[nodiscard]] std::vector<TestCase> changeEnumValueTestCases( const Protocol& protocol) { std::vector<TestCase> ret; using Enums = std::tuple< StandardEnumStruct, NoZeroEnumStruct, LessFieldEnumStruct, DifferentNameEnumStruct, DifferentValueEnumStruct>; folly::for_each(Enums{}, [&](auto old_data) { folly::for_each(Enums{}, [&](auto new_data) { ret.push_back( changeEnumValueTestCase(protocol, old_data, 0, new_data, 0)); ret.push_back( changeEnumValueTestCase(protocol, old_data, 1, new_data, 1)); }); }); // Remove field 0 ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 0, NoZeroEnumStruct{}, 0)); // Remove field ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, LessFieldEnumStruct{}, -1)); // Rename field ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, DifferentNameEnumStruct{}, 2)); // Change value ret.push_back(changeEnumValueTestCase( protocol, StandardEnumStruct{}, 2, DifferentValueEnumStruct{}, -1)); return ret; } template <typename TT> Test createCompatibilityTest(const Protocol& protocol) { Test test; test.name() = protocol.name(); auto addToTest = [&](std::vector<TestCase>&& tests) { for (auto& t : tests) { test.testCases()->push_back(std::move(t)); } }; addToTest({addFieldTestCase<TT>(protocol)}); addToTest(removeFieldTestCase<TT>(protocol)); addToTest(changeFieldTypeTestCase<type::i32_t, type::i16_t, false>(protocol)); addToTest(changeFieldTypeTestCase<type::i32_t, type::i64_t, false>(protocol)); addToTest( changeFieldTypeTestCase<type::string_t, type::binary_t, true>(protocol)); addToTest(changeFieldTypeTestCase<type::binary_t, type::string_t, true>( protocol, [](auto&& value) { return value.name != "bad_utf8"; })); addToTest(changeFieldTypeTestCase<type::binary_t, type::string_t, false>( protocol, [](auto&& value) { return value.name == "bad_utf8"; })); addToTest(changeFieldTypeTestCase< type::set<type::i64_t>, type::list<type::i64_t>, false>(protocol)); addToTest(changeFieldTypeTestCase< type::list<type::i64_t>, type::set<type::i64_t>, false>(protocol)); // TODO: Test change between enum and integer. addToTest( changeQualifierTestCase<mod_set<>, mod_set<FieldModifier::Optional>>( protocol)); addToTest( changeQualifierTestCase<mod_set<>, mod_set<FieldModifier::Required>>( protocol)); addToTest( changeQualifierTestCase<mod_set<FieldModifier::Optional>, mod_set<>>( protocol)); addToTest(changeQualifierTestCase< mod_set<FieldModifier::Optional>, mod_set<FieldModifier::Required>>(protocol)); addToTest( changeQualifierTestCase<mod_set<FieldModifier::Required>, mod_set<>>( protocol)); addToTest(changeQualifierTestCase< mod_set<FieldModifier::Required>, mod_set<FieldModifier::Optional>>(protocol)); addToTest(changeEnumValueTestCases(protocol)); addToTest({addFieldWithCustomDefaultTestCase<TT>(protocol)}); addToTest({addOptionalFieldWithCustomDefaultTestCase<TT>(protocol)}); return test; } } // namespace TestSuite createCompatibilitySuite() { TestSuite suite; suite.name() = "CompatibilityTest"; for (const auto& protocol : detail::toProtocols(detail::kDefaultProtocols)) { mp11::mp_for_each<detail::PrimaryTypeTags>([&](auto t) { suite.tests()->emplace_back( createCompatibilityTest<decltype(t)>(protocol)); }); } return suite; } } // namespace apache::thrift::conformance::data
Test custom default on new field
Test custom default on new field Reviewed By: thedavekwon Differential Revision: D38417566 fbshipit-source-id: 6bc258564f64d83e209a37ba2acba328690363b3
C++
apache-2.0
facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift
ae1fdc2107f94912b1e9cee01e2ff355a5de258b
libcontextprovider/src/context.cpp
libcontextprovider/src/context.cpp
/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "context.h" #include "logging.h" #include "manager.h" #include "manageradaptor.h" #include "sconnect.h" #include "loggingfeatures.h" using namespace ContextProvider; /*! \class Context \brief The main class used to provide context data. Typically, to provide some keys you would: \code QStringList keys; keys.append("Some.Key1"); keys.append("Some.Key2"); Context::initService(QDBusConnection::SessionBus, "org.test.somename", keys); Context someKey1("Some.Key1"); Context someKey2("Some.Key2"); // Do something with someKey1, someKey2... \endcode \c Context::initService initializes a new bus connection with a specified service name and creates a Manager object on it. The clients obtain Subscriber objects through this Manager. For each service there is one Manager object. */ QHash<QString, Manager*> Context::busesToManagers; QHash<QString, QDBusConnection*> Context::busesToConnections; QHash<QString, Manager*> Context::keysToManagers; /// Constructor. This creates a new context property that should /// be used to provide/set values and get notified about subscribers appearing. Context::Context(const QString &k, QObject* parent) : QObject(parent), key(k) { contextDebug() << F_CONTEXT << "Creating new Context for key:" << key; manager = keysToManagers.value(key); if (manager == NULL) { contextCritical() << key << "is currently not provided by any service"; return; } sconnect(manager, SIGNAL(firstSubscriberAppeared(const QString&)), this, SLOT(onManagerFirstSubscriberAppeared(const QString&))); sconnect(manager, SIGNAL(lastSubscriberDisappeared(const QString&)), this, SLOT(onManagerLastSubscriberDisappeared(const QString&))); } /// Checks if a Context is valid (can be set/get/manipulated), prints an error message if not. /// Returns true if the Context is valid. False otherwise. Helper for the Context::set /// and Context::get familly of functions. bool Context::keyCheck() const { if (manager == NULL) { contextWarning() << "Trying to manipulate an invalid key:" << key; return false; } else return true; } /// Returns true if the key is valid. bool Context::isValid() const { return (manager != NULL); } /// Returns true if the key is set (it's value is determined). bool Context::isSet() const { if (! keyCheck()) return false; return (manager->getKeyValue(key) != QVariant()); } /// Returns the name of the key this Context represents. QString Context::getKey() const { return key; } /// Unsets the key value. The key value becomes undetermined. void Context::unset() { if (! keyCheck()) return; manager->setKeyValue(key, QVariant()); } /// Sets the key value to boolean \a v. void Context::set(bool v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to integer \a v. void Context::set(int v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to double \a v. void Context::set(double v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to QString \a v. void Context::set(const QString &v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to QVariant \a v. void Context::set(const QVariant &v) { if (! keyCheck()) return; manager->setKeyValue(key, v); } /// Returns the current value of the key. The returned QVariant is invalid /// if the key value is undetermined or the Context is invalid. QVariant Context::get() { if (! keyCheck()) return QVariant(); return manager->getKeyValue(key); } /// Called by Manager when first subscriber appears. Delegated if /// this concerns us. void Context::onManagerFirstSubscriberAppeared(const QString &key) { if (key == this->key) { contextDebug() << F_SIGNALS << F_CONTEXT << "First subscriber appeared for key:" << key; emit firstSubscriberAppeared(key); } } /// Called by Manager when last subscriber disappears. Delegate if /// this concerns us. void Context::onManagerLastSubscriberDisappeared(const QString &key) { if (key == this->key) { contextDebug() << F_SIGNALS << F_CONTEXT << "Last subscriber disappeared for key:" << key; emit lastSubscriberDisappeared(key); } } /// Destructor. Context::~Context() { contextDebug() << F_CONTEXT << F_DESTROY << "Destroying Context for key:" << key; } /// Initialize a new service on a bus \a busType with service name \a busName and a given /// set of \a keys. This is the main method used to setup/bootstrap the keys that /// we want to provide. /// Returns true if service was registered, false otherwise. bool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys) { contextDebug() << F_CONTEXT << "Initializing service for bus:" << busName; // Basic sanity check if (busesToManagers.contains(busName)) { contextCritical() << busName << "service is already registered"; return false; } QDBusConnection *connection = new QDBusConnection(QDBusConnection::connectToBus(busType, busName)); Manager *manager = new Manager(keys); ManagerAdaptor *managerAdaptor = new ManagerAdaptor(manager, connection); // Register service if (! connection->registerService(busName)) { contextCritical() << "Failed to register service with name" << busName; return false; } // Register object if (managerAdaptor && !connection->registerObject("/org/freedesktop/ContextKit/Manager", manager)) { contextCritical() << "Failed to register the Manager object for" << busName; return false; } busesToManagers.insert(busName, manager); busesToConnections.insert(busName, connection); // Add a mapping for all the keys -> manager foreach(QString key, keys) { if (keysToManagers.contains(key)) { contextCritical() << key << "is already provided by another manager/service!"; return false; } else { keysToManagers.insert(key, manager); } } return true; } /// Stops the previously started (with initService) service with the given \a busName. void Context::stopService(const QString &busName) { contextDebug() << F_CONTEXT << "Stopping service for bus:" << busName; // Basic sanity check if (! busesToManagers.contains(busName)) { contextCritical() << busName << "service is not started!"; return; } // The manager... Manager *manager = busesToManagers.value(busName); // Remove all key mappings foreach(QString key, QStringList(manager->getKeys())) { keysToManagers.remove(key); } // The connection... QDBusConnection *connection = busesToConnections.value(busName); // Unregister connection->unregisterObject("/org/freedesktop/ContextKit/Manager"); connection->unregisterService(busName); // Remove the remaining mappings busesToManagers.remove(busName); busesToConnections.remove(busName); // Dealloc delete manager; delete connection; }
/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "context.h" #include "logging.h" #include "manager.h" #include "manageradaptor.h" #include "sconnect.h" #include "loggingfeatures.h" using namespace ContextProvider; /*! \class Context \brief The main class used to provide context data. Typically, to provide some keys you would: \code QStringList keys; keys.append("Some.Key1"); keys.append("Some.Key2"); Context::initService(QDBusConnection::SessionBus, "org.test.somename", keys); Context someKey1("Some.Key1"); Context someKey2("Some.Key2"); // Do something with someKey1, someKey2... \endcode \c Context::initService initializes a new bus connection with a specified service name and creates a Manager object on it. The clients obtain Subscriber objects through this Manager. For each service there is one Manager object. */ QHash<QString, Manager*> Context::busesToManagers; QHash<QString, QDBusConnection*> Context::busesToConnections; QHash<QString, Manager*> Context::keysToManagers; /// Constructor. This creates a new context property that should /// be used to provide/set values and get notified about subscribers appearing. Context::Context(const QString &k, QObject* parent) : QObject(parent), key(k) { contextDebug() << F_CONTEXT << "Creating new Context for key:" << key; manager = keysToManagers.value(key); if (manager == NULL) { contextCritical() << key << "is currently not provided by any service"; return; } sconnect(manager, SIGNAL(firstSubscriberAppeared(const QString&)), this, SLOT(onManagerFirstSubscriberAppeared(const QString&))); sconnect(manager, SIGNAL(lastSubscriberDisappeared(const QString&)), this, SLOT(onManagerLastSubscriberDisappeared(const QString&))); } /// Checks if a Context is valid (can be set/get/manipulated), prints an error message if not. /// Returns true if the Context is valid. False otherwise. Helper for the Context::set /// and Context::get familly of functions. bool Context::keyCheck() const { if (manager == NULL) { contextWarning() << "Trying to manipulate an invalid key:" << key; return false; } else return true; } /// Returns true if the key is valid. bool Context::isValid() const { return (manager != NULL); } /// Returns true if the key is set (it's value is determined). bool Context::isSet() const { if (! keyCheck()) return false; return (manager->getKeyValue(key) != QVariant()); } /// Returns the name of the key this Context represents. QString Context::getKey() const { return key; } /// Unsets the key value. The key value becomes undetermined. void Context::unset() { if (! keyCheck()) return; manager->setKeyValue(key, QVariant()); } /// Sets the key value to boolean \a v. void Context::set(bool v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to integer \a v. void Context::set(int v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to double \a v. void Context::set(double v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to QString \a v. void Context::set(const QString &v) { if (! keyCheck()) return; manager->setKeyValue(key, QVariant(v)); } /// Sets the key value to QVariant \a v. void Context::set(const QVariant &v) { if (! keyCheck()) return; manager->setKeyValue(key, v); } /// Returns the current value of the key. The returned QVariant is invalid /// if the key value is undetermined or the Context is invalid. QVariant Context::get() { if (! keyCheck()) return QVariant(); return manager->getKeyValue(key); } /// Called by Manager when first subscriber appears. Delegated if /// this concerns us. void Context::onManagerFirstSubscriberAppeared(const QString &key) { if (key == this->key) { contextDebug() << F_SIGNALS << F_CONTEXT << "First subscriber appeared for key:" << key; emit firstSubscriberAppeared(key); } } /// Called by Manager when last subscriber disappears. Delegate if /// this concerns us. void Context::onManagerLastSubscriberDisappeared(const QString &key) { if (key == this->key) { contextDebug() << F_SIGNALS << F_CONTEXT << "Last subscriber disappeared for key:" << key; emit lastSubscriberDisappeared(key); } } /// Destructor. Context::~Context() { contextDebug() << F_CONTEXT << F_DESTROY << "Destroying Context for key:" << key; } /// Initialize a new service on a bus \a busType with service name \a busName and a given /// set of \a keys. This is the main method used to setup/bootstrap the keys that /// we want to provide. /// Returns true if service was registered, false otherwise. bool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys) { contextDebug() << F_CONTEXT << "Initializing service for bus:" << busName; // Basic sanity check if (busesToManagers.contains(busName)) { contextCritical() << busName << "service is already registered"; return false; } QDBusConnection *connection = new QDBusConnection(QDBusConnection::connectToBus(busType, busName)); Manager *manager = new Manager(keys); ManagerAdaptor *managerAdaptor = new ManagerAdaptor(manager, connection); // Register service if (! connection->registerService(busName)) { contextCritical() << "Failed to register service with name" << busName; return false; } // Register object if (managerAdaptor && !connection->registerObject("/org/freedesktop/ContextKit/Manager", manager)) { contextCritical() << "Failed to register the Manager object for" << busName; return false; } busesToManagers.insert(busName, manager); busesToConnections.insert(busName, connection); // Add a mapping for all the keys -> manager foreach(QString key, keys) { if (keysToManagers.contains(key)) { contextCritical() << key << "is already provided by another manager/service!"; return false; } else { keysToManagers.insert(key, manager); } } return true; } /// Stops the previously started (with initService) service with the given \a busName. void Context::stopService(const QString &busName) { contextDebug() << F_CONTEXT << "Stopping service for bus:" << busName; // Basic sanity check if (! busesToManagers.contains(busName)) { contextCritical() << busName << "service is not started!"; return; } // The manager... Manager *manager = busesToManagers.value(busName); // Remove all key mappings foreach(QString key, QStringList(manager->getKeys())) { keysToManagers.remove(key); } // The connection... QDBusConnection *connection = busesToConnections.value(busName); // Unregister connection->unregisterObject("/org/freedesktop/ContextKit/Manager"); connection->unregisterService(busName); // Remove the remaining mappings busesToManagers.remove(busName); busesToConnections.remove(busName); // Dealloc delete manager; delete connection; }
Make sure that the brief description of Context is a whole sentence.
Make sure that the brief description of Context is a whole sentence.
C++
lgpl-2.1
rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck
e19fab18c21cbe504ba3ba7b77c4e565e3ac44bc
libhoomd/analyzers/IMDInterface.cc
libhoomd/analyzers/IMDInterface.cc
/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // $Id$ // $URL$ // Maintainer: joaander /*! \file IMDInterface.cc \brief Defines the IMDInterface class */ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <boost/shared_array.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace boost; #include "IMDInterface.h" #include "SignalHandler.h" #include "vmdsock.h" #include "imd.h" #include <stdexcept> using namespace std; /*! After construction, IMDInterface is listening for connections on port \a port. analyze() must be called to handle any incoming connections. \param sysdef SystemDefinition containing the ParticleData that will be transmitted to VMD \param port port number to listen for connections on \param pause Set to true to pause the simulation and waith for IMD_GO before continuing \param rate Initial rate at which to send data */ IMDInterface::IMDInterface(boost::shared_ptr<SystemDefinition> sysdef, int port, bool pause, unsigned int rate) : Analyzer(sysdef) { int err = 0; if (port <= 0) { cerr << endl << "***Error! Invalid port specified" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } // start by initializing memory m_tmp_coords = new float[m_pdata->getN() * 3]; // intialize the listening socket vmdsock_init(); m_listen_sock = vmdsock_create(); // check for errors if (m_listen_sock == NULL) { cerr << endl << "***Error! Unable to create listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } // bind the socket and start listening for connections on that port m_connected_sock = NULL; err = vmdsock_bind(m_listen_sock, port); if (err == -1) { cerr << endl << "***Error! Unable to bind listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } err = vmdsock_listen(m_listen_sock); if (err == -1) { cerr << endl << "***Error! Unable to listen on listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } cout << "analyze.imd: listening on port " << port << endl; // initialize state m_active = false; m_paused = pause; m_trate = rate; m_count = 0; } IMDInterface::~IMDInterface() { // free all used memory delete[] m_tmp_coords; vmdsock_destroy(m_connected_sock); vmdsock_destroy(m_listen_sock); m_tmp_coords = NULL; m_connected_sock = NULL; m_listen_sock = NULL; } /*! If there is no active connection, analyze() will check to see if a connection attempt has been made since the last call. If so, it will attempt to handshake with VMD and on success will start transmitting data every time analyze() is called \param timestep Current time step of the simulation */ void IMDInterface::analyze(unsigned int timestep) { m_count++; do { // establish a connection if one has not been made if (m_connected_sock == NULL) establishConnectionAttempt(); // dispatch incoming commands if (m_connected_sock) dispatch(); // quit if cntrl-C was pressed if (g_sigint_recvd) { g_sigint_recvd = 0; throw runtime_error("SIG INT received while paused in IMD"); } } while (m_paused); // send data when active, connected, and the rate matches if (m_connected_sock && m_active && (m_trate == 0 || m_count % m_trate == 0)) sendCoords(timestep); } /*! \pre \a m_connected_sock is connected and handshaking has occured */ void IMDInterface::dispatch() { assert(m_connected_sock != NULL); // wait for messages, but only when paused int timeout = 0; if (m_paused) timeout = 5; // begin by checking to see if any commands have been received int length; int res = vmdsock_selread(m_connected_sock, timeout); // check to see if there are any errors if (res == -1) { cout << "analyze.imd: connection appears to have been terminated" << endl; processDeadConnection(); return; } // if a command is waiting if (res == 1) { // receive the header IMDType header = imd_recv_header(m_connected_sock, &length); switch (header) { case IMD_DISCONNECT: processIMD_DISCONNECT(); break; case 1: processIMD_GO(); break; case IMD_KILL: processIMD_KILL(); break; case IMD_MDCOMM: processIMD_MDCOMM(length); break; case IMD_TRATE: processIMD_TRATE(length); break; case IMD_PAUSE: processIMD_PAUSE(); break; case IMD_IOERROR: processIMD_IOERROR(); break; default: cout << "analyze.imd: received an unimplemented command (" << header << "), disconnecting" << endl; processDeadConnection(); break; } } // otherwise no message was received, do nothing } void IMDInterface::processIMD_DISCONNECT() { // cleanly disconnect and continue running the simulation. This is no different than what we do with a dead // connection processDeadConnection(); } void IMDInterface::processIMD_GO() { // unpause and start transmitting data m_paused = false; m_active = true; cout << "analyze.imd: Received IMD_GO, transmitting data now" << endl; } void IMDInterface::processIMD_KILL() { // disconnect (no different from handling a dead connection) processDeadConnection(); // terminate the simulation cout << "analyze.imd: Received IMD_KILL message, stopping the simulation" << endl; throw runtime_error("Received IMD_KILL message"); } void IMDInterface::processIMD_MDCOMM(unsigned int n) { // mdcomm is not currently handled cout << "**Warning! Ignoring IMD_MDCOMM message" << endl; shared_array<int32> indices(new int32[n]); shared_array<float> forces(new float[3*n]); int err = imd_recv_mdcomm(m_connected_sock, n, &indices[0], &forces[0]); if (err) { cerr << endl << "***Error! Error receiving mdcomm data, disconnecting" << endl << endl; processDeadConnection(); return; } } void IMDInterface::processIMD_TRATE(int rate) { cout << "analyze.imd: Received IMD_TRATE, setting trate to " << rate << endl; m_trate = rate; } void IMDInterface::processIMD_PAUSE() { cout << "analyze.imd: Received IMD_PAUSE, pausing simulation" << endl; m_paused = true; } void IMDInterface::processIMD_IOERROR() { // disconnect (no different from handling a dead connection) processDeadConnection(); // terminate the simulation cerr << endl << "***Error! Received IMD_IOERROR message, dropping the connection" << endl << endl; } void IMDInterface::processDeadConnection() { vmdsock_destroy(m_connected_sock); m_connected_sock = NULL; m_active = false; m_paused = false; } /*! \pre \a m_connected_sock is not connected \pre \a m_listen_sock is listening \a m_listen_sock is checked for any incoming connections. If an incoming connection is found, a handshake is made and \a m_connected_sock is set. If no connection is established, \a m_connected_sock is set to NULL. */ void IMDInterface::establishConnectionAttempt() { assert(m_listen_sock != NULL); assert(m_connected_sock == NULL); // wait for messages, but only when paused int timeout = 0; if (m_paused) timeout = 5; // check to see if there is an incoming connection if (vmdsock_selread(m_listen_sock, timeout) > 0) { // create the connection m_connected_sock = vmdsock_accept(m_listen_sock); if (imd_handshake(m_connected_sock)) { vmdsock_destroy(m_connected_sock); m_connected_sock = NULL; return; } else { cout << "analyze.imd: accepted connection" << endl; } } } /*! \param timestep Current time step of the simulation \pre A connection has been established Sends the current coordinates to VMD for display. */ void IMDInterface::sendCoords(unsigned int timestep) { assert(m_connected_sock != NULL); // setup and send the energies structure IMDEnergies energies; energies.tstep = timestep; energies.T = 0.0f; energies.Etot = 0.0f; energies.Epot = 0.0f; energies.Evdw = 0.0f; energies.Eelec = 0.0f; energies.Ebond = 0.0f; energies.Eangle = 0.0f; energies.Edihe = 0.0f; energies.Eimpr = 0.0f; int err = imd_send_energies(m_connected_sock, &energies); if (err) { cerr << endl << "***Error! Error sending energies, disconnecting" << endl << endl; processDeadConnection(); return; } // copy the particle data to the holding array and send it ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); for (unsigned int i = 0; i < arrays.nparticles; i++) { unsigned int tag = arrays.tag[i]; m_tmp_coords[tag*3] = float(arrays.x[i]); m_tmp_coords[tag*3 + 1] = float(arrays.y[i]); m_tmp_coords[tag*3 + 2] = float(arrays.z[i]); } m_pdata->release(); err = imd_send_fcoords(m_connected_sock, arrays.nparticles, m_tmp_coords); if (err) { cerr << "***Error! Error sending coordinates, disconnecting" << endl << endl; processDeadConnection(); return; } } void export_IMDInterface() { class_<IMDInterface, boost::shared_ptr<IMDInterface>, bases<Analyzer>, boost::noncopyable> ("IMDInterface", init< boost::shared_ptr<SystemDefinition>, int, bool, unsigned int >()) ; } #ifdef WIN32 #pragma warning( pop ) #endif
/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // $Id$ // $URL$ // Maintainer: joaander /*! \file IMDInterface.cc \brief Defines the IMDInterface class */ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <boost/shared_array.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace boost; #include "IMDInterface.h" #include "SignalHandler.h" #include "vmdsock.h" #include "imd.h" #include <stdexcept> using namespace std; /*! After construction, IMDInterface is listening for connections on port \a port. analyze() must be called to handle any incoming connections. \param sysdef SystemDefinition containing the ParticleData that will be transmitted to VMD \param port port number to listen for connections on \param pause Set to true to pause the simulation and waith for IMD_GO before continuing \param rate Initial rate at which to send data */ IMDInterface::IMDInterface(boost::shared_ptr<SystemDefinition> sysdef, int port, bool pause, unsigned int rate) : Analyzer(sysdef) { int err = 0; if (port <= 0) { cerr << endl << "***Error! Invalid port specified" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } // start by initializing memory m_tmp_coords = new float[m_pdata->getN() * 3]; // intialize the listening socket vmdsock_init(); m_listen_sock = vmdsock_create(); // check for errors if (m_listen_sock == NULL) { cerr << endl << "***Error! Unable to create listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } // bind the socket and start listening for connections on that port m_connected_sock = NULL; err = vmdsock_bind(m_listen_sock, port); if (err == -1) { cerr << endl << "***Error! Unable to bind listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } err = vmdsock_listen(m_listen_sock); if (err == -1) { cerr << endl << "***Error! Unable to listen on listening socket" << endl << endl; throw runtime_error("Error initializing IMDInterface"); } cout << "analyze.imd: listening on port " << port << endl; // initialize state m_active = false; m_paused = pause; m_trate = rate; m_count = 0; } IMDInterface::~IMDInterface() { // free all used memory delete[] m_tmp_coords; vmdsock_destroy(m_connected_sock); vmdsock_destroy(m_listen_sock); m_tmp_coords = NULL; m_connected_sock = NULL; m_listen_sock = NULL; } /*! If there is no active connection, analyze() will check to see if a connection attempt has been made since the last call. If so, it will attempt to handshake with VMD and on success will start transmitting data every time analyze() is called \param timestep Current time step of the simulation */ void IMDInterface::analyze(unsigned int timestep) { m_count++; do { // establish a connection if one has not been made if (m_connected_sock == NULL) establishConnectionAttempt(); // dispatch incoming commands if (m_connected_sock) dispatch(); // quit if cntrl-C was pressed if (g_sigint_recvd) { g_sigint_recvd = 0; throw runtime_error("SIG INT received while paused in IMD"); } } while (m_paused); // send data when active, connected, and the rate matches if (m_connected_sock && m_active && (m_trate == 0 || m_count % m_trate == 0)) sendCoords(timestep); } /*! \pre \a m_connected_sock is connected and handshaking has occured */ void IMDInterface::dispatch() { assert(m_connected_sock != NULL); // wait for messages, but only when paused int timeout = 0; if (m_paused) timeout = 5; // begin by checking to see if any commands have been received int length; int res = vmdsock_selread(m_connected_sock, timeout); // check to see if there are any errors if (res == -1) { cout << "analyze.imd: connection appears to have been terminated" << endl; processDeadConnection(); return; } // if a command is waiting if (res == 1) { // receive the header IMDType header = imd_recv_header(m_connected_sock, &length); switch (header) { case IMD_DISCONNECT: processIMD_DISCONNECT(); break; case IMD_GO: processIMD_GO(); break; case IMD_KILL: processIMD_KILL(); break; case IMD_MDCOMM: processIMD_MDCOMM(length); break; case IMD_TRATE: processIMD_TRATE(length); break; case IMD_PAUSE: processIMD_PAUSE(); break; case IMD_IOERROR: processIMD_IOERROR(); break; default: cout << "analyze.imd: received an unimplemented command (" << header << "), disconnecting" << endl; processDeadConnection(); break; } } // otherwise no message was received, do nothing } void IMDInterface::processIMD_DISCONNECT() { // cleanly disconnect and continue running the simulation. This is no different than what we do with a dead // connection processDeadConnection(); } void IMDInterface::processIMD_GO() { // unpause and start transmitting data m_paused = false; m_active = true; cout << "analyze.imd: Received IMD_GO, transmitting data now" << endl; } void IMDInterface::processIMD_KILL() { // disconnect (no different from handling a dead connection) processDeadConnection(); // terminate the simulation cout << "analyze.imd: Received IMD_KILL message, stopping the simulation" << endl; throw runtime_error("Received IMD_KILL message"); } void IMDInterface::processIMD_MDCOMM(unsigned int n) { // mdcomm is not currently handled cout << "**Warning! Ignoring IMD_MDCOMM message" << endl; shared_array<int32> indices(new int32[n]); shared_array<float> forces(new float[3*n]); int err = imd_recv_mdcomm(m_connected_sock, n, &indices[0], &forces[0]); if (err) { cerr << endl << "***Error! Error receiving mdcomm data, disconnecting" << endl << endl; processDeadConnection(); return; } } void IMDInterface::processIMD_TRATE(int rate) { cout << "analyze.imd: Received IMD_TRATE, setting trate to " << rate << endl; m_trate = rate; } void IMDInterface::processIMD_PAUSE() { cout << "analyze.imd: Received IMD_PAUSE, pausing simulation" << endl; m_paused = true; } void IMDInterface::processIMD_IOERROR() { // disconnect (no different from handling a dead connection) processDeadConnection(); // terminate the simulation cerr << endl << "***Error! Received IMD_IOERROR message, dropping the connection" << endl << endl; } void IMDInterface::processDeadConnection() { vmdsock_destroy(m_connected_sock); m_connected_sock = NULL; m_active = false; m_paused = false; } /*! \pre \a m_connected_sock is not connected \pre \a m_listen_sock is listening \a m_listen_sock is checked for any incoming connections. If an incoming connection is found, a handshake is made and \a m_connected_sock is set. If no connection is established, \a m_connected_sock is set to NULL. */ void IMDInterface::establishConnectionAttempt() { assert(m_listen_sock != NULL); assert(m_connected_sock == NULL); // wait for messages, but only when paused int timeout = 0; if (m_paused) timeout = 5; // check to see if there is an incoming connection if (vmdsock_selread(m_listen_sock, timeout) > 0) { // create the connection m_connected_sock = vmdsock_accept(m_listen_sock); if (imd_handshake(m_connected_sock)) { vmdsock_destroy(m_connected_sock); m_connected_sock = NULL; return; } else { cout << "analyze.imd: accepted connection" << endl; } } } /*! \param timestep Current time step of the simulation \pre A connection has been established Sends the current coordinates to VMD for display. */ void IMDInterface::sendCoords(unsigned int timestep) { assert(m_connected_sock != NULL); // setup and send the energies structure IMDEnergies energies; energies.tstep = timestep; energies.T = 0.0f; energies.Etot = 0.0f; energies.Epot = 0.0f; energies.Evdw = 0.0f; energies.Eelec = 0.0f; energies.Ebond = 0.0f; energies.Eangle = 0.0f; energies.Edihe = 0.0f; energies.Eimpr = 0.0f; int err = imd_send_energies(m_connected_sock, &energies); if (err) { cerr << endl << "***Error! Error sending energies, disconnecting" << endl << endl; processDeadConnection(); return; } // copy the particle data to the holding array and send it ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); for (unsigned int i = 0; i < arrays.nparticles; i++) { unsigned int tag = arrays.tag[i]; m_tmp_coords[tag*3] = float(arrays.x[i]); m_tmp_coords[tag*3 + 1] = float(arrays.y[i]); m_tmp_coords[tag*3 + 2] = float(arrays.z[i]); } m_pdata->release(); err = imd_send_fcoords(m_connected_sock, arrays.nparticles, m_tmp_coords); if (err) { cerr << "***Error! Error sending coordinates, disconnecting" << endl << endl; processDeadConnection(); return; } } void export_IMDInterface() { class_<IMDInterface, boost::shared_ptr<IMDInterface>, bases<Analyzer>, boost::noncopyable> ("IMDInterface", init< boost::shared_ptr<SystemDefinition>, int, bool, unsigned int >()) ; } #ifdef WIN32 #pragma warning( pop ) #endif
Fix bug processing IMD_GO
Fix bug processing IMD_GO git-svn-id: 4ba210d0a933e3fb1aa9ab096f190cd38965d92a@2839 fa922fa7-2fde-0310-acd8-f43f465a7996
C++
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
5cb89d115fa03bcda9171d24a6cd2a525406f1a6
src/World.cpp
src/World.cpp
/* This file is part of Ingen. Copyright 2007-2016 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include "ingen/World.hpp" #include "ingen/Atom.hpp" #include "ingen/Configuration.hpp" #include "ingen/DataAccess.hpp" #include "ingen/EngineBase.hpp" #include "ingen/FilePath.hpp" #include "ingen/Forge.hpp" #include "ingen/InstanceAccess.hpp" #include "ingen/LV2Features.hpp" #include "ingen/Library.hpp" #include "ingen/Log.hpp" #include "ingen/Module.hpp" #include "ingen/Parser.hpp" #include "ingen/Serialiser.hpp" #include "ingen/URI.hpp" #include "ingen/URIMap.hpp" #include "ingen/URIs.hpp" #include "ingen/ingen.h" #include "ingen/runtime_paths.hpp" #include "lilv/lilv.h" #include "lv2/log/log.h" #include "lv2/urid/urid.h" #include "sord/sordmm.hpp" #include <cstdint> #include <list> #include <map> #include <memory> #include <string> #include <utility> using std::string; namespace ingen { class Interface; class Store; /** Load a dynamic module from the default path. * * This will check in the directories specified in the environment variable * INGEN_MODULE_PATH (typical colon delimited format), then the default module * installation directory (ie /usr/local/lib/ingen), in that order. * * \param name The base name of the module, e.g. "ingen_jack" */ static std::unique_ptr<Library> ingen_load_library(Log& log, const string& name) { const auto path = ingen_module_path(name); if (path.empty()) { log.error("Failed to find %1% (%2%)\n", name, Library::get_last_error()); return nullptr; } std::unique_ptr<Library> library = std::make_unique<Library>(path); if (*library) { return library; } log.error("Unable to load %1% from %2% (%3%)\n", name, path, Library::get_last_error()); return nullptr; } class World::Impl { public: Impl(LV2_URID_Map* map, LV2_URID_Unmap* unmap, LV2_Log_Log* log_feature) : argc(nullptr) , argv(nullptr) , lv2_features(nullptr) , rdf_world(new Sord::World()) , lilv_world(lilv_world_new(), lilv_world_free) , uri_map(log, map, unmap) , forge(uri_map) , uris(forge, &uri_map, lilv_world.get()) , conf(forge) , log(log_feature, uris) { lv2_features = new LV2Features(); lv2_features->add_feature(uri_map.urid_map_feature()); lv2_features->add_feature(uri_map.urid_unmap_feature()); lv2_features->add_feature(std::make_shared<InstanceAccess>()); lv2_features->add_feature(std::make_shared<DataAccess>()); lv2_features->add_feature(std::make_shared<Log::Feature>()); lilv_world_load_all(lilv_world.get()); // Set up RDF namespaces rdf_world->add_prefix("atom", "http://lv2plug.in/ns/ext/atom#"); rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#"); rdf_world->add_prefix("ingen", INGEN_NS); rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#"); rdf_world->add_prefix("midi", "http://lv2plug.in/ns/ext/midi#"); rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#"); rdf_world->add_prefix("patch", "http://lv2plug.in/ns/ext/patch#"); rdf_world->add_prefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#"); // Load internal 'plugin' information into lilv world LilvNode* rdf_type = lilv_new_uri(lilv_world.get(), "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); LilvNode* ingen_Plugin = lilv_new_uri(lilv_world.get(), INGEN__Plugin); LilvNodes* internals = lilv_world_find_nodes(lilv_world.get(), nullptr, rdf_type, ingen_Plugin); LILV_FOREACH (nodes, i, internals) { const LilvNode* internal = lilv_nodes_get(internals, i); lilv_world_load_resource(lilv_world.get(), internal); } lilv_nodes_free(internals); lilv_node_free(rdf_type); lilv_node_free(ingen_Plugin); } ~Impl() { if (engine) { engine->quit(); } // Delete module objects but save pointers to libraries using Libs = std::list<std::unique_ptr<Library>>; Libs libs; for (auto& m : modules) { libs.emplace_back(std::move(m.second->library)); delete m.second; } serialiser.reset(); parser.reset(); interface.reset(); engine.reset(); store.reset(); interface_factories.clear(); script_runners.clear(); delete lv2_features; // Module libraries go out of scope and close here } Impl(const Impl&) = delete; Impl(Impl&&) = delete; Impl& operator=(const Impl&) = delete; Impl& operator=(Impl&&) = delete; using Modules = std::map<std::string, Module*>; Modules modules; using InterfaceFactories = std::map<const std::string, World::InterfaceFactory>; InterfaceFactories interface_factories; using ScriptRunner = bool (*)(World& world, const char* filename); using ScriptRunners = std::map<const std::string, ScriptRunner>; ScriptRunners script_runners; using LilvWorldUPtr = std::unique_ptr<LilvWorld, decltype(&lilv_world_free)>; int* argc; char*** argv; LV2Features* lv2_features; std::unique_ptr<Sord::World> rdf_world; LilvWorldUPtr lilv_world; URIMap uri_map; Forge forge; URIs uris; Configuration conf; Log log; std::shared_ptr<Interface> interface; std::shared_ptr<EngineBase> engine; std::shared_ptr<Serialiser> serialiser; std::shared_ptr<Parser> parser; std::shared_ptr<Store> store; std::mutex rdf_mutex; std::string jack_uuid; }; World::World(LV2_URID_Map* map, LV2_URID_Unmap* unmap, LV2_Log_Log* log) : _impl(new Impl(map, unmap, log)) { _impl->serialiser = std::make_shared<Serialiser>(*this); _impl->parser = std::make_shared<Parser>(); } World::~World() { delete _impl; } void World::load_configuration(int& argc, char**& argv) { _impl->argc = &argc; _impl->argv = &argv; // Parse default configuration files const auto files = _impl->conf.load_default("ingen", "options.ttl"); for (const auto& f : files) { _impl->log.info("Loaded configuration %1%\n", f); } // Parse command line options, overriding configuration file values _impl->conf.parse(argc, argv); _impl->log.set_flush(_impl->conf.option("flush-log").get<int32_t>()); _impl->log.set_trace(_impl->conf.option("trace").get<int32_t>()); } void World::set_engine(const std::shared_ptr<EngineBase>& e) { _impl->engine = e; } void World::set_interface(const std::shared_ptr<Interface>& i) { _impl->interface = i; } void World::set_store(const std::shared_ptr<Store>& s) { _impl->store = s; } std::shared_ptr<EngineBase> World::engine() { return _impl->engine; } std::shared_ptr<Interface> World::interface() { return _impl->interface; } std::shared_ptr<Parser> World::parser() { return _impl->parser; } std::shared_ptr<Serialiser> World::serialiser() { return _impl->serialiser; } std::shared_ptr<Store> World::store() { return _impl->store; } int& World::argc() { return *_impl->argc; } char**& World::argv() { return *_impl->argv; } Configuration& World::conf() { return _impl->conf; } Log& World::log() { return _impl->log; } std::mutex& World::rdf_mutex() { return _impl->rdf_mutex; } Sord::World* World::rdf_world() { return _impl->rdf_world.get(); } LilvWorld* World::lilv_world() { return _impl->lilv_world.get(); } LV2Features& World::lv2_features() { return *_impl->lv2_features; } Forge& World::forge() { return _impl->forge; } URIs& World::uris() { return _impl->uris; } URIMap& World::uri_map() { return _impl->uri_map; } bool World::load_module(const char* name) { auto i = _impl->modules.find(name); if (i != _impl->modules.end()) { return true; } log().info("Loading %1% module\n", name); std::unique_ptr<ingen::Library> lib = ingen_load_library(log(), name); ingen::Module* (*module_load)() = lib ? reinterpret_cast<ingen::Module* (*)()>( lib->get_function("ingen_module_load")) : nullptr; if (module_load) { Module* module = module_load(); if (module) { module->library = std::move(lib); module->load(*this); _impl->modules.emplace(string(name), module); return true; } } log().error("Failed to load module `%1%' (%2%)\n", name, lib->get_last_error()); return false; } bool World::run_module(const char* name) { auto i = _impl->modules.find(name); if (i == _impl->modules.end()) { log().error("Attempt to run unloaded module `%1%'\n", name); return false; } i->second->run(*this); return true; } /** Get an interface for a remote engine at `engine_uri` */ std::shared_ptr<Interface> World::new_interface(const URI& engine_uri, const std::shared_ptr<Interface>& respondee) { const Impl::InterfaceFactories::const_iterator i = _impl->interface_factories.find(std::string(engine_uri.scheme())); if (i == _impl->interface_factories.end()) { log().warn("Unknown URI scheme `%1%'\n", engine_uri.scheme()); return nullptr; } return i->second(*this, engine_uri, respondee); } /** Run a script of type `mime_type` at filename `filename` */ bool World::run(const std::string& mime_type, const std::string& filename) { const Impl::ScriptRunners::const_iterator i = _impl->script_runners.find(mime_type); if (i == _impl->script_runners.end()) { log().warn("Unknown script MIME type `%1%'\n", mime_type); return false; } return i->second(*this, filename.c_str()); } void World::add_interface_factory(const std::string& scheme, InterfaceFactory factory) { _impl->interface_factories.emplace(scheme, factory); } void World::set_jack_uuid(const std::string& uuid) { _impl->jack_uuid = uuid; } std::string World::jack_uuid() { return _impl->jack_uuid; } } // namespace ingen
/* This file is part of Ingen. Copyright 2007-2016 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include "ingen/World.hpp" #include "ingen/Atom.hpp" #include "ingen/Configuration.hpp" #include "ingen/DataAccess.hpp" #include "ingen/EngineBase.hpp" #include "ingen/FilePath.hpp" #include "ingen/Forge.hpp" #include "ingen/InstanceAccess.hpp" #include "ingen/LV2Features.hpp" #include "ingen/Library.hpp" #include "ingen/Log.hpp" #include "ingen/Module.hpp" #include "ingen/Parser.hpp" #include "ingen/Serialiser.hpp" #include "ingen/URI.hpp" #include "ingen/URIMap.hpp" #include "ingen/URIs.hpp" #include "ingen/ingen.h" #include "ingen/runtime_paths.hpp" #include "lilv/lilv.h" #include "lv2/log/log.h" #include "lv2/urid/urid.h" #include "sord/sordmm.hpp" #include <cstdint> #include <list> #include <map> #include <memory> #include <string> #include <utility> using std::string; namespace ingen { class Interface; class Store; /** Load a dynamic module from the default path. * * This will check in the directories specified in the environment variable * INGEN_MODULE_PATH (typical colon delimited format), then the default module * installation directory (ie /usr/local/lib/ingen), in that order. * * \param name The base name of the module, e.g. "ingen_jack" */ static std::unique_ptr<Library> ingen_load_library(Log& log, const string& name) { const auto path = ingen_module_path(name); if (path.empty()) { log.error("Failed to find %1% (%2%)\n", name, Library::get_last_error()); return nullptr; } log.info("Loading module %1%\n", path); std::unique_ptr<Library> library = std::make_unique<Library>(path); if (*library) { return library; } log.error("Unable to load %1% from %2% (%3%)\n", name, path, Library::get_last_error()); return nullptr; } class World::Impl { public: Impl(LV2_URID_Map* map, LV2_URID_Unmap* unmap, LV2_Log_Log* log_feature) : argc(nullptr) , argv(nullptr) , lv2_features(nullptr) , rdf_world(new Sord::World()) , lilv_world(lilv_world_new(), lilv_world_free) , uri_map(log, map, unmap) , forge(uri_map) , uris(forge, &uri_map, lilv_world.get()) , conf(forge) , log(log_feature, uris) { lv2_features = new LV2Features(); lv2_features->add_feature(uri_map.urid_map_feature()); lv2_features->add_feature(uri_map.urid_unmap_feature()); lv2_features->add_feature(std::make_shared<InstanceAccess>()); lv2_features->add_feature(std::make_shared<DataAccess>()); lv2_features->add_feature(std::make_shared<Log::Feature>()); lilv_world_load_all(lilv_world.get()); // Set up RDF namespaces rdf_world->add_prefix("atom", "http://lv2plug.in/ns/ext/atom#"); rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#"); rdf_world->add_prefix("ingen", INGEN_NS); rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#"); rdf_world->add_prefix("midi", "http://lv2plug.in/ns/ext/midi#"); rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#"); rdf_world->add_prefix("patch", "http://lv2plug.in/ns/ext/patch#"); rdf_world->add_prefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#"); // Load internal 'plugin' information into lilv world LilvNode* rdf_type = lilv_new_uri(lilv_world.get(), "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); LilvNode* ingen_Plugin = lilv_new_uri(lilv_world.get(), INGEN__Plugin); LilvNodes* internals = lilv_world_find_nodes(lilv_world.get(), nullptr, rdf_type, ingen_Plugin); LILV_FOREACH (nodes, i, internals) { const LilvNode* internal = lilv_nodes_get(internals, i); lilv_world_load_resource(lilv_world.get(), internal); } lilv_nodes_free(internals); lilv_node_free(rdf_type); lilv_node_free(ingen_Plugin); } ~Impl() { if (engine) { engine->quit(); } // Delete module objects but save pointers to libraries using Libs = std::list<std::unique_ptr<Library>>; Libs libs; for (auto& m : modules) { libs.emplace_back(std::move(m.second->library)); delete m.second; } serialiser.reset(); parser.reset(); interface.reset(); engine.reset(); store.reset(); interface_factories.clear(); script_runners.clear(); delete lv2_features; // Module libraries go out of scope and close here } Impl(const Impl&) = delete; Impl(Impl&&) = delete; Impl& operator=(const Impl&) = delete; Impl& operator=(Impl&&) = delete; using Modules = std::map<std::string, Module*>; Modules modules; using InterfaceFactories = std::map<const std::string, World::InterfaceFactory>; InterfaceFactories interface_factories; using ScriptRunner = bool (*)(World& world, const char* filename); using ScriptRunners = std::map<const std::string, ScriptRunner>; ScriptRunners script_runners; using LilvWorldUPtr = std::unique_ptr<LilvWorld, decltype(&lilv_world_free)>; int* argc; char*** argv; LV2Features* lv2_features; std::unique_ptr<Sord::World> rdf_world; LilvWorldUPtr lilv_world; URIMap uri_map; Forge forge; URIs uris; Configuration conf; Log log; std::shared_ptr<Interface> interface; std::shared_ptr<EngineBase> engine; std::shared_ptr<Serialiser> serialiser; std::shared_ptr<Parser> parser; std::shared_ptr<Store> store; std::mutex rdf_mutex; std::string jack_uuid; }; World::World(LV2_URID_Map* map, LV2_URID_Unmap* unmap, LV2_Log_Log* log) : _impl(new Impl(map, unmap, log)) { _impl->serialiser = std::make_shared<Serialiser>(*this); _impl->parser = std::make_shared<Parser>(); } World::~World() { delete _impl; } void World::load_configuration(int& argc, char**& argv) { _impl->argc = &argc; _impl->argv = &argv; // Parse default configuration files const auto files = _impl->conf.load_default("ingen", "options.ttl"); for (const auto& f : files) { _impl->log.info("Loaded configuration %1%\n", f); } // Parse command line options, overriding configuration file values _impl->conf.parse(argc, argv); _impl->log.set_flush(_impl->conf.option("flush-log").get<int32_t>()); _impl->log.set_trace(_impl->conf.option("trace").get<int32_t>()); } void World::set_engine(const std::shared_ptr<EngineBase>& e) { _impl->engine = e; } void World::set_interface(const std::shared_ptr<Interface>& i) { _impl->interface = i; } void World::set_store(const std::shared_ptr<Store>& s) { _impl->store = s; } std::shared_ptr<EngineBase> World::engine() { return _impl->engine; } std::shared_ptr<Interface> World::interface() { return _impl->interface; } std::shared_ptr<Parser> World::parser() { return _impl->parser; } std::shared_ptr<Serialiser> World::serialiser() { return _impl->serialiser; } std::shared_ptr<Store> World::store() { return _impl->store; } int& World::argc() { return *_impl->argc; } char**& World::argv() { return *_impl->argv; } Configuration& World::conf() { return _impl->conf; } Log& World::log() { return _impl->log; } std::mutex& World::rdf_mutex() { return _impl->rdf_mutex; } Sord::World* World::rdf_world() { return _impl->rdf_world.get(); } LilvWorld* World::lilv_world() { return _impl->lilv_world.get(); } LV2Features& World::lv2_features() { return *_impl->lv2_features; } Forge& World::forge() { return _impl->forge; } URIs& World::uris() { return _impl->uris; } URIMap& World::uri_map() { return _impl->uri_map; } bool World::load_module(const char* name) { auto i = _impl->modules.find(name); if (i != _impl->modules.end()) { return true; } std::unique_ptr<ingen::Library> lib = ingen_load_library(log(), name); ingen::Module* (*module_load)() = lib ? reinterpret_cast<ingen::Module* (*)()>( lib->get_function("ingen_module_load")) : nullptr; if (module_load) { Module* module = module_load(); if (module) { module->library = std::move(lib); module->load(*this); _impl->modules.emplace(string(name), module); return true; } } log().error("Failed to load module `%1%' (%2%)\n", name, lib->get_last_error()); return false; } bool World::run_module(const char* name) { auto i = _impl->modules.find(name); if (i == _impl->modules.end()) { log().error("Attempt to run unloaded module `%1%'\n", name); return false; } i->second->run(*this); return true; } /** Get an interface for a remote engine at `engine_uri` */ std::shared_ptr<Interface> World::new_interface(const URI& engine_uri, const std::shared_ptr<Interface>& respondee) { const Impl::InterfaceFactories::const_iterator i = _impl->interface_factories.find(std::string(engine_uri.scheme())); if (i == _impl->interface_factories.end()) { log().warn("Unknown URI scheme `%1%'\n", engine_uri.scheme()); return nullptr; } return i->second(*this, engine_uri, respondee); } /** Run a script of type `mime_type` at filename `filename` */ bool World::run(const std::string& mime_type, const std::string& filename) { const Impl::ScriptRunners::const_iterator i = _impl->script_runners.find(mime_type); if (i == _impl->script_runners.end()) { log().warn("Unknown script MIME type `%1%'\n", mime_type); return false; } return i->second(*this, filename.c_str()); } void World::add_interface_factory(const std::string& scheme, InterfaceFactory factory) { _impl->interface_factories.emplace(scheme, factory); } void World::set_jack_uuid(const std::string& uuid) { _impl->jack_uuid = uuid; } std::string World::jack_uuid() { return _impl->jack_uuid; } } // namespace ingen
Improve log output
Improve log output
C++
agpl-3.0
drobilla/ingen,drobilla/ingen,drobilla/ingen,drobilla/ingen
d3e0d2e926eb79c7772d7df6ed443666e20a43b5
library/Collections/Collection.cpp
library/Collections/Collection.cpp
/////////////////////////////////////////////////////////////////////////////// // // File: Collection.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Collection top class definition // /////////////////////////////////////////////////////////////////////////////// #include <Collections/Collection.h> #include <sstream> namespace Nektar { namespace Collections { /** * */ Collection::Collection( vector<StdRegions::StdExpansionSharedPtr> pCollExp, OperatorImpMap &impTypes) { OperatorImpMap::iterator it; // Initialise geometry data. m_geomData = MemoryManager<CoalescedGeomData>::AllocateSharedPtr(); // Loop over all operator types. for (int i = 0; i < SIZE_OperatorType; ++i) { OperatorType opType = (OperatorType)i; ImplementationType impType; if (it = impTypes.find(opType) != impTypes.end()) { impType = it->second; OperatorKey opKey(pCollExp[0]->DetShapeType(), opType, impType, pCollExp[0]->IsNodalNonTensorialExp()); stringstream ss; ss << opKey; ASSERTL0(GetOperatorFactory().ModuleExists(opKey), "Requested unknown operator "+ss.str()); m_ops[opType] = GetOperatorFactory().CreateInstance( opKey, pCollExp, m_geomData); } } } } }
/////////////////////////////////////////////////////////////////////////////// // // File: Collection.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Collection top class definition // /////////////////////////////////////////////////////////////////////////////// #include <Collections/Collection.h> #include <sstream> namespace Nektar { namespace Collections { /** * */ Collection::Collection( vector<StdRegions::StdExpansionSharedPtr> pCollExp, OperatorImpMap &impTypes) { OperatorImpMap::iterator it; // Initialise geometry data. m_geomData = MemoryManager<CoalescedGeomData>::AllocateSharedPtr(); // Loop over all operator types. for (int i = 0; i < SIZE_OperatorType; ++i) { OperatorType opType = (OperatorType)i; ImplementationType impType; if ((it = impTypes.find(opType)) != impTypes.end()) { impType = it->second; OperatorKey opKey(pCollExp[0]->DetShapeType(), opType, impType, pCollExp[0]->IsNodalNonTensorialExp()); stringstream ss; ss << opKey; ASSERTL0(GetOperatorFactory().ModuleExists(opKey), "Requested unknown operator "+ss.str()); m_ops[opType] = GetOperatorFactory().CreateInstance( opKey, pCollExp, m_geomData); } } } } }
Fix compile error.
Fix compile error.
C++
mit
certik/nektar,certik/nektar,certik/nektar
a065c9fb86a78a627732e64623c79d82b1905c94
src/Debug.cpp
src/Debug.cpp
/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2004 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id: Debug.cpp 1268 2007-01-19 10:15:08Z robux4 $ \author Steve Lhomme <robux4 @ users.sf.net> \author Moritz Bunkus <moritz @ bunkus.org> */ #include <stdio.h> #ifdef WIN32 #include <windows.h> // For OutputDebugString #else #include <time.h> #include <sys/time.h> #endif // WIN32 #include "ebml/Debug.h" START_LIBEBML_NAMESPACE class ADbg globalDebug; #if defined(LIBEBML_DEBUG) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ADbg::ADbg(int level) :my_level(level) ,my_time_included(false) ,my_use_file(false) ,my_debug_output(true) ,hFile(NULL) { prefix[0] = '\0'; OutPut(-1,"ADbg Creation at debug level = %d (0x%08X)",my_level,this); } ADbg::~ADbg() { unsetDebugFile(); OutPut(-1,"ADbg Deletion (0x%08X)",this); } inline int ADbg::_OutPut(const char * format,va_list params) const { int result; char tst[1000]; char myformat[256]; #ifdef WIN32 if (my_time_included) { SYSTEMTIME time; GetSystemTime(&time); if (prefix[0] == '\0') wsprintfA(myformat,"%04d/%02d/%02d %02d:%02d:%02d.%03d UTC : %s\r\n", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds, format); else wsprintfA(myformat,"%04d/%02d/%02d %02d:%02d:%02d.%03d UTC : %s - %s\r\n", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds, prefix, format); } else { if (prefix[0] == '\0') wsprintfA( myformat, "%s\r\n", format); else wsprintfA( myformat, "%s - %s\r\n", prefix, format); } result = vsprintf(tst,myformat,params); if (my_debug_output) OutputDebugStringA(tst); if (my_use_file && (hFile != NULL)) { SetFilePointer( hFile, 0, 0, FILE_END ); DWORD written; WriteFile( hFile, tst, lstrlenA(tst), &written, NULL ); } #else if (my_time_included) { time_t nowSecs; struct tm *now; struct timeval tv; nowSecs = time(NULL); gettimeofday(&tv, NULL); now = gmtime(&nowSecs); if (prefix[0] == '\0') sprintf(myformat,"%04d/%02d/%02d %02d:%02d:%02ld.%03ld UTC : %s\r\n", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, tv.tv_sec, (long)tv.tv_usec / 1000, format); else sprintf(myformat,"%04d/%02d/%02d %02d:%02d:%02ld.%03ld UTC : %s - %s\r\n", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, tv.tv_sec, (long)tv.tv_usec / 1000, prefix, format); } else { if (prefix[0] == '\0') sprintf( myformat, "%s\r\n", format); else sprintf( myformat, "%s - %s\r\n", prefix, format); } result = vsprintf(tst,myformat,params); if (my_debug_output) fputs(tst, stderr); if (my_use_file && (hFile != NULL)) fputs(tst, hFile); #endif return result; } int ADbg::OutPut(int forLevel, const char * format,...) const { int result=0; if (forLevel >= my_level) { va_list tstlist; va_start(tstlist, format); result = _OutPut(format,tstlist); } return result; } int ADbg::OutPut(const char * format,...) const { va_list tstlist; va_start(tstlist, format); return _OutPut(format,tstlist); } bool ADbg::setDebugFile(const char * NewFilename) { bool result; result = unsetDebugFile(); if (!result) return false; result = false; #ifdef WIN32 hFile = CreateFileA(NewFilename, GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if (hFile != INVALID_HANDLE_VALUE) { SetFilePointer( hFile, 0, 0, FILE_END ); result = true; } #else hFile = fopen(NewFilename, "w+"); if (hFile != NULL) { fseek(hFile, 0, SEEK_END); result = true; } #endif if (result) OutPut(-1,"Debug hFile Opening succeeded"); else OutPut(-1,"Debug hFile %s Opening failed",NewFilename); return result; } bool ADbg::unsetDebugFile() { bool result = (hFile == NULL); if (result) return true; #ifdef WIN32 result = (CloseHandle(hFile) != 0); #else result = (fclose(hFile) == 0); #endif if (result) { OutPut(-1,"Debug hFile Closing succeeded"); hFile = NULL; } return result; } #endif // defined(LIBEBML_DEBUG) END_LIBEBML_NAMESPACE
/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2004 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id: Debug.cpp 1268 2007-01-19 10:15:08Z robux4 $ \author Steve Lhomme <robux4 @ users.sf.net> \author Moritz Bunkus <moritz @ bunkus.org> */ #include <stdio.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> // For OutputDebugString #else #include <time.h> #include <sys/time.h> #endif // WIN32 #include "ebml/Debug.h" START_LIBEBML_NAMESPACE class ADbg globalDebug; #if defined(LIBEBML_DEBUG) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ADbg::ADbg(int level) :my_level(level) ,my_time_included(false) ,my_use_file(false) ,my_debug_output(true) ,hFile(NULL) { prefix[0] = '\0'; OutPut(-1,"ADbg Creation at debug level = %d (0x%08X)",my_level,this); } ADbg::~ADbg() { unsetDebugFile(); OutPut(-1,"ADbg Deletion (0x%08X)",this); } inline int ADbg::_OutPut(const char * format,va_list params) const { int result; char tst[1000]; char myformat[256]; #if defined(WIN32) || defined(_WIN32) if (my_time_included) { SYSTEMTIME time; GetSystemTime(&time); if (prefix[0] == '\0') wsprintfA(myformat,"%04d/%02d/%02d %02d:%02d:%02d.%03d UTC : %s\r\n", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds, format); else wsprintfA(myformat,"%04d/%02d/%02d %02d:%02d:%02d.%03d UTC : %s - %s\r\n", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds, prefix, format); } else { if (prefix[0] == '\0') wsprintfA( myformat, "%s\r\n", format); else wsprintfA( myformat, "%s - %s\r\n", prefix, format); } result = vsprintf(tst,myformat,params); if (my_debug_output) OutputDebugStringA(tst); if (my_use_file && (hFile != NULL)) { SetFilePointer( hFile, 0, 0, FILE_END ); DWORD written; WriteFile( hFile, tst, lstrlenA(tst), &written, NULL ); } #else if (my_time_included) { time_t nowSecs; struct tm *now; struct timeval tv; nowSecs = time(NULL); gettimeofday(&tv, NULL); now = gmtime(&nowSecs); if (prefix[0] == '\0') sprintf(myformat,"%04d/%02d/%02d %02d:%02d:%02ld.%03ld UTC : %s\r\n", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, tv.tv_sec, (long)tv.tv_usec / 1000, format); else sprintf(myformat,"%04d/%02d/%02d %02d:%02d:%02ld.%03ld UTC : %s - %s\r\n", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, tv.tv_sec, (long)tv.tv_usec / 1000, prefix, format); } else { if (prefix[0] == '\0') sprintf( myformat, "%s\r\n", format); else sprintf( myformat, "%s - %s\r\n", prefix, format); } result = vsprintf(tst,myformat,params); if (my_debug_output) fputs(tst, stderr); if (my_use_file && (hFile != NULL)) fputs(tst, hFile); #endif return result; } int ADbg::OutPut(int forLevel, const char * format,...) const { int result=0; if (forLevel >= my_level) { va_list tstlist; va_start(tstlist, format); result = _OutPut(format,tstlist); } return result; } int ADbg::OutPut(const char * format,...) const { va_list tstlist; va_start(tstlist, format); return _OutPut(format,tstlist); } bool ADbg::setDebugFile(const char * NewFilename) { bool result; result = unsetDebugFile(); if (!result) return false; result = false; #if defined(WIN32) || defined(_WIN32) hFile = CreateFileA(NewFilename, GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if (hFile != INVALID_HANDLE_VALUE) { SetFilePointer( hFile, 0, 0, FILE_END ); result = true; } #else hFile = fopen(NewFilename, "w+"); if (hFile != NULL) { fseek(hFile, 0, SEEK_END); result = true; } #endif if (result) OutPut(-1,"Debug hFile Opening succeeded"); else OutPut(-1,"Debug hFile %s Opening failed",NewFilename); return result; } bool ADbg::unsetDebugFile() { bool result = (hFile == NULL); if (result) return true; #if defined(WIN32) || defined(_WIN32) result = (CloseHandle(hFile) != 0); #else result = (fclose(hFile) == 0); #endif if (result) { OutPut(-1,"Debug hFile Closing succeeded"); hFile = NULL; } return result; } #endif // defined(LIBEBML_DEBUG) END_LIBEBML_NAMESPACE
fix the WIN32 compilation detection
fix the WIN32 compilation detection It's done that way in all the other places.
C++
lgpl-2.1
Matroska-Org/libebml,Matroska-Org/libebml
7a555b3a04f560245bdc7bd3366e3c08d585b6b7
src/agent.cpp
src/agent.cpp
#include "agent.h" #include "modules/echo.h" #include "external_module.h" #include "log.h" #include "schemas.h" #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> namespace CthunAgent { Agent::Agent() { // declare internal modules modules_["echo"] = std::unique_ptr<Module>(new Modules::Echo); // load external modules boost::filesystem::path module_path { "modules" }; boost::filesystem::directory_iterator end; for (auto file = boost::filesystem::directory_iterator(module_path); file != end; ++file) { if (!boost::filesystem::is_directory(file->status())) { BOOST_LOG_TRIVIAL(info) << file->path().string(); try { ExternalModule* external = new ExternalModule(file->path().string()); modules_[external->name] = std::shared_ptr<Module>(external); } catch (...) { BOOST_LOG_TRIVIAL(error) << "Error loading " << file->path().string(); } } } } void Agent::list_modules() { BOOST_LOG_TRIVIAL(info) << "Loaded modules:"; for (auto module : modules_) { BOOST_LOG_TRIVIAL(info) << " " << module.first; for (auto action : module.second->actions) { BOOST_LOG_TRIVIAL(info) << " " << action.first; } } } void Agent::run(std::string module, std::string action) { list_modules(); Module* the_module = modules_[module].get(); Json::Reader reader; Json::Value input; BOOST_LOG_TRIVIAL(info) << "loading stdin"; if (!reader.parse(std::cin, input)) { BOOST_LOG_TRIVIAL(error) << "Parse error: " << reader.getFormatedErrorMessages(); return; } try { Json::Value output; the_module->validate_and_call_action(action, input, output); BOOST_LOG_TRIVIAL(info) << output.toStyledString(); } catch (...) { BOOST_LOG_TRIVIAL(error) << "Badness occured"; } } } // namespace CthunAgent
#include "agent.h" #include "modules/echo.h" #include "external_module.h" #include "log.h" #include "schemas.h" #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> namespace CthunAgent { Agent::Agent() { // declare internal modules modules_["echo"] = std::unique_ptr<Module>(new Modules::Echo); // load external modules boost::filesystem::path module_path { "modules" }; boost::filesystem::directory_iterator end; for (auto file = boost::filesystem::directory_iterator(module_path); file != end; ++file) { if (!boost::filesystem::is_directory(file->status())) { BOOST_LOG_TRIVIAL(info) << file->path().string(); try { ExternalModule* external = new ExternalModule(file->path().string()); modules_[external->name] = std::shared_ptr<Module>(external); } catch (...) { BOOST_LOG_TRIVIAL(error) << "Error loading " << file->path().string(); } } } } void Agent::list_modules() { BOOST_LOG_TRIVIAL(info) << "Loaded modules:"; for (auto module : modules_) { BOOST_LOG_TRIVIAL(info) << " " << module.first; for (auto action : module.second->actions) { BOOST_LOG_TRIVIAL(info) << " " << action.first; } } } void Agent::run(std::string module, std::string action) { list_modules(); std::shared_ptr<Module> the_module = modules_[module]; Json::Reader reader; Json::Value input; BOOST_LOG_TRIVIAL(info) << "loading stdin"; if (!reader.parse(std::cin, input)) { BOOST_LOG_TRIVIAL(error) << "Parse error: " << reader.getFormatedErrorMessages(); return; } try { Json::Value output; the_module->validate_and_call_action(action, input, output); BOOST_LOG_TRIVIAL(info) << output.toStyledString(); } catch (...) { BOOST_LOG_TRIVIAL(error) << "Badness occured"; } } } // namespace CthunAgent
use a shared_ptr rather than a raw pointer
use a shared_ptr rather than a raw pointer
C++
apache-2.0
puppetlabs/pxp-agent,puppetlabs/pxp-agent,puppetlabs/pxp-agent
1f4f29c3efaa2a757f0b7635d5859a4f3259d3fd
src/alert.cpp
src/alert.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The PPCoin developers // Copyright (c) 2013-2014 The ShinyCoin developers #include "alert.h" #include "key.h" #include "kernel.h" #include "checkpoints.h" #include "ui_interface.h" static const std::string strAlertMasterPubKey = "0433a92a2e6b9ddc052bee5b742e20e3efbc52f512a3b31dcaa435ab61956e34c232e7ea0d260a484efd0c3f938a00698a006fa2af8cbcc85f5e855b9cf50ea023"; std::map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; std::string strMintMessage = _("Info: Minting suspended due to locked wallet."); std::string strMintWarning; std::string GetWarnings(std::string strFor) { int nPriority = 0; std::string strStatusBar; std::string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // ppcoin: wallet lock warning for minting if (strMintWarning != "") { nPriority = 0; strStatusBar = strMintWarning; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // ppcoin: should not enter safe mode for longer invalid chain // ppcoin: if sync-checkpoint is too old do not enter safe mode if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet) { nPriority = 100; strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers of the issue."; } // ppcoin: if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers of the issue."; } // ppcoin: if detected unmet upgrade requirement enter safe mode // Note: v0.4 upgrade requires blockchain redownload if past protocol switch if (IsProtocolV04(nProtocolV04UpgradeTime + 60*60*24)) // 1 day margin { nPriority = 5000; strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v0.4 upgrade deadline."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) strRPC = strStatusBar; // ppcoin: safe mode for high alert } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (std::map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(std::make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(strAlertMasterPubKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The PPCoin developers // Copyright (c) 2013-2014 The ShinyCoin developers #include "alert.h" #include "key.h" #include "kernel.h" #include "checkpoints.h" #include "ui_interface.h" static const std::string strAlertMasterPubKey = "0433a92a2e6b9ddc052bee5b742e20e3efbc52f512a3b31dcaa435ab61956e34c232e7ea0d260a484efd0c3f938a00698a006fa2af8cbcc85f5e855b9cf50ea023"; std::map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; std::string strMintMessage = _("Info: Minting suspended due to locked wallet."); std::string strMintWarning; std::string GetWarnings(std::string strFor) { int nPriority = 0; std::string strStatusBar; std::string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // ppcoin: wallet lock warning for minting if (strMintWarning != "") { nPriority = 0; strStatusBar = strMintWarning; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // ppcoin: should not enter safe mode for longer invalid chain // ppcoin: if sync-checkpoint is too old do not enter safe mode if (!IsInitialBlockDownload() && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet) { nPriority = 100; strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers of the issue."; } // ppcoin: if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers of the issue."; } // ppcoin: if detected unmet upgrade requirement enter safe mode // Note: v0.4 upgrade requires blockchain redownload if past protocol switch if (IsProtocolV04(nProtocolV04UpgradeTime + 60*60*24)) // 1 day margin { nPriority = 5000; strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v0.4 upgrade deadline."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) strRPC = strStatusBar; // ppcoin: safe mode for high alert } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (std::map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(std::make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(strAlertMasterPubKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; }
Fix to show progress bar when syncing for first time
Fix to show progress bar when syncing for first time
C++
mit
sunny-prince/shinycoin,sunny-prince/shinycoin,sunny-prince/shinycoin,sunny-prince/shinycoin
3bb8b2ce002e37ffff127c85d663de0230a6cdeb
tensorflow/c/experimental/gradients/math_grad_test.cc
tensorflow/c/experimental/gradients/math_grad_test.cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/experimental/gradients/math_grad.h" #include "tensorflow/c/eager/c_api_test_util.h" #include "tensorflow/c/eager/c_api_unified_experimental_internal.h" #include "tensorflow/c/eager/unified_api_testutil.h" #include "tensorflow/c/experimental/gradients/grad_test_helper.h" #include "tensorflow/c/experimental/gradients/tape/tape_context.h" #include "tensorflow/c/experimental/ops/math_ops.h" #include "tensorflow/c/tf_status_helper.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace gradients { namespace internal { namespace { using tensorflow::TF_StatusPtr; Status AddModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { return ops::Add(ctx, inputs, outputs, "Add"); } Status AddGradModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { GradientRegistry registry; TF_RETURN_IF_ERROR(registry.Register("AddV2", AddRegisterer)); Tape tape(/*persistent=*/false); tape.Watch(inputs[0]); tape.Watch(inputs[1]); std::vector<AbstractTensorHandle*> temp_outputs(1); AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry)); TF_RETURN_IF_ERROR(ops::Add(tape_ctx.get(), inputs, absl::MakeSpan(temp_outputs), "AddGrad")); TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs, /*sources=*/inputs, /*output_gradients=*/{}, outputs)); for (auto temp_output : temp_outputs) { temp_output->Unref(); } return Status::OK(); } Status ExpModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { return ops::Exp(ctx, inputs, outputs, "Exp"); } Status ExpGradModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { GradientRegistry registry; TF_RETURN_IF_ERROR(registry.Register("Exp", ExpRegisterer)); Tape tape(/*persistent=*/false); tape.Watch(inputs[0]); std::vector<AbstractTensorHandle*> temp_outputs(1); AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry)); TF_RETURN_IF_ERROR(ops::Exp(tape_ctx.get(), inputs, absl::MakeSpan(temp_outputs), "ExpGrad")); TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs, /*sources=*/inputs, /*output_gradients=*/{}, outputs)); for (auto temp_output : temp_outputs) { temp_output->Unref(); } return Status::OK(); } class CppGradients : public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> { protected: void SetUp() override { TF_StatusPtr status(TF_NewStatus()); TF_SetTracingImplementation(std::get<0>(GetParam()), status.get()); Status s = StatusFromTF_Status(status.get()); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); { AbstractContext* ctx_raw = nullptr; Status s = BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); ctx_.reset(ctx_raw); } } AbstractContextPtr ctx_; public: bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; } bool UseFunction() const { return std::get<2>(GetParam()); } }; TEST_P(CppGradients, TestAddGrad) { AbstractTensorHandlePtr x; { AbstractTensorHandle* x_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); x.reset(x_raw); } AbstractTensorHandlePtr y; { AbstractTensorHandle* y_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &y_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); y.reset(y_raw); } ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients( AddModel, AddGradModel, ctx_.get(), {x.get(), y.get()}, UseFunction())); } TEST_P(CppGradients, TestExpGrad) { AbstractTensorHandlePtr x; { AbstractTensorHandle* x_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); x.reset(x_raw); } ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients( ExpModel, ExpGradModel, ctx_.get(), {x.get()}, UseFunction())); } #ifdef PLATFORM_GOOGLE INSTANTIATE_TEST_SUITE_P( UnifiedCAPI, CppGradients, ::testing::Combine(::testing::Values("graphdef", "mlir"), /*tfrt*/ ::testing::Values(false), /*use_function*/ ::testing::Values(true, false))); #else INSTANTIATE_TEST_SUITE_P( UnifiedCAPI, CppGradients, ::testing::Combine(::testing::Values("graphdef", "mlir"), /*tfrt*/ ::testing::Values(false), /*use_function*/ ::testing::Values(true, false))); #endif } // namespace } // namespace internal } // namespace gradients } // namespace tensorflow
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/experimental/gradients/math_grad.h" #include "tensorflow/c/eager/c_api_test_util.h" #include "tensorflow/c/eager/c_api_unified_experimental_internal.h" #include "tensorflow/c/eager/unified_api_testutil.h" #include "tensorflow/c/experimental/gradients/grad_test_helper.h" #include "tensorflow/c/experimental/gradients/tape/tape_context.h" #include "tensorflow/c/experimental/ops/math_ops.h" #include "tensorflow/c/tf_status_helper.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace gradients { namespace internal { namespace { using tensorflow::TF_StatusPtr; Status AddModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { return ops::Add(ctx, inputs, outputs, "Add"); } Status AddGradModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { GradientRegistry registry; TF_RETURN_IF_ERROR(registry.Register("AddV2", AddRegisterer)); Tape tape(/*persistent=*/false); tape.Watch(inputs[0]); tape.Watch(inputs[1]); std::vector<AbstractTensorHandle*> temp_outputs(1); AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry)); TF_RETURN_IF_ERROR(ops::Add(tape_ctx.get(), inputs, absl::MakeSpan(temp_outputs), "AddGrad")); TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs, /*sources=*/inputs, /*output_gradients=*/{}, outputs)); for (auto temp_output : temp_outputs) { temp_output->Unref(); } return Status::OK(); } Status ExpModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { return ops::Exp(ctx, inputs, outputs, "Exp"); } Status ExpGradModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { GradientRegistry registry; TF_RETURN_IF_ERROR(registry.Register("Exp", ExpRegisterer)); Tape tape(/*persistent=*/false); tape.Watch(inputs[0]); std::vector<AbstractTensorHandle*> temp_outputs(1); AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry)); TF_RETURN_IF_ERROR(ops::Exp(tape_ctx.get(), inputs, absl::MakeSpan(temp_outputs), "ExpGrad")); TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs, /*sources=*/inputs, /*output_gradients=*/{}, outputs)); for (auto temp_output : temp_outputs) { temp_output->Unref(); } return Status::OK(); } Status SqrtModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { return ops::Sqrt(ctx, inputs, outputs, "Sqrt"); } Status SqrtGradModel(AbstractContext* ctx, absl::Span<AbstractTensorHandle* const> inputs, absl::Span<AbstractTensorHandle*> outputs) { GradientRegistry registry; TF_RETURN_IF_ERROR(registry.Register("Sqrt", SqrtRegisterer)); Tape tape(/*persistent=*/false); tape.Watch(inputs[0]); std::vector<AbstractTensorHandle*> temp_outputs(1); AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry)); TF_RETURN_IF_ERROR(ops::Sqrt(tape_ctx.get(), inputs, absl::MakeSpan(temp_outputs), "SqrtGrad")); TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs, /*sources=*/inputs, /*output_gradients=*/{}, outputs)); for (auto temp_output : temp_outputs) { temp_output->Unref(); } return Status::OK(); } class CppGradients : public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> { protected: void SetUp() override { TF_StatusPtr status(TF_NewStatus()); TF_SetTracingImplementation(std::get<0>(GetParam()), status.get()); Status s = StatusFromTF_Status(status.get()); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); { AbstractContext* ctx_raw = nullptr; Status s = BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); ctx_.reset(ctx_raw); } } AbstractContextPtr ctx_; public: bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; } bool UseFunction() const { return std::get<2>(GetParam()); } }; TEST_P(CppGradients, TestAddGrad) { AbstractTensorHandlePtr x; { AbstractTensorHandle* x_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); x.reset(x_raw); } AbstractTensorHandlePtr y; { AbstractTensorHandle* y_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &y_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); y.reset(y_raw); } ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients( AddModel, AddGradModel, ctx_.get(), {x.get(), y.get()}, UseFunction())); } TEST_P(CppGradients, TestExpGrad) { AbstractTensorHandlePtr x; { AbstractTensorHandle* x_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); x.reset(x_raw); } ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients( ExpModel, ExpGradModel, ctx_.get(), {x.get()}, UseFunction())); } TEST_P(CppGradients, TestSqrtGrad) { AbstractTensorHandlePtr x; { AbstractTensorHandle* x_raw = nullptr; Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw); ASSERT_EQ(errors::OK, s.code()) << s.error_message(); x.reset(x_raw); } ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients( SqrtModel, SqrtGradModel, ctx_.get(), {x.get()}, UseFunction())); } #ifdef PLATFORM_GOOGLE INSTANTIATE_TEST_SUITE_P( UnifiedCAPI, CppGradients, ::testing::Combine(::testing::Values("graphdef", "mlir"), /*tfrt*/ ::testing::Values(false), /*use_function*/ ::testing::Values(true, false))); #else INSTANTIATE_TEST_SUITE_P( UnifiedCAPI, CppGradients, ::testing::Combine(::testing::Values("graphdef", "mlir"), /*tfrt*/ ::testing::Values(false), /*use_function*/ ::testing::Values(true, false))); #endif } // namespace } // namespace internal } // namespace gradients } // namespace tensorflow
add `TestSqrtGrad` to `math_grad_test`
add `TestSqrtGrad` to `math_grad_test`
C++
apache-2.0
annarev/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,petewarden/tensorflow,petewarden/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,petewarden/tensorflow,yongtang/tensorflow,sarvex/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,karllessard/tensorflow,karllessard/tensorflow,karllessard/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,karllessard/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,karllessard/tensorflow,sarvex/tensorflow,annarev/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,sarvex/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,sarvex/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once
a42928acf901b5ab18594a6bd7d793df26c28bb7
include/abc/testing/unit.hxx
include/abc/testing/unit.hxx
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC 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. ABC 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 ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef ABC_TESTING_UNIT_HXX #define ABC_TESTING_UNIT_HXX #include <abc/testing/core.hxx> #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abc/testing/runner.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit namespace abc { namespace testing { /** Base class for unit tests. */ class ABCTESTINGAPI unit { public: /** Constructor. */ unit(); /** Destructor. */ virtual ~unit(); /** Initializes the object. Split into a method separated from the constructor so that derived classes don’t need to declare a constructor just to forward its arguments. prunner Pointer to the test runner. */ void init(runner * prunner); /** Executes the unit test. */ virtual void run() = 0; /** Returns a short description for the testing unit. return Unit title. */ virtual istr title() = 0; protected: /** Validates an assertion. bExpr Result of the assertion expression. pszExpr Failed assertion. */ void assert(bool bExpr, istr const & sExpr); /** Validates an expectation. bExpr Result of the expectation expression. pszExpr Failed assertion. */ void expect(bool bExpr, istr const & sExpr); protected: /** Runner executing this test. */ runner * m_prunner; }; } //namespace testing } //namespace abc /** Asserts that the specified expression evaluates as non-false (true); throws an exception if the assertion fails. expr Expression that should evaulate to non-false (true). */ #define ABC_TESTING_ASSERT(expr) \ this->assert(!!(expr), SL(#expr)) /** Verifies that the specified expression evaluates as non-false (true). expr Expression that should evaulate to non-false (true). */ #define ABC_TESTING_EXPECT(expr) \ this->expect(!!(expr), SL(#expr)) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit_factory_impl namespace abc { namespace testing { /** Maintains a list of abc::testing::unit-derived classes that can be used by an abc::testing::runner instance to instantiate and execute each unit. */ class ABCTESTINGAPI unit_factory_impl { public: /** Factory function, returning an abc::testing::unit instance. */ typedef std::unique_ptr<unit> (* factory_fn)(runner * prunner); /** Linked list item. */ struct factory_list_item { factory_list_item * pfliNext; factory_fn pfnFactory; }; public: /** Constructor. pfli Pointer to the derived class’s factory list item. */ unit_factory_impl(factory_list_item * pfli) { pfli->pfliNext = sm_pfliHead; sm_pfliHead = pfli; } /** Returns a pointer to the head of the list of factory functions, which the caller can then use to walk the entire list (ending when an item’s next pointer is NULL). return Pointer to the head of the list. */ static factory_list_item * get_factory_list_head() { return sm_pfliHead; } private: /** Pointer to the head of the list of factory functions. */ static factory_list_item * sm_pfliHead; }; } //namespace testing } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit_factory namespace abc { namespace testing { /** Template version of abc::testing::unit_factory_impl, able to instantiate classes derived from abc::testing::unit. */ template <class T> class unit_factory : public unit_factory_impl { public: /** Constructor. */ unit_factory() : unit_factory_impl(&sm_fli) { } /** Class factory for T. prunner Runner to provide to the unit. */ static std::unique_ptr<unit> factory(runner * prunner) { std::unique_ptr<T> pt(new T()); pt->init(prunner); return std::move(pt); } private: /** Entry in the list of factory functions for this class. */ static factory_list_item sm_fli; }; /** Registers an abc::testing::unit-derived class for execution by an abc::testing::runner instance. cls Unit class. */ #define ABC_TESTING_UNIT_REGISTER(cls) \ namespace abc { \ namespace testing { \ \ unit_factory<cls> ABC_CPP_APPEND_UID(g__uf); \ template <> \ /*static*/ unit_factory_impl::factory_list_item unit_factory<cls>::sm_fli = { \ NULL, \ unit_factory<cls>::factory \ }; \ \ } /*namespace testing*/ \ } /*namespace abc*/ } //namespace testing } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef ABC_TESTING_UNIT_HXX
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC 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. ABC 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 ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef ABC_TESTING_UNIT_HXX #define ABC_TESTING_UNIT_HXX #include <abc/testing/core.hxx> #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abc/testing/runner.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit namespace abc { namespace testing { /** Base class for unit tests. */ class ABCTESTINGAPI unit { public: /** Constructor. */ unit(); /** Destructor. */ virtual ~unit(); /** Initializes the object. Split into a method separated from the constructor so that derived classes don’t need to declare a constructor just to forward its arguments. prunner Pointer to the test runner. */ void init(runner * prunner); /** Executes the unit test. */ virtual void run() = 0; /** Returns a short description for the testing unit. return Unit title. */ virtual istr title() = 0; protected: /** Validates an assertion. bExpr Result of the assertion expression. pszExpr Failed assertion. */ void assert(bool bExpr, istr const & sExpr); /** Validates an expectation. bExpr Result of the expectation expression. pszExpr Failed assertion. */ void expect(bool bExpr, istr const & sExpr); protected: /** Runner executing this test. */ runner * m_prunner; }; } //namespace testing } //namespace abc /** Asserts that the specified expression evaluates as non-false (true); throws an exception if the assertion fails. expr Expression that should evaulate to non-false (true). */ #define ABC_TESTING_ASSERT(expr) \ this->assert(!!(expr), SL(#expr)) /** Verifies that the specified expression evaluates as non-false (true). expr Expression that should evaulate to non-false (true). */ #define ABC_TESTING_EXPECT(expr) \ this->expect(!!(expr), SL(#expr)) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit_factory_impl namespace abc { namespace testing { /** Maintains a list of abc::testing::unit-derived classes that can be used by an abc::testing::runner instance to instantiate and execute each unit. */ class ABCTESTINGAPI unit_factory_impl { public: /** Factory function, returning an abc::testing::unit instance. */ typedef std::unique_ptr<unit> (* factory_fn)(runner * prunner); /** Linked list item. */ struct factory_list_item { factory_list_item * pfliNext; factory_fn pfnFactory; }; public: /** Constructor. pfli Pointer to the derived class’s factory list item. */ unit_factory_impl(factory_list_item * pfli) { pfli->pfliNext = sm_pfliHead; sm_pfliHead = pfli; } /** Returns a pointer to the head of the list of factory functions, which the caller can then use to walk the entire list (ending when an item’s next pointer is NULL). return Pointer to the head of the list. */ static factory_list_item * get_factory_list_head() { return sm_pfliHead; } private: /** Pointer to the head of the list of factory functions. */ static factory_list_item * sm_pfliHead; }; } //namespace testing } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::unit_factory namespace abc { namespace testing { /** Template version of abc::testing::unit_factory_impl, able to instantiate classes derived from abc::testing::unit. */ template <class T> class unit_factory : public unit_factory_impl { public: /** Constructor. */ unit_factory() : unit_factory_impl(&sm_fli) { } /** Class factory for T. prunner Runner to provide to the unit. */ static std::unique_ptr<unit> factory(runner * prunner) { std::unique_ptr<T> pt(new T()); pt->init(prunner); return std::move(pt); } private: /** Entry in the list of factory functions for this class. */ static factory_list_item sm_fli; }; } //namespace testing } //namespace abc /** Registers an abc::testing::unit-derived class for execution by an abc::testing::runner instance. cls Unit class. */ #define ABC_TESTING_UNIT_REGISTER(cls) \ namespace abc { \ namespace testing { \ \ unit_factory<cls> ABC_CPP_APPEND_UID(g__uf); \ template <> \ /*static*/ unit_factory_impl::factory_list_item unit_factory<cls>::sm_fli = { \ NULL, \ unit_factory<cls>::factory \ }; \ \ } /*namespace testing*/ \ } /*namespace abc*/ //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef ABC_TESTING_UNIT_HXX
Move macro out of namespace
Move macro out of namespace
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
ecece7f8976c4da355443d998f5773a0598314a9
tensorflow/core/kernels/data/parallel_map_iterator.cc
tensorflow/core/kernels/data/parallel_map_iterator.cc
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/parallel_map_iterator.h" #include <atomic> #include <deque> #include <functional> #include <memory> #include <utility> #include <vector> #include "tensorflow/core/framework/stats_aggregator.h" #include "tensorflow/core/kernels/data/stats_utils.h" #include "tensorflow/core/lib/gtl/cleanup.h" #include "tensorflow/core/platform/cpu_info.h" namespace tensorflow { namespace data { namespace { class ParallelMapIterator : public DatasetBaseIterator { public: struct Params { Params(std::unique_ptr<ParallelMapFunctor> parallel_map_functor, int32 num_parallel_calls, bool sloppy, bool preserve_cardinality) : parallel_map_functor(std::move(parallel_map_functor)), num_parallel_calls(num_parallel_calls), sloppy(sloppy), preserve_cardinality(preserve_cardinality) {} std::unique_ptr<ParallelMapFunctor> parallel_map_functor; int32 num_parallel_calls; bool sloppy; bool preserve_cardinality; }; ParallelMapIterator( const typename DatasetBaseIterator::BaseParams& base_params, const DatasetBase* input_dataset, Params params) : DatasetBaseIterator(base_params), input_dataset_(input_dataset), parallel_map_functor_(std::move(params.parallel_map_functor)), mu_(std::make_shared<mutex>()), cond_var_(std::make_shared<condition_variable>()), num_parallel_calls_(std::make_shared<model::SharedState>( params.num_parallel_calls, mu_, cond_var_)), sloppy_(params.sloppy), preserve_cardinality_(params.preserve_cardinality) { key_prefix_ = base_params.dataset->node_name(); } ~ParallelMapIterator() override { mutex_lock l(*mu_); // Cancel the runner thread. cancelled_ = true; cond_var_->notify_all(); // Wait for all in-flight calls to complete. while (num_calls_ > 0) { cond_var_->wait(l); } } Status Initialize(IteratorContext* ctx) override { mutex_lock l(*mu_); if (num_parallel_calls_->value == model::kAutoTune) { num_parallel_calls_->value = ctx->runner_threadpool_size(); } TF_RETURN_IF_ERROR( input_dataset_->MakeIterator(ctx, prefix(), &input_impl_)); return parallel_map_functor_->InitFunc(ctx); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { std::shared_ptr<InvocationResult> result; { mutex_lock l(*mu_); EnsureRunnerThreadStarted(ctx); while (ShouldWait(&result)) { RecordStop(ctx); cond_var_->wait(l); RecordStart(ctx); } } RecordStop(ctx); result->notification.WaitForNotification(); RecordStart(ctx); return ProcessResult(ctx, result, out_tensors, end_of_sequence); } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeAsyncKnownRatioNode( std::move(args), /*ratio=*/1, {model::MakeParameter("parallelism", num_parallel_calls_, /*min=*/1, /*max=*/ctx->runner_threadpool_size())}); } Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(*mu_); // Wait for all in-flight calls to complete. while (num_calls_ > 0) { cond_var_->wait(l); } CHECK_EQ(num_calls_, 0); TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_)); TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("invocation_results.size"), invocation_results_.size())); for (size_t i = 0; i < invocation_results_.size(); i++) { const auto& result = *(invocation_results_[i]); TF_RETURN_IF_ERROR(WriteStatusLocked(writer, i, result.status)); TF_RETURN_IF_ERROR(writer->WriteScalar( full_name(strings::StrCat("invocation_results[", i, "].size")), result.return_values.size())); for (size_t j = 0; j < result.return_values.size(); j++) { TF_RETURN_IF_ERROR(writer->WriteTensor( full_name(strings::StrCat("invocation_results[", i, "][", j, "]")), result.return_values[j])); } if (result.end_of_input) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name(strings::StrCat("invocation_results[", i, "].end_of_input")), "")); } } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(*mu_); TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); int64 invocation_results_size; TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("invocation_results.size"), &invocation_results_size)); for (size_t i = 0; i < invocation_results_size; i++) { invocation_results_.push_back(std::make_shared<InvocationResult>()); auto& result = *invocation_results_.back(); TF_RETURN_IF_ERROR(ReadStatusLocked(reader, i, &result.status)); size_t num_return_values; { int64 size; TF_RETURN_IF_ERROR(reader->ReadScalar( full_name(strings::StrCat("invocation_results[", i, "].size")), &size)); num_return_values = static_cast<size_t>(size); if (num_return_values != size) { return errors::InvalidArgument(strings::StrCat( full_name(strings::StrCat("invocation_results[", i, "].size")), ": ", size, " is not a valid value of type size_t.")); } } result.return_values.reserve(num_return_values); for (size_t j = 0; j < num_return_values; j++) { result.return_values.emplace_back(); TF_RETURN_IF_ERROR(reader->ReadTensor( full_name(strings::StrCat("invocation_results[", i, "][", j, "]")), &result.return_values.back())); } result.end_of_input = reader->Contains(full_name( strings::StrCat("invocation_results[", i, "].end_of_input"))); result.notification.Notify(); } return Status::OK(); } private: struct InvocationResult { Notification notification; Status status; std::vector<Tensor> return_values; bool end_of_input; }; void EnsureRunnerThreadStarted(IteratorContext* ctx) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { if (!runner_thread_) { auto ctx_copy = std::make_shared<IteratorContext>(*ctx); runner_thread_ = ctx->StartThread( "tf_data_parallel_map", std::bind(&ParallelMapIterator::RunnerThread, this, ctx_copy)); } } void CallCompleted(const std::shared_ptr<IteratorContext>& ctx, const std::shared_ptr<InvocationResult>& result) LOCKS_EXCLUDED(*mu_) { mutex_lock l(*mu_); num_calls_--; const auto& stats_aggregator = ctx->stats_aggregator(); if (stats_aggregator) { stats_aggregator->AddScalar( stats_utils::ThreadUtilizationScalarName(key_prefix_), static_cast<float>(num_calls_) / static_cast<float>(num_parallel_calls_->value), num_elements()); } RecordBufferEnqueue(ctx.get(), result->return_values); result->notification.Notify(); cond_var_->notify_all(); } void CallFunction(const std::shared_ptr<IteratorContext>& ctx, const std::shared_ptr<InvocationResult>& result) LOCKS_EXCLUDED(*mu_) { // Get the next input element. std::vector<Tensor> input_element; result->status = input_impl_->GetNext(ctx.get(), &input_element, &result->end_of_input); if (result->end_of_input || !result->status.ok()) { CallCompleted(ctx, result); return; } auto done = [this, ctx, result](Status status) { result->status.Update(status); CallCompleted(ctx, result); }; // Apply the map function on `input_element`, storing the result in // `result->return_values`, and invoking `done` when finished. parallel_map_functor_->MapFunc(ctx.get(), prefix(), std::move(input_element), &result->return_values, std::move(done)); } Status ProcessResult(IteratorContext* ctx, const std::shared_ptr<InvocationResult>& result, std::vector<Tensor>* out_tensors, bool* end_of_sequence) LOCKS_EXCLUDED(*mu_) { if (!result->end_of_input && result->status.ok()) { *out_tensors = std::move(result->return_values); RecordBufferDequeue(ctx, *out_tensors); *end_of_sequence = false; return Status::OK(); } if (errors::IsOutOfRange(result->status)) { if (preserve_cardinality_) { // To guarantee that the transformation preserves the cardinality of the // dataset, we convert `OutOfRange` to `InvalidArgument` as the former // may be interpreted by a caller as the end of sequence. return errors::InvalidArgument( "Function invocation produced OutOfRangeError: ", result->status.error_message()); } else { // `f` may deliberately raise `errors::OutOfRange` to indicate // that we should terminate the iteration early. *end_of_sequence = true; return Status::OK(); } } *end_of_sequence = result->end_of_input; return result->status; } void RunnerThread(const std::shared_ptr<IteratorContext>& ctx) LOCKS_EXCLUDED(*mu_) { RecordStart(ctx.get()); auto cleanup = gtl::MakeCleanup([this, ctx] { RecordStop(ctx.get()); }); std::vector<std::shared_ptr<InvocationResult>> new_calls; { tf_shared_lock l(*mu_); // mu_ == num_parallel_calls_->mu new_calls.reserve(num_parallel_calls_->value); } auto busy = [this]() EXCLUSIVE_LOCKS_REQUIRED(*mu_) -> bool { int64 num_parallel_calls = num_parallel_calls_->value; return num_calls_ >= num_parallel_calls || invocation_results_.size() >= num_parallel_calls; }; while (true) { { mutex_lock l(*mu_); while (!cancelled_ && busy()) { RecordStop(ctx.get()); cond_var_->wait(l); RecordStart(ctx.get()); } if (cancelled_) { return; } while (!busy()) { invocation_results_.push_back(std::make_shared<InvocationResult>()); new_calls.push_back(invocation_results_.back()); num_calls_++; } const auto& stats_aggregator = ctx->stats_aggregator(); if (stats_aggregator) { stats_aggregator->AddScalar( stats_utils::ThreadUtilizationScalarName(key_prefix_), static_cast<float>(num_calls_) / static_cast<float>(num_parallel_calls_->value), num_elements()); } cond_var_->notify_all(); } for (const auto& call : new_calls) { CallFunction(ctx, call); } new_calls.clear(); } } // Determines whether the caller needs to wait for a result. Upon returning // false, `result` will point to the result. bool ShouldWait(std::shared_ptr<InvocationResult>* result) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { if (sloppy_) { for (auto it = invocation_results_.begin(); it != invocation_results_.end(); ++it) { if ((*it)->notification.HasBeenNotified() && (it == invocation_results_.begin() || !(*it)->end_of_input)) { std::swap(*result, *it); invocation_results_.erase(it); cond_var_->notify_all(); return false; } } } else if (!invocation_results_.empty()) { std::swap(*result, invocation_results_.front()); invocation_results_.pop_front(); cond_var_->notify_all(); return false; } return true; } Status WriteStatusLocked(IteratorStateWriter* writer, size_t index, const Status& status) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { TF_RETURN_IF_ERROR( writer->WriteScalar(CodeKey(index), static_cast<int64>(status.code()))); if (!status.ok()) { TF_RETURN_IF_ERROR( writer->WriteScalar(ErrorMessageKey(index), status.error_message())); } return Status::OK(); } Status ReadStatusLocked(IteratorStateReader* reader, size_t index, Status* status) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { int64 code_int; TF_RETURN_IF_ERROR(reader->ReadScalar(CodeKey(index), &code_int)); error::Code code = static_cast<error::Code>(code_int); if (code != error::Code::OK) { string error_message; TF_RETURN_IF_ERROR( reader->ReadScalar(ErrorMessageKey(index), &error_message)); *status = Status(code, error_message); } else { *status = Status::OK(); } return Status::OK(); } string CodeKey(size_t index) { return full_name(strings::StrCat("invocation_results[", index, "].code")); } string ErrorMessageKey(size_t index) { return full_name( strings::StrCat("invocation_results[", index, "].error_message")); } const DatasetBase* const input_dataset_; // Not owned. std::unique_ptr<ParallelMapFunctor> parallel_map_functor_; // Used for coordination between the main thread and the runner thread. const std::shared_ptr<mutex> mu_; // Used for coordination between the main thread and the runner thread. In // particular, the runner thread should only schedule new calls when the // number of in-flight calls is less than the user specified level of // parallelism and there are slots available in the `invocation_results_` // buffer. const std::shared_ptr<condition_variable> cond_var_; // Identifies the maximum number of parallel calls. const std::shared_ptr<model::SharedState> num_parallel_calls_; // Determines whether outputs can be produced in non-deterministic order. const bool sloppy_; const bool preserve_cardinality_; // Counts the number of outstanding calls. int64 num_calls_ GUARDED_BY(*mu_) = 0; std::unique_ptr<IteratorBase> input_impl_; // Buffer for storing the invocation results. std::deque<std::shared_ptr<InvocationResult>> invocation_results_ GUARDED_BY(*mu_); std::unique_ptr<Thread> runner_thread_ GUARDED_BY(*mu_); bool cancelled_ GUARDED_BY(*mu_) = false; string key_prefix_; }; } // namespace std::unique_ptr<IteratorBase> NewParallelMapIterator( const DatasetBaseIterator::BaseParams& params, const DatasetBase* input_dataset, std::unique_ptr<ParallelMapFunctor> parallel_map_functor, int32 num_parallel_calls, bool sloppy, bool preserve_cardinality) { return absl::make_unique<ParallelMapIterator>( params, input_dataset, ParallelMapIterator::Params{std::move(parallel_map_functor), num_parallel_calls, sloppy, preserve_cardinality}); } } // namespace data } // namespace tensorflow
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/parallel_map_iterator.h" #include <atomic> #include <deque> #include <functional> #include <memory> #include <utility> #include <vector> #include "tensorflow/core/framework/stats_aggregator.h" #include "tensorflow/core/kernels/data/stats_utils.h" #include "tensorflow/core/lib/gtl/cleanup.h" #include "tensorflow/core/platform/cpu_info.h" namespace tensorflow { namespace data { namespace { class ParallelMapIterator : public DatasetBaseIterator { public: struct Params { Params(std::unique_ptr<ParallelMapFunctor> parallel_map_functor, int32 num_parallel_calls, bool sloppy, bool preserve_cardinality) : parallel_map_functor(std::move(parallel_map_functor)), num_parallel_calls(num_parallel_calls), sloppy(sloppy), preserve_cardinality(preserve_cardinality) {} std::unique_ptr<ParallelMapFunctor> parallel_map_functor; int32 num_parallel_calls; bool sloppy; bool preserve_cardinality; }; ParallelMapIterator( const typename DatasetBaseIterator::BaseParams& base_params, const DatasetBase* input_dataset, Params params) : DatasetBaseIterator(base_params), input_dataset_(input_dataset), parallel_map_functor_(std::move(params.parallel_map_functor)), mu_(std::make_shared<mutex>()), cond_var_(std::make_shared<condition_variable>()), num_parallel_calls_(std::make_shared<model::SharedState>( params.num_parallel_calls, mu_, cond_var_)), sloppy_(params.sloppy), preserve_cardinality_(params.preserve_cardinality) { key_prefix_ = base_params.dataset->node_name(); } ~ParallelMapIterator() override { mutex_lock l(*mu_); // Cancel the runner thread. cancelled_ = true; cond_var_->notify_all(); // Wait for all in-flight calls to complete. while (num_calls_ > 0) { cond_var_->wait(l); } } Status Initialize(IteratorContext* ctx) override { mutex_lock l(*mu_); if (num_parallel_calls_->value == model::kAutoTune) { num_parallel_calls_->value = ctx->runner_threadpool_size(); } TF_RETURN_IF_ERROR( input_dataset_->MakeIterator(ctx, prefix(), &input_impl_)); return parallel_map_functor_->InitFunc(ctx); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { std::shared_ptr<InvocationResult> result; { mutex_lock l(*mu_); EnsureRunnerThreadStarted(ctx); while (ShouldWait(&result)) { RecordStop(ctx); cond_var_->wait(l); RecordStart(ctx); } } RecordStop(ctx); result->notification.WaitForNotification(); RecordStart(ctx); return ProcessResult(ctx, result, out_tensors, end_of_sequence); } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeAsyncKnownRatioNode( std::move(args), /*ratio=*/1, {model::MakeParameter("parallelism", num_parallel_calls_, /*min=*/1, /*max=*/ctx->runner_threadpool_size())}); } Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(*mu_); // Wait for all in-flight calls to complete. while (num_calls_ > 0) { cond_var_->wait(l); } CHECK_EQ(num_calls_, 0); TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_)); TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("invocation_results.size"), invocation_results_.size())); for (size_t i = 0; i < invocation_results_.size(); i++) { const auto& result = *(invocation_results_[i]); TF_RETURN_IF_ERROR(WriteStatusLocked(writer, i, result.status)); TF_RETURN_IF_ERROR(writer->WriteScalar( full_name(strings::StrCat("invocation_results[", i, "].size")), result.return_values.size())); for (size_t j = 0; j < result.return_values.size(); j++) { TF_RETURN_IF_ERROR(writer->WriteTensor( full_name(strings::StrCat("invocation_results[", i, "][", j, "]")), result.return_values[j])); } if (result.end_of_input) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name(strings::StrCat("invocation_results[", i, "].end_of_input")), "")); } } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(*mu_); TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); int64 invocation_results_size; TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("invocation_results.size"), &invocation_results_size)); if (!invocation_results_.empty()) invocation_results_.clear(); for (size_t i = 0; i < invocation_results_size; i++) { invocation_results_.push_back(std::make_shared<InvocationResult>()); auto& result = *invocation_results_.back(); TF_RETURN_IF_ERROR(ReadStatusLocked(reader, i, &result.status)); size_t num_return_values; { int64 size; TF_RETURN_IF_ERROR(reader->ReadScalar( full_name(strings::StrCat("invocation_results[", i, "].size")), &size)); num_return_values = static_cast<size_t>(size); if (num_return_values != size) { return errors::InvalidArgument(strings::StrCat( full_name(strings::StrCat("invocation_results[", i, "].size")), ": ", size, " is not a valid value of type size_t.")); } } result.return_values.reserve(num_return_values); for (size_t j = 0; j < num_return_values; j++) { result.return_values.emplace_back(); TF_RETURN_IF_ERROR(reader->ReadTensor( full_name(strings::StrCat("invocation_results[", i, "][", j, "]")), &result.return_values.back())); } result.end_of_input = reader->Contains(full_name( strings::StrCat("invocation_results[", i, "].end_of_input"))); result.notification.Notify(); } return Status::OK(); } private: struct InvocationResult { Notification notification; Status status; std::vector<Tensor> return_values; bool end_of_input; }; void EnsureRunnerThreadStarted(IteratorContext* ctx) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { if (!runner_thread_) { auto ctx_copy = std::make_shared<IteratorContext>(*ctx); runner_thread_ = ctx->StartThread( "tf_data_parallel_map", std::bind(&ParallelMapIterator::RunnerThread, this, ctx_copy)); } } void CallCompleted(const std::shared_ptr<IteratorContext>& ctx, const std::shared_ptr<InvocationResult>& result) LOCKS_EXCLUDED(*mu_) { mutex_lock l(*mu_); num_calls_--; const auto& stats_aggregator = ctx->stats_aggregator(); if (stats_aggregator) { stats_aggregator->AddScalar( stats_utils::ThreadUtilizationScalarName(key_prefix_), static_cast<float>(num_calls_) / static_cast<float>(num_parallel_calls_->value), num_elements()); } RecordBufferEnqueue(ctx.get(), result->return_values); result->notification.Notify(); cond_var_->notify_all(); } void CallFunction(const std::shared_ptr<IteratorContext>& ctx, const std::shared_ptr<InvocationResult>& result) LOCKS_EXCLUDED(*mu_) { // Get the next input element. std::vector<Tensor> input_element; result->status = input_impl_->GetNext(ctx.get(), &input_element, &result->end_of_input); if (result->end_of_input || !result->status.ok()) { CallCompleted(ctx, result); return; } auto done = [this, ctx, result](Status status) { result->status.Update(status); CallCompleted(ctx, result); }; // Apply the map function on `input_element`, storing the result in // `result->return_values`, and invoking `done` when finished. parallel_map_functor_->MapFunc(ctx.get(), prefix(), std::move(input_element), &result->return_values, std::move(done)); } Status ProcessResult(IteratorContext* ctx, const std::shared_ptr<InvocationResult>& result, std::vector<Tensor>* out_tensors, bool* end_of_sequence) LOCKS_EXCLUDED(*mu_) { if (!result->end_of_input && result->status.ok()) { *out_tensors = std::move(result->return_values); RecordBufferDequeue(ctx, *out_tensors); *end_of_sequence = false; return Status::OK(); } if (errors::IsOutOfRange(result->status)) { if (preserve_cardinality_) { // To guarantee that the transformation preserves the cardinality of the // dataset, we convert `OutOfRange` to `InvalidArgument` as the former // may be interpreted by a caller as the end of sequence. return errors::InvalidArgument( "Function invocation produced OutOfRangeError: ", result->status.error_message()); } else { // `f` may deliberately raise `errors::OutOfRange` to indicate // that we should terminate the iteration early. *end_of_sequence = true; return Status::OK(); } } *end_of_sequence = result->end_of_input; return result->status; } void RunnerThread(const std::shared_ptr<IteratorContext>& ctx) LOCKS_EXCLUDED(*mu_) { RecordStart(ctx.get()); auto cleanup = gtl::MakeCleanup([this, ctx] { RecordStop(ctx.get()); }); std::vector<std::shared_ptr<InvocationResult>> new_calls; { tf_shared_lock l(*mu_); // mu_ == num_parallel_calls_->mu new_calls.reserve(num_parallel_calls_->value); } auto busy = [this]() EXCLUSIVE_LOCKS_REQUIRED(*mu_) -> bool { int64 num_parallel_calls = num_parallel_calls_->value; return num_calls_ >= num_parallel_calls || invocation_results_.size() >= num_parallel_calls; }; while (true) { { mutex_lock l(*mu_); while (!cancelled_ && busy()) { RecordStop(ctx.get()); cond_var_->wait(l); RecordStart(ctx.get()); } if (cancelled_) { return; } while (!busy()) { invocation_results_.push_back(std::make_shared<InvocationResult>()); new_calls.push_back(invocation_results_.back()); num_calls_++; } const auto& stats_aggregator = ctx->stats_aggregator(); if (stats_aggregator) { stats_aggregator->AddScalar( stats_utils::ThreadUtilizationScalarName(key_prefix_), static_cast<float>(num_calls_) / static_cast<float>(num_parallel_calls_->value), num_elements()); } cond_var_->notify_all(); } for (const auto& call : new_calls) { CallFunction(ctx, call); } new_calls.clear(); } } // Determines whether the caller needs to wait for a result. Upon returning // false, `result` will point to the result. bool ShouldWait(std::shared_ptr<InvocationResult>* result) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { if (sloppy_) { for (auto it = invocation_results_.begin(); it != invocation_results_.end(); ++it) { if ((*it)->notification.HasBeenNotified() && (it == invocation_results_.begin() || !(*it)->end_of_input)) { std::swap(*result, *it); invocation_results_.erase(it); cond_var_->notify_all(); return false; } } } else if (!invocation_results_.empty()) { std::swap(*result, invocation_results_.front()); invocation_results_.pop_front(); cond_var_->notify_all(); return false; } return true; } Status WriteStatusLocked(IteratorStateWriter* writer, size_t index, const Status& status) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { TF_RETURN_IF_ERROR( writer->WriteScalar(CodeKey(index), static_cast<int64>(status.code()))); if (!status.ok()) { TF_RETURN_IF_ERROR( writer->WriteScalar(ErrorMessageKey(index), status.error_message())); } return Status::OK(); } Status ReadStatusLocked(IteratorStateReader* reader, size_t index, Status* status) EXCLUSIVE_LOCKS_REQUIRED(*mu_) { int64 code_int; TF_RETURN_IF_ERROR(reader->ReadScalar(CodeKey(index), &code_int)); error::Code code = static_cast<error::Code>(code_int); if (code != error::Code::OK) { string error_message; TF_RETURN_IF_ERROR( reader->ReadScalar(ErrorMessageKey(index), &error_message)); *status = Status(code, error_message); } else { *status = Status::OK(); } return Status::OK(); } string CodeKey(size_t index) { return full_name(strings::StrCat("invocation_results[", index, "].code")); } string ErrorMessageKey(size_t index) { return full_name( strings::StrCat("invocation_results[", index, "].error_message")); } const DatasetBase* const input_dataset_; // Not owned. std::unique_ptr<ParallelMapFunctor> parallel_map_functor_; // Used for coordination between the main thread and the runner thread. const std::shared_ptr<mutex> mu_; // Used for coordination between the main thread and the runner thread. In // particular, the runner thread should only schedule new calls when the // number of in-flight calls is less than the user specified level of // parallelism and there are slots available in the `invocation_results_` // buffer. const std::shared_ptr<condition_variable> cond_var_; // Identifies the maximum number of parallel calls. const std::shared_ptr<model::SharedState> num_parallel_calls_; // Determines whether outputs can be produced in non-deterministic order. const bool sloppy_; const bool preserve_cardinality_; // Counts the number of outstanding calls. int64 num_calls_ GUARDED_BY(*mu_) = 0; std::unique_ptr<IteratorBase> input_impl_; // Buffer for storing the invocation results. std::deque<std::shared_ptr<InvocationResult>> invocation_results_ GUARDED_BY(*mu_); std::unique_ptr<Thread> runner_thread_ GUARDED_BY(*mu_); bool cancelled_ GUARDED_BY(*mu_) = false; string key_prefix_; }; } // namespace std::unique_ptr<IteratorBase> NewParallelMapIterator( const DatasetBaseIterator::BaseParams& params, const DatasetBase* input_dataset, std::unique_ptr<ParallelMapFunctor> parallel_map_functor, int32 num_parallel_calls, bool sloppy, bool preserve_cardinality) { return absl::make_unique<ParallelMapIterator>( params, input_dataset, ParallelMapIterator::Params{std::move(parallel_map_functor), num_parallel_calls, sloppy, preserve_cardinality}); } } // namespace data } // namespace tensorflow
Clear the invocation results in the buffer before retoring
Clear the invocation results in the buffer before retoring
C++
apache-2.0
jhseu/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,gunan/tensorflow,yongtang/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,jhseu/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,arborh/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,renyi533/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,alsrgv/tensorflow,renyi533/tensorflow,sarvex/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,annarev/tensorflow,xzturn/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,jhseu/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,aldian/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,alsrgv/tensorflow,renyi533/tensorflow,aam-at/tensorflow,aldian/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,ghchinoy/tensorflow,karllessard/tensorflow,gunan/tensorflow,renyi533/tensorflow,karllessard/tensorflow,aldian/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,ghchinoy/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,alsrgv/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,arborh/tensorflow,renyi533/tensorflow,davidzchen/tensorflow,aldian/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,annarev/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,petewarden/tensorflow,petewarden/tensorflow,aam-at/tensorflow,alsrgv/tensorflow,karllessard/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,chemelnucfin/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,xzturn/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,karllessard/tensorflow,alsrgv/tensorflow,gunan/tensorflow,paolodedios/tensorflow,DavidNorman/tensorflow,davidzchen/tensorflow,aldian/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,arborh/tensorflow,adit-chandra/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,ghchinoy/tensorflow,arborh/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alsrgv/tensorflow,jhseu/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,cxxgtxy/tensorflow,DavidNorman/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,DavidNorman/tensorflow,jhseu/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,karllessard/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,alsrgv/tensorflow,gunan/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,jhseu/tensorflow,alsrgv/tensorflow,gunan/tensorflow,Intel-Corporation/tensorflow,adit-chandra/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,sarvex/tensorflow,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,chemelnucfin/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,aam-at/tensorflow,chemelnucfin/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,jhseu/tensorflow,xzturn/tensorflow,aam-at/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,annarev/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,alsrgv/tensorflow,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alsrgv/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,adit-chandra/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alsrgv/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,petewarden/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,annarev/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,davidzchen/tensorflow,arborh/tensorflow,aam-at/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,freedomtan/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,adit-chandra/tensorflow,karllessard/tensorflow,arborh/tensorflow,arborh/tensorflow,paolodedios/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,gunan/tensorflow,arborh/tensorflow,ghchinoy/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,freedomtan/tensorflow,annarev/tensorflow,ghchinoy/tensorflow,alsrgv/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred
14c52d931e62a6f421594486cd89d10d87fe50a5
include/cybozu/exception.hpp
include/cybozu/exception.hpp
#pragma once /** @file @brief definition of abstruct exception class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <string> #include <algorithm> #include <sstream> #include <errno.h> #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #else #include <string.h> // for strerror_r #endif #include <cybozu/inttype.hpp> #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE #include <cybozu/stacktrace.hpp> #endif namespace cybozu { const bool DontThrow = true; namespace exception { /* get max 16 characters to avoid buffer overrun */ inline std::string makeString(const char *str, size_t size) { return std::string(str, std::min<size_t>(size, 16)); } } // cybozu::exception /** convert errno to string @param err [in] errno @note for both windows and linux */ inline std::string ConvertErrorNoToString(int err) { char errBuf[256]; std::string ret; #ifdef _WIN32 if (strerror_s(errBuf, sizeof(errBuf), err) == 0) { ret = errBuf; } else { ret = "err"; } #elif defined(_GNU_SOURCE) ret = ::strerror_r(err, errBuf, sizeof(errBuf)); #else if (strerror_r(err, errBuf, sizeof(errBuf)) == 0) { ret = errBuf; } else { ret = "err"; } #endif char buf2[64]; CYBOZU_SNPRINTF(buf2, sizeof(buf2), "(%d)", err); ret += buf2; return ret; } class Exception : public std::exception { mutable std::string str_; #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE mutable std::string stackTrace_; #endif public: explicit Exception(const std::string& name = "", bool enableStackTrace = true) : str_(name) { #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE if (enableStackTrace) stackTrace_ = cybozu::StackTrace().toString(); #else cybozu::disable_warning_unused_variable(enableStackTrace); #endif } ~Exception() throw() {} const char *what() const throw() { return toString().c_str(); } const std::string& toString() const throw() { #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE try { if (!stackTrace_.empty()) { #ifdef CYBOZU_STACKTRACE_ONELINE str_ += "\n<<<STACKTRACE>>> "; str_ += stackTrace_; #else str_ += "\n<<<STACKTRACE\n"; str_ += stackTrace_; str_ += "\n>>>STACKTRACE"; #endif } } catch (...) { } stackTrace_.clear(); #endif return str_; } template<class T> Exception& operator<<(const T& x) { str_ += ':'; std::ostringstream os; os << x; str_ += os.str(); return *this; } }; class ErrorNo { public: #ifdef _WIN32 typedef unsigned int NativeErrorNo; #else typedef int NativeErrorNo; #endif explicit ErrorNo(NativeErrorNo err) : err_(err) { } ErrorNo() : err_(getLatestNativeErrorNo()) { } NativeErrorNo getLatestNativeErrorNo() const { #ifdef _WIN32 return ::GetLastError(); #else return errno; #endif } /** convert NativeErrNo to string(maybe UTF8) @param err [in] errno @note Linux : same as ConvertErrorNoToString Windows : for Win32 API(use en-us) */ std::string toString() const { #ifdef _WIN32 const int msgSize = 256; wchar_t msg[msgSize]; int size = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err_, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), msg, msgSize, NULL ); if (size <= 0) return ""; // remove last "\r\n" if (size > 2 && msg[size - 2] == '\r') { msg[size - 2] = 0; size -= 2; } std::string ret; ret.resize(size); // assume ascii only for (int i = 0; i < size; i++) { ret[i] = (char)msg[i]; } char buf2[64]; CYBOZU_SNPRINTF(buf2, sizeof(buf2), "(%d)", err_); ret += buf2; return ret; #else return ConvertErrorNoToString(err_); #endif } private: NativeErrorNo err_; }; inline std::ostream& operator<<(std::ostream& os, const cybozu::ErrorNo& self) { return os << self.toString(); } } // cybozu
#pragma once /** @file @brief definition of abstruct exception class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <string> #include <algorithm> #include <sstream> #include <errno.h> #include <stdio.h> #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #else #include <string.h> // for strerror_r #endif #include <cybozu/inttype.hpp> #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE #include <cybozu/stacktrace.hpp> #endif namespace cybozu { const bool DontThrow = true; namespace exception { /* get max 16 characters to avoid buffer overrun */ inline std::string makeString(const char *str, size_t size) { return std::string(str, std::min<size_t>(size, 16)); } } // cybozu::exception /** convert errno to string @param err [in] errno @note for both windows and linux */ inline std::string ConvertErrorNoToString(int err) { char errBuf[256]; std::string ret; #ifdef _WIN32 if (strerror_s(errBuf, sizeof(errBuf), err) == 0) { ret = errBuf; } else { ret = "err"; } #elif defined(_GNU_SOURCE) ret = ::strerror_r(err, errBuf, sizeof(errBuf)); #else if (strerror_r(err, errBuf, sizeof(errBuf)) == 0) { ret = errBuf; } else { ret = "err"; } #endif char buf2[64]; CYBOZU_SNPRINTF(buf2, sizeof(buf2), "(%d)", err); ret += buf2; return ret; } class Exception : public std::exception { mutable std::string str_; #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE mutable std::string stackTrace_; #endif public: explicit Exception(const std::string& name = "", bool enableStackTrace = true) : str_(name) { #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE if (enableStackTrace) stackTrace_ = cybozu::StackTrace().toString(); #else cybozu::disable_warning_unused_variable(enableStackTrace); #endif } ~Exception() throw() {} const char *what() const throw() { return toString().c_str(); } const std::string& toString() const throw() { #ifdef CYBOZU_EXCEPTION_WITH_STACKTRACE try { if (!stackTrace_.empty()) { #ifdef CYBOZU_STACKTRACE_ONELINE str_ += "\n<<<STACKTRACE>>> "; str_ += stackTrace_; #else str_ += "\n<<<STACKTRACE\n"; str_ += stackTrace_; str_ += "\n>>>STACKTRACE"; #endif } } catch (...) { } stackTrace_.clear(); #endif return str_; } template<class T> Exception& operator<<(const T& x) { str_ += ':'; std::ostringstream os; os << x; str_ += os.str(); return *this; } }; class ErrorNo { public: #ifdef _WIN32 typedef unsigned int NativeErrorNo; #else typedef int NativeErrorNo; #endif explicit ErrorNo(NativeErrorNo err) : err_(err) { } ErrorNo() : err_(getLatestNativeErrorNo()) { } NativeErrorNo getLatestNativeErrorNo() const { #ifdef _WIN32 return ::GetLastError(); #else return errno; #endif } /** convert NativeErrNo to string(maybe UTF8) @param err [in] errno @note Linux : same as ConvertErrorNoToString Windows : for Win32 API(use en-us) */ std::string toString() const { #ifdef _WIN32 const int msgSize = 256; wchar_t msg[msgSize]; int size = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err_, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), msg, msgSize, NULL ); if (size <= 0) return ""; // remove last "\r\n" if (size > 2 && msg[size - 2] == '\r') { msg[size - 2] = 0; size -= 2; } std::string ret; ret.resize(size); // assume ascii only for (int i = 0; i < size; i++) { ret[i] = (char)msg[i]; } char buf2[64]; CYBOZU_SNPRINTF(buf2, sizeof(buf2), "(%d)", err_); ret += buf2; return ret; #else return ConvertErrorNoToString(err_); #endif } private: NativeErrorNo err_; }; inline std::ostream& operator<<(std::ostream& os, const cybozu::ErrorNo& self) { return os << self.toString(); } } // cybozu
add include header
add include header
C++
bsd-3-clause
herumi/cybozulib,herumi/cybozulib
a41a6b0eb27cd72666141654c192634c863e7e48
include/libpc/exceptions.hpp
include/libpc/exceptions.hpp
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: Exception subclasses for C++ libLAS * Author: Mateusz Loskot, [email protected] * ****************************************************************************** * Copyright (c) 2008, Mateusz Loskot * Copyright (c) 2008, Howard Butler * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of the Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef LIBPC_EXCEPTION_HPP_INCLUDED #define LIBPC_EXCEPTION_HPP_INCLUDED #include <libpc/libpc.hpp> #include <stdexcept> namespace libpc { // base class for all libpc exceptions class libpc_error : public std::runtime_error { public: libpc_error(std::string const& msg) : std::runtime_error(msg) {} }; /// Exception reporting invalid point data. /// It's usually thrown by Point::Validate function. class invalid_point_data : public libpc_error { public: invalid_point_data(std::string const& msg, unsigned int who) : libpc_error(msg), m_who(who) {} /// Return flags identifying invalid point data members. /// Flags are composed with composed with Point::DataMemberFlag. /// Testing flags example: bool timeValid = e.who() & Point::eTime; unsigned int who() const { return m_who; } private: unsigned int m_who; }; class invalid_expression : public libpc_error { public: invalid_expression(std::string const& msg) : libpc_error(msg) {} }; class invalid_format : public libpc_error { public: invalid_format(std::string const& msg) : libpc_error(msg) {} }; // for when a stage doesn't get the schema it expects class impedance_invalid : public libpc_error { public: impedance_invalid(std::string const& msg) : libpc_error(msg) {} }; // use this for attempts to use a feature not compiled in, e.g. laszip or gdal class configuration_error : public libpc_error { public: configuration_error(std::string const& msg) : libpc_error(msg) {} }; // use this for situations where indeterminate point counts prevent some // operation from happening class indeterminate_count_error : public libpc_error { public: indeterminate_count_error(std::string const& msg) : libpc_error(msg) {} }; // use this for code still under development class not_yet_implemented : public libpc_error { public: not_yet_implemented(std::string const& msg) : libpc_error(msg) {} }; } // namespace libpc #endif // LIBPC_EXCEPTION_HPP_INCLUDED
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: Exception subclasses for C++ libLAS * Author: Mateusz Loskot, [email protected] * ****************************************************************************** * Copyright (c) 2008, Mateusz Loskot * Copyright (c) 2008, Howard Butler * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of the Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef LIBPC_EXCEPTION_HPP_INCLUDED #define LIBPC_EXCEPTION_HPP_INCLUDED #include <libpc/libpc.hpp> #include <stdexcept> namespace libpc { // base class for all libpc exceptions class libpc_error : public std::runtime_error { public: libpc_error(std::string const& msg) : std::runtime_error(msg) {} }; /// Exception reporting invalid point data. /// It's usually thrown by Point::Validate function. class invalid_point_data : public libpc_error { public: invalid_point_data(std::string const& msg, unsigned int who) : libpc_error(msg), m_who(who) {} /// Return flags identifying invalid point data members. /// Flags are composed with composed with Point::DataMemberFlag. /// Testing flags example: bool timeValid = e.who() & Point::eTime; unsigned int who() const { return m_who; } private: unsigned int m_who; }; class invalid_expression : public libpc_error { public: invalid_expression(std::string const& msg) : libpc_error(msg) {} }; class invalid_format : public libpc_error { public: invalid_format(std::string const& msg) : libpc_error(msg) {} }; // for when a stage doesn't get the schema it expects class impedance_invalid : public libpc_error { public: impedance_invalid(std::string const& msg) : libpc_error(msg) {} }; // use this for attempts to use a feature not compiled in, e.g. laszip or gdal class configuration_error : public libpc_error { public: configuration_error(std::string const& msg) : libpc_error(msg) {} }; // use this for situations where indeterminate point counts prevent some // operation from happening class indeterminate_count_error : public libpc_error { public: indeterminate_count_error(std::string const& msg) : libpc_error(msg) {} }; class dimension_not_found : public libpc_error { public: dimension_not_found(std::string const& msg) : libpc_error(msg) {} }; // use this for code still under development class not_yet_implemented : public libpc_error { public: not_yet_implemented(std::string const& msg) : libpc_error(msg) {} }; } // namespace libpc #endif // LIBPC_EXCEPTION_HPP_INCLUDED
add dimension_not_found exception
add dimension_not_found exception
C++
bsd-3-clause
boundlessgeo/PDAL,verma/PDAL,jwomeara/PDAL,Sciumo/PDAL,DougFirErickson/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,verma/PDAL,verma/PDAL,mtCarto/PDAL,lucadelu/PDAL,lucadelu/PDAL,radiantbluetechnologies/PDAL,Sciumo/PDAL,lucadelu/PDAL,boundlessgeo/PDAL,boundlessgeo/PDAL,mpgerlek/PDAL-old,mtCarto/PDAL,DougFirErickson/PDAL,jwomeara/PDAL,lucadelu/PDAL,Sciumo/PDAL,mtCarto/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,mpgerlek/PDAL-old,mpgerlek/PDAL-old,jwomeara/PDAL,jwomeara/PDAL,verma/PDAL,DougFirErickson/PDAL,verma/PDAL,DougFirErickson/PDAL,radiantbluetechnologies/PDAL,mtCarto/PDAL,Sciumo/PDAL
53a1cbf92cddb6e790b8b8703e059cca1e264684
include/mckl/random/seed.hpp
include/mckl/random/seed.hpp
//============================================================================ // MCKL/include/mckl/random/seed.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2016, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef MCKL_RANDOM_SEED_HPP #define MCKL_RANDOM_SEED_HPP #include <mckl/random/internal/common.hpp> #include <mckl/random/counter.hpp> #include <mckl/random/threefry.hpp> namespace mckl { namespace internal { template <typename RNGType, typename ResultType, typename StateType> inline ResultType seed_enc(const StateType &state) { static_assert(sizeof(StateType) == sizeof(ResultType), "**seed_enc** state and result have different sizes"); static_assert(sizeof(StateType) == sizeof(typename RNGType::ctr_type), "**seed_enc** state and RNGType::ctr_type have different sizes"); union { StateType state; ResultType result; typename RNGType::ctr_type ctr; } buf; buf.state = state; RNGType rng(0); rng.enc(buf.ctr, buf.ctr); return buf.result; } } // namespace mckl::internal /// \brief Seed generator for use with RNG accepting scalar seeds template <typename ResultType, typename ID = ResultType, bool Randomize = true> class SeedGenerator { static_assert(std::is_unsigned<ResultType>::value, "**SeedGenerator** ResultType is not an unsigned integer type"); public: using result_type = ResultType; SeedGenerator(const SeedGenerator<ResultType, ID, Randomize> &) = delete; SeedGenerator<ResultType, ID, Randomize> &operator=( const SeedGenerator<ResultType, ID, Randomize> &) = delete; static SeedGenerator<ResultType, ID, Randomize> &instance() { static SeedGenerator<ResultType, ID, Randomize> seed; return seed; } /// \brief Set the internal seed void set(result_type s) { seed_ = s; } /// \brief Get the next seed result_type get() { result_type s = seed_.fetch_add(1); s %= maxs_; s *= np_; s += rank_; return enc(s, std::integral_constant<bool, Randomize>()); } /// \brief The number of partitions result_type np() const { return np_; } /// \brief The rank of this partition result_type rank() const { return rank_; } /// \brief Set the number of partitions and the rank of this partition void partition(result_type np, result_type rank) { runtime_assert(np > 0, "**SeedGenerator::partition** the number of the partitions is " "zero"); if (np < 1) np = 1; runtime_assert(np > rank, "**SeedGenerator::partition** the rank is not smaller than the " "number of partitions"); if (rank >= np) rank = 0; result_type maxs = std::numeric_limits<result_type>::max(); if (np > 1) maxs = (maxs - rank) / np + 1; np_ = np; rank_ = rank; maxs_ = maxs; } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const SeedGenerator<ResultType, ID, Randomize> &sg) { if (!os) return os; os << sg.np_ << ' '; os << sg.rank_ << ' '; os << sg.maxs_ << ' '; os << sg.seed_ << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, SeedGenerator<ResultType, ID, Randomize> &sg) { if (!is) return is; result_type np; result_type rank; result_type maxs; result_type seed; is >> std::ws >> np; is >> std::ws >> rank; is >> std::ws >> maxs; is >> std::ws >> seed; if (is) { sg.np_ = np; sg.rank_ = rank; sg.maxs_ = maxs; sg.seed_ = seed; } return is; } protected: SeedGenerator() : seed_(1) { partition(1, 0); } private: result_type np_; result_type rank_; result_type maxs_; std::atomic<result_type> seed_; result_type enc(result_type s, std::false_type) { return s; } result_type enc(result_type s, std::true_type) { return enc(s, std::integral_constant<int, std::numeric_limits<result_type>::digits>()); } template <std::size_t D> result_type enc(result_type s, std::integral_constant<int, D>) { return enc(s, std::false_type()); } result_type enc(result_type s, std::integral_constant<int, 32>) { return s; } result_type enc(result_type s, std::integral_constant<int, 64>) { return internal::seed_enc<Threefry2x32, result_type>(s); } }; // class SeedGenerator /// \brief Seed generator for RNG with fixed width keys as seeds template <typename T, std::size_t K, typename ID, bool Randomize> class SeedGenerator<std::array<T, K>, ID, Randomize> { public: using seed_type = typename std::conditional<K != 0 && sizeof(T) * K % sizeof(std::uint64_t) == 0, std::uint64_t, T>::type; using result_type = std::array<T, K>; SeedGenerator( const SeedGenerator<std::array<T, K>, ID, Randomize> &) = delete; SeedGenerator<std::array<T, K>, ID, Randomize> &operator=( const SeedGenerator<std::array<T, K>, ID, Randomize> &) = delete; static SeedGenerator<std::array<T, K>, ID, Randomize> &instance() { static SeedGenerator<std::array<T, K>, ID, Randomize> seed; return seed; } /// \brief Set the internal seed void set(seed_type s) { seed_ = s; } /// \brief Get the next key result_type get() { return get(std::integral_constant<bool, (M_ > 1)>()); } /// \brief The number of partitions seed_type np() const { return np_; } /// \brief The rank of this partition seed_type rank() const { return rank_; } /// \brief Set the number of partitions and the rank of this partition void partition(seed_type np, seed_type rank) { partition(np, rank, std::integral_constant<bool, (M_ > 1)>()); } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const SeedGenerator<std::array<T, K>, ID, Randomize> &sg) { if (!os) return os; os << sg.np_ << ' '; os << sg.rank_ << ' '; os << sg.maxs_ << ' '; os << sg.seed_ << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, SeedGenerator<std::array<T, K>, ID, Randomize> &sg) { if (!is) return is; seed_type np; seed_type rank; seed_type maxs; seed_type seed; is >> std::ws >> np; is >> std::ws >> rank; is >> std::ws >> maxs; is >> std::ws >> seed; if (is) { sg.np_ = np; sg.rank_ = rank; sg.maxs_ = maxs; sg.seed_ = seed; } return is; } protected: SeedGenerator() : seed_(1) { partition(1, 0); } private: static constexpr std::size_t M_ = K != 0 && sizeof(T) * K % sizeof(std::uint64_t) == 0 ? sizeof(T) * K / sizeof(std::uint64_t) : K; seed_type np_; seed_type rank_; seed_type maxs_; std::atomic<seed_type> seed_; void partition(seed_type np, seed_type rank, std::true_type) { np_ = np; rank_ = rank; maxs_ = std::numeric_limits<seed_type>::max(); } void partition(seed_type np, seed_type rank, std::false_type) { runtime_assert(np > 0, "**SeedGenerator::partition** the number of the partitions is " "zero"); if (np < 1) np = 1; runtime_assert(np > rank, "**SeedGenerator::partition** the rank is not smaller than the " "number of partitions"); if (rank >= np) rank = 0; seed_type maxs = std::numeric_limits<seed_type>::max(); if (np > 1) maxs = (maxs - rank) / np + 1; np_ = np; rank_ = rank; maxs_ = maxs; } result_type get(std::true_type) { seed_type s = seed_.fetch_add(1); std::array<seed_type, M_> k = {{0}}; k.front() = s; k.back() = rank_; return enc(k, std::integral_constant<bool, Randomize>()); } result_type get(std::false_type) { seed_type s = seed_.fetch_add(1); s %= maxs_; s *= np_; s += rank_; std::array<seed_type, M_> k = {{s}}; return enc(k, std::integral_constant<bool, Randomize>()); } result_type enc(const std::array<seed_type, M_> &k, std::false_type) { union { result_type result; std::array<seed_type, M_> k; } buf; buf.k = k; return buf.result; } result_type enc(const std::array<seed_type, M_> &k, std::true_type) { return enc(k, std::integral_constant<int, std::numeric_limits<T>::digits * K>()); } template <int D> result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, D>) { return enc(k, std::false_type()); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 64>) { return internal::seed_enc<Threefry2x32, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 128>) { return internal::seed_enc<Threefry2x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 256>) { return internal::seed_enc<Threefry4x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 512>) { return internal::seed_enc<Threefry8x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 1024>) { return internal::seed_enc<Threefry16x64, result_type>(k); } }; // class Seed /// \brief Seeding RNG engines /// \ingroup Random template <typename RNGType, typename ID = typename SeedType<RNGType>::type, bool Randomize = true> using Seed = SeedGenerator<typename SeedType<RNGType>::type, ID, Randomize>; } // namespace mckl #endif // MCKL_RANDOM_SEED_HPP
//============================================================================ // MCKL/include/mckl/random/seed.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2016, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef MCKL_RANDOM_SEED_HPP #define MCKL_RANDOM_SEED_HPP #include <mckl/random/internal/common.hpp> #include <mckl/random/counter.hpp> #include <mckl/random/threefry.hpp> namespace mckl { namespace internal { template <typename RNGType, typename ResultType, typename StateType> inline ResultType seed_enc(const StateType &state) { static_assert(sizeof(StateType) == sizeof(ResultType), "**seed_enc** state and result have different sizes"); static_assert(sizeof(StateType) == sizeof(typename RNGType::ctr_type), "**seed_enc** state and RNGType::ctr_type have different sizes"); union { StateType state; ResultType result; typename RNGType::ctr_type ctr; } buf; buf.state = state; RNGType rng(0); rng.enc(buf.ctr, buf.ctr); return buf.result; } } // namespace mckl::internal /// \brief Seed generator for use with RNG accepting scalar seeds template <typename ResultType, typename ID = ResultType, bool Randomize = true> class SeedGenerator { static_assert(std::is_unsigned<ResultType>::value, "**SeedGenerator** ResultType is not an unsigned integer type"); public: using seed_type = ResultType; using result_type = ResultType; SeedGenerator(const SeedGenerator<ResultType, ID, Randomize> &) = delete; SeedGenerator<ResultType, ID, Randomize> &operator=( const SeedGenerator<ResultType, ID, Randomize> &) = delete; static SeedGenerator<ResultType, ID, Randomize> &instance() { static SeedGenerator<ResultType, ID, Randomize> seed; return seed; } /// \brief Set the internal seed void set(seed_type s) { seed_ = s; } /// \brief Get the next seed result_type get() { seed_type s = seed_.fetch_add(1); s %= maxs_; s *= np_; s += rank_; return enc(s, std::integral_constant<bool, Randomize>()); } /// \brief The number of partitions seed_type np() const { return np_; } /// \brief The rank of this partition seed_type rank() const { return rank_; } /// \brief Set the number of partitions and the rank of this partition void partition(seed_type np, seed_type rank) { runtime_assert(np > 0, "**SeedGenerator::partition** the number of the partitions is " "zero"); if (np < 1) np = 1; runtime_assert(np > rank, "**SeedGenerator::partition** the rank is not smaller than the " "number of partitions"); if (rank >= np) rank = 0; seed_type maxs = std::numeric_limits<seed_type>::max(); if (np > 1) maxs = (maxs - rank) / np + 1; np_ = np; rank_ = rank; maxs_ = maxs; } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const SeedGenerator<ResultType, ID, Randomize> &sg) { if (!os) return os; os << sg.np_ << ' '; os << sg.rank_ << ' '; os << sg.maxs_ << ' '; os << sg.seed_ << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, SeedGenerator<ResultType, ID, Randomize> &sg) { if (!is) return is; seed_type np; seed_type rank; seed_type maxs; seed_type seed; is >> std::ws >> np; is >> std::ws >> rank; is >> std::ws >> maxs; is >> std::ws >> seed; if (is) { sg.np_ = np; sg.rank_ = rank; sg.maxs_ = maxs; sg.seed_ = seed; } return is; } protected: SeedGenerator() : seed_(1) { partition(1, 0); } private: seed_type np_; seed_type rank_; seed_type maxs_; std::atomic<seed_type> seed_; result_type enc(seed_type s, std::false_type) { return s; } result_type enc(seed_type s, std::true_type) { return enc(s, std::integral_constant<int, std::numeric_limits<seed_type>::digits>()); } template <std::size_t D> result_type enc(seed_type s, std::integral_constant<int, D>) { return enc(s, std::false_type()); } result_type enc(seed_type s, std::integral_constant<int, 32>) { return s; } result_type enc(seed_type s, std::integral_constant<int, 64>) { return internal::seed_enc<Threefry2x32, result_type>(s); } }; // class SeedGenerator /// \brief Seed generator for RNG with fixed width keys as seeds template <typename T, std::size_t K, typename ID, bool Randomize> class SeedGenerator<std::array<T, K>, ID, Randomize> { public: using seed_type = typename std::conditional<K != 0 && sizeof(T) * K % sizeof(std::uint64_t) == 0, std::uint64_t, T>::type; using result_type = std::array<T, K>; SeedGenerator( const SeedGenerator<std::array<T, K>, ID, Randomize> &) = delete; SeedGenerator<std::array<T, K>, ID, Randomize> &operator=( const SeedGenerator<std::array<T, K>, ID, Randomize> &) = delete; static SeedGenerator<std::array<T, K>, ID, Randomize> &instance() { static SeedGenerator<std::array<T, K>, ID, Randomize> seed; return seed; } /// \brief Set the internal seed void set(seed_type s) { seed_ = s; } /// \brief Get the next key result_type get() { return get(std::integral_constant<bool, (M_ > 1)>()); } /// \brief The number of partitions seed_type np() const { return np_; } /// \brief The rank of this partition seed_type rank() const { return rank_; } /// \brief Set the number of partitions and the rank of this partition void partition(seed_type np, seed_type rank) { partition(np, rank, std::integral_constant<bool, (M_ > 1)>()); } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const SeedGenerator<std::array<T, K>, ID, Randomize> &sg) { if (!os) return os; os << sg.np_ << ' '; os << sg.rank_ << ' '; os << sg.maxs_ << ' '; os << sg.seed_ << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, SeedGenerator<std::array<T, K>, ID, Randomize> &sg) { if (!is) return is; seed_type np; seed_type rank; seed_type maxs; seed_type seed; is >> std::ws >> np; is >> std::ws >> rank; is >> std::ws >> maxs; is >> std::ws >> seed; if (is) { sg.np_ = np; sg.rank_ = rank; sg.maxs_ = maxs; sg.seed_ = seed; } return is; } protected: SeedGenerator() : seed_(1) { partition(1, 0); } private: static constexpr std::size_t M_ = K != 0 && sizeof(T) * K % sizeof(std::uint64_t) == 0 ? sizeof(T) * K / sizeof(std::uint64_t) : K; seed_type np_; seed_type rank_; seed_type maxs_; std::atomic<seed_type> seed_; void partition(seed_type np, seed_type rank, std::true_type) { np_ = np; rank_ = rank; maxs_ = std::numeric_limits<seed_type>::max(); } void partition(seed_type np, seed_type rank, std::false_type) { runtime_assert(np > 0, "**SeedGenerator::partition** the number of the partitions is " "zero"); if (np < 1) np = 1; runtime_assert(np > rank, "**SeedGenerator::partition** the rank is not smaller than the " "number of partitions"); if (rank >= np) rank = 0; seed_type maxs = std::numeric_limits<seed_type>::max(); if (np > 1) maxs = (maxs - rank) / np + 1; np_ = np; rank_ = rank; maxs_ = maxs; } result_type get(std::true_type) { seed_type s = seed_.fetch_add(1); std::array<seed_type, M_> k = {{0}}; k.front() = s; k.back() = rank_; return enc(k, std::integral_constant<bool, Randomize>()); } result_type get(std::false_type) { seed_type s = seed_.fetch_add(1); s %= maxs_; s *= np_; s += rank_; std::array<seed_type, M_> k = {{s}}; return enc(k, std::integral_constant<bool, Randomize>()); } result_type enc(const std::array<seed_type, M_> &k, std::false_type) { union { result_type result; std::array<seed_type, M_> k; } buf; buf.k = k; return buf.result; } result_type enc(const std::array<seed_type, M_> &k, std::true_type) { return enc(k, std::integral_constant<int, std::numeric_limits<T>::digits * K>()); } template <int D> result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, D>) { return enc(k, std::false_type()); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 64>) { return internal::seed_enc<Threefry2x32, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 128>) { return internal::seed_enc<Threefry2x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 256>) { return internal::seed_enc<Threefry4x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 512>) { return internal::seed_enc<Threefry8x64, result_type>(k); } result_type enc( const std::array<seed_type, M_> &k, std::integral_constant<int, 1024>) { return internal::seed_enc<Threefry16x64, result_type>(k); } }; // class Seed /// \brief Seeding RNG engines /// \ingroup Random template <typename RNGType, typename ID = typename SeedType<RNGType>::type, bool Randomize = true> using Seed = SeedGenerator<typename SeedType<RNGType>::type, ID, Randomize>; } // namespace mckl #endif // MCKL_RANDOM_SEED_HPP
add a seed_type for scalar seed generator
add a seed_type for scalar seed generator
C++
bsd-2-clause
zhouyan/MCKL,zhouyan/MCKL,zhouyan/MCKL,zhouyan/MCKL
e29d7ad8997a693987b02b144a90b25be59c9836
indra/llcommon/nd/ndfile.cpp
indra/llcommon/nd/ndfile.cpp
/** * $LicenseInfo:firstyear=2013&license=fsviewerlgpl$ * Phoenix Firestorm Viewer Source Code * Copyright (C) 2013, Nicky Dasmijn * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA * http://www.firestormviewer.org * $/LicenseInfo$ */ #include "ndfile.h" #include "llerror.h" #include "llfile.h" #ifdef LL_WINDOWS #include <io.h> #else #include <sys/file.h> #endif namespace nd { namespace apr { ndFile::ndFile() : mFile(NULL) { } ndFile::ndFile(const std::string& filename, apr_int32_t flags, ndVolatileAPRPool* pool) : mFile(NULL) { open(filename, flags, pool); } ndFile::~ndFile() { close() ; } apr_status_t ndFile::close() { FILE *pFile(mFile); mFile = 0; return close( pFile, 0 ); } apr_status_t ndFile::open(const std::string& filename, apr_int32_t flags, ndVolatileAPRPool* pool, S32* sizep) { return nd::aprhelper::ndOpenFile( filename, flags, mFile, sizep ); } apr_status_t ndFile::open(const std::string& filename, apr_int32_t flags, BOOL use_global_pool) { return nd::aprhelper::ndOpenFile( filename, flags, mFile ); } S32 ndFile::read(void *buf, S32 nbytes) { if( !mFile ) { llwarns << "File is not open, cannot read" << llendl; return 0; } S32 read = fread(buf, 1, nbytes, mFile ); if( nbytes != read ) { llwarns << "Error when reading, wanted " << nbytes << " read " << read << llendl; } return read; } S32 ndFile::write(const void *buf, S32 nbytes) { if( !mFile ) { llwarns << "File is not open, cannot write" << llendl; return 0; } S32 written = fwrite( buf, 1, nbytes, mFile ); if( nbytes != written ) { llwarns << "Error when writing, wanted " << nbytes << " wrote " << written << llendl; } return written; } S32 ndFile::seek(apr_seek_where_t where, S32 offset) { return ndFile::seek(mFile, where, offset) ; } apr_status_t ndFile::close(FILE* file_handle, ndVolatileAPRPool* pool) { if( 0 == LLFile::close( file_handle ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + errno; } FILE* ndFile::open(const std::string& filename, ndVolatileAPRPool* pool, apr_int32_t flags) { FILE *pFile(0); if( APR_SUCCESS == nd::aprhelper::ndOpenFile( filename, flags, pFile ) && pFile ) return pFile; return 0; } S32 ndFile::seek(FILE* file_handle, apr_seek_where_t where, S32 offset) { if( !file_handle ) return -1; int seekStatus(0); if( offset >= 0 ) seekStatus = fseek( file_handle, offset, nd::aprhelper::ndConvertSeekFlags( where ) ); else seekStatus = fseek( file_handle, 0, SEEK_END ); if( 0 != seekStatus ) { int err = errno; llwarns << "Seek failed with errno " << err << llendl; return -1; } S32 offsetNew = ftell( file_handle ); if( offset != 0 && SEEK_SET == nd::aprhelper::ndConvertSeekFlags( where ) && offset != offsetNew ) { llwarns << "Seek failed, wanted offset " << offset << " got " << offsetNew << llendl; } return offsetNew; } S32 ndFile::readEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, ndVolatileAPRPool* pool) { FILE* file_handle = open(filename, pool, APR_READ|APR_BINARY); if (!file_handle) return 0; llassert(offset >= 0); if (offset > 0) offset = ndFile::seek(file_handle, APR_SET, offset); apr_size_t bytes_read; if (offset < 0) bytes_read = 0; else bytes_read = fread(buf, 1, nbytes, file_handle ); close(file_handle, pool); if( nbytes != bytes_read ) { llwarns << "Error when reading, wanted " << nbytes << " read " << bytes_read << " offset " << offset << llendl; } return (S32)bytes_read; } S32 ndFile::writeEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, ndVolatileAPRPool* pool) { apr_int32_t flags = APR_CREATE|APR_WRITE|APR_BINARY; if (offset < 0) { flags |= APR_APPEND; offset = 0; } FILE* file_handle = open(filename, pool, flags); if (!file_handle) return 0; if (offset > 0) offset = ndFile::seek(file_handle, APR_SET, offset); apr_size_t bytes_written; if (offset < 0) bytes_written = 0; else bytes_written = fwrite(buf, 1, nbytes, file_handle ); ndFile::close(file_handle, pool); if( nbytes != bytes_written ) llwarns << "Error when writing, wanted " << nbytes << " wrote " << bytes_written << " offset " << offset << llendl; return (S32)bytes_written; } bool ndFile::remove(const std::string& filename, ndVolatileAPRPool* pool) { return 0 == LLFile::remove( filename ); } bool ndFile::rename(const std::string& filename, const std::string& newname, ndVolatileAPRPool* pool) { return 0 == LLFile::rename( filename, newname ); } bool ndFile::isExist(const std::string& filename, ndVolatileAPRPool* pool, apr_int32_t flags) { llstat oStat; int nRes = LLFile::stat( filename, &oStat ); if( 0 == nRes ) return S_ISREG( oStat.st_mode ); return false; } S32 ndFile::size(const std::string& aFilename, ndVolatileAPRPool* pool) { llstat oStat; int nRes = LLFile::stat( aFilename, &oStat ); if( 0 == nRes ) return oStat.st_size; return 0; } bool ndFile::makeDir(const std::string& dirname, ndVolatileAPRPool* pool) { return 0 != LLFile::mkdir( dirname ); } bool ndFile::removeDir(const std::string& dirname, ndVolatileAPRPool* pool) { return 0 == LLFile::rmdir( dirname ); } } } namespace nd { namespace aprhelper { std::string ndConvertFilename( std::string const &aFilename ) { #ifdef LL_WINDOWS // For safety reason (don't change any behaviour) do nothing different if filename is already ASCII std::string::const_iterator itr = std::find_if( aFilename.begin(), aFilename.end(), [&]( char const & aVal ){ return aVal < 0; } ); if( aFilename.end() == itr ) return aFilename; wchar_t aShort[ MAX_PATH ] = {0}; DWORD nRes = ::GetShortPathNameW( utf8str_to_utf16str( aFilename ).c_str(), aShort, _countof( aShort ) ); if( nRes == 0 || nRes >= _countof( aShort ) ) return aFilename; return utf16str_to_utf8str( aShort ); #else return aFilename; #endif } char const *openR = "r"; char const *openRB = "rb"; char const *openRP = "r+"; char const *openRBP = "rb+"; char const *openW = "w"; char const *openWB = "wb"; char const *openWP = "w+"; char const *openWBP = "wb+"; char const *openA = "a"; char const *openAB = "ab"; char const* ndConvertOpenFlags( apr_int32_t aFlags, std::string const &aFilename ) { bool isBinary = (aFlags & APR_BINARY); bool doCreate = (aFlags & APR_CREATE); bool doTruncate = (aFlags & APR_TRUNCATE); bool doesExist = LLFile::isfile( aFilename ); if( aFlags & APR_READ && aFlags & APR_WRITE ) { if( doTruncate || !doesExist ) { if( isBinary ) return openWBP; else return openWP; } else { if( isBinary ) return openRBP; else return openRP; } } if( aFlags & APR_READ ) { if( isBinary ) return openRB; else return openR; } if( aFlags & APR_WRITE ) { if( ( doesExist && !doTruncate ) || !doCreate ) { if( isBinary ) return openRBP; else return openRP; } else { if( isBinary ) return openWB; else return openW; } } if( aFlags & APR_APPEND ) { if( isBinary ) return openAB; else return openA; } return openR; } apr_status_t ndOpenFile( const std::string& aFilename, apr_int32_t aOpenflags, FILE *&aFileout, S32* aSizeout) { aFileout = 0; if( aSizeout ) *aSizeout = 0; apr_status_t s = APR_SUCCESS; FILE *pFile = LLFile::fopen( aFilename, ndConvertOpenFlags( aOpenflags, aFilename ) ); if ( !pFile ) { s = APR_OS_START_SYSERR + errno; } else if (aSizeout) { llstat oStat; int nRes = LLFile::stat( aFilename, &oStat ); if ( 0 == nRes ) *aSizeout = oStat.st_size; else { int err = errno; llwarns << "stat for file " << aFilename << " failed with errno " << err << llendl; } } aFileout = pFile; return s; } } } int apr_file_close( FILE *aFile ) { if( 0 == fclose( aFile ) ) return APR_SUCCESS; return APR_OS_START_SYSERR+errno; } int apr_file_printf( FILE *aFile, char const *aFmt, ... ) { va_list vaLst; va_start( vaLst, aFmt ); int nPrinted = vfprintf( aFile, aFmt, vaLst ); va_end( vaLst ); if( nPrinted >= 0 ) return APR_SUCCESS; return APR_OS_START_SYSERR+errno; } int apr_file_eof( FILE *aFile ) { if( 0 == feof(aFile) ) return APR_SUCCESS; else return APR_EOF; } int apr_file_gets( char *aBuffer, U32 aMax, FILE *aFile ) { if( fgets( aBuffer, aMax, aFile ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + ferror( aFile ); } int apr_file_lock( FILE *aFile, int aLock ) { #ifndef LL_WINDOWS int fd = fileno( aFile ); if( -1 == fd ) return APR_OS_START_SYSERR + errno; int lockType = LOCK_SH; if( aLock & APR_FLOCK_EXCLUSIVE ) lockType = LOCK_EX; if( aLock & APR_FLOCK_NONBLOCK ) lockType |= LOCK_NB; int nRes; do { nRes = flock( fd, lockType ); } while( nRes && errno == EINTR ); if( 0 == nRes ) return APR_SUCCESS; return APR_OS_START_SYSERR + errno; #else int fd = _fileno( aFile ); if( -1 == fd ) return APR_OS_START_SYSERR + errno; HANDLE fHandle = reinterpret_cast<HANDLE>( _get_osfhandle( fd ) ); if( INVALID_HANDLE_VALUE == fHandle ) return APR_OS_START_SYSERR + errno; DWORD lockType = 0; if( aLock & APR_FLOCK_NONBLOCK ) lockType |= LOCKFILE_FAIL_IMMEDIATELY; if( aLock & APR_FLOCK_EXCLUSIVE ) lockType |= LOCKFILE_EXCLUSIVE_LOCK; OVERLAPPED oOverlapped; memset( &oOverlapped, 0, sizeof( OVERLAPPED ) ); if( ::LockFileEx( fHandle, lockType, 0, 0, UINT_MAX, &oOverlapped ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + ::GetLastError(); #endif } int apr_file_read( FILE *aFile, void *aBuffer, apr_size_t *aLen ) { llassert_always( aLen ); U32 nRead = fread( aBuffer, 1, *aLen, aFile ); if( 0 == nRead ) return APR_OS_START_SYSERR + ferror( aFile ); if( aLen ) *aLen = nRead; return APR_SUCCESS; }
/** * $LicenseInfo:firstyear=2013&license=fsviewerlgpl$ * Phoenix Firestorm Viewer Source Code * Copyright (C) 2013, Nicky Dasmijn * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA * http://www.firestormviewer.org * $/LicenseInfo$ */ #include "ndfile.h" #include "llerror.h" #include "llfile.h" #ifdef LL_WINDOWS #include <io.h> #else #include <sys/file.h> #endif namespace nd { namespace apr { ndFile::ndFile() : mFile(NULL) { } ndFile::ndFile(const std::string& filename, apr_int32_t flags, ndVolatileAPRPool* pool) : mFile(NULL) { open(filename, flags, pool); } ndFile::~ndFile() { close() ; } apr_status_t ndFile::close() { FILE *pFile(mFile); mFile = 0; return close( pFile, 0 ); } apr_status_t ndFile::open(const std::string& filename, apr_int32_t flags, ndVolatileAPRPool* pool, S32* sizep) { return nd::aprhelper::ndOpenFile( filename, flags, mFile, sizep ); } apr_status_t ndFile::open(const std::string& filename, apr_int32_t flags, BOOL use_global_pool) { return nd::aprhelper::ndOpenFile( filename, flags, mFile ); } S32 ndFile::read(void *buf, S32 nbytes) { if( !mFile ) { llwarns << "File is not open, cannot read" << llendl; return 0; } S32 read = fread(buf, 1, nbytes, mFile ); if( nbytes != read ) { llwarns << "Error when reading, wanted " << nbytes << " read " << read << llendl; } return read; } S32 ndFile::write(const void *buf, S32 nbytes) { if( !mFile ) { llwarns << "File is not open, cannot write" << llendl; return 0; } S32 written = fwrite( buf, 1, nbytes, mFile ); if( nbytes != written ) { llwarns << "Error when writing, wanted " << nbytes << " wrote " << written << llendl; } return written; } S32 ndFile::seek(apr_seek_where_t where, S32 offset) { return ndFile::seek(mFile, where, offset) ; } apr_status_t ndFile::close(FILE* file_handle, ndVolatileAPRPool* pool) { if( 0 == LLFile::close( file_handle ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + errno; } FILE* ndFile::open(const std::string& filename, ndVolatileAPRPool* pool, apr_int32_t flags) { FILE *pFile(0); if( APR_SUCCESS == nd::aprhelper::ndOpenFile( filename, flags, pFile ) && pFile ) return pFile; return 0; } S32 ndFile::seek(FILE* file_handle, apr_seek_where_t where, S32 offset) { if( !file_handle ) return -1; int seekStatus(0); if( offset >= 0 ) seekStatus = fseek( file_handle, offset, nd::aprhelper::ndConvertSeekFlags( where ) ); else seekStatus = fseek( file_handle, 0, SEEK_END ); if( 0 != seekStatus ) { int err = errno; llwarns << "Seek failed with errno " << err << llendl; return -1; } S32 offsetNew = ftell( file_handle ); if( offset != 0 && SEEK_SET == nd::aprhelper::ndConvertSeekFlags( where ) && offset != offsetNew ) { llwarns << "Seek failed, wanted offset " << offset << " got " << offsetNew << llendl; } return offsetNew; } S32 ndFile::readEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, ndVolatileAPRPool* pool) { FILE* file_handle = open(filename, pool, APR_READ|APR_BINARY); if (!file_handle) return 0; llassert(offset >= 0); if (offset > 0) offset = ndFile::seek(file_handle, APR_SET, offset); apr_size_t bytes_read; if (offset < 0) bytes_read = 0; else bytes_read = fread(buf, 1, nbytes, file_handle ); close(file_handle, pool); if( nbytes != bytes_read ) { llwarns << "Error when reading, wanted " << nbytes << " read " << bytes_read << " offset " << offset << llendl; } return (S32)bytes_read; } S32 ndFile::writeEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, ndVolatileAPRPool* pool) { apr_int32_t flags = APR_CREATE|APR_WRITE|APR_BINARY; if (offset < 0) { flags |= APR_APPEND; offset = 0; } FILE* file_handle = open(filename, pool, flags); if (!file_handle) return 0; if (offset > 0) offset = ndFile::seek(file_handle, APR_SET, offset); apr_size_t bytes_written; if (offset < 0) bytes_written = 0; else bytes_written = fwrite(buf, 1, nbytes, file_handle ); ndFile::close(file_handle, pool); if( nbytes != bytes_written ) llwarns << "Error when writing, wanted " << nbytes << " wrote " << bytes_written << " offset " << offset << llendl; return (S32)bytes_written; } bool ndFile::remove(const std::string& filename, ndVolatileAPRPool* pool) { return 0 == LLFile::remove( filename ); } bool ndFile::rename(const std::string& filename, const std::string& newname, ndVolatileAPRPool* pool) { return 0 == LLFile::rename( filename, newname ); } bool ndFile::isExist(const std::string& filename, ndVolatileAPRPool* pool, apr_int32_t flags) { llstat oStat; int nRes = LLFile::stat( filename, &oStat ); if( 0 == nRes ) return S_ISREG( oStat.st_mode ); return false; } S32 ndFile::size(const std::string& aFilename, ndVolatileAPRPool* pool) { llstat oStat; int nRes = LLFile::stat( aFilename, &oStat ); if( 0 == nRes ) return oStat.st_size; return 0; } bool ndFile::makeDir(const std::string& dirname, ndVolatileAPRPool* pool) { return 0 != LLFile::mkdir( dirname ); } bool ndFile::removeDir(const std::string& dirname, ndVolatileAPRPool* pool) { return 0 == LLFile::rmdir( dirname ); } } } namespace nd { namespace aprhelper { std::string ndConvertFilename( std::string const &aFilename ) { #ifdef LL_WINDOWS // For safety reason (don't change any behaviour) do nothing different if filename is already ASCII std::string::const_iterator itr = std::find_if( aFilename.begin(), aFilename.end(), [&]( char const & aVal ){ return aVal < 0; } ); if( aFilename.end() == itr ) return aFilename; wchar_t aShort[ MAX_PATH ] = {0}; DWORD nRes = ::GetShortPathNameW( utf8str_to_utf16str( aFilename ).c_str(), aShort, _countof( aShort ) ); if( nRes == 0 || nRes >= _countof( aShort ) ) return aFilename; return utf16str_to_utf8str( aShort ); #else return aFilename; #endif } char const *openR = "r"; char const *openRB = "rb"; char const *openRP = "r+"; char const *openRBP = "rb+"; char const *openW = "w"; char const *openWB = "wb"; char const *openWP = "w+"; char const *openWBP = "wb+"; char const *openA = "a"; char const *openAB = "ab"; char const* ndConvertOpenFlags( apr_int32_t aFlags, std::string const &aFilename ) { bool isBinary = (aFlags & APR_BINARY); bool doCreate = (aFlags & APR_CREATE); bool doTruncate = (aFlags & APR_TRUNCATE); if( aFlags & APR_READ && aFlags & APR_WRITE ) { if( doTruncate || !LLFile::isfile( aFilename ) ) { if( isBinary ) return openWBP; else return openWP; } else { if( isBinary ) return openRBP; else return openRP; } } if( aFlags & APR_READ ) { if( isBinary ) return openRB; else return openR; } if( aFlags & APR_WRITE ) { if( ( !doTruncate && LLFile::isfile( aFilename ) ) || !doCreate ) { if( isBinary ) return openRBP; else return openRP; } else { if( isBinary ) return openWB; else return openW; } } if( aFlags & APR_APPEND ) { if( isBinary ) return openAB; else return openA; } return openR; } apr_status_t ndOpenFile( const std::string& aFilename, apr_int32_t aOpenflags, FILE *&aFileout, S32* aSizeout) { aFileout = 0; if( aSizeout ) *aSizeout = 0; apr_status_t s = APR_SUCCESS; FILE *pFile = LLFile::fopen( aFilename, ndConvertOpenFlags( aOpenflags, aFilename ) ); if ( !pFile ) { s = APR_OS_START_SYSERR + errno; } else if (aSizeout) { llstat oStat; int nRes = LLFile::stat( aFilename, &oStat ); if ( 0 == nRes ) *aSizeout = oStat.st_size; else { int err = errno; llwarns << "stat for file " << aFilename << " failed with errno " << err << llendl; } } aFileout = pFile; return s; } } } int apr_file_close( FILE *aFile ) { if( 0 == fclose( aFile ) ) return APR_SUCCESS; return APR_OS_START_SYSERR+errno; } int apr_file_printf( FILE *aFile, char const *aFmt, ... ) { va_list vaLst; va_start( vaLst, aFmt ); int nPrinted = vfprintf( aFile, aFmt, vaLst ); va_end( vaLst ); if( nPrinted >= 0 ) return APR_SUCCESS; return APR_OS_START_SYSERR+errno; } int apr_file_eof( FILE *aFile ) { if( 0 == feof(aFile) ) return APR_SUCCESS; else return APR_EOF; } int apr_file_gets( char *aBuffer, U32 aMax, FILE *aFile ) { if( fgets( aBuffer, aMax, aFile ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + ferror( aFile ); } int apr_file_lock( FILE *aFile, int aLock ) { #ifndef LL_WINDOWS int fd = fileno( aFile ); if( -1 == fd ) return APR_OS_START_SYSERR + errno; int lockType = LOCK_SH; if( aLock & APR_FLOCK_EXCLUSIVE ) lockType = LOCK_EX; if( aLock & APR_FLOCK_NONBLOCK ) lockType |= LOCK_NB; int nRes; do { nRes = flock( fd, lockType ); } while( nRes && errno == EINTR ); if( 0 == nRes ) return APR_SUCCESS; return APR_OS_START_SYSERR + errno; #else int fd = _fileno( aFile ); if( -1 == fd ) return APR_OS_START_SYSERR + errno; HANDLE fHandle = reinterpret_cast<HANDLE>( _get_osfhandle( fd ) ); if( INVALID_HANDLE_VALUE == fHandle ) return APR_OS_START_SYSERR + errno; DWORD lockType = 0; if( aLock & APR_FLOCK_NONBLOCK ) lockType |= LOCKFILE_FAIL_IMMEDIATELY; if( aLock & APR_FLOCK_EXCLUSIVE ) lockType |= LOCKFILE_EXCLUSIVE_LOCK; OVERLAPPED oOverlapped; memset( &oOverlapped, 0, sizeof( OVERLAPPED ) ); if( ::LockFileEx( fHandle, lockType, 0, 0, UINT_MAX, &oOverlapped ) ) return APR_SUCCESS; return APR_OS_START_SYSERR + ::GetLastError(); #endif } int apr_file_read( FILE *aFile, void *aBuffer, apr_size_t *aLen ) { llassert_always( aLen ); U32 nRead = fread( aBuffer, 1, *aLen, aFile ); if( 0 == nRead ) return APR_OS_START_SYSERR + ferror( aFile ); if( aLen ) *aLen = nRead; return APR_SUCCESS; }
Make less calls to LLFile::isFile.
Make less calls to LLFile::isFile.
C++
lgpl-2.1
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
af485c03b9d43d752156fa2973dca50470554a54
indra/newview/llvoclouds.cpp
indra/newview/llvoclouds.cpp
/** * @file llvoclouds.cpp * @brief Implementation of LLVOClouds class which is a derivation fo LLViewerObject * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llvoclouds.h" #include "lldrawpoolalpha.h" #include "llviewercontrol.h" #include "llagent.h" // to get camera position #include "lldrawable.h" #include "llface.h" #include "llprimitive.h" #include "llsky.h" #include "llviewercamera.h" #include "llviewertexturelist.h" #include "llviewerobjectlist.h" #include "llviewerregion.h" #include "llvosky.h" #include "llworld.h" #include "pipeline.h" #include "llspatialpartition.h" LLUUID gCloudTextureID = IMG_CLOUD_POOF; LLVOClouds::LLVOClouds(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp) : LLAlphaObject(id, LL_VO_CLOUDS, regionp) { mCloudGroupp = NULL; mbCanSelect = FALSE; setNumTEs(1); LLViewerTexture* image = LLViewerTextureManager::getFetchedTexture(gCloudTextureID); image->setBoostLevel(LLViewerTexture::BOOST_CLOUDS); setTEImage(0, image); } LLVOClouds::~LLVOClouds() { } BOOL LLVOClouds::isActive() const { return TRUE; } BOOL LLVOClouds::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time) { static LLFastTimer::DeclareTimer ftm("Idle Clouds"); LLFastTimer t(ftm); if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS))) { return TRUE; } // Set dirty flag (so renderer will rebuild primitive) if (mDrawable) { gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE); } return TRUE; } void LLVOClouds::setPixelAreaAndAngle(LLAgent &agent) { mAppAngle = 50; mPixelArea = 1500*100; } void LLVOClouds::updateTextures() { getTEImage(0)->addTextureStats(mPixelArea); } LLDrawable* LLVOClouds::createDrawable(LLPipeline *pipeline) { pipeline->allocDrawable(this); mDrawable->setLit(FALSE); mDrawable->setRenderType(LLPipeline::RENDER_TYPE_CLOUDS); return mDrawable; } static LLFastTimer::DeclareTimer FTM_UPDATE_CLOUDS("Update Clouds"); BOOL LLVOClouds::updateGeometry(LLDrawable *drawable) { LLFastTimer ftm(FTM_UPDATE_CLOUDS); if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS))) { return TRUE; } if (drawable->isVisible()) { dirtySpatialGroup(TRUE); } LLFace *facep; S32 num_faces = mCloudGroupp->getNumPuffs(); if (num_faces > drawable->getNumFaces()) { drawable->setNumFacesFast(num_faces, NULL, getTEImage(0)); } mDepth = (getPositionAgent()-LLViewerCamera::getInstance()->getOrigin())*LLViewerCamera::getInstance()->getAtAxis(); S32 face_indx = 0; for ( ; face_indx < num_faces; face_indx++) { facep = drawable->getFace(face_indx); if (!facep) { llwarns << "No facep for index " << face_indx << llendl; continue; } facep->setSize(4, 6); facep->setTEOffset(face_indx); facep->setTexture(getTEImage(0)); const LLCloudPuff &puff = mCloudGroupp->getPuff(face_indx); const LLVector3 puff_pos_agent = gAgent.getPosAgentFromGlobal(puff.getPositionGlobal()); facep->mCenterLocal = puff_pos_agent; /// Update cloud color based on sun color. LLColor4 float_color(LLColor3(gSky.getSunDiffuseColor() + gSky.getSunAmbientColor()),puff.getAlpha()); facep->setFaceColor(float_color); } for ( ; face_indx < drawable->getNumFaces(); face_indx++) { facep = drawable->getFace(face_indx); if (!facep) { llwarns << "No facep for index " << face_indx << llendl; continue; } facep->setTEOffset(face_indx); facep->setSize(0,0); } drawable->movePartition(); return TRUE; } F32 LLVOClouds::getPartSize(S32 idx) { return (CLOUD_PUFF_HEIGHT+CLOUD_PUFF_WIDTH)*0.5f; } void LLVOClouds::getGeometry(S32 te, LLStrider<LLVector3>& verticesp, LLStrider<LLVector3>& normalsp, LLStrider<LLVector2>& texcoordsp, LLStrider<LLColor4U>& colorsp, LLStrider<U16>& indicesp) { if (te >= mCloudGroupp->getNumPuffs()) { return; } LLDrawable* drawable = mDrawable; LLFace *facep = drawable->getFace(te); if (!facep->hasGeometry()) { return; } LLVector3 normal(0.f,0.f,-1.f); const LLCloudPuff &puff = mCloudGroupp->getPuff(te); S32 index_offset = facep->getGeomIndex(); LLColor4 float_color(LLColor3(gSky.getSunDiffuseColor() + gSky.getSunAmbientColor()),puff.getAlpha()); LLColor4U color; color.setVec(float_color); facep->setFaceColor(float_color); LLVector3 up; LLVector3 right; LLVector3 at; const LLVector3& puff_pos_agent = facep->mCenterLocal; LLVector2 uvs[4]; uvs[0].setVec(0.f, 1.f); uvs[1].setVec(0.f, 0.f); uvs[2].setVec(1.f, 1.f); uvs[3].setVec(1.f, 0.f); LLVector3 vtx[4]; at = LLViewerCamera::getInstance()->getAtAxis(); right = at % LLVector3(0.f, 0.f, 1.f); right.normVec(); up = right % at; up.normVec(); right *= 0.5f*CLOUD_PUFF_WIDTH; up *= 0.5f*CLOUD_PUFF_HEIGHT;; *colorsp++ = color; *colorsp++ = color; *colorsp++ = color; *colorsp++ = color; vtx[0] = puff_pos_agent - right + up; vtx[1] = puff_pos_agent - right - up; vtx[2] = puff_pos_agent + right + up; vtx[3] = puff_pos_agent + right - up; *verticesp++ = vtx[0]; *verticesp++ = vtx[1]; *verticesp++ = vtx[2]; *verticesp++ = vtx[3]; *texcoordsp++ = uvs[0]; *texcoordsp++ = uvs[1]; *texcoordsp++ = uvs[2]; *texcoordsp++ = uvs[3]; *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *indicesp++ = index_offset + 0; *indicesp++ = index_offset + 1; *indicesp++ = index_offset + 2; *indicesp++ = index_offset + 1; *indicesp++ = index_offset + 3; *indicesp++ = index_offset + 2; } U32 LLVOClouds::getPartitionType() const { return LLViewerRegion::PARTITION_CLOUD; } // virtual void LLVOClouds::updateDrawable(BOOL force_damped) { // Force an immediate rebuild on any update if (mDrawable.notNull()) { mDrawable->updateXform(TRUE); gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE); } clearChanged(SHIFTED); } LLCloudPartition::LLCloudPartition() { mDrawableType = LLPipeline::RENDER_TYPE_CLOUDS; mPartitionType = LLViewerRegion::PARTITION_CLOUD; }
/** * @file llvoclouds.cpp * @brief Implementation of LLVOClouds class which is a derivation fo LLViewerObject * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llvoclouds.h" #include "lldrawpoolalpha.h" #include "llviewercontrol.h" #include "llagent.h" // to get camera position #include "lldrawable.h" #include "llface.h" #include "llprimitive.h" #include "llsky.h" #include "llviewercamera.h" #include "llviewertexturelist.h" #include "llviewerobjectlist.h" #include "llviewerregion.h" #include "llvosky.h" #include "llworld.h" #include "pipeline.h" #include "llspatialpartition.h" LLUUID gCloudTextureID = IMG_CLOUD_POOF; LLVOClouds::LLVOClouds(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp) : LLAlphaObject(id, LL_VO_CLOUDS, regionp) { mCloudGroupp = NULL; mbCanSelect = FALSE; setNumTEs(1); LLViewerTexture* image = LLViewerTextureManager::getFetchedTexture(gCloudTextureID); image->setBoostLevel(LLViewerTexture::BOOST_CLOUDS); setTEImage(0, image); } LLVOClouds::~LLVOClouds() { } BOOL LLVOClouds::isActive() const { return TRUE; } BOOL LLVOClouds::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time) { static LLFastTimer::DeclareTimer ftm("Idle Clouds"); LLFastTimer t(ftm); if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS))) { return TRUE; } // Set dirty flag (so renderer will rebuild primitive) if (mDrawable) { gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_VOLUME, TRUE); } return TRUE; } void LLVOClouds::setPixelAreaAndAngle(LLAgent &agent) { mAppAngle = 50; mPixelArea = 1500*100; } void LLVOClouds::updateTextures() { getTEImage(0)->addTextureStats(mPixelArea); } LLDrawable* LLVOClouds::createDrawable(LLPipeline *pipeline) { pipeline->allocDrawable(this); mDrawable->setLit(FALSE); mDrawable->setRenderType(LLPipeline::RENDER_TYPE_CLOUDS); return mDrawable; } static LLFastTimer::DeclareTimer FTM_UPDATE_CLOUDS("Update Clouds"); BOOL LLVOClouds::updateGeometry(LLDrawable *drawable) { LLFastTimer ftm(FTM_UPDATE_CLOUDS); if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS))) { return TRUE; } if (drawable->isVisible()) { dirtySpatialGroup(TRUE); } LLFace *facep; S32 num_faces = mCloudGroupp->getNumPuffs(); if (num_faces > drawable->getNumFaces()) { drawable->setNumFacesFast(num_faces, NULL, getTEImage(0)); } mDepth = (getPositionAgent()-LLViewerCamera::getInstance()->getOrigin())*LLViewerCamera::getInstance()->getAtAxis(); S32 face_indx = 0; for ( ; face_indx < num_faces; face_indx++) { facep = drawable->getFace(face_indx); if (!facep) { llwarns << "No facep for index " << face_indx << llendl; continue; } facep->setSize(4, 6); facep->setTEOffset(face_indx); facep->setTexture(getTEImage(0)); const LLCloudPuff &puff = mCloudGroupp->getPuff(face_indx); const LLVector3 puff_pos_agent = gAgent.getPosAgentFromGlobal(puff.getPositionGlobal()); facep->mCenterLocal = puff_pos_agent; /// Update cloud color based on sun color. LLColor4 float_color(LLColor3(gSky.getSunDiffuseColor() + gSky.getSunAmbientColor()),puff.getAlpha()); facep->setFaceColor(float_color); } for ( ; face_indx < drawable->getNumFaces(); face_indx++) { facep = drawable->getFace(face_indx); if (!facep) { llwarns << "No facep for index " << face_indx << llendl; continue; } facep->setTEOffset(face_indx); facep->setSize(0,0); } drawable->movePartition(); return TRUE; } F32 LLVOClouds::getPartSize(S32 idx) { return (CLOUD_PUFF_HEIGHT+CLOUD_PUFF_WIDTH)*0.5f; } void LLVOClouds::getGeometry(S32 te, LLStrider<LLVector3>& verticesp, LLStrider<LLVector3>& normalsp, LLStrider<LLVector2>& texcoordsp, LLStrider<LLColor4U>& colorsp, LLStrider<U16>& indicesp) { if (te >= mCloudGroupp->getNumPuffs()) { return; } LLDrawable* drawable = mDrawable; LLFace *facep = drawable->getFace(te); if (!facep->hasGeometry()) { return; } LLVector3 normal(0.f,0.f,-1.f); const LLCloudPuff &puff = mCloudGroupp->getPuff(te); S32 index_offset = facep->getGeomIndex(); LLColor4 float_color(LLColor3(gSky.getSunDiffuseColor() + gSky.getSunAmbientColor()),puff.getAlpha()); LLColor4U color; color.setVec(float_color); facep->setFaceColor(float_color); LLVector3 up; LLVector3 right; LLVector3 at; const LLVector3& puff_pos_agent = facep->mCenterLocal; LLVector2 uvs[4]; uvs[0].setVec(0.f, 1.f); uvs[1].setVec(0.f, 0.f); uvs[2].setVec(1.f, 1.f); uvs[3].setVec(1.f, 0.f); LLVector3 vtx[4]; at = LLViewerCamera::getInstance()->getAtAxis(); right = at % LLVector3(0.f, 0.f, 1.f); right.normVec(); up = right % at; up.normVec(); right *= 0.5f*CLOUD_PUFF_WIDTH; up *= 0.5f*CLOUD_PUFF_HEIGHT;; *colorsp++ = color; *colorsp++ = color; *colorsp++ = color; *colorsp++ = color; vtx[0] = puff_pos_agent - right + up; vtx[1] = puff_pos_agent - right - up; vtx[2] = puff_pos_agent + right + up; vtx[3] = puff_pos_agent + right - up; verticesp->mV[3] = 0.f; *verticesp++ = vtx[0]; verticesp->mV[3] = 0.f; *verticesp++ = vtx[1]; verticesp->mV[3] = 0.f; *verticesp++ = vtx[2]; verticesp->mV[3] = 0.f; *verticesp++ = vtx[3]; *texcoordsp++ = uvs[0]; *texcoordsp++ = uvs[1]; *texcoordsp++ = uvs[2]; *texcoordsp++ = uvs[3]; *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *indicesp++ = index_offset + 0; *indicesp++ = index_offset + 1; *indicesp++ = index_offset + 2; *indicesp++ = index_offset + 1; *indicesp++ = index_offset + 3; *indicesp++ = index_offset + 2; } U32 LLVOClouds::getPartitionType() const { return LLViewerRegion::PARTITION_CLOUD; } // virtual void LLVOClouds::updateDrawable(BOOL force_damped) { // Force an immediate rebuild on any update if (mDrawable.notNull()) { mDrawable->updateXform(TRUE); gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE); } clearChanged(SHIFTED); } LLCloudPartition::LLCloudPartition() { mDrawableType = LLPipeline::RENDER_TYPE_CLOUDS; mPartitionType = LLViewerRegion::PARTITION_CLOUD; }
Fix for classic clouds being busted.
Fix for classic clouds being busted.
C++
lgpl-2.1
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
12a282c758c571e4b802d02555dd30b668cdfa47
ink_stroke_modeler/params.cc
ink_stroke_modeler/params.cc
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "ink_stroke_modeler/params.h" #include <cmath> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/types/variant.h" #include "ink_stroke_modeler/internal/validation.h" // This convenience macro evaluates the given expression, and if it does not // return an OK status, returns and propagates the status. #define RETURN_IF_ERROR(expr) \ do { \ if (auto status = (expr); !status.ok()) return status; \ } while (false) namespace ink { namespace stroke_model { absl::Status ValidatePositionModelerParams( const PositionModelerParams& params) { RETURN_IF_ERROR(ValidateGreaterThanZero(params.spring_mass_constant, "PredictionParams::spring_mass")); return ValidateGreaterThanZero(params.drag_constant, "PredictionParams::drag_ratio"); } absl::Status ValidateSamplingParams(const SamplingParams& params) { RETURN_IF_ERROR(ValidateGreaterThanZero(params.min_output_rate, "PredictionParams::min_output_rate")); RETURN_IF_ERROR(ValidateGreaterThanZero( params.end_of_stroke_stopping_distance, "PredictionParams::end_of_stroke_stopping_distance")); return ValidateGreaterThanZero( params.end_of_stroke_max_iterations, "PredictionParams::end_of_stroke_stopping_distance"); } absl::Status ValidateStylusStateModelerParams( const StylusStateModelerParams& params) { return ValidateGreaterThanZero(params.max_input_samples, "StylusStateModelerParams::max_input_samples"); } absl::Status ValidateWobbleSmootherParams(const WobbleSmootherParams& params) { RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( params.timeout.Value(), "WobbleSmootherParams::timeout")); RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( params.speed_floor, "WobbleSmootherParams::speed_floor")); RETURN_IF_ERROR(ValidateIsFiniteNumber( params.speed_ceiling, "WobbleSmootherParams::speed_ceiling")); if (params.speed_ceiling < params.speed_floor) { return absl::InvalidArgumentError(absl::Substitute( "WobbleSmootherParams::speed_ceiling must be greater than or " "equal to WobbleSmootherParams::speed_floor ($0). Actual " "value: $1", params.speed_floor, params.speed_ceiling)); } return absl::OkStatus(); } absl::Status ValidatePredictionParams(const PredictionParams& params) { if (absl::holds_alternative<StrokeEndPredictorParams>(params)) { // Nothing to validate. return absl::OkStatus(); } const KalmanPredictorParams& kalman_params = absl::get<KalmanPredictorParams>(params); RETURN_IF_ERROR(ValidateGreaterThanZero( kalman_params.process_noise, "KalmanPredictorParams::process_noise")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.measurement_noise, "KalmanPredictorParams::measurement_noise")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.min_stable_iteration, "KalmanPredictorParams::min_stable_iteration")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.max_time_samples, "KalmanPredictorParams::max_time_samples")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.min_catchup_velocity, "KalmanPredictorParams::min_catchup_velocity")); RETURN_IF_ERROR( ValidateIsFiniteNumber(kalman_params.acceleration_weight, "KalmanPredictorParams::acceleration_weight")); RETURN_IF_ERROR(ValidateIsFiniteNumber(kalman_params.jerk_weight, "KalmanPredictorParams::jerk_weight")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.prediction_interval.Value(), "KalmanPredictorParams::jerk_weight")); const KalmanPredictorParams::ConfidenceParams& confidence_params = kalman_params.confidence_params; RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.desired_number_of_samples, "KalmanPredictorParams::ConfidenceParams::desired_number_of_samples")); RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.max_estimation_distance, "KalmanPredictorParams::ConfidenceParams::max_estimation_distance")); RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( confidence_params.min_travel_speed, "KalmanPredictorParams::ConfidenceParams::min_travel_speed")); RETURN_IF_ERROR(ValidateIsFiniteNumber( confidence_params.max_travel_speed, "KalmanPredictorParams::ConfidenceParams::max_travel_speed")); if (confidence_params.max_travel_speed < confidence_params.min_travel_speed) { return absl::InvalidArgumentError( absl::Substitute("KalmanPredictorParams::ConfidenceParams::max_" "travel_speed must be greater than or equal to " "KalmanPredictorParams::ConfidenceParams::min_" "travel_speed ($0). Actual value: $1", confidence_params.min_travel_speed, confidence_params.max_travel_speed)); } RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.max_linear_deviation, "KalmanPredictorParams::ConfidenceParams::max_linear_deviation")); if (confidence_params.baseline_linearity_confidence < 0 || confidence_params.baseline_linearity_confidence > 1) { return absl::InvalidArgumentError(absl::Substitute( "KalmanPredictorParams::ConfidenceParams::baseline_linearity_" "confidence must lie in the interval [0, 1]. Actual value: $0", confidence_params.baseline_linearity_confidence)); } return absl::OkStatus(); } absl::Status ValidateStrokeModelParams(const StrokeModelParams& params) { RETURN_IF_ERROR(ValidateWobbleSmootherParams(params.wobble_smoother_params)); RETURN_IF_ERROR( ValidatePositionModelerParams(params.position_modeler_params)); RETURN_IF_ERROR(ValidateSamplingParams(params.sampling_params)); RETURN_IF_ERROR( ValidateStylusStateModelerParams(params.stylus_state_modeler_params)); return ValidatePredictionParams(params.prediction_params); } } // namespace stroke_model } // namespace ink #undef RETURN_IF_ERROR
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "ink_stroke_modeler/params.h" #include <cmath> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/types/variant.h" #include "ink_stroke_modeler/internal/validation.h" // This convenience macro evaluates the given expression, and if it does not // return an OK status, returns and propagates the status. #define RETURN_IF_ERROR(expr) \ do { \ if (auto status = (expr); !status.ok()) return status; \ } while (false) namespace ink { namespace stroke_model { absl::Status ValidatePositionModelerParams( const PositionModelerParams& params) { RETURN_IF_ERROR(ValidateGreaterThanZero(params.spring_mass_constant, "PredictionParams::spring_mass")); return ValidateGreaterThanZero(params.drag_constant, "PredictionParams::drag_ratio"); } absl::Status ValidateSamplingParams(const SamplingParams& params) { RETURN_IF_ERROR(ValidateGreaterThanZero(params.min_output_rate, "PredictionParams::min_output_rate")); RETURN_IF_ERROR(ValidateGreaterThanZero( params.end_of_stroke_stopping_distance, "PredictionParams::end_of_stroke_stopping_distance")); return ValidateGreaterThanZero( params.end_of_stroke_max_iterations, "PredictionParams::end_of_stroke_max_iterations"); } absl::Status ValidateStylusStateModelerParams( const StylusStateModelerParams& params) { return ValidateGreaterThanZero(params.max_input_samples, "StylusStateModelerParams::max_input_samples"); } absl::Status ValidateWobbleSmootherParams(const WobbleSmootherParams& params) { RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( params.timeout.Value(), "WobbleSmootherParams::timeout")); RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( params.speed_floor, "WobbleSmootherParams::speed_floor")); RETURN_IF_ERROR(ValidateIsFiniteNumber( params.speed_ceiling, "WobbleSmootherParams::speed_ceiling")); if (params.speed_ceiling < params.speed_floor) { return absl::InvalidArgumentError(absl::Substitute( "WobbleSmootherParams::speed_ceiling must be greater than or " "equal to WobbleSmootherParams::speed_floor ($0). Actual " "value: $1", params.speed_floor, params.speed_ceiling)); } return absl::OkStatus(); } absl::Status ValidatePredictionParams(const PredictionParams& params) { if (absl::holds_alternative<StrokeEndPredictorParams>(params)) { // Nothing to validate. return absl::OkStatus(); } const KalmanPredictorParams& kalman_params = absl::get<KalmanPredictorParams>(params); RETURN_IF_ERROR(ValidateGreaterThanZero( kalman_params.process_noise, "KalmanPredictorParams::process_noise")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.measurement_noise, "KalmanPredictorParams::measurement_noise")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.min_stable_iteration, "KalmanPredictorParams::min_stable_iteration")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.max_time_samples, "KalmanPredictorParams::max_time_samples")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.min_catchup_velocity, "KalmanPredictorParams::min_catchup_velocity")); RETURN_IF_ERROR( ValidateIsFiniteNumber(kalman_params.acceleration_weight, "KalmanPredictorParams::acceleration_weight")); RETURN_IF_ERROR(ValidateIsFiniteNumber(kalman_params.jerk_weight, "KalmanPredictorParams::jerk_weight")); RETURN_IF_ERROR( ValidateGreaterThanZero(kalman_params.prediction_interval.Value(), "KalmanPredictorParams::jerk_weight")); const KalmanPredictorParams::ConfidenceParams& confidence_params = kalman_params.confidence_params; RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.desired_number_of_samples, "KalmanPredictorParams::ConfidenceParams::desired_number_of_samples")); RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.max_estimation_distance, "KalmanPredictorParams::ConfidenceParams::max_estimation_distance")); RETURN_IF_ERROR(ValidateGreaterThanOrEqualToZero( confidence_params.min_travel_speed, "KalmanPredictorParams::ConfidenceParams::min_travel_speed")); RETURN_IF_ERROR(ValidateIsFiniteNumber( confidence_params.max_travel_speed, "KalmanPredictorParams::ConfidenceParams::max_travel_speed")); if (confidence_params.max_travel_speed < confidence_params.min_travel_speed) { return absl::InvalidArgumentError( absl::Substitute("KalmanPredictorParams::ConfidenceParams::max_" "travel_speed must be greater than or equal to " "KalmanPredictorParams::ConfidenceParams::min_" "travel_speed ($0). Actual value: $1", confidence_params.min_travel_speed, confidence_params.max_travel_speed)); } RETURN_IF_ERROR(ValidateGreaterThanZero( confidence_params.max_linear_deviation, "KalmanPredictorParams::ConfidenceParams::max_linear_deviation")); if (confidence_params.baseline_linearity_confidence < 0 || confidence_params.baseline_linearity_confidence > 1) { return absl::InvalidArgumentError(absl::Substitute( "KalmanPredictorParams::ConfidenceParams::baseline_linearity_" "confidence must lie in the interval [0, 1]. Actual value: $0", confidence_params.baseline_linearity_confidence)); } return absl::OkStatus(); } absl::Status ValidateStrokeModelParams(const StrokeModelParams& params) { RETURN_IF_ERROR(ValidateWobbleSmootherParams(params.wobble_smoother_params)); RETURN_IF_ERROR( ValidatePositionModelerParams(params.position_modeler_params)); RETURN_IF_ERROR(ValidateSamplingParams(params.sampling_params)); RETURN_IF_ERROR( ValidateStylusStateModelerParams(params.stylus_state_modeler_params)); return ValidatePredictionParams(params.prediction_params); } } // namespace stroke_model } // namespace ink #undef RETURN_IF_ERROR
Fix mislabeled output in ValidateSamplingParams
Fix mislabeled output in ValidateSamplingParams PiperOrigin-RevId: 438083113
C++
apache-2.0
google/ink-stroke-modeler,google/ink-stroke-modeler
c7fe29f3fae47aca4274552500ddc7f3344421b5
assets/code/cpp/macro_yield.cpp
assets/code/cpp/macro_yield.cpp
// clang -std=c++17 -lstdc++ prod.cpp -o prod && ./prod #include <cstdlib> #include <ctime> #include <iostream> #include <functional> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> using namespace std; template<typename T> void print(vector<T>& vec) { for(int i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; } cout << endl; } template<typename S> class Source : public std::enable_shared_from_this<Source<S>> { public: virtual ~Source() {} virtual bool operator()(S& output) = 0; bool next(S& output) { return (*this)(output); } shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); } }; template<typename S> class Gen : public Source<S> { public: int state; bool isAlive; Gen() : state(0), isAlive(true) {} virtual bool step(S& output) = 0; bool operator()(S& output) { while(!step(output)); return isAlive; } }; #define GEN_BEG \ switch(state) { \ case BEG: {} #define GEN_END \ default: { isAlive = false; return true; } } #define BEG(name) BEG_##name #define ELSE(name) ELSE_##name #define END(name) END_##name #define IF(name,c,a,b) \ case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \ case ELSE(name): { b; } \ case END(name): {} #define LOOP(name,s) \ case BEG(name): { {s;} state = BEG(name); return false; } \ case END(name): {} #define WHILE(name,c,s) \ case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \ case END(name): {} #define YIELD(name) \ case BEG(name): { state = END(name); isAlive = true; return true; } \ case END(name): {} #define CONTINUE(loop) { state = BEG(loop); return false; } #define BREAK(loop) { state = END(loop); return false; } #define GOTO(label) { state = label; return false; } #define DEC_BEG enum { BEG = 0, #define DEC_IF(name) BEG(name), ELSE(name), END(name) #define DEC_LOOP(name) BEG(name), END(name) #define DEC_YIELD(name) BEG(name), END(name) #define DEC_END }; /* L: def prod_iter(s): 0: if len(s) == 0: 1: yield [] 2: else: 3: x = 0 4: while true: 5: xs = [] 6: iter = generator.create(prod_iter(s[1:])) 7: while true: 8: xs, isAlive = iter.resume() 9: if !isAlive: 10 break 11 yield [x] + xs 12 x += 1 13 if x >= s[0]: 14 break -1 return */ class OneMoreProdGen : public Gen<vector<int> > { public: vector<unsigned int> s; int x; shared_ptr<Source<vector<int> > > iter; vector<int> xs; OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {} bool step(vector<int>& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_IF(if3), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG IF(if1, s.size()==0, { output.clear(); YIELD(y1); }, { x = 0; WHILE(loop1, true, { IF(if3, x >= s[0], BREAK(loop1), {}); { vector<unsigned int> ss(s.begin() + 1, s.end()); iter = make_shared<OneMoreProdGen>(ss); } WHILE(loop2, iter->next(xs), { output.clear(); output.push_back(x); output.insert(output.end(), xs.begin(), xs.end()); YIELD(y2); }); x += 1; }) }); GEN_END } }; /* def hanoi(n, a, b, c): if n == 1: s = str(a) + ' --> ' + str(c) yield s else: for s in hanoi(n - 1, a, c, b): yield s for s in hanoi(1 , a, b, c): yield s for s in hanoi(n - 1, b, a, c): yield s */ class OneMoreHanoiGen : public Gen<string> { public: int n; string a, b, c; shared_ptr<Gen<string> > iter; OneMoreHanoiGen(int _n, string _a, string _b, string _c): n(_n), a(_a), b(_b), c(_c) {} bool step(string& output) { DEC_BEG DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3), DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4) DEC_END GEN_BEG IF(if1, n == 1, { output = a + " --> " + c; YIELD(y1); }, { iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b); WHILE(loop1, iter->next(output), YIELD(y2)); iter = make_shared<OneMoreHanoiGen>(1, a, b, c); WHILE(loop2, iter->next(output), YIELD(y3)); iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c); WHILE(loop3, iter->next(output), YIELD(y4)); }); GEN_END } }; class PrimeGen : public Gen<int> { public: vector<int> primes; int i, j; PrimeGen() {} bool step(int& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1) DEC_END GEN_BEG i = 2; WHILE(loop1, true, { j = 0; WHILE(loop2, j < primes.size(), { IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++); }); primes.push_back(i); output = i; YIELD(y1); }); GEN_END } }; template<typename S, typename T> class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> { public: int state; bool isAlive; Coroutine() : state(0), isAlive(true) {} virtual ~Coroutine() {} virtual bool step(S& input, T& output) = 0; bool next(S& input, T& output) { while(!step(input, output)); return isAlive; } bool operator()(S& input, T& output) { return next(input, output); } shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); } }; class GuessNumber : public Coroutine<int, int> { public: int t, num; GuessNumber() {} bool step(int& input, int& output) { DEC_BEG DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG t = 0; srand(time(0)); cout << "Guess a number between 0 and 100!" << endl; WHILE(loop1, true, { cout << "Match " << t << endl; num = rand() % 100; cout << "input a number:"; YIELD(y1); WHILE(loop2, input != num, { IF(if1, input < num, { cout << "Too small!" << endl; output = -1; }, { cout << "Too large!" << endl; output = 1; }); cout << "input a number agian:"; YIELD(y2); }); cout << "Bingo! It's " << num << "!" << endl; cout << "Let's play it again!" << endl; t++; output = 0; }); GEN_END } }; void testGuessNumber() { GuessNumber guess; int num, output; guess(num, output); while(true) { cin >> num; guess(num, output); } } int main() { cout << "HanoiGen" << endl; string s; OneMoreHanoiGen hanoiGen(3, "A", "B", "C"); while(hanoiGen(s)) cout << s << endl; cout << "CartesianProduct" << endl; vector<unsigned int> dimSize({2,3,4}); vector<int> output(dimSize.size()); OneMoreProdGen prodGen(dimSize); while(prodGen(output)) print(output); cout << "Prime numbers" << endl; PrimeGen primeGen; int p; for(int i = 0; i < 30; ++i) { primeGen(p); cout << p << " "; } cout << endl; testGuessNumber(); return 0; }
// clang -std=c++17 -lstdc++ prod.cpp -o prod && ./prod #include <cstdlib> #include <ctime> #include <iostream> #include <functional> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> using namespace std; template<typename T> void print(vector<T>& vec) { for(int i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; } cout << endl; } template<typename S> class Source : public std::enable_shared_from_this<Source<S>> { public: virtual ~Source() {} virtual bool operator()(S& output) = 0; bool next(S& output) { return (*this)(output); } shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); } }; template<typename S> class Gen : public Source<S> { public: int state; bool isAlive; Gen() : state(0), isAlive(true) {} virtual bool step(S& output) = 0; bool operator()(S& output) { while(!step(output)); return isAlive; } }; #define GEN_BEG \ switch(state) { \ case BEG: {} #define GEN_END \ default: { isAlive = false; return true; } } #define BEG(name) BEG_##name #define ELSE(name) ELSE_##name #define END(name) END_##name #define IF(name,c,a,b) \ case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \ case ELSE(name): { b; } \ case END(name): {} #define LOOP(name,s) \ case BEG(name): { {s;} state = BEG(name); return false; } \ case END(name): {} #define WHILE(name,c,s) \ case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \ case END(name): {} #define YIELD(name) \ case BEG(name): { state = END(name); isAlive = true; return true; } \ case END(name): {} #define CONTINUE(loop) { state = BEG(loop); return false; } #define BREAK(loop) { state = END(loop); return false; } #define GOTO(label) { state = label; return false; } #define DEC_BEG enum { BEG = 0, #define DEC_IF(name) BEG(name), ELSE(name), END(name) #define DEC_LOOP(name) BEG(name), END(name) #define DEC_YIELD(name) BEG(name), END(name) #define DEC_END }; /* L: def prod_iter(s): 0: if len(s) == 0: 1: yield [] 2: else: 3: x = 0 4: while true: 5: xs = [] 6: iter = generator.create(prod_iter(s[1:])) 7: while true: 8: xs, isAlive = iter.resume() 9: if !isAlive: 10 break 11 yield [x] + xs 12 x += 1 13 if x >= s[0]: 14 break -1 return */ class OneMoreProdGen : public Gen<vector<int> > { public: vector<unsigned int> s; int x; shared_ptr<Source<vector<int> > > iter; vector<int> xs; OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {} bool step(vector<int>& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_IF(if3), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG IF(if1, s.size()==0, { output.clear(); YIELD(y1); }, { x = 0; WHILE(loop1, true, { IF(if3, x >= s[0], BREAK(loop1), {}); { vector<unsigned int> ss(s.begin() + 1, s.end()); iter = make_shared<OneMoreProdGen>(ss); } WHILE(loop2, iter->next(xs), { output.clear(); output.push_back(x); output.insert(output.end(), xs.begin(), xs.end()); YIELD(y2); }); x += 1; }) }); GEN_END } }; /* def hanoi(n, a, b, c): if n == 1: s = str(a) + ' --> ' + str(c) yield s else: for s in hanoi(n - 1, a, c, b): yield s for s in hanoi(1 , a, b, c): yield s for s in hanoi(n - 1, b, a, c): yield s */ class OneMoreHanoiGen : public Gen<string> { public: int n; string a, b, c; shared_ptr<Gen<string> > iter; OneMoreHanoiGen(int _n, string _a, string _b, string _c): n(_n), a(_a), b(_b), c(_c) {} bool step(string& output) { DEC_BEG DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3), DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4) DEC_END GEN_BEG IF(if1, n == 1, { output = a + " --> " + c; YIELD(y1); }, { iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b); WHILE(loop1, iter->next(output), YIELD(y2)); iter = make_shared<OneMoreHanoiGen>(1, a, b, c); WHILE(loop2, iter->next(output), YIELD(y3)); iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c); WHILE(loop3, iter->next(output), YIELD(y4)); }); GEN_END } }; class PrimeGen : public Gen<int> { public: vector<int> primes; int i, j; PrimeGen() {} bool step(int& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1) DEC_END GEN_BEG i = 2; WHILE(loop1, true, { j = 0; WHILE(loop2, j < primes.size(), { IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++); }); primes.push_back(i); output = i; YIELD(y1); }); GEN_END } }; template<typename S, typename T> class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> { public: int state; bool isAlive; Coroutine() : state(0), isAlive(true) {} virtual ~Coroutine() {} virtual bool step(S& input, T& output) = 0; bool next(S& input, T& output) { while(!step(input, output)); return isAlive; } bool operator()(S& input, T& output) { return next(input, output); } shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); } }; class GuessNumber : public Coroutine<int, int> { public: int t, num; GuessNumber() {} bool step(int& input, int& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG t = 0; srand(time(0)); cout << "Guess a number between 0 and 100!" << endl; WHILE(loop1, true, { cout << "Match " << t << endl; num = rand() % 100; cout << "input a number:"; YIELD(y1); WHILE(loop2, input != num, { IF(if2, input == -1, BREAK(loop1), {}); IF(if1, input < num, { cout << "Too small!" << endl; output = -1; }, { cout << "Too large!" << endl; output = 1; }); cout << "input a number agian:"; YIELD(y2); }); cout << "Bingo! It's " << num << "!" << endl; cout << "Let's play it again!" << endl; t++; output = 0; }); cout << "ByeBye!" << endl; GEN_END } }; void testGuessNumber() { GuessNumber guess; int num, output; guess(num, output); do { cin >> num; } while(guess(num, output)); } int main() { cout << "HanoiGen" << endl; string s; OneMoreHanoiGen hanoiGen(3, "A", "B", "C"); while(hanoiGen(s)) cout << s << endl; cout << "CartesianProduct" << endl; vector<unsigned int> dimSize({2,3,4}); vector<int> output(dimSize.size()); OneMoreProdGen prodGen(dimSize); while(prodGen(output)) print(output); cout << "Prime numbers" << endl; PrimeGen primeGen; int p; for(int i = 0; i < 30; ++i) { primeGen(p); cout << p << " "; } cout << endl; testGuessNumber(); return 0; }
Update macro_yield.cpp
Update macro_yield.cpp
C++
mit
FiveEye/FiveEye.github.io
75102608425f73902f67c6e87c0b6ce45a27396e
src/streams/arinputstream.cpp
src/streams/arinputstream.cpp
/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "arinputstream.h" #include "strigiconfig.h" #include "subinputstream.h" #include <stdlib.h> #include <cstring> using namespace Strigi; bool ArInputStream::checkHeader(const char* data, int32_t datasize) { static const char magic[] = {0x21,0x3c,0x61,0x72,0x63,0x68,0x3e,0x0a}; if (datasize < 8) return false; bool ok = memcmp(data, magic, 8) == 0; return ok; } ArInputStream::ArInputStream(InputStream* input) : SubStreamProvider(input) { // check header const char*b; if (input->read(b, 8, 8) != 8 || !checkHeader(b, 8)) { m_status = Error; } } ArInputStream::~ArInputStream() { } InputStream* ArInputStream::nextEntry() { if (m_status) return 0; if (m_entrystream) { m_entrystream->skip(m_entrystream->size()); delete m_entrystream; m_entrystream = 0; } readHeader(); if (m_status) return 0; m_entrystream = new SubInputStream(m_input, m_entryinfo.size); return m_entrystream; } void ArInputStream::readHeader() { const char *b; int32_t toread; int32_t nread; int64_t pos = m_input->position(); if (pos%2) { m_input->skip(1); } // read the first 60 characters toread = 60; nread = m_input->read(b, toread, toread); if (m_input->status() == Error) { m_error = "Error reading ar header: "; m_error += m_input->error(); m_status = Error; return; } if (nread <= 1) { // allow for a closing byte m_status = Eof; return; } if (nread != toread) { m_error = "Error reading ar header: premature end of file."; m_status = Error; return; } int len; for (len=0; len<16; len++) { char c = b[len]; if (c == ' ' || c == '/' || c == '\0') { break; } } // we must copy this string to safely call atoi char bc[61]; memcpy(bc, b, 60); bc[60] = '\0'; m_entryinfo.size = atoi(bc+48); if (m_entryinfo.size < 0) { m_error = "Error: negative file size."; m_status = Error; return; } m_entryinfo.mtime = atoi(bc+16); if (len == 0) { if (b[1] == '/') { fprintf(stderr, "SIZE: %lli\n", m_entryinfo.size); nread = m_input->read(b, m_entryinfo.size, m_entryinfo.size); if (nread != m_entryinfo.size) { m_error = "premature end of stream"; m_status = Error; return; } gnufilenames.assign(b, m_entryinfo.size); readHeader(); } else if (b[1] == ' ') { m_input->skip(m_entryinfo.size); readHeader(); } else { int p = atoi(bc+1); if (gnufilenames.length() <= p) { m_error = "Invalid name field."; m_status = Error; return; } const char* c = gnufilenames.c_str() + p; const char* e = strchr(c, '/'); if (e) { m_entryinfo.filename = std::string(c, e-c); } else { m_entryinfo.filename = c; } } } else { m_entryinfo.filename = std::string(b, len); } }
/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "arinputstream.h" #include "strigiconfig.h" #include "subinputstream.h" #include <stdlib.h> #include <cstring> using namespace Strigi; bool ArInputStream::checkHeader(const char* data, int32_t datasize) { static const char magic[] = {0x21,0x3c,0x61,0x72,0x63,0x68,0x3e,0x0a}; if (datasize < 8) return false; bool ok = memcmp(data, magic, 8) == 0; return ok; } ArInputStream::ArInputStream(InputStream* input) : SubStreamProvider(input) { // check header const char*b; if (input->read(b, 8, 8) != 8 || !checkHeader(b, 8)) { m_status = Error; } } ArInputStream::~ArInputStream() { } InputStream* ArInputStream::nextEntry() { if (m_status) return 0; if (m_entrystream) { m_entrystream->skip(m_entrystream->size()); delete m_entrystream; m_entrystream = 0; } readHeader(); if (m_status) return 0; m_entrystream = new SubInputStream(m_input, m_entryinfo.size); return m_entrystream; } void ArInputStream::readHeader() { const char *b; int32_t toread; int32_t nread; int64_t pos = m_input->position(); if (pos%2) { m_input->skip(1); } // read the first 60 characters toread = 60; nread = m_input->read(b, toread, toread); if (m_input->status() == Error) { m_error = "Error reading ar header: "; m_error += m_input->error(); m_status = Error; return; } if (nread <= 1) { // allow for a closing byte m_status = Eof; return; } if (nread != toread) { m_error = "Error reading ar header: premature end of file."; m_status = Error; return; } int len; for (len=0; len<16; len++) { char c = b[len]; if (c == ' ' || c == '/' || c == '\0') { break; } } // we must copy this string to safely call atoi char bc[61]; memcpy(bc, b, 60); bc[60] = '\0'; m_entryinfo.size = atoi(bc+48); if (m_entryinfo.size < 0) { m_error = "Error: negative file size."; m_status = Error; return; } m_entryinfo.mtime = atoi(bc+16); if (len == 0) { if (b[1] == '/') { // fprintf(stderr, "SIZE: %lli\n", m_entryinfo.size); nread = m_input->read(b, m_entryinfo.size, m_entryinfo.size); if (nread != m_entryinfo.size) { m_error = "premature end of stream"; m_status = Error; return; } gnufilenames.assign(b, m_entryinfo.size); readHeader(); } else if (b[1] == ' ') { m_input->skip(m_entryinfo.size); readHeader(); } else { int p = atoi(bc+1); if (gnufilenames.length() <= p) { m_error = "Invalid name field."; m_status = Error; return; } const char* c = gnufilenames.c_str() + p; const char* e = strchr(c, '/'); if (e) { m_entryinfo.filename = std::string(c, e-c); } else { m_entryinfo.filename = c; } } } else { m_entryinfo.filename = std::string(b, len); } }
remove debug message
remove debug message svn path=/trunk/kdesupport/strigi/; revision=694509
C++
lgpl-2.1
KDE/strigi
dbc945b26bab4cf755c9ad4a30974f78bdc0c4a0
test.cpp
test.cpp
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <string> #include <sstream> #include "nicestream.hpp" using namespace nstr; TEST_CASE("Regex parsing", "[regex]") { // simple literals CHECK_NOTHROW(sep("abcdz!!--<>\n\t^^^")); CHECK_NOTHROW(sep("abc\\.\\*\\?\\+\\[\\")); CHECK_NOTHROW(sep("(abcabc)(cabcab)")); CHECK_NOTHROW(sep("(ab(cabc)(ca(bc))ab)")); CHECK_THROWS_AS(sep("(zzz"), invalid_regex); CHECK_THROWS_AS(sep("(zz(z)"), invalid_regex); // ?, *, + CHECK_NOTHROW(sep("x?")); CHECK_NOTHROW(sep("(xy)?")); CHECK_NOTHROW(sep("x.?")); CHECK_THROWS_AS(sep("?zzz"), invalid_regex); CHECK_NOTHROW(sep("x*")); CHECK_NOTHROW(sep("(xy)*")); CHECK_NOTHROW(sep("x.*")); CHECK_THROWS_AS(sep("*zzz"), invalid_regex); CHECK_NOTHROW(sep("x+")); CHECK_NOTHROW(sep("(xy)+")); CHECK_NOTHROW(sep("x.+")); CHECK_THROWS_AS(sep("+zzz"), invalid_regex); // quantifiers CHECK_NOTHROW(sep("x{4}")); CHECK_NOTHROW(sep("(xy){4}")); CHECK_NOTHROW(sep("x{4,}")); CHECK_NOTHROW(sep("(xy){4,}")); CHECK_NOTHROW(sep("x{4,30}")); CHECK_NOTHROW(sep("(xy){4,30}")); CHECK_THROWS_AS(sep("x{,5}"), invalid_regex); CHECK_THROWS_AS(sep("x{,}"), invalid_regex); CHECK_THROWS_AS(sep("x{}"), invalid_regex); CHECK_THROWS_AS(sep("x{10,7}"), invalid_regex); CHECK_THROWS_AS(sep("x{blah}"), invalid_regex); CHECK_THROWS_AS(sep("x{1,7,8,9}"), invalid_regex); CHECK_THROWS_AS(sep("x{1,7"), invalid_regex); CHECK_THROWS_AS(sep("x{1,"), invalid_regex); CHECK_THROWS_AS(sep("x{1"), invalid_regex); // character classes CHECK_NOTHROW(sep("[a-k7-9%=]")); CHECK_NOTHROW(sep("[a\\-*\\][]")); CHECK_NOTHROW(sep("\\d\\D\\w\\W\\s\\S")); CHECK_NOTHROW(sep("[^a-z678]")); CHECK_NOTHROW(sep("[]")); // FIXME: should this be accepted? CHECK_NOTHROW(sep("[^]")); // FIXME: should this be accepted? CHECK_THROWS_AS(sep("[a^b]"), invalid_regex); CHECK_THROWS_AS(sep("[a-b"), invalid_regex); CHECK_THROWS_AS(sep("[a-b-c]"), invalid_regex); CHECK_THROWS_AS(sep("[z-b]"), invalid_regex); CHECK_THROWS_AS(sep("[-z]"), invalid_regex); CHECK_THROWS_AS(sep("[z-]"), invalid_regex); // unions CHECK_NOTHROW(sep("(aaaa|bbb)")); CHECK_NOTHROW(sep("((a(aa|)a|bbb)|zzzz)")); CHECK_NOTHROW(sep("(a|)")); CHECK_NOTHROW(sep("(a|\\|a)")); CHECK_THROWS_AS(sep("(a|b|c)"), invalid_regex); // FIXME: maybe this isn't invalid CHECK_THROWS_AS(sep("(a|c()"), invalid_regex); }
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <string> #include <sstream> #include "nicestream.hpp" using namespace nstr; typedef std::stringstream sstr; TEST_CASE("Regex parsing", "[regex]") { // simple literals CHECK_NOTHROW(sep("abcdz!!--<>\n\t^^^")); CHECK_NOTHROW(sep("abc\\.\\*\\?\\+\\[\\")); CHECK_NOTHROW(sep("(abcabc)(cabcab)")); CHECK_NOTHROW(sep("(ab(cabc)(ca(bc))ab)")); CHECK_THROWS_AS(sep("(zzz"), invalid_regex); CHECK_THROWS_AS(sep("(zz(z)"), invalid_regex); // ?, *, + CHECK_NOTHROW(sep("x?")); CHECK_NOTHROW(sep("(xy)?")); CHECK_NOTHROW(sep("x.?")); CHECK_THROWS_AS(sep("?zzz"), invalid_regex); CHECK_NOTHROW(sep("x*")); CHECK_NOTHROW(sep("(xy)*")); CHECK_NOTHROW(sep("x.*")); CHECK_THROWS_AS(sep("*zzz"), invalid_regex); CHECK_NOTHROW(sep("x+")); CHECK_NOTHROW(sep("(xy)+")); CHECK_NOTHROW(sep("x.+")); CHECK_THROWS_AS(sep("+zzz"), invalid_regex); // quantifiers CHECK_NOTHROW(sep("x{4}")); CHECK_NOTHROW(sep("(xy){4}")); CHECK_NOTHROW(sep("x{4,}")); CHECK_NOTHROW(sep("(xy){4,}")); CHECK_NOTHROW(sep("x{4,30}")); CHECK_NOTHROW(sep("(xy){4,30}")); CHECK_THROWS_AS(sep("x{,5}"), invalid_regex); CHECK_THROWS_AS(sep("x{,}"), invalid_regex); CHECK_THROWS_AS(sep("x{}"), invalid_regex); CHECK_THROWS_AS(sep("x{10,7}"), invalid_regex); CHECK_THROWS_AS(sep("x{blah}"), invalid_regex); CHECK_THROWS_AS(sep("x{1,7,8,9}"), invalid_regex); CHECK_THROWS_AS(sep("x{1,7"), invalid_regex); CHECK_THROWS_AS(sep("x{1,"), invalid_regex); CHECK_THROWS_AS(sep("x{1"), invalid_regex); // character classes CHECK_NOTHROW(sep("[a-k7-9%=]")); CHECK_NOTHROW(sep("[a\\-*\\][]")); CHECK_NOTHROW(sep("\\d\\D\\w\\W\\s\\S")); CHECK_NOTHROW(sep("[^a-z678]")); CHECK_NOTHROW(sep("[]")); // FIXME: should this be accepted? CHECK_NOTHROW(sep("[^]")); // FIXME: should this be accepted? CHECK_THROWS_AS(sep("[a^b]"), invalid_regex); CHECK_THROWS_AS(sep("[a-b"), invalid_regex); CHECK_THROWS_AS(sep("[a-b-c]"), invalid_regex); CHECK_THROWS_AS(sep("[z-b]"), invalid_regex); CHECK_THROWS_AS(sep("[-z]"), invalid_regex); CHECK_THROWS_AS(sep("[z-]"), invalid_regex); // unions CHECK_NOTHROW(sep("(aaaa|bbb)")); CHECK_NOTHROW(sep("((a(aa|)a|bbb)|zzzz)")); CHECK_NOTHROW(sep("(a|)")); CHECK_NOTHROW(sep("(a|\\|a)")); CHECK_THROWS_AS(sep("(a|b|c)"), invalid_regex); // FIXME: maybe this isn't invalid CHECK_THROWS_AS(sep("(a|c()"), invalid_regex); } TEST_CASE("nstr::skip", "[skip]") { { int i, j; sstr("10 20 30 40") >> i >> skip<int, int>() >> j; CHECK(i == 10); CHECK(j == 40); } { int i, j; sstr("10 20 30 40") >> i >> skip<int>() >> j; CHECK(i == 10); CHECK(j == 30); } { int i, j; sstr("10 20 30 40") >> i >> skip<>() >> j; CHECK(i == 10); CHECK(j == 20); } { int i; std::string s; sstr("10 20 abc def") >> i >> skip<int, std::string>() >> s; CHECK(i == 10); CHECK(s == "def"); } }
Add tests for skip.
Add tests for skip.
C++
mit
lipk/nicestream
266365bcb911b6a4b9def3c20641e3c35b88696e
c_src/DbOpenTask.cpp
c_src/DbOpenTask.cpp
/** * This file is a part of Kyte released under the MIT licence. * See the LICENCE file for more information */ #include "DbOpenTask.h" #include <stdio.h> #include <string.h> namespace kyte { using kyotocabinet::PolyDB; DbOpenTask::DbOpenTask() { _DbFile[0] = '\0'; } DbOpenTask::~DbOpenTask() {} void DbOpenTask::Run() { PolyDB* db = new PolyDB; int dbPos = place_to_the_pool(db, _OpenDatabases, MAX_OPEN_DBS); if ( dbPos == -1 ) { delete db; Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "error"), enif_make_atom(Env(), "max_db_count_reached") ) ); } else { if ( db->open(_DbFile, PolyDB::OCREATE | PolyDB::OWRITER) ) { Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "ok"), enif_make_int(Env(), dbPos) ) ); } else { _OpenDatabases[dbPos] = NULL; Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "error"), enif_make_string(Env(), db->error().name(), ERL_NIF_LATIN1) ) ); delete db; } } } void DbOpenTask::SetDbFile(const char* file) { // strlcpy(_DbFile, file, MAX_PATH_LEN); for (int i = 0; i < MAX_PATH_LEN; i++) { _DbFile[i] = file[i]; if ( file[i] == '\0' ) break; } } }
/** * This file is a part of Kyte released under the MIT licence. * See the LICENCE file for more information */ #include "DbOpenTask.h" #include <stdio.h> #include <string.h> namespace kyte { using kyotocabinet::PolyDB; DbOpenTask::DbOpenTask() { _DbFile[0] = '\0'; } DbOpenTask::~DbOpenTask() {} void DbOpenTask::Run() { PolyDB* db = new PolyDB; int dbPos = place_to_the_pool(db, _OpenDatabases, MAX_OPEN_DBS); if ( dbPos == -1 ) { delete db; Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "error"), enif_make_atom(Env(), "max_db_count_reached") ) ); } else { if ( db->open(_DbFile, PolyDB::OCREATE | PolyDB::OWRITER | PolyDB::OAUTOTRAN) ) { Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "ok"), enif_make_int(Env(), dbPos) ) ); } else { _OpenDatabases[dbPos] = NULL; Reply( enif_make_tuple2(Env(), enif_make_atom(Env(), "error"), enif_make_string(Env(), db->error().name(), ERL_NIF_LATIN1) ) ); delete db; } } } void DbOpenTask::SetDbFile(const char* file) { // strlcpy(_DbFile, file, MAX_PATH_LEN); for (int i = 0; i < MAX_PATH_LEN; i++) { _DbFile[i] = file[i]; if ( file[i] == '\0' ) break; } } }
Add auto transaction option. It doesn't cause performance degradation and fixes long startup when the db wasn't close properly
Add auto transaction option. It doesn't cause performance degradation and fixes long startup when the db wasn't close properly
C++
mit
RGafiyatullin/kyte,RGafiyatullin/kyte,RGafiyatullin/kyte
c8d422e889e7f4cb6cec4cf7ebc9ea12d0ceb309
ksp_plugin_test/pile_up_test.cpp
ksp_plugin_test/pile_up_test.cpp
#include "ksp_plugin/pile_up.hpp" #include "ksp_plugin/part.hpp" #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/componentwise.hpp" namespace principia { namespace ksp_plugin { namespace internal_pile_up { using geometry::Displacement; using geometry::R3Element; using geometry::Velocity; using physics::DegreesOfFreedom; using quantities::Length; using quantities::Speed; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Newton; using quantities::si::Second; using testing_utilities::AlmostEquals; using testing_utilities::Componentwise; using ::testing::Return; using ::testing::ReturnRef; class PileUpTest : public testing::Test { protected: PileUpTest() : p1_(part_id1_, mass1_), p2_(part_id2_, mass2_) { p1_.increment_intrinsic_force( Vector<Force, Barycentric>({1 * Newton, 2 * Newton, 3 * Newton})); p2_.increment_intrinsic_force( Vector<Force, Barycentric>({11 * Newton, 21 * Newton, 31 * Newton})); p1_.set_degrees_of_freedom(p1_dof_); p2_.set_degrees_of_freedom(p2_dof_); } using RigidPileUp = PileUp::RigidPileUp; PartId const part_id1_ = 111; PartId const part_id2_ = 222; Mass const mass1_ = 1 * Kilogram; Mass const mass2_ = 2 * Kilogram; DegreesOfFreedom<Bubble> const p1_dof_ = DegreesOfFreedom<Bubble>( Bubble::origin + Displacement<Bubble>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<Bubble>( {10 * Metre / Second, 20 * Metre / Second, 30 * Metre / Second})); DegreesOfFreedom<Bubble> const p2_dof_ = DegreesOfFreedom<Bubble>( Bubble::origin + Displacement<Bubble>({6 * Metre, 5 * Metre, 4 * Metre}), Velocity<Bubble>( {60 * Metre / Second, 50 * Metre / Second, 40 * Metre / Second})); DegreesOfFreedom<Barycentric> const bubble_barycentre = DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>({7 * Metre, 8 * Metre, 9 * Metre}), Velocity<Barycentric>( {70 * Metre / Second, 80 * Metre / Second, 90 * Metre / Second})); Part p1_; Part p2_; }; TEST_F(PileUpTest, Lifecycle) { PileUp pile_up({&p1_, &p2_}, bubble_barycentre, astronomy::J2000); EXPECT_EQ(3 * Kilogram, pile_up.mass_); EXPECT_THAT(pile_up.intrinsic_force_, AlmostEquals(Vector<Force, Barycentric>( {12 * Newton, 23 * Newton, 34 * Newton}), 0)); EXPECT_THAT( pile_up.psychohistory_.last().degrees_of_freedom(), Componentwise(AlmostEquals(Barycentric::origin + Displacement<Barycentric>( {34.0 / 3.0 * Metre, 12.0 * Metre, 38.0 / 3.0 * Metre}), 0), AlmostEquals(Velocity<Barycentric>( {34.0 / 3.0 * Metre / Second, 12.0 * Metre / Second, 38.0 / 3.0 * Metre / Second}), 0))); EXPECT_THAT( pile_up.actual_part_degrees_of_freedom_.at(&p1_), Componentwise(AlmostEquals(RigidPileUp::origin + Displacement<RigidPileUp>( {-10.0 / 3.0 * Metre, -2.0 * Metre, -2.0 / 3.0 * Metre}), 0), AlmostEquals(Velocity<RigidPileUp>( {-100.0 / 3.0 * Metre / Second, -20.0 * Metre / Second, -20.0 / 3.0 * Metre / Second}), 0))); EXPECT_THAT( pile_up.actual_part_degrees_of_freedom_.at(&p2_), Componentwise(AlmostEquals(RigidPileUp::origin + Displacement<RigidPileUp>( {5.0 / 3.0 * Metre, 1.0 * Metre, 1.0 / 3.0 * Metre}), 0), AlmostEquals(Velocity<RigidPileUp>( {-50.0 / 3.0 * Metre / Second, 10.0 * Metre / Second, 10.0 / 3.0 * Metre / Second}), 0))); //pile_up.SetPartApparentDegreesOfFreedom( // &p1_, // DegreesOfFreedom<ApparentBubble>( // ApparentBubble::origin + // Displacement<ApparentBubble>({1 * Metre, 2 * Metre, 3 * Metre}), // Velocity<ApparentBubble>({10 * Metre / Second, // 20 * Metre / Second, // 30 * Metre / Second}))); //pile_up.SetPartApparentDegreesOfFreedom( // &p2_, // DegreesOfFreedom<ApparentBubble>( // ApparentBubble::origin + // Displacement<ApparentBubble>({6 * Metre, 5 * Metre, 4 * Metre}), // Velocity<ApparentBubble>({60 * Metre / Second, // 50 * Metre / Second, // 40 * Metre / Second}))); //pile_up.DeformPileUpIfNeeded(); } } // namespace internal_pile_up } // namespace ksp_plugin } // namespace principia
#include "ksp_plugin/pile_up.hpp" #include "ksp_plugin/part.hpp" #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/componentwise.hpp" namespace principia { namespace ksp_plugin { namespace internal_pile_up { using geometry::Displacement; using geometry::R3Element; using geometry::Velocity; using physics::DegreesOfFreedom; using quantities::Length; using quantities::Speed; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Newton; using quantities::si::Second; using testing_utilities::AlmostEquals; using testing_utilities::Componentwise; using ::testing::Return; using ::testing::ReturnRef; class PileUpTest : public testing::Test { protected: PileUpTest() : p1_(part_id1_, mass1_), p2_(part_id2_, mass2_) { p1_.increment_intrinsic_force( Vector<Force, Barycentric>({1 * Newton, 2 * Newton, 3 * Newton})); p2_.increment_intrinsic_force( Vector<Force, Barycentric>({11 * Newton, 21 * Newton, 31 * Newton})); p1_.set_degrees_of_freedom(p1_dof_); p2_.set_degrees_of_freedom(p2_dof_); } using RigidPileUp = PileUp::RigidPileUp; PartId const part_id1_ = 111; PartId const part_id2_ = 222; Mass const mass1_ = 1 * Kilogram; Mass const mass2_ = 2 * Kilogram; DegreesOfFreedom<Bubble> const p1_dof_ = DegreesOfFreedom<Bubble>( Bubble::origin + Displacement<Bubble>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<Bubble>( {10 * Metre / Second, 20 * Metre / Second, 30 * Metre / Second})); DegreesOfFreedom<Bubble> const p2_dof_ = DegreesOfFreedom<Bubble>( Bubble::origin + Displacement<Bubble>({6 * Metre, 5 * Metre, 4 * Metre}), Velocity<Bubble>( {60 * Metre / Second, 50 * Metre / Second, 40 * Metre / Second})); DegreesOfFreedom<Barycentric> const bubble_barycentre = DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>({7 * Metre, 8 * Metre, 9 * Metre}), Velocity<Barycentric>( {70 * Metre / Second, 80 * Metre / Second, 90 * Metre / Second})); Part p1_; Part p2_; }; TEST_F(PileUpTest, Lifecycle) { PileUp pile_up({&p1_, &p2_}, bubble_barycentre, astronomy::J2000); EXPECT_EQ(3 * Kilogram, pile_up.mass_); EXPECT_THAT(pile_up.intrinsic_force_, AlmostEquals(Vector<Force, Barycentric>( {12 * Newton, 23 * Newton, 34 * Newton}), 0)); EXPECT_THAT( pile_up.psychohistory_.last().degrees_of_freedom(), Componentwise(AlmostEquals(Barycentric::origin + Displacement<Barycentric>( {34.0 / 3.0 * Metre, 12.0 * Metre, 38.0 / 3.0 * Metre}), 1), AlmostEquals(Velocity<Barycentric>( {340.0 / 3.0 * Metre / Second, 120.0 * Metre / Second, 380.0 / 3.0 * Metre / Second}), 1))); EXPECT_THAT( pile_up.actual_part_degrees_of_freedom_.at(&p1_), Componentwise(AlmostEquals(RigidPileUp::origin + Displacement<RigidPileUp>( {-10.0 / 3.0 * Metre, -2.0 * Metre, -2.0 / 3.0 * Metre}), 1), AlmostEquals(Velocity<RigidPileUp>( {-100.0 / 3.0 * Metre / Second, -20.0 * Metre / Second, -20.0 / 3.0 * Metre / Second}), 3))); EXPECT_THAT( pile_up.actual_part_degrees_of_freedom_.at(&p2_), Componentwise(AlmostEquals(RigidPileUp::origin + Displacement<RigidPileUp>( {5.0 / 3.0 * Metre, 1.0 * Metre, 1.0 / 3.0 * Metre}), 3), AlmostEquals(Velocity<RigidPileUp>( {50.0 / 3.0 * Metre / Second, 10.0 * Metre / Second, 10.0 / 3.0 * Metre / Second}), 5))); //pile_up.SetPartApparentDegreesOfFreedom( // &p1_, // DegreesOfFreedom<ApparentBubble>( // ApparentBubble::origin + // Displacement<ApparentBubble>({1 * Metre, 2 * Metre, 3 * Metre}), // Velocity<ApparentBubble>({10 * Metre / Second, // 20 * Metre / Second, // 30 * Metre / Second}))); //pile_up.SetPartApparentDegreesOfFreedom( // &p2_, // DegreesOfFreedom<ApparentBubble>( // ApparentBubble::origin + // Displacement<ApparentBubble>({6 * Metre, 5 * Metre, 4 * Metre}), // Velocity<ApparentBubble>({60 * Metre / Second, // 50 * Metre / Second, // 40 * Metre / Second}))); //pile_up.DeformPileUpIfNeeded(); } } // namespace internal_pile_up } // namespace ksp_plugin } // namespace principia
Test tolerances.
Test tolerances.
C++
mit
pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia
263e7c68f4ed1901a91b96a87ac45a1fe002757c
src/console.cpp
src/console.cpp
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <sstream> #include "console.hpp" #include "assert.hpp" std::string budget::format_code(int attr, int fg, int bg){ std::stringstream stream; stream << "" << '\033' << "[" << attr << ";" << (fg + 30) << (bg + 40) << "m"; return stream.str(); } std::string budget::format_money(const budget::money& m){ if(m.positive()){ return "::green" + budget::to_string(m); } else if(m.negative()){ return "::red" + budget::to_string(m); } else if(m.zero()){ return budget::to_string(m); } else { return budget::to_string(m); } } std::string budget::format_money_reverse(const budget::money& m){ if(m.positive()){ return "::red" + budget::to_string(m); } else if(m.negative()){ return "::green" + budget::to_string(m); } else if(m.zero()){ return budget::to_string(m); } else { return budget::to_string(m); } } std::size_t budget::rsize(const std::string& value){ auto v = value; if(v.substr(0, 5) == "::red"){ v = v.substr(5); } else if(v.substr(0, 7) == "::green"){ v = v.substr(7); } static wchar_t buf[1025]; return mbstowcs(buf, v.c_str(), 1024); } bool budget::option(const std::string& option, std::vector<std::string>& args){ auto it = args.begin(); auto end = args.end(); bool found = false; while(it != end){ if(*it == option){ it = args.erase(it); end = args.end(); found = true; } else { ++it; } } return found; } std::string budget::option_value(const std::string& option, std::vector<std::string>& args, const std::string& default_value){ auto it = args.begin(); auto end = args.end(); auto value = default_value; while(it != end){ if (it->find(option + "=") == 0){ value = std::string(it->begin() + option.size() + 1, it->end()); it = args.erase(it); end = args.end(); } else { ++it; } } return value; } std::string budget::format(const std::string& v){ if(v.substr(0, 5) == "::red"){ auto value = v.substr(5); std::cout << "\033[0;31m"; return value; } else if(v.substr(0, 7) == "::green"){ auto value = v.substr(7); std::cout << "\033[0;32m"; return value; } return v; } void budget::display_table(std::vector<std::string> columns, std::vector<std::vector<std::string>> contents, std::size_t groups){ budget_assert(groups > 0, "There must be at least 1 group"); for(auto& row : contents){ for(auto& cell : row){ trim(cell); } } std::vector<std::size_t> widths; std::vector<std::size_t> header_widths; if(!contents.size()){ for(auto& column : columns){ widths.push_back(rsize(column)); } } else { auto& first = contents[0]; widths.assign(first.size(), 0); for(auto& row : contents){ for(std::size_t i = 0; i < row.size(); ++i){ widths[i] = std::max(widths[i], rsize(row[i]) + 1); } } } budget_assert(widths.size() == groups * columns.size(), "Widths incorrectly computed"); for(std::size_t i = 0; i < columns.size(); ++i){ auto& column = columns[i]; std::size_t width = 0; for(std::size_t j = i * groups; j < (i + 1) * groups; ++j){ width += widths[j]; } width = std::max(width, rsize(column)); header_widths.push_back(width + (i < columns.size() - 1 && rsize(column) >= width ? 1 : 0)); //The last space is not underlined --width; std::cout << format_code(4, 0, 7) << column << (width > rsize(column) ? std::string(width - rsize(column), ' ') : "") << format_code(0, 0, 7); //The very last column has no trailing space if(i < columns.size() - 1){ std::cout << " "; } } std::cout << std::endl; for(std::size_t i = 0; i < contents.size(); ++i){ auto& row = contents[i]; std::cout << format_code(0, 0, 7); for(std::size_t j = 0; j < row.size(); j += groups){ std::size_t acc_width = 0; //First columns of the group for(std::size_t k = 0; k < groups - 1; ++k){ auto column = j + k; std::string value = format(row[column]); acc_width += widths[column]; std::cout << value; //The content of the column can change the style, it is //important to reapply it std::cout << format_code(0, 0, 7); std::cout << std::string(widths[column] - rsize(value), ' '); } //The last column of the group auto last_column = j + (groups - 1); auto width = widths[last_column]; acc_width += width; //Pad with spaces to fit the header column width if(header_widths[j / groups] > acc_width){ width += header_widths[j / groups] - acc_width; } else if(last_column == row.size() - 1){ --width; } auto value = format(row[last_column]); std::cout << value; //The content of the column can change the style, it is //important to reapply it std::cout << format_code(0, 0, 7); std::cout << std::string(width - rsize(row[last_column]), ' '); } std::cout << std::endl; } }
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <sstream> #include "console.hpp" #include "assert.hpp" std::string budget::format_code(int attr, int fg, int bg){ std::stringstream stream; stream << "" << '\033' << "[" << attr << ";" << (fg + 30) << (bg + 40) << "m"; return stream.str(); } std::string budget::format_money(const budget::money& m){ if(m.positive()){ return "::green" + budget::to_string(m); } else if(m.negative()){ return "::red" + budget::to_string(m); } else if(m.zero()){ return budget::to_string(m); } else { return budget::to_string(m); } } std::string budget::format_money_reverse(const budget::money& m){ if(m.positive()){ return "::red" + budget::to_string(m); } else if(m.negative()){ return "::green" + budget::to_string(m); } else if(m.zero()){ return budget::to_string(m); } else { return budget::to_string(m); } } std::size_t budget::rsize(const std::string& value){ auto v = value; if(v.substr(0, 5) == "::red"){ v = v.substr(5); } else if(v.substr(0, 7) == "::green"){ v = v.substr(7); } static wchar_t buf[1025]; return mbstowcs(buf, v.c_str(), 1024); } bool budget::option(const std::string& option, std::vector<std::string>& args){ auto before = args.size(); args.erase(std::remove(args.begin(), args.end(), option), args.end()); return before != args.size(); } std::string budget::option_value(const std::string& option, std::vector<std::string>& args, const std::string& default_value){ auto it = args.begin(); auto end = args.end(); auto value = default_value; while(it != end){ if (it->find(option + "=") == 0){ value = std::string(it->begin() + option.size() + 1, it->end()); it = args.erase(it); end = args.end(); } else { ++it; } } return value; } std::string budget::format(const std::string& v){ if(v.substr(0, 5) == "::red"){ auto value = v.substr(5); std::cout << "\033[0;31m"; return value; } else if(v.substr(0, 7) == "::green"){ auto value = v.substr(7); std::cout << "\033[0;32m"; return value; } return v; } void budget::display_table(std::vector<std::string> columns, std::vector<std::vector<std::string>> contents, std::size_t groups){ budget_assert(groups > 0, "There must be at least 1 group"); for(auto& row : contents){ for(auto& cell : row){ trim(cell); } } std::vector<std::size_t> widths; std::vector<std::size_t> header_widths; if(!contents.size()){ for(auto& column : columns){ widths.push_back(rsize(column)); } } else { auto& first = contents[0]; widths.assign(first.size(), 0); for(auto& row : contents){ for(std::size_t i = 0; i < row.size(); ++i){ widths[i] = std::max(widths[i], rsize(row[i]) + 1); } } } budget_assert(widths.size() == groups * columns.size(), "Widths incorrectly computed"); for(std::size_t i = 0; i < columns.size(); ++i){ auto& column = columns[i]; std::size_t width = 0; for(std::size_t j = i * groups; j < (i + 1) * groups; ++j){ width += widths[j]; } width = std::max(width, rsize(column)); header_widths.push_back(width + (i < columns.size() - 1 && rsize(column) >= width ? 1 : 0)); //The last space is not underlined --width; std::cout << format_code(4, 0, 7) << column << (width > rsize(column) ? std::string(width - rsize(column), ' ') : "") << format_code(0, 0, 7); //The very last column has no trailing space if(i < columns.size() - 1){ std::cout << " "; } } std::cout << std::endl; for(std::size_t i = 0; i < contents.size(); ++i){ auto& row = contents[i]; std::cout << format_code(0, 0, 7); for(std::size_t j = 0; j < row.size(); j += groups){ std::size_t acc_width = 0; //First columns of the group for(std::size_t k = 0; k < groups - 1; ++k){ auto column = j + k; std::string value = format(row[column]); acc_width += widths[column]; std::cout << value; //The content of the column can change the style, it is //important to reapply it std::cout << format_code(0, 0, 7); std::cout << std::string(widths[column] - rsize(value), ' '); } //The last column of the group auto last_column = j + (groups - 1); auto width = widths[last_column]; acc_width += width; //Pad with spaces to fit the header column width if(header_widths[j / groups] > acc_width){ width += header_widths[j / groups] - acc_width; } else if(last_column == row.size() - 1){ --width; } auto value = format(row[last_column]); std::cout << value; //The content of the column can change the style, it is //important to reapply it std::cout << format_code(0, 0, 7); std::cout << std::string(width - rsize(row[last_column]), ' '); } std::cout << std::endl; } }
Use STL
Use STL
C++
mit
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
6a1755ae00e11289ebf5f8a1bd4573e59c48273c
src/test/rpc_wallet_tests.cpp
src/test/rpc_wallet_tests.cpp
// Copyright (c) 2013-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "base58.h" #include "main.h" #include "wallet/wallet.h" #include "test/test_bitcoin.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace json_spirit; extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL); extern Value CallRPC(string args); extern CWallet* pwalletMain; BOOST_FIXTURE_TEST_SUITE(rpc_wallet_tests, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_addmultisig) { LOCK(pwalletMain->cs_wallet); rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor; // old, 65-byte-long: const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8"; // new, compressed: const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4"; Value v; CBitcoinAddress address; BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet) { // Test RPC calls for various wallet statistics Value r; LOCK2(cs_main, pwalletMain->cs_wallet); CPubKey demoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); Value retValue; string strAccount = "walletDemoAccount"; string strPurpose = "receive"; BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; account.vchPubKey = demoPubkey; pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose); walletdb.WriteAccount(strAccount, account); }); CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); /********************************* * setaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error); BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error); /********************************* * getbalance *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getbalance")); BOOST_CHECK_NO_THROW(CallRPC("getbalance " + demoAddress.ToString())); /********************************* * listunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listunspent")); BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []")); BOOST_CHECK(r.get_array().empty()); /********************************* * listreceivedbyaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); /********************************* * listreceivedbyaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); /********************************* * listsinceblock *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listsinceblock")); /********************************* * listtransactions *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listtransactions")); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString())); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20")); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20 0")); BOOST_CHECK_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " not_int"), runtime_error); /********************************* * listlockunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listlockunspent")); /********************************* * listaccounts *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listaccounts")); /********************************* * listaddressgroupings *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listaddressgroupings")); /********************************* * getrawchangeaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress")); /********************************* * getnewaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getnewaddress")); BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount")); /********************************* * getaccountaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\"")); BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount)); BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get()); /********************************* * getaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); /********************************* * signmessage + verifymessage *********************************/ BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); /* Should throw error because this address is not loaded in the wallet */ BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error); /* missing arguments */ BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error); BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error); /* Illegal address */ BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error); /* wrong address */ /* FIXME: fatal error BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false); */ /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2013-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "base58.h" #include "main.h" #include "wallet/wallet.h" #include "test/test_bitcoin.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace json_spirit; extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL); extern Value CallRPC(string args); extern CWallet* pwalletMain; BOOST_FIXTURE_TEST_SUITE(rpc_wallet_tests, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_addmultisig) { LOCK(pwalletMain->cs_wallet); rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor; // old, 65-byte-long: const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8"; // new, compressed: const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4"; Value v; CBitcoinAddress address; BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet) { // Test RPC calls for various wallet statistics Value r; LOCK2(cs_main, pwalletMain->cs_wallet); CPubKey demoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); Value retValue; string strAccount = "walletDemoAccount"; string strPurpose = "receive"; BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; account.vchPubKey = demoPubkey; pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose); walletdb.WriteAccount(strAccount, account); }); CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); /********************************* * setaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error); BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error); /********************************* * getbalance *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getbalance")); BOOST_CHECK_NO_THROW(CallRPC("getbalance " + demoAddress.ToString())); /********************************* * listunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listunspent")); BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []")); BOOST_CHECK(r.get_array().empty()); /********************************* * listreceivedbyaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); /********************************* * listreceivedbyaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); /********************************* * listsinceblock *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listsinceblock")); /********************************* * listtransactions *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listtransactions")); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString())); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20")); BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20 0")); BOOST_CHECK_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " not_int"), runtime_error); /********************************* * listlockunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listlockunspent")); /********************************* * listaccounts *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listaccounts")); /********************************* * listaddressgroupings *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listaddressgroupings")); /********************************* * getrawchangeaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress")); /********************************* * getnewaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getnewaddress")); BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount")); /********************************* * getaccountaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\"")); BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount)); BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get()); /********************************* * getaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); /********************************* * signmessage + verifymessage *********************************/ BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); /* Should throw error because this address is not loaded in the wallet */ BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error); /* missing arguments */ BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error); BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error); /* Illegal address */ BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error); /* wrong address */ BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage"), runtime_error); /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); } BOOST_AUTO_TEST_SUITE_END()
Fix fatal error in test.
Fix fatal error in test.
C++
mit
vcoin-project/vcoincore,TrainMAnB/vcoincore,TrainMAnB/vcoincore,vcoin-project/vcoincore,TrainMAnB/vcoincore,vcoin-project/vcoincore,TrainMAnB/vcoincore,TrainMAnB/vcoincore,TrainMAnB/vcoincore,vcoin-project/vcoincore,vcoin-project/vcoincore,vcoin-project/vcoincore
36f69815336a0bd5424e88a5b29e488631791ae4
src/video_annotator/player.cc
src/video_annotator/player.cc
#include "fish_annotator/video_annotator/player.h" #include <QTime> #include <QCoreApplication> #include <QEventLoop> #include <QMutexLocker> namespace fish_annotator { namespace video_annotator { Player::Player() : QObject() , video_path_() , frame_rate_(0.0) , stopped_(true) , image_() , current_speed_(0.0) , codec_context_(nullptr) , format_context_(avformat_alloc_context()) , packet_() , stream_index_(-1) , frame_(av_frame_alloc()) , frame_rgb_(av_frame_alloc()) , sws_context_(nullptr) , delay_(0.0) , frame_index_(0) , seek_map_() , mutex_() , condition_() { av_register_all(); av_init_packet(&packet_); } Player::~Player() { QMutexLocker locker(&mutex_); if(codec_context_ != nullptr) { avcodec_close(codec_context_); codec_context_ = nullptr; } if(format_context_ != nullptr) { avformat_close_input(&format_context_); format_context_ = nullptr; } if(frame_rgb_ != nullptr) { if(frame_rgb_->data[0] != nullptr) { av_freep(&frame_rgb_->data[0]); } av_frame_free(&frame_rgb_); frame_rgb_ = nullptr; } if(frame_ != nullptr) { av_frame_free(&frame_); frame_ = nullptr; } stopped_ = true; condition_.wakeOne(); } void Player::loadVideo(QString filename) { video_path_ = filename; if(format_context_ != nullptr) { avformat_close_input(&format_context_); format_context_ = nullptr; } int status = avformat_open_input( &format_context_, filename.toStdString().c_str(), nullptr, nullptr); if(status != 0) { std::string msg( std::string("Failed to load media at ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avformat_find_stream_info(format_context_, nullptr); if(status < 0) { std::string msg( std::string("Couldn't find stream information for video ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } stream_index_ = -1; status = av_find_best_stream( format_context_, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0); if(status < 0) { std::string msg( std::string("File does not contain a video stream ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } stream_index_ = status; AVStream *stream = format_context_->streams[stream_index_]; AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id); if(codec == nullptr) { std::string msg( std::string("Unsupported codec in file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } if(codec_context_ != nullptr) { avcodec_free_context(&codec_context_); } codec_context_ = avcodec_alloc_context3(codec); if(codec_context_ == nullptr) { std::string msg( std::string("Failed to allocate codec context for file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avcodec_parameters_to_context(codec_context_, stream->codecpar); if(status < 0) { std::string msg( std::string("Failed to copy codec parameters to codec context for ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avcodec_open2(codec_context_, codec, nullptr); if(status < 0) { std::string msg( std::string("Could not open codec for file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } sws_context_ = sws_getContext( codec_context_->width, codec_context_->height, codec_context_->pix_fmt, codec_context_->width, codec_context_->height, AV_PIX_FMT_RGB24, SWS_BICUBIC, nullptr, nullptr, nullptr); seek_map_.clear(); qint64 frame_index = 0; while(true) { status = av_read_frame(format_context_, &packet_); if(status < 0) { break; } if(packet_.stream_index == stream_index_) { seek_map_.left.insert({frame_index, packet_.dts}); ++frame_index; } } av_seek_frame( format_context_, stream_index_, seek_map_.right.begin()->first, AVSEEK_FLAG_BACKWARD); frame_rate_ = static_cast<double>(stream->avg_frame_rate.num) / static_cast<double>(stream->avg_frame_rate.den); current_speed_ = frame_rate_; image_ = QImage( codec_context_->width, codec_context_->height, QImage::Format_RGB32); if(frame_rgb_ != nullptr) { if(frame_rgb_->data[0] != nullptr) { av_freep(&frame_rgb_->data[0]); } } av_image_alloc( frame_rgb_->data, frame_rgb_->linesize, codec_context_->width, codec_context_->height, AV_PIX_FMT_RGB24, 1); emit mediaLoaded(filename, frame_rate_); emit playbackRateChanged(current_speed_); emit durationChanged(seek_map_.size()); emit resolutionChanged(codec_context_->width, codec_context_->height); } void Player::play() { if(stopped_ == true) { stopped_ = false; } emit stateChanged(stopped_); while(stopped_ == false) { QTime t; t.start(); getOneFrame(); emit processedImage(image_, frame_index_); double usec = 1000.0 * t.restart(); processWait(std::round(delay_ - usec)); } } void Player::stop() { stopped_ = true; emit stateChanged(stopped_); } void Player::getOneFrame() { QMutexLocker locker(&mutex_); while(true) { int status = av_read_frame(format_context_, &packet_); if(status < 0) { break; } if(packet_.stream_index == stream_index_) { auto it = seek_map_.right.find(packet_.dts); if(it == seek_map_.right.end()) { emit error("Could not find decompression timestamp!"); return; } else { frame_index_ = it->second; } status = avcodec_send_packet(codec_context_, &packet_); if(status < 0) { emit error("Error while sending packet to the decoder!"); return; } while(status >= 0) { status = avcodec_receive_frame(codec_context_, frame_); if(status == AVERROR_EOF) { stopped_ = true; break; } else if(status == AVERROR(EAGAIN)) { break; } else if(status < 0) { emit error("Error while receiving a frame from the decoder!"); return; } else { sws_scale( sws_context_, frame_->data, frame_->linesize, 0, codec_context_->height, frame_rgb_->data, frame_rgb_->linesize); uint8_t *src = (uint8_t*)(frame_rgb_->data[0]); for(int y = 0; y < codec_context_->height; ++y) { QRgb *scan_line = (QRgb*)image_.scanLine(y); for(int x = 0; x < codec_context_->width; ++x) { scan_line[x] = qRgb(src[3*x], src[3*x+1], src[3*x+2]); } src += frame_rgb_->linesize[0]; } return; } } } } } void Player::speedUp() { delay_ /= 2.0; if(delay_ < 1.0) delay_ = 1.0; current_speed_ *= 2.0; emit playbackRateChanged(current_speed_); } void Player::slowDown() { delay_ *= 2.0; current_speed_ /= 2.0; emit playbackRateChanged(current_speed_); } void Player::nextFrame() { getOneFrame(); emit processedImage(image_, frame_index_); } void Player::prevFrame() { setCurrentFrame(frame_index_ - 1); emit processedImage(image_, frame_index_); } void Player::setCurrentFrame(qint64 frame_num) { qint64 bounded = frame_num < 0 ? 0 : frame_num; const qint64 max_frame = seek_map_.left.rbegin()->first; bounded = bounded > max_frame ? max_frame : bounded; qint64 seek_to = bounded - 3; seek_to = seek_to < 0 ? 0 : seek_to; auto it = seek_map_.left.find(seek_to); if(it != seek_map_.left.end()) { int status = av_seek_frame( format_context_, stream_index_, it->second, AVSEEK_FLAG_BACKWARD); if(status < 0) { emit error("Error seeking to frame!"); return; } avcodec_flush_buffers(codec_context_); while(true) { getOneFrame(); if(frame_index_ >= bounded) { break; } } } } void Player::setFrame(qint64 frame) { setCurrentFrame(frame); emit processedImage(image_, frame_index_); } void Player::processWait(qint64 usec) { QTime die_time = QTime::currentTime().addMSecs(usec / 1000); QCoreApplication::processEvents(QEventLoop::AllEvents, 1); while(QTime::currentTime() < die_time) { QCoreApplication::processEvents(QEventLoop::AllEvents, 1); } } #include "../../include/fish_annotator/video_annotator/moc_player.cpp" }} // namespace fish_annotator::gui
#include "fish_annotator/video_annotator/player.h" #include <QTime> #include <QCoreApplication> #include <QEventLoop> #include <QMutexLocker> namespace fish_annotator { namespace video_annotator { Player::Player() : QObject() , video_path_() , frame_rate_(0.0) , stopped_(true) , image_() , current_speed_(0.0) , codec_context_(nullptr) , format_context_(avformat_alloc_context()) , packet_() , stream_index_(-1) , frame_(av_frame_alloc()) , frame_rgb_(av_frame_alloc()) , sws_context_(nullptr) , delay_(0.0) , frame_index_(0) , seek_map_() , mutex_() , condition_() { av_register_all(); av_init_packet(&packet_); } Player::~Player() { QMutexLocker locker(&mutex_); if(codec_context_ != nullptr) { avcodec_close(codec_context_); codec_context_ = nullptr; } if(format_context_ != nullptr) { avformat_close_input(&format_context_); format_context_ = nullptr; } if(frame_rgb_ != nullptr) { if(frame_rgb_->data[0] != nullptr) { av_freep(&frame_rgb_->data[0]); } av_frame_free(&frame_rgb_); frame_rgb_ = nullptr; } if(frame_ != nullptr) { av_frame_free(&frame_); frame_ = nullptr; } stopped_ = true; condition_.wakeOne(); } void Player::loadVideo(QString filename) { video_path_ = filename; if(format_context_ != nullptr) { avformat_close_input(&format_context_); format_context_ = nullptr; } int status = avformat_open_input( &format_context_, filename.toStdString().c_str(), nullptr, nullptr); if(status != 0) { std::string msg( std::string("Failed to load media at ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avformat_find_stream_info(format_context_, nullptr); if(status < 0) { std::string msg( std::string("Couldn't find stream information for video ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } stream_index_ = -1; status = av_find_best_stream( format_context_, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0); if(status < 0) { std::string msg( std::string("File does not contain a video stream ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } stream_index_ = status; AVStream *stream = format_context_->streams[stream_index_]; AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id); if(codec == nullptr) { std::string msg( std::string("Unsupported codec in file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } if(codec_context_ != nullptr) { avcodec_free_context(&codec_context_); } codec_context_ = avcodec_alloc_context3(codec); if(codec_context_ == nullptr) { std::string msg( std::string("Failed to allocate codec context for file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avcodec_parameters_to_context(codec_context_, stream->codecpar); if(status < 0) { std::string msg( std::string("Failed to copy codec parameters to codec context for ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } status = avcodec_open2(codec_context_, codec, nullptr); if(status < 0) { std::string msg( std::string("Could not open codec for file ") + filename.toStdString() + std::string("!")); emit error(QString(msg.c_str())); return; } sws_context_ = sws_getContext( codec_context_->width, codec_context_->height, codec_context_->pix_fmt, codec_context_->width, codec_context_->height, AV_PIX_FMT_RGB24, SWS_BICUBIC, nullptr, nullptr, nullptr); seek_map_.clear(); qint64 frame_index = 0; while(true) { status = av_read_frame(format_context_, &packet_); if(status < 0) { break; } if(packet_.stream_index == stream_index_) { seek_map_.left.insert({frame_index, packet_.dts}); ++frame_index; } } av_seek_frame( format_context_, stream_index_, seek_map_.right.begin()->first, AVSEEK_FLAG_BACKWARD); frame_rate_ = static_cast<double>(stream->avg_frame_rate.num) / static_cast<double>(stream->avg_frame_rate.den); current_speed_ = frame_rate_; delay_ = 1000000.0 / frame_rate_; image_ = QImage( codec_context_->width, codec_context_->height, QImage::Format_RGB32); if(frame_rgb_ != nullptr) { if(frame_rgb_->data[0] != nullptr) { av_freep(&frame_rgb_->data[0]); } } av_image_alloc( frame_rgb_->data, frame_rgb_->linesize, codec_context_->width, codec_context_->height, AV_PIX_FMT_RGB24, 1); emit mediaLoaded(filename, frame_rate_); emit playbackRateChanged(current_speed_); emit durationChanged(seek_map_.size()); emit resolutionChanged(codec_context_->width, codec_context_->height); } void Player::play() { if(stopped_ == true) { stopped_ = false; } emit stateChanged(stopped_); while(stopped_ == false) { QTime t; t.start(); getOneFrame(); emit processedImage(image_, frame_index_); double usec = 1000.0 * t.restart(); processWait(std::round(delay_ - usec)); } } void Player::stop() { stopped_ = true; emit stateChanged(stopped_); } void Player::getOneFrame() { QMutexLocker locker(&mutex_); while(true) { int status = av_read_frame(format_context_, &packet_); if(status < 0) { break; } if(packet_.stream_index == stream_index_) { auto it = seek_map_.right.find(packet_.dts); if(it == seek_map_.right.end()) { emit error("Could not find decompression timestamp!"); return; } else { frame_index_ = it->second; } status = avcodec_send_packet(codec_context_, &packet_); if(status < 0) { emit error("Error while sending packet to the decoder!"); return; } while(status >= 0) { status = avcodec_receive_frame(codec_context_, frame_); if(status == AVERROR_EOF) { stopped_ = true; break; } else if(status == AVERROR(EAGAIN)) { break; } else if(status < 0) { emit error("Error while receiving a frame from the decoder!"); return; } else { sws_scale( sws_context_, frame_->data, frame_->linesize, 0, codec_context_->height, frame_rgb_->data, frame_rgb_->linesize); uint8_t *src = (uint8_t*)(frame_rgb_->data[0]); for(int y = 0; y < codec_context_->height; ++y) { QRgb *scan_line = (QRgb*)image_.scanLine(y); for(int x = 0; x < codec_context_->width; ++x) { scan_line[x] = qRgb(src[3*x], src[3*x+1], src[3*x+2]); } src += frame_rgb_->linesize[0]; } return; } } } } } void Player::speedUp() { delay_ /= 2.0; if(delay_ < 1.0) delay_ = 1.0; current_speed_ *= 2.0; emit playbackRateChanged(current_speed_); } void Player::slowDown() { delay_ *= 2.0; current_speed_ /= 2.0; emit playbackRateChanged(current_speed_); } void Player::nextFrame() { getOneFrame(); emit processedImage(image_, frame_index_); } void Player::prevFrame() { setCurrentFrame(frame_index_ - 1); emit processedImage(image_, frame_index_); } void Player::setCurrentFrame(qint64 frame_num) { qint64 bounded = frame_num < 0 ? 0 : frame_num; const qint64 max_frame = seek_map_.left.rbegin()->first; bounded = bounded > max_frame ? max_frame : bounded; qint64 seek_to = bounded - 3; seek_to = seek_to < 0 ? 0 : seek_to; auto it = seek_map_.left.find(seek_to); if(it != seek_map_.left.end()) { int status = av_seek_frame( format_context_, stream_index_, it->second, AVSEEK_FLAG_BACKWARD); if(status < 0) { emit error("Error seeking to frame!"); return; } avcodec_flush_buffers(codec_context_); while(true) { getOneFrame(); if(frame_index_ >= bounded) { break; } } } } void Player::setFrame(qint64 frame) { setCurrentFrame(frame); emit processedImage(image_, frame_index_); } void Player::processWait(qint64 usec) { QTime die_time = QTime::currentTime().addMSecs(usec / 1000); QCoreApplication::processEvents(QEventLoop::AllEvents, 1); while(QTime::currentTime() < die_time) { QCoreApplication::processEvents(QEventLoop::AllEvents, 1); } } #include "../../include/fish_annotator/video_annotator/moc_player.cpp" }} // namespace fish_annotator::gui
Set delay
Set delay
C++
mit
BGWoodward/FishDetector
dae5a783b181da8cc56c6180f01b8067a4ecc107
src/vk0.10-pipeline_cache.cpp
src/vk0.10-pipeline_cache.cpp
/* * Vulkan Samples Kit * * Copyright (C) 2016 Valve Corporation * Copyright (C) 2016 Google, Inc. * * 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. */ /* VULKAN_SAMPLE_SHORT_DESCRIPTION Create and use a pipeline cache accross runs. */ #include <util_init.hpp> #include <assert.h> #include <string.h> #include <cstdlib> #include "cube_data.h" // This sample tries to save and reuse pipeline cache data between runs // On first run, no cache will be found, it will be created and saved // to disk. On later runs, the cache should be found, loaded, and used. // Hopefully a speedup will observed. In the future, the pipeline could // be complicated a bit, to show a greater cache benefit. Also, two // pipelines could be created and merged. const char *vertShaderText = "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (std140, binding = 0) uniform buf {\n" " mat4 mvp;\n" "} ubuf;\n" "layout (location = 0) in vec4 pos;\n" "layout (location = 1) in vec2 inTexCoords;\n" "layout (location = 0) out vec2 texcoord;\n" "out gl_PerVertex { \n" " vec4 gl_Position;\n" "};\n" "void main() {\n" " texcoord = inTexCoords;\n" " gl_Position = ubuf.mvp * pos;\n" "\n" " // GL->VK conventions\n" " gl_Position.y = -gl_Position.y;\n" " gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n" "}\n"; const char *fragShaderText= "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (binding = 1) uniform sampler2D tex;\n" "layout (location = 0) in vec2 texcoord;\n" "layout (location = 0) out vec4 outColor;\n" "void main() {\n" " outColor = textureLod(tex, texcoord, 0.0);\n" "}\n"; int main(int argc, char **argv) { VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Pipeline Cache"; const bool depthPresent = true; init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_device(info); info.width = info.height = 500; init_connection(info); init_window(info); init_swapchain_extension(info); init_command_pool(info); init_command_buffer(info); execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); init_depth_buffer(info); init_texture(info, "blue.ppm"); init_uniform_buffer(info); init_descriptor_and_pipeline_layouts(info, true); init_renderpass(info, depthPresent); init_shaders(info, vertShaderText, fragShaderText); init_framebuffers(info, depthPresent); init_vertex_buffer(info, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), true); init_descriptor_pool(info, true); init_descriptor_set(info, true); /* VULKAN_KEY_START */ // Check disk for existing cache data size_t startCacheSize = 0; void* startCacheData = nullptr; const char* readFileName = "pipeline_cache_data.bin"; FILE *pReadFile = fopen(readFileName, "rb"); if (pReadFile) { // Determine cache size fseek(pReadFile, 0 , SEEK_END); startCacheSize = ftell(pReadFile); rewind(pReadFile); // Allocate memory to hold the initial cache data startCacheData = (char*) malloc(sizeof(char) * startCacheSize); if (startCacheData == nullptr) { fputs("Memory error",stderr); exit(EXIT_FAILURE); } // Read the data into our buffer size_t result = fread(startCacheData, 1, startCacheSize, pReadFile); if (result != startCacheSize) { fputs("Reading error", stderr); free(startCacheData); exit(EXIT_FAILURE); } // Clean up and print results fclose(pReadFile); printf(" Pipeline cache HIT!\n"); printf(" cacheData loaded from %s\n", readFileName); } else { // No cache found on disk printf(" Pipeline cache miss!\n"); } if (startCacheData != nullptr) { // // Check for cache validity // // TODO: Update this as the spec evolves. The fields are not defined by the header. // // The code below supports SDK 0.10 Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 a device ID equal to VkPhysicalDeviceProperties::DeviceId written // as a stream of bytes, with the least significant byte first // // 4 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // // // The code must be updated for latest Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 length in bytes of the entire pipeline cache header written as a // stream of bytes, with the least significant byte first // 4 4 a VkPipelineCacheHeaderVersion value written as a stream of bytes, // with the least significant byte first // 8 4 a vendor ID equal to VkPhysicalDeviceProperties::vendorID written // as a stream of bytes, with the least significant byte first // 12 4 a device ID equal to VkPhysicalDeviceProperties::deviceID written // as a stream of bytes, with the least significant byte first // 16 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // uint8_t pipelineCacheUUID[VK_UUID_SIZE] = {}; uint32_t deviceID = 0; deviceID = *((uint32_t*)startCacheData); memcpy(pipelineCacheUUID, (uint8_t *)startCacheData + 4, VK_UUID_SIZE); // Check each field and report bad values before freeing existing cache bool badCache = false; if (deviceID != info.gpu_props.deviceID) { badCache = true; printf(" Device ID mismatch in %s.\n", readFileName); printf(" Cache contains: 0x%.8x\n", deviceID); printf(" Driver expects: 0x%.8x\n", info.gpu_props.deviceID); } if (memcmp(pipelineCacheUUID, info.gpu_props.pipelineCacheUUID, sizeof(pipelineCacheUUID)) != 0) { badCache = true; printf(" UUID mismatch in %s.\n", readFileName); printf(" Cache contains: "); print_UUID(pipelineCacheUUID); printf("\n"); printf(" Driver expects: "); print_UUID(info.gpu_props.pipelineCacheUUID); printf("\n"); } if (badCache) { // Don't submit initial cache data if any version info is incorrect free(startCacheData); startCacheSize = 0; startCacheData = nullptr; // And clear out the old cache file for use in next run printf(" Deleting cache entry %s to repopulate.\n", readFileName); if (remove(readFileName) != 0) { fputs("Reading error", stderr); exit(EXIT_FAILURE); } } } // Feed the initial cache data into pipeline creation VkPipelineCacheCreateInfo pipelineCache; pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; pipelineCache.pNext = NULL; pipelineCache.initialDataSize = startCacheSize; pipelineCache.pInitialData = startCacheData; pipelineCache.flags = 0; res = vkCreatePipelineCache(info.device, &pipelineCache, nullptr, &info.pipelineCache); assert(res == VK_SUCCESS); // Free our initialData now that pipeline has been created free(startCacheData); // Time (roughly) taken to create the graphics pipeline timestamp_t start = get_milliseconds(); init_pipeline(info, depthPresent); timestamp_t elapsed = get_milliseconds() - start; printf(" vkCreateGraphicsPipeline time: %0.f ms\n", (double)elapsed); // Begin standard draw stuff init_presentable_image(info); VkClearValue clear_values[2]; init_clear_color_and_depth(info, clear_values); VkRenderPassBeginInfo rp_begin; init_render_pass_begin_info(info, rp_begin); rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline); vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS, info.desc_set.data(), 0, NULL); const VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets); init_viewports(info); init_scissors(info); vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0); vkCmdEndRenderPass(info.cmd); execute_pre_present_barrier(info); res = vkEndCommandBuffer(info.cmd); assert(res == VK_SUCCESS); VkFence drawFence = {}; init_fence(info, drawFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submit_info = {}; init_submit_info(info, submit_info, pipe_stage_flags); /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, &submit_info, drawFence); assert(res == VK_SUCCESS); /* Now present the image in the window */ VkPresentInfoKHR present = {}; init_present_info(info, present); /* Make sure command buffer is finished before presenting */ do { res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); } while(res == VK_TIMEOUT); assert(res == VK_SUCCESS); res = info.fpQueuePresentKHR(info.queue, &present); assert(res == VK_SUCCESS); wait_seconds(1); // End standard draw stuff if (startCacheData) { // TODO: Create another pipeline, preferably different from the first one // and merge it here. Then store the merged one. } // Store away the cache that we've populated. This could conceivably happen earlier, // depends on when the pipeline cache stops being populated internally. size_t endCacheSize = 0; void* endCacheData = nullptr; // Call with nullptr to get cache size vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, nullptr); // Allocate memory to hold the populated cache data endCacheData = (char*) malloc(sizeof(char) * endCacheSize); if (!endCacheData) { fputs("Memory error", stderr); exit(EXIT_FAILURE); } // Call again with pointer to buffer vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, endCacheData); // Write the file to disk, overwriting whatever was there FILE * pWriteFile; const char* writeFileName = "pipeline_cache_data.bin"; pWriteFile = fopen(writeFileName, "wb"); if (pWriteFile) { fwrite(endCacheData, sizeof(char), endCacheSize, pWriteFile); fclose(pWriteFile); printf(" cacheData written to %s\n", writeFileName); } else { // Something bad happened printf(" Unable to write cache data to disk!\n"); } /* VULKAN_KEY_END */ vkDestroyFence(info.device, drawFence, NULL); vkDestroySemaphore(info.device, info.presentCompleteSemaphore, NULL); destroy_pipeline(info); destroy_pipeline_cache(info); destroy_textures(info); destroy_descriptor_pool(info); destroy_vertex_buffer(info); destroy_framebuffers(info); destroy_shaders(info); destroy_renderpass(info); destroy_descriptor_and_pipeline_layouts(info); destroy_uniform_buffer(info); destroy_depth_buffer(info); destroy_swap_chain(info); destroy_command_buffer(info); destroy_command_pool(info); destroy_window(info); destroy_device(info); destroy_instance(info); }
/* * Vulkan Samples Kit * * Copyright (C) 2016 Valve Corporation * Copyright (C) 2016 Google, Inc. * * 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. */ /* VULKAN_SAMPLE_SHORT_DESCRIPTION Create and use a pipeline cache accross runs. */ #include <util_init.hpp> #include <assert.h> #include <string.h> #include <cstdlib> #include "cube_data.h" // This sample tries to save and reuse pipeline cache data between runs // On first run, no cache will be found, it will be created and saved // to disk. On later runs, the cache should be found, loaded, and used. // Hopefully a speedup will observed. In the future, the pipeline could // be complicated a bit, to show a greater cache benefit. Also, two // pipelines could be created and merged. const char *vertShaderText = "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (std140, binding = 0) uniform buf {\n" " mat4 mvp;\n" "} ubuf;\n" "layout (location = 0) in vec4 pos;\n" "layout (location = 1) in vec2 inTexCoords;\n" "layout (location = 0) out vec2 texcoord;\n" "out gl_PerVertex { \n" " vec4 gl_Position;\n" "};\n" "void main() {\n" " texcoord = inTexCoords;\n" " gl_Position = ubuf.mvp * pos;\n" "\n" " // GL->VK conventions\n" " gl_Position.y = -gl_Position.y;\n" " gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n" "}\n"; const char *fragShaderText= "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (binding = 1) uniform sampler2D tex;\n" "layout (location = 0) in vec2 texcoord;\n" "layout (location = 0) out vec4 outColor;\n" "void main() {\n" " outColor = textureLod(tex, texcoord, 0.0);\n" "}\n"; int main(int argc, char **argv) { VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Pipeline Cache"; const bool depthPresent = true; init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_device(info); info.width = info.height = 500; init_connection(info); init_window(info); init_swapchain_extension(info); init_command_pool(info); init_command_buffer(info); execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); init_depth_buffer(info); init_texture(info, "blue.ppm"); init_uniform_buffer(info); init_descriptor_and_pipeline_layouts(info, true); init_renderpass(info, depthPresent); init_shaders(info, vertShaderText, fragShaderText); init_framebuffers(info, depthPresent); init_vertex_buffer(info, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), true); init_descriptor_pool(info, true); init_descriptor_set(info, true); /* VULKAN_KEY_START */ // Check disk for existing cache data size_t startCacheSize = 0; void* startCacheData = nullptr; const char* readFileName = "pipeline_cache_data.bin"; FILE *pReadFile = fopen(readFileName, "rb"); if (pReadFile) { // Determine cache size fseek(pReadFile, 0 , SEEK_END); startCacheSize = ftell(pReadFile); rewind(pReadFile); // Allocate memory to hold the initial cache data startCacheData = (char*) malloc(sizeof(char) * startCacheSize); if (startCacheData == nullptr) { fputs("Memory error",stderr); exit(EXIT_FAILURE); } // Read the data into our buffer size_t result = fread(startCacheData, 1, startCacheSize, pReadFile); if (result != startCacheSize) { fputs("Reading error", stderr); free(startCacheData); exit(EXIT_FAILURE); } // Clean up and print results fclose(pReadFile); printf(" Pipeline cache HIT!\n"); printf(" cacheData loaded from %s\n", readFileName); } else { // No cache found on disk printf(" Pipeline cache miss!\n"); } if (startCacheData != nullptr) { // // Check for cache validity // // TODO: Update this as the spec evolves. The fields are not defined by the header. // // The code below supports SDK 0.10 Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 a device ID equal to VkPhysicalDeviceProperties::DeviceId written // as a stream of bytes, with the least significant byte first // // 4 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // // // The code must be updated for latest Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 length in bytes of the entire pipeline cache header written as a // stream of bytes, with the least significant byte first // 4 4 a VkPipelineCacheHeaderVersion value written as a stream of bytes, // with the least significant byte first // 8 4 a vendor ID equal to VkPhysicalDeviceProperties::vendorID written // as a stream of bytes, with the least significant byte first // 12 4 a device ID equal to VkPhysicalDeviceProperties::deviceID written // as a stream of bytes, with the least significant byte first // 16 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // uint32_t headerLength = 0; uint32_t cacheHeaderVersion = 0; uint32_t vendorID = 0; uint32_t deviceID = 0; uint8_t pipelineCacheUUID[VK_UUID_SIZE] = {}; memcpy(&headerLength, (uint8_t *)startCacheData + 0, 4); memcpy(&cacheHeaderVersion, (uint8_t *)startCacheData + 4, 4); memcpy(&vendorID, (uint8_t *)startCacheData + 8, 4); memcpy(&deviceID, (uint8_t *)startCacheData + 12, 4); memcpy(pipelineCacheUUID, (uint8_t *)startCacheData + 16, VK_UUID_SIZE); // Check each field and report bad values before freeing existing cache bool badCache = false; if (headerLength <= 0) { badCache = true; printf(" Bad header length in %s.\n", readFileName); printf(" Cache contains: 0x%.8x\n", headerLength); } if (cacheHeaderVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE) { badCache = true; printf(" Unsupported cache header version in %s.\n", readFileName); printf(" Cache contains: 0x%.8x\n", cacheHeaderVersion); } if (vendorID != info.gpu_props.vendorID) { badCache = true; printf(" Vendor ID mismatch in %s.\n", readFileName); printf(" Cache contains: 0x%.8x\n", vendorID); printf(" Driver expects: 0x%.8x\n", info.gpu_props.vendorID); } if (deviceID != info.gpu_props.deviceID) { badCache = true; printf(" Device ID mismatch in %s.\n", readFileName); printf(" Cache contains: 0x%.8x\n", deviceID); printf(" Driver expects: 0x%.8x\n", info.gpu_props.deviceID); } if (memcmp(pipelineCacheUUID, info.gpu_props.pipelineCacheUUID, sizeof(pipelineCacheUUID)) != 0) { badCache = true; printf(" UUID mismatch in %s.\n", readFileName); printf(" Cache contains: "); print_UUID(pipelineCacheUUID); printf("\n"); printf(" Driver expects: "); print_UUID(info.gpu_props.pipelineCacheUUID); printf("\n"); } if (badCache) { // Don't submit initial cache data if any version info is incorrect free(startCacheData); startCacheSize = 0; startCacheData = nullptr; // And clear out the old cache file for use in next run printf(" Deleting cache entry %s to repopulate.\n", readFileName); if (remove(readFileName) != 0) { fputs("Reading error", stderr); exit(EXIT_FAILURE); } } } // Feed the initial cache data into pipeline creation VkPipelineCacheCreateInfo pipelineCache; pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; pipelineCache.pNext = NULL; pipelineCache.initialDataSize = startCacheSize; pipelineCache.pInitialData = startCacheData; pipelineCache.flags = 0; res = vkCreatePipelineCache(info.device, &pipelineCache, nullptr, &info.pipelineCache); assert(res == VK_SUCCESS); // Free our initialData now that pipeline has been created free(startCacheData); // Time (roughly) taken to create the graphics pipeline timestamp_t start = get_milliseconds(); init_pipeline(info, depthPresent); timestamp_t elapsed = get_milliseconds() - start; printf(" vkCreateGraphicsPipeline time: %0.f ms\n", (double)elapsed); // Begin standard draw stuff init_presentable_image(info); VkClearValue clear_values[2]; init_clear_color_and_depth(info, clear_values); VkRenderPassBeginInfo rp_begin; init_render_pass_begin_info(info, rp_begin); rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline); vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS, info.desc_set.data(), 0, NULL); const VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets); init_viewports(info); init_scissors(info); vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0); vkCmdEndRenderPass(info.cmd); execute_pre_present_barrier(info); res = vkEndCommandBuffer(info.cmd); assert(res == VK_SUCCESS); VkFence drawFence = {}; init_fence(info, drawFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submit_info = {}; init_submit_info(info, submit_info, pipe_stage_flags); /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, &submit_info, drawFence); assert(res == VK_SUCCESS); /* Now present the image in the window */ VkPresentInfoKHR present = {}; init_present_info(info, present); /* Make sure command buffer is finished before presenting */ do { res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); } while(res == VK_TIMEOUT); assert(res == VK_SUCCESS); res = info.fpQueuePresentKHR(info.queue, &present); assert(res == VK_SUCCESS); wait_seconds(1); // End standard draw stuff if (startCacheData) { // TODO: Create another pipeline, preferably different from the first one // and merge it here. Then store the merged one. } // Store away the cache that we've populated. This could conceivably happen earlier, // depends on when the pipeline cache stops being populated internally. size_t endCacheSize = 0; void* endCacheData = nullptr; // Call with nullptr to get cache size vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, nullptr); // Allocate memory to hold the populated cache data endCacheData = (char*) malloc(sizeof(char) * endCacheSize); if (!endCacheData) { fputs("Memory error", stderr); exit(EXIT_FAILURE); } // Call again with pointer to buffer vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, endCacheData); // Write the file to disk, overwriting whatever was there FILE * pWriteFile; const char* writeFileName = "pipeline_cache_data.bin"; pWriteFile = fopen(writeFileName, "wb"); if (pWriteFile) { fwrite(endCacheData, sizeof(char), endCacheSize, pWriteFile); fclose(pWriteFile); printf(" cacheData written to %s\n", writeFileName); } else { // Something bad happened printf(" Unable to write cache data to disk!\n"); } /* VULKAN_KEY_END */ vkDestroyFence(info.device, drawFence, NULL); vkDestroySemaphore(info.device, info.presentCompleteSemaphore, NULL); destroy_pipeline(info); destroy_pipeline_cache(info); destroy_textures(info); destroy_descriptor_pool(info); destroy_vertex_buffer(info); destroy_framebuffers(info); destroy_shaders(info); destroy_renderpass(info); destroy_descriptor_and_pipeline_layouts(info); destroy_uniform_buffer(info); destroy_depth_buffer(info); destroy_swap_chain(info); destroy_command_buffer(info); destroy_command_pool(info); destroy_window(info); destroy_device(info); destroy_instance(info); }
Update pipeline cache memory layout
samples: Update pipeline cache memory layout
C++
apache-2.0
Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples
7c04af7f6b4a0f120fc1d9850683cba0605763ed
pam_ldapdb.cpp
pam_ldapdb.cpp
#include <map> #include <string> #include <utility> #define PAM_SM_AUTH #include <security/pam_modules.h> #include <security/pam_ext.h> #define LDAP_DEPRECATED 1 #include <ldap.h> typedef std::map<std::string, std::string> ArgMap; static int ldap_to_pam_rc(int ldap_rc) { switch (ldap_rc) { case LDAP_SUCCESS: /* everything was fine */ return PAM_SUCCESS; case LDAP_UNAVAILABLE: case LDAP_TIMELIMIT_EXCEEDED: case LDAP_OPERATIONS_ERROR: case LDAP_BUSY: case LDAP_LOOP_DETECT: case LDAP_SERVER_DOWN: case LDAP_TIMEOUT: case LDAP_CONNECT_ERROR: case LDAP_NO_RESULTS_RETURNED: /* cannot access LDAP correctly */ return PAM_AUTHINFO_UNAVAIL; } /* something else went wrong */ return PAM_AUTH_ERR; } static int verify(const char* host, const char* binddn, const char* pw) { LDAP* ld; int ldap_rc, pam_rc; ldap_rc = ldap_initialize(&ld, host); pam_rc = ldap_to_pam_rc(ldap_rc); if (pam_rc != PAM_SUCCESS) return pam_rc; ldap_rc = ldap_simple_bind_s(ld, binddn, pw); return ldap_to_pam_rc(ldap_rc); } static ArgMap get_args(int argc, const char** argv) { ArgMap arguments; for (int i = 0; i < argc; i++) { std::string arg(argv[i]); std::string::size_type pos = arg.find("="); if (pos != std::string::npos) { std::string key = arg.substr(0, pos); std::string value = ""; if (arg.length() > pos+1) { value = arg.substr(pos+1); } arguments.insert(std::make_pair(key, value)); } } return arguments; } static void replace_all(std::string& s, const std::string& search_s, const std::string& replace_s) { std::string::size_type last_pos = 0; while ((last_pos = s.find(search_s, last_pos)) != std::string::npos) { s.replace(last_pos, search_s.length(), replace_s); } } PAM_EXTERN int pam_sm_authenticate(pam_handle_t* pamh, int flags, int argc, const char** argv) { const char* user; const char* pass; ArgMap arguments = get_args(argc, argv); if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) { return PAM_AUTH_ERR; } if (pam_get_authtok(pamh, PAM_AUTHTOK, &pass, NULL) != PAM_SUCCESS) { return PAM_AUTH_ERR; } // ensure uri and binddn PAM parameters were specified if (arguments.find("uri") == arguments.end() || arguments.find("binddn") == arguments.end()) { return PAM_AUTH_ERR; } std::string binddn = arguments["binddn"]; replace_all(binddn, "%s", user); // check against ldap database return verify(arguments["uri"].c_str(), binddn.c_str(), pass); } PAM_EXTERN int pam_sm_setcred(pam_handle_t* pamh, int flags, int argc, const char** argv) { return PAM_SUCCESS; }
#include <map> #include <string> #include <utility> #define PAM_SM_AUTH #include <security/pam_modules.h> #include <security/pam_ext.h> #define LDAP_DEPRECATED 1 #include <ldap.h> typedef std::map<std::string, std::string> ArgMap; static int ldap_to_pam_rc(int ldap_rc) { switch (ldap_rc) { case LDAP_SUCCESS: /* everything was fine */ return PAM_SUCCESS; case LDAP_UNAVAILABLE: case LDAP_TIMELIMIT_EXCEEDED: case LDAP_OPERATIONS_ERROR: case LDAP_BUSY: case LDAP_LOOP_DETECT: case LDAP_SERVER_DOWN: case LDAP_TIMEOUT: case LDAP_CONNECT_ERROR: case LDAP_NO_RESULTS_RETURNED: /* cannot access LDAP correctly */ return PAM_AUTHINFO_UNAVAIL; } /* something else went wrong */ return PAM_AUTH_ERR; } static int verify(const char* host, const char* binddn, const char* pw) { LDAP* ld; int ldap_rc, pam_rc; ldap_rc = ldap_initialize(&ld, host); pam_rc = ldap_to_pam_rc(ldap_rc); if (pam_rc != PAM_SUCCESS) return pam_rc; ldap_rc = ldap_simple_bind_s(ld, binddn, pw); return ldap_to_pam_rc(ldap_rc); } static ArgMap get_args(int argc, const char** argv) { ArgMap arguments; for (int i = 0; i < argc; i++) { std::string arg(argv[i]); std::string::size_type pos = arg.find("="); if (pos != std::string::npos) { std::string key = arg.substr(0, pos); std::string value = ""; if (arg.length() > pos+1) { value = arg.substr(pos+1); } arguments.insert(std::make_pair(key, value)); } } return arguments; } static void replace_all(std::string& s, const std::string& search_s, const std::string& replace_s) { std::string::size_type last_pos = 0; while ((last_pos = s.find(search_s, last_pos)) != std::string::npos) { s.replace(last_pos, search_s.length(), replace_s); } } PAM_EXTERN int pam_sm_authenticate(pam_handle_t* pamh, int /* flags */, int argc, const char** argv) { const char* user; const char* pass; ArgMap arguments = get_args(argc, argv); if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) { return PAM_AUTH_ERR; } if (pam_get_authtok(pamh, PAM_AUTHTOK, &pass, NULL) != PAM_SUCCESS) { return PAM_AUTH_ERR; } // ensure uri and binddn PAM parameters were specified if (arguments.find("uri") == arguments.end() || arguments.find("binddn") == arguments.end()) { return PAM_AUTH_ERR; } std::string binddn = arguments["binddn"]; replace_all(binddn, "%s", user); // check against ldap database return verify(arguments["uri"].c_str(), binddn.c_str(), pass); } PAM_EXTERN int pam_sm_setcred(pam_handle_t* /* pamh */, int /* flags */, int /* argc */, const char** /* argv */) { return PAM_SUCCESS; }
fix unused parameter warnings
pam_ldapdb: fix unused parameter warnings Comment-out paramter names whch are unused in their functions. This fixes following warnings: pam_ldapdb.cpp: In function ‘int pam_sm_authenticate(pam_handle_t*, int, int, const char**)’: pam_ldapdb.cpp:90:40: warning: unused parameter ‘flags’ [-Wunused-parameter] int flags, ^~~~~ pam_ldapdb.cpp: In function ‘int pam_sm_setcred(pam_handle_t*, int, int, const char**)’: pam_ldapdb.cpp:119:45: warning: unused parameter ‘pamh’ [-Wunused-parameter] PAM_EXTERN int pam_sm_setcred(pam_handle_t* pamh, ^~~~ pam_ldapdb.cpp:120:35: warning: unused parameter ‘flags’ [-Wunused-parameter] int flags, ^~~~~ pam_ldapdb.cpp:121:35: warning: unused parameter ‘argc’ [-Wunused-parameter] int argc, ^~~~ pam_ldapdb.cpp:122:44: warning: unused parameter ‘argv’ [-Wunused-parameter] const char** argv) ^~~~ Signed-off-by: Richard Leitner <[email protected]>
C++
mit
rmbreak/pam_ldapdb
bf77fd7f3a756b0e3606e57572d1d202a2ed5bf2
libcontextsubscriber/unit-tests/infoxmlbackend/infoxmlbackendunittest.cpp
libcontextsubscriber/unit-tests/infoxmlbackend/infoxmlbackendunittest.cpp
/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include "fileutils.h" #include "infoxmlbackend.h" class InfoXmlBackendUnitTest : public QObject { Q_OBJECT InfoXmlBackend *backend; private: bool inSpyHasOneInList(QSignalSpy &spy, const QString &v); private slots: void initTestCase(); void paths(); void name(); void listKeys(); void typeForKey(); void docForKey(); void keyDeclared(); void listProviders(); void dynamics(); void cleanupTestCase(); }; bool InfoXmlBackendUnitTest::inSpyHasOneInList(QSignalSpy &spy, const QString &v) { if (spy.count() == 0) return false; while (spy.count() > 0) { QList<QVariant> args = spy.takeFirst(); foreach (QString s, args.at(0).toStringList()) { if (s == v) return true; } } return false; } void InfoXmlBackendUnitTest::initTestCase() { utilCopyLocalAtomically("providers1.src", "providers1.context"); utilCopyLocalWithRemove("providers2v1.src", "providers2.context"); utilSetEnv("CONTEXT_PROVIDERS", "./"); utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null"); backend = new InfoXmlBackend(); } void InfoXmlBackendUnitTest::listKeys() { QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 10); QVERIFY(keys.contains("Battery.ChargePercentage")); QVERIFY(keys.contains("Battery.LowBattery")); QVERIFY(keys.contains("Key.With.Attribute")); QVERIFY(keys.contains("Key.With.bool")); QVERIFY(keys.contains("Key.With.int32")); QVERIFY(keys.contains("Key.With.string")); QVERIFY(keys.contains("Key.With.double")); QVERIFY(keys.contains("Key.With.complex")); QVERIFY(keys.contains("Battery.Charging")); QVERIFY(keys.contains("Battery.Voltage")); } void InfoXmlBackendUnitTest::name() { QCOMPARE(backend->name(), QString("xml")); } void InfoXmlBackendUnitTest::typeForKey() { QCOMPARE(backend->typeForKey("Battery.ChargePercentage"), QString()); QCOMPARE(backend->typeForKey("Key.With.Attribute"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Battery.LowBattery"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Key.With.bool"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Key.With.int32"), QString("INT")); QCOMPARE(backend->typeForKey("Key.With.string"), QString("STRING")); QCOMPARE(backend->typeForKey("Key.With.double"), QString("DOUBLE")); QCOMPARE(backend->typeForKey("Key.With.complex"), QString()); QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Battery.Voltage"), QString("INTEGER")); QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString()); } void InfoXmlBackendUnitTest::docForKey() { QCOMPARE(backend->docForKey("Battery.ChargePercentage"), QString()); QCOMPARE(backend->docForKey("Battery.LowBattery"), QString("This is true when battery is low")); QCOMPARE(backend->docForKey("Key.With.bool"), QString()); QCOMPARE(backend->docForKey("Key.With.int32"), QString()); QCOMPARE(backend->docForKey("Key.With.string"), QString()); QCOMPARE(backend->docForKey("Key.With.double"), QString()); QCOMPARE(backend->docForKey("Key.With.complex"), QString()); QCOMPARE(backend->docForKey("Battery.Charging"), QString("This is true when battery is charging")); QCOMPARE(backend->docForKey("Does.Not.Exist"), QString()); } void InfoXmlBackendUnitTest::keyDeclared() { foreach (QString key, backend->listKeys()) QCOMPARE(backend->keyDeclared(key), true); QCOMPARE(backend->keyDeclared("Does.Not.Exist"), false); QCOMPARE(backend->keyDeclared("Battery.Charging"), true); } void InfoXmlBackendUnitTest::paths() { QVERIFY(InfoXmlBackend::registryPath() == QString("./") || InfoXmlBackend::registryPath() == QString(".")); QCOMPARE(InfoXmlBackend::coreDeclPath(), QString("/dev/null")); } void InfoXmlBackendUnitTest::listProviders() { QList <ContextProviderInfo> list1 = backend->listProviders("Battery.Charging"); QCOMPARE(list1.count(), 1); QCOMPARE(list1.at(0).plugin, QString("contextkit-dbus")); QCOMPARE(list1.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd2")); QList <ContextProviderInfo> list2 = backend->listProviders("Does.Not.Exist"); QCOMPARE(list2.count(), 0); } void InfoXmlBackendUnitTest::dynamics() { // Sanity check QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 10); QVERIFY(keys.contains("Battery.Charging")); QCOMPARE(backend->keyDeclared("System.Active"), false); // Setup the spy observers QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList))); QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList))); QSignalSpy spy3(backend, SIGNAL(keyChanged(QString))); QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList))); utilCopyLocalWithRemove("providers2v2.src", "providers2.context"); utilCopyLocalWithRemove("providers3.src", "providers3.context"); // Again, some basic check QCOMPARE(backend->keyDeclared("System.Active"), true); QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER")); // Test emissions QVERIFY(inSpyHasOneInList(spy1, "Battery.Voltage")); QVERIFY(inSpyHasOneInList(spy2, "Battery.Charging")); QVERIFY(inSpyHasOneInList(spy3, "Battery.Charging")); QVERIFY(inSpyHasOneInList(spy4, "System.Active")); } void InfoXmlBackendUnitTest::cleanupTestCase() { QFile::remove("providers1.context"); QFile::remove("providers2.context"); QFile::remove("providers3.context"); } #include "infoxmlbackendunittest.moc" QTEST_MAIN(InfoXmlBackendUnitTest);
/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include "fileutils.h" #include "infoxmlbackend.h" class InfoXmlBackendUnitTest : public QObject { Q_OBJECT InfoXmlBackend *backend; private: bool inSpyHasOneInList(QSignalSpy &spy, const QString &v); private slots: void initTestCase(); void paths(); void name(); void listKeys(); void typeForKey(); void docForKey(); void keyDeclared(); void listProviders(); void dynamics(); void cleanupTestCase(); }; bool InfoXmlBackendUnitTest::inSpyHasOneInList(QSignalSpy &spy, const QString &v) { if (spy.count() == 0) return false; while (spy.count() > 0) { QList<QVariant> args = spy.takeFirst(); foreach (QString s, args.at(0).toStringList()) { if (s == v) return true; } } return false; } void InfoXmlBackendUnitTest::initTestCase() { utilCopyLocalAtomically("providers1.src", "providers1.context"); utilCopyLocalWithRemove("providers2v1.src", "providers2.context"); utilSetEnv("CONTEXT_PROVIDERS", "./"); utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null"); backend = new InfoXmlBackend(); } void InfoXmlBackendUnitTest::listKeys() { QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 10); QVERIFY(keys.contains("Battery.ChargePercentage")); QVERIFY(keys.contains("Battery.LowBattery")); QVERIFY(keys.contains("Key.With.Attribute")); QVERIFY(keys.contains("Key.With.bool")); QVERIFY(keys.contains("Key.With.int32")); QVERIFY(keys.contains("Key.With.string")); QVERIFY(keys.contains("Key.With.double")); QVERIFY(keys.contains("Key.With.complex")); QVERIFY(keys.contains("Battery.Charging")); QVERIFY(keys.contains("Battery.Voltage")); } void InfoXmlBackendUnitTest::name() { QCOMPARE(backend->name(), QString("xml")); } void InfoXmlBackendUnitTest::typeForKey() { QCOMPARE(backend->typeForKey("Battery.ChargePercentage"), QString()); QCOMPARE(backend->typeForKey("Key.With.Attribute"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Battery.LowBattery"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Key.With.bool"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Key.With.int32"), QString("INT")); QCOMPARE(backend->typeForKey("Key.With.string"), QString("STRING")); QCOMPARE(backend->typeForKey("Key.With.double"), QString("DOUBLE")); QCOMPARE(backend->typeForKey("Key.With.complex"), QString()); QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH")); QCOMPARE(backend->typeForKey("Battery.Voltage"), QString("INTEGER")); QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString()); } void InfoXmlBackendUnitTest::docForKey() { QCOMPARE(backend->docForKey("Battery.ChargePercentage"), QString()); QCOMPARE(backend->docForKey("Battery.LowBattery"), QString("This is true when battery is low")); QCOMPARE(backend->docForKey("Key.With.bool"), QString()); QCOMPARE(backend->docForKey("Key.With.int32"), QString()); QCOMPARE(backend->docForKey("Key.With.string"), QString()); QCOMPARE(backend->docForKey("Key.With.double"), QString()); QCOMPARE(backend->docForKey("Key.With.complex"), QString()); QCOMPARE(backend->docForKey("Battery.Charging"), QString("This is true when battery is charging")); QCOMPARE(backend->docForKey("Does.Not.Exist"), QString()); } void InfoXmlBackendUnitTest::keyDeclared() { foreach (QString key, backend->listKeys()) QCOMPARE(backend->keyDeclared(key), true); QCOMPARE(backend->keyDeclared("Does.Not.Exist"), false); QCOMPARE(backend->keyDeclared("Battery.Charging"), true); } void InfoXmlBackendUnitTest::paths() { QVERIFY(InfoXmlBackend::registryPath() == QString("./") || InfoXmlBackend::registryPath() == QString(".")); QCOMPARE(InfoXmlBackend::coreDeclPath(), QString("/dev/null")); } void InfoXmlBackendUnitTest::listProviders() { QList <ContextProviderInfo> list1 = backend->listProviders("Battery.Charging"); QCOMPARE(list1.count(), 1); QCOMPARE(list1.at(0).plugin, QString("contextkit-dbus")); QCOMPARE(list1.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd2")); QList <ContextProviderInfo> list2 = backend->listProviders("Does.Not.Exist"); QCOMPARE(list2.count(), 0); } void InfoXmlBackendUnitTest::dynamics() { // Sanity check QStringList keys = backend->listKeys(); QCOMPARE(keys.count(), 10); QVERIFY(keys.contains("Battery.Charging")); QCOMPARE(backend->keyDeclared("System.Active"), false); // Setup the spy observers QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList))); QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList))); QSignalSpy spy3(backend, SIGNAL(keyChanged(QString))); QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList))); utilCopyLocalWithRemove("providers2v2.src", "providers2.context"); utilCopyLocalWithRemove("providers3.src", "providers3.context"); // Again, some basic check QCOMPARE(backend->keyDeclared("System.Active"), true); QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER")); // Test emissions QVERIFY(inSpyHasOneInList(spy1, "Battery.Voltage")); QVERIFY(inSpyHasOneInList(spy2, "Battery.Charging")); QVERIFY(inSpyHasOneInList(spy3, "Battery.Charging")); QVERIFY(inSpyHasOneInList(spy4, "System.Active")); // Check providers QList <ContextProviderInfo> list1 = backend->listProviders("Battery.Charging"); QCOMPARE(list1.count(), 1); QCOMPARE(list1.at(0).plugin, QString("contextkit-dbus")); QCOMPARE(list1.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd2")); QList <ContextProviderInfo> list2 = backend->listProviders("System.Active"); QCOMPARE(list2.count(), 1); QCOMPARE(list2.at(0).plugin, QString("contextkit-dbus")); QCOMPARE(list2.at(0).constructionString, QString("system:com.nokia.daemon")); QList <ContextProviderInfo> list3 = backend->listProviders("Battery.Voltage"); QCOMPARE(list3.count(), 0); } void InfoXmlBackendUnitTest::cleanupTestCase() { QFile::remove("providers1.context"); QFile::remove("providers2.context"); QFile::remove("providers3.context"); } #include "infoxmlbackendunittest.moc" QTEST_MAIN(InfoXmlBackendUnitTest);
Test providers() more carefully in dynamics().
Test providers() more carefully in dynamics().
C++
lgpl-2.1
rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck
5804aee7eaa5c05c5f783aa9590855815f338b32
src/io/io.cpp
src/io/io.cpp
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/io/io.hpp" #include "flusspferd/io/file_class.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/class.hpp" using namespace flusspferd; using namespace flusspferd::io; object flusspferd::io::load_io(object container) { local_root_scope scope; value previous = container.get_property("IO"); if (previous.is_object()) return previous.to_object(); object IO = flusspferd::create_object(); load_class<stream_base>(IO); load_class<file_class>(IO); container.define_property( "IO", IO, object::read_only_property | object::dont_enumerate); return IO; }
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/io/io.hpp" #include "flusspferd/io/file_class.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/class.hpp" #include <iostream> using namespace flusspferd; using namespace flusspferd::io; object flusspferd::io::load_io(object container) { local_root_scope scope; value previous = container.get_property("IO"); if (previous.is_object()) return previous.to_object(); object IO = flusspferd::create_object(); load_class<stream_base>(IO); load_class<file_class>(IO); IO.define_property( "stdout", create_native_object<stream_base>(object(), std::cout.rdbuf())); IO.define_property( "stderr", create_native_object<stream_base>(object(), std::cerr.rdbuf())); IO.define_property( "stdin", create_native_object<stream_base>(object(), std::cin.rdbuf())); container.define_property( "IO", IO, object::read_only_property | object::dont_enumerate); return IO; }
add stdin/stdout/stderr
IO: add stdin/stdout/stderr
C++
mit
Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd
c3a95cea3e6359b26ed59cf0443738b5d20c24c2
src/music.cpp
src/music.cpp
#include "music.h" #include <string> #include <iostream> #include "globals.h" // #include "defs.h" #include "configuration.h" #include "util/thread.h" #include "util/funcs.h" #include "util/file-system.h" #include "util/music-player.h" using namespace std; static Music * instance = NULL; static double volume = 1.0; // static bool muted = false; static Util::Thread::Id musicThread; static Util::Thread::Lock musicMutex; static bool alive = true; static void * playMusic( void * ); #define synchronized for( int __l( ! Util::Thread::acquireLock(&musicMutex)); __l; __l = 0, Util::Thread::releaseLock(&musicMutex) ) #define LOCK Util::Thread::acquireLock(&musicMutex); #define UNLOCK Util::Thread::releaseLock(&musicMutex); /* #undef LOCK #undef UNLOCK #define LOCK #define UNLOCK */ static void * bogus_thread( void * x){ return NULL; } Music::Music(bool on): playing(false), enabled(on), fading(0), musicPlayer(NULL), currentSong(""){ if (instance != NULL){ cerr << "Trying to instantiate music object twice!" << endl; return; } volume = (double) Configuration::getMusicVolume() / 100.0; instance = this; Util::Thread::initializeLock(&musicMutex); Global::debug(1) << "Creating music thread" << endl; if (on){ Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) playMusic, (void *)instance); } else { /* FIXME: just don't create a thread at all.. */ Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) bogus_thread, NULL); } } /* static bool isAlive(){ bool f = false; synchronized{ f = alive; } return f; } */ static void * playMusic( void * _music ){ Music * music = (Music *) _music; Global::debug(1) << "Playing music" << endl; /* unsigned int tick = 0; unsigned int counter; */ bool playing = true; while (playing){ LOCK;{ playing = alive; music->doPlay(); } UNLOCK; Util::rest(10); // Util::YIELD(); // pthread_yield(); } // cout << "Done with music thread" << endl; return NULL; } double Music::getVolume(){ double vol = 0; LOCK;{ vol = volume; } UNLOCK; return vol; } void Music::doPlay(){ if (this->playing){ double f = fading / 500.0; switch (fading){ case -1: { if (volume + f < 0){ fading = 0; volume = 0; } else { volume += f; this->_setVolume(volume); } break; } case 1: { if (volume + f > 1.0){ fading = 0; volume = 1.0; } else { volume += f; this->_setVolume(volume); } break; } } musicPlayer->poll(); } } /* Music::Music( const char * song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } Music::Music( const string & song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } */ void Music::fadeIn( double vol ){ LOCK;{ volume = vol; instance->_fadeIn(); } UNLOCK; } void Music::fadeOut( double vol ){ LOCK;{ volume = vol; instance->_fadeOut(); } UNLOCK; } void Music::_fadeIn(){ fading = 1; } void Music::_fadeOut(){ fading = -1; } bool Music::loadSong( const char * song ){ bool loaded = false; LOCK;{ loaded = instance->internal_loadSong( song ); } UNLOCK; return loaded; // muted = false; } /* remove an element from a vector at index 'pos' and return it */ template< class Tx_ > static Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){ int count = 0; typename vector< Tx_ >::iterator it; for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ ); if ( it == toRemove.end() ){ /* this isnt right, but whatever */ return toRemove.front(); } const Tx_ & removed = toRemove[ pos ]; toRemove.erase( it ); return removed; } void Music::loadSong( const vector<Filesystem::AbsolutePath> & Songs ){ /* cout << "Songs = " << &Songs << endl; if ( ! loadSong( "music/song5.xm" ) ){ cerr << "Could not load music/song5.xm" << endl; } return; */ vector<Filesystem::AbsolutePath> _songs = Songs; vector<Filesystem::AbsolutePath> songs; while ( ! _songs.empty() ){ int i = Util::rnd( _songs.size() ); songs.push_back(removeVectorElement(_songs, i)); } /* songs.clear(); songs.push_back( "music/song3.xm" ); */ for ( vector<Filesystem::AbsolutePath>::iterator it = songs.begin(); it != songs.end(); it++ ){ Global::debug( 1 ) << "Trying to load song " << (*it).path() << endl; if (loadSong((*it).path())){ break; } } } bool Music::loadSong( const string & song ){ return loadSong( song.c_str() ); } void Music::_play(){ if (playing == false && musicPlayer != NULL){ musicPlayer->play(); playing = true; } } void Music::play(){ LOCK;{ instance->_play(); } UNLOCK; } void Music::_pause(){ playing = false; if (musicPlayer != NULL){ musicPlayer->pause(); } } void Music::pause(){ LOCK;{ instance->_pause(); } UNLOCK; } void Music::soften(){ LOCK;{ instance->_soften(); } UNLOCK; } void Music::_soften(){ if ( volume > 0.1 ){ volume -= 0.1; } else { volume = 0.0; } _setVolume(volume); } void Music::louden(){ LOCK;{ instance->_louden(); } UNLOCK; } void Music::_louden(){ if ( volume < 0.9 ){ volume += 0.1; } else { volume = 1.0; } _setVolume( volume ); } void Music::mute(){ setVolume(0); } void Music::setVolume( double vol ){ LOCK;{ volume = vol; if ( volume > 1.0 ){ volume = 1.0; } if ( volume < 0 ){ volume = 0; } instance->_setVolume( volume ); } UNLOCK; } void Music::_setVolume(double vol){ if (musicPlayer){ musicPlayer->setVolume(vol); } } Music::~Music(){ LOCK;{ if (musicPlayer){ delete musicPlayer; } alive = false; playing = false; } UNLOCK; Global::debug( 1 ) << "Waiting for music thread to die" << endl; Util::Thread::joinThread(musicThread); } static string getExtension(const char * path_){ string path(path_); if (path.rfind('.') != string::npos){ return Util::lowerCaseAll(path.substr(path.rfind('.') + 1)); } return ""; } /* true if the file extension is something DUMB will probably recognize */ static bool isDumbFile(const char * path){ string extension = getExtension(path); return extension == "mod" || extension == "s3m" || extension == "it" || extension == "xm"; } static bool isGMEFile(const char * path){ string extension = getExtension(path); return extension == "nsf" || extension == "spc" || extension == "gym"; } static bool isOggFile(const char * path){ string extension = getExtension(path); return extension == "ogg"; } bool Music::internal_loadSong( const char * path ){ if (!enabled){ return false; } // cout << "Trying to load '" << path << "'" << endl; // Check current song and/or set it if (currentSong.compare(std::string(path))==0){ return true; } else { currentSong = std::string(path); } if (musicPlayer != NULL){ delete musicPlayer; musicPlayer = NULL; } try { if (isDumbFile(path)){ musicPlayer = new Util::DumbPlayer(path); musicPlayer->play(); playing = true; } else if (isGMEFile(path)){ musicPlayer = new Util::GMEPlayer(path); musicPlayer->play(); playing = true; #ifdef HAVE_OGG } else if (isOggFile(path)){ musicPlayer = new Util::OggPlayer(path); musicPlayer->play(); playing = true; #endif } else { return false; } if (musicPlayer != NULL){ musicPlayer->setVolume(volume); } } catch (const Exception::Base & ex){ //! FIXME Change from Base exception in the futer return false; } return true; } void Music::changeSong(){ pause(); fadeIn(0.3); loadSong(Filesystem::getFiles(Filesystem::find(Filesystem::RelativePath("music/")), "*")); play(); } #undef synchronized #undef LOCK #undef UNLOCK
#include "music.h" #include <string> #include <iostream> #include "globals.h" // #include "defs.h" #include "configuration.h" #include "util/thread.h" #include "util/funcs.h" #include "util/file-system.h" #include "util/music-player.h" using namespace std; static Music * instance = NULL; static double volume = 1.0; // static bool muted = false; static Util::Thread::Id musicThread; static Util::Thread::Lock musicMutex; static bool alive = true; static void * playMusic( void * ); #define synchronized for( int __l( ! Util::Thread::acquireLock(&musicMutex)); __l; __l = 0, Util::Thread::releaseLock(&musicMutex) ) #define LOCK Util::Thread::acquireLock(&musicMutex); #define UNLOCK Util::Thread::releaseLock(&musicMutex); /* #undef LOCK #undef UNLOCK #define LOCK #define UNLOCK */ static void * bogus_thread( void * x){ return NULL; } Music::Music(bool on): playing(false), enabled(on), fading(0), musicPlayer(NULL), currentSong(""){ if (instance != NULL){ cerr << "Trying to instantiate music object twice!" << endl; return; } volume = (double) Configuration::getMusicVolume() / 100.0; instance = this; Util::Thread::initializeLock(&musicMutex); Global::debug(1) << "Creating music thread" << endl; if (on){ Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) playMusic, (void *)instance); } else { /* FIXME: just don't create a thread at all.. */ Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) bogus_thread, NULL); } } /* static bool isAlive(){ bool f = false; synchronized{ f = alive; } return f; } */ static void * playMusic( void * _music ){ Music * music = (Music *) _music; Global::debug(1) << "Playing music" << endl; /* unsigned int tick = 0; unsigned int counter; */ bool playing = true; while (playing){ LOCK;{ playing = alive; music->doPlay(); } UNLOCK; Util::rest(10); // Util::YIELD(); // pthread_yield(); } // cout << "Done with music thread" << endl; return NULL; } double Music::getVolume(){ double vol = 0; LOCK;{ vol = volume; } UNLOCK; return vol; } void Music::doPlay(){ if (this->playing){ double f = fading / 500.0; switch (fading){ case -1: { if (volume + f < 0){ fading = 0; volume = 0; } else { volume += f; this->_setVolume(volume); } break; } case 1: { if (volume + f > 1.0){ fading = 0; volume = 1.0; } else { volume += f; this->_setVolume(volume); } break; } } musicPlayer->poll(); } } /* Music::Music( const char * song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } Music::Music( const string & song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } */ void Music::fadeIn(double vol){ LOCK;{ // volume = vol; instance->_fadeIn(); } UNLOCK; } void Music::fadeOut( double vol ){ LOCK;{ // volume = vol; instance->_fadeOut(); } UNLOCK; } /* FIXME */ void Music::_fadeIn(){ // fading = 1; } void Music::_fadeOut(){ // fading = -1; } bool Music::loadSong( const char * song ){ bool loaded = false; LOCK;{ loaded = instance->internal_loadSong(song); } UNLOCK; return loaded; // muted = false; } /* remove an element from a vector at index 'pos' and return it */ template< class Tx_ > static Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){ int count = 0; typename vector< Tx_ >::iterator it; for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ ); if ( it == toRemove.end() ){ /* this isnt right, but whatever */ return toRemove.front(); } const Tx_ & removed = toRemove[ pos ]; toRemove.erase( it ); return removed; } void Music::loadSong( const vector<Filesystem::AbsolutePath> & Songs ){ /* cout << "Songs = " << &Songs << endl; if ( ! loadSong( "music/song5.xm" ) ){ cerr << "Could not load music/song5.xm" << endl; } return; */ vector<Filesystem::AbsolutePath> _songs = Songs; vector<Filesystem::AbsolutePath> songs; while ( ! _songs.empty() ){ int i = Util::rnd( _songs.size() ); songs.push_back(removeVectorElement(_songs, i)); } /* songs.clear(); songs.push_back( "music/song3.xm" ); */ for ( vector<Filesystem::AbsolutePath>::iterator it = songs.begin(); it != songs.end(); it++ ){ Global::debug( 1 ) << "Trying to load song " << (*it).path() << endl; if (loadSong((*it).path())){ break; } } } bool Music::loadSong( const string & song ){ return loadSong( song.c_str() ); } void Music::_play(){ if (playing == false && musicPlayer != NULL){ musicPlayer->play(); playing = true; } } void Music::play(){ LOCK;{ instance->_play(); } UNLOCK; } void Music::_pause(){ playing = false; if (musicPlayer != NULL){ musicPlayer->pause(); } } void Music::pause(){ LOCK;{ instance->_pause(); } UNLOCK; } void Music::soften(){ LOCK;{ instance->_soften(); } UNLOCK; } void Music::_soften(){ if (volume > 0.1){ volume -= 0.1; } else { volume = 0.0; } _setVolume(volume); } void Music::louden(){ LOCK;{ instance->_louden(); } UNLOCK; } void Music::_louden(){ if ( volume < 0.9 ){ volume += 0.1; } else { volume = 1.0; } _setVolume(volume); } void Music::mute(){ setVolume(0); } void Music::setVolume( double vol ){ LOCK;{ volume = vol; if ( volume > 1.0 ){ volume = 1.0; } if ( volume < 0 ){ volume = 0; } instance->_setVolume( volume ); } UNLOCK; } void Music::_setVolume(double vol){ if (musicPlayer){ musicPlayer->setVolume(vol); } } Music::~Music(){ LOCK;{ if (musicPlayer){ delete musicPlayer; } alive = false; playing = false; } UNLOCK; Global::debug( 1 ) << "Waiting for music thread to die" << endl; Util::Thread::joinThread(musicThread); } static string getExtension(const char * path_){ string path(path_); if (path.rfind('.') != string::npos){ return Util::lowerCaseAll(path.substr(path.rfind('.') + 1)); } return ""; } /* true if the file extension is something DUMB will probably recognize */ static bool isDumbFile(const char * path){ string extension = getExtension(path); return extension == "mod" || extension == "s3m" || extension == "it" || extension == "xm"; } static bool isGMEFile(const char * path){ string extension = getExtension(path); return extension == "nsf" || extension == "spc" || extension == "gym"; } static bool isOggFile(const char * path){ string extension = getExtension(path); return extension == "ogg"; } bool Music::internal_loadSong( const char * path ){ if (!enabled){ return false; } // cout << "Trying to load '" << path << "'" << endl; // Check current song and/or set it if (currentSong.compare(std::string(path))==0){ return true; } else { currentSong = std::string(path); } if (musicPlayer != NULL){ delete musicPlayer; musicPlayer = NULL; } try { if (isDumbFile(path)){ musicPlayer = new Util::DumbPlayer(path); musicPlayer->play(); playing = true; } else if (isGMEFile(path)){ musicPlayer = new Util::GMEPlayer(path); musicPlayer->play(); playing = true; #ifdef HAVE_OGG } else if (isOggFile(path)){ musicPlayer = new Util::OggPlayer(path); musicPlayer->play(); playing = true; #endif } else { return false; } if (musicPlayer != NULL){ musicPlayer->setVolume(volume); } } catch (const Exception::Base & ex){ //! FIXME Change from Base exception in the futer return false; } return true; } void Music::changeSong(){ pause(); fadeIn(0.3); loadSong(Filesystem::getFiles(Filesystem::find(Filesystem::RelativePath("music/")), "*")); play(); } #undef synchronized #undef LOCK #undef UNLOCK
disable music fading
disable music fading git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@5069 662fdd30-d327-0410-a531-f549c87e1e9e
C++
bsd-3-clause
Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown
12e4b971ba5aa30d78cbb3e6b2bb9353a02c37b4
ssdb-1.9.2/src/ssdb/t_set.cpp
ssdb-1.9.2/src/ssdb/t_set.cpp
// // Created by a1 on 16-11-21. // #include "ssdb_impl.h" int SSDBImpl::GetSetMetaVal(const std::string &meta_key, SetMetaVal &sv){ std::string meta_val; leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &meta_val); if (s.IsNotFound()){ return 0; } else if (!s.ok() && !s.IsNotFound()){ return -1; } else{ int ret = sv.DecodeMetaVal(meta_val); if (ret == -1){ return -1; } else if (sv.del == KEY_DELETE_MASK){ return 0; } else if (sv.type != DataType::SSIZE){ return -1; } } return 1; } int SSDBImpl::GetSetItemValInternal(const std::string &item_key){ std::string val; leveldb::Status s = ldb->Get(leveldb::ReadOptions(), item_key, &val); if (s.IsNotFound()){ return 0; } else if (!s.ok() && !s.IsNotFound()){ return -1; } return 1; } int SSDBImpl::sadd_one(leveldb::WriteBatch &batch, const Bytes &key, const Bytes &member) { int ret = 0; std::string dbval; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return -1; } else if (ret == 0 && sv.del == KEY_DELETE_MASK){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string hkey = encode_set_key(key, member, version); batch.Put(hkey, slice("")); ret = 1; } else if (ret == 0){ std::string hkey = encode_set_key(key, member); batch.Put(hkey, slice("")); ret = 1; } else{ std::string item_key = encode_set_key(key, member, sv.version); ret = GetSetItemValInternal(item_key); if (ret == -1){ return -1; } else if (ret == 1){ ret = 0; } else{ batch.Put(item_key, slice("")); ret = 1; } } return ret; } int SSDBImpl::srem_one(leveldb::WriteBatch &batch, const Bytes &key, const Bytes &member) { SetMetaVal sv; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (ret != 1){ return ret; } std::string hkey = encode_set_key(key, member, sv.version); ret = GetSetItemValInternal(hkey); if (ret != 1){ return ret; } batch.Delete(hkey); return 1; } int SSDBImpl::incr_ssize(leveldb::WriteBatch &batch, const Bytes &key, int64_t incr){ SetMetaVal sv; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return ret; } else if (ret == 0 && sv.del == KEY_DELETE_MASK){ if (incr > 0){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string size_val = encode_set_meta_val((uint64_t)incr, version); batch.Put(meta_key, size_val); } else{ return -1; } } else if (ret == 0){ if (incr > 0){ std::string size_val = encode_set_meta_val((uint64_t)incr); batch.Put(meta_key, size_val); } else{ return -1; } } else{ uint64_t len = sv.length; if (incr > 0) { len += incr; } else if (incr < 0) { uint64_t u64 = static_cast<uint64_t>(-incr); if (len < u64) { return -1; } len = len - u64; } if (len == 0){ std::string del_key = encode_delete_key(key, sv.version); std::string meta_val = encode_set_meta_val(sv.length, sv.version, KEY_DELETE_MASK); batch.Put(del_key, ""); batch.Put(meta_key, meta_val); this->edel_one(batch, key); //del expire ET key } else{ std::string size_val = encode_set_meta_val(len, sv.version); batch.Put(meta_key, size_val); } } return 0; } SIterator* SSDBImpl::sscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit, const leveldb::Snapshot *snapshot) { std::string key_start, key_end; key_start = encode_set_key(name, start, version); if(!end.empty()){ key_end = encode_set_key(name, end, version); } return new SIterator(this->iterator(key_start, key_end, limit, snapshot), name, version); } SIterator* SSDBImpl::sscan(const Bytes &key, const Bytes &start, const Bytes &end, uint64_t limit) { SetMetaVal sv; uint16_t version; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (0 == ret && sv.del == KEY_DELETE_MASK){ version = sv.version + (uint16_t)1; } else if (ret > 0){ version = sv.version; } else { version = 0; } return sscan_internal(key, start, end, version, limit, nullptr); } int SSDBImpl::sadd(const Bytes &key, const Bytes &member){ RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = sadd_one(batch, key, member); if (ret >= 0){ if(ret > 0){ if(incr_ssize(batch, key, ret) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } } return ret; } int SSDBImpl::saddNoLock(const Bytes &key, const std::set<Bytes> &mem_set, int64_t *num) { leveldb::WriteBatch batch; int ret = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return -1; } *num = 0; std::set<Bytes>::iterator it = mem_set.begin(); for (; it != mem_set.end(); ++it) { const Bytes& member= *it; int change = 0; if (ret == 0 && sv.del == KEY_DELETE_MASK){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string hkey = encode_set_key(key, member, version); batch.Put(hkey, slice("")); change = 1; } else if (ret == 0){ std::string hkey = encode_set_key(key, member); batch.Put(hkey, slice("")); change = 1; } else{ std::string item_key = encode_set_key(key, member, sv.version); int s = GetSetItemValInternal(item_key); if (s == -1){ return -1; } else if (s == 1){ change = 0; } else{ batch.Put(item_key, slice("")); change = 1; } } *num += change; } if (*num > 0){ if(incr_ssize(batch, key, *num) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return 1; } int SSDBImpl::multi_sadd(const Bytes &key, const std::set<Bytes> &mem_set, int64_t *num) { RecordLock l(&mutex_record_, key.String()); return saddNoLock(key, mem_set, num); } int SSDBImpl::multi_srem(const Bytes &key, const std::vector<Bytes> &members, int64_t *num) { RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = 0; *num = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret != 1){ return ret; } for (int i = 2; i < members.size(); ++i){ const Bytes& member= members[i]; std::string hkey = encode_set_key(key, member, sv.version); int s = GetSetItemValInternal(hkey); if (s == 1){ *num += 1; batch.Delete(hkey); } else if (s == -1){ return -1; } } if (*num > 0){ if(incr_ssize(batch, key, (-1)*(*num)) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return ret; } int SSDBImpl::srem(const Bytes &key, const Bytes &member) { RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = srem_one(batch, key, member); if(ret >= 0){ if(ret > 0){ if(incr_ssize(batch, key, -ret) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } } return ret; } int SSDBImpl::scard(const Bytes &key, uint64_t *llen) { *llen = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); int s = GetSetMetaVal(meta_key, sv); if (1 == s){ *llen = sv.length; } return s; } int SSDBImpl::sismember(const Bytes &key, const Bytes &member) { SetMetaVal sv; std::string meta_key = encode_meta_key(key); int s = GetSetMetaVal(meta_key, sv); if (1 == s){ std::string hkey = encode_set_key(key, member, sv.version); s = GetSetItemValInternal(hkey); } return s; } int SSDBImpl::smembers(const Bytes &key, std::vector<std::string> &members) { members.clear(); const leveldb::Snapshot* snapshot = nullptr; SetMetaVal sv; int s; { RecordLock l(&mutex_record_, key.String()); std::string meta_key = encode_meta_key(key); s = GetSetMetaVal(meta_key, sv); if (s != 1){ return s; } snapshot = ldb->GetSnapshot(); } SnapshotPtr spl(ldb, snapshot); //auto release auto it = std::unique_ptr<SIterator>(sscan_internal(key, "", "", sv.version, -1, snapshot)); while (it->next()){ members.push_back(it->key); } return s; } int SSDBImpl::sunion_internal(const std::vector<Bytes> &keys, int offset, std::set<std::string> &members) { members.clear(); int size = (int)keys.size(); for (int i = offset; i < size; ++i) { const leveldb::Snapshot* snapshot = nullptr; SetMetaVal sv; { RecordLock l(&mutex_record_, keys[i].String()); std::string meta_key = encode_meta_key(keys[i]); int s = GetSetMetaVal(meta_key, sv); if (s == -1){ members.clear(); return -1; } else if (s == 0){ continue; } snapshot = ldb->GetSnapshot(); } SnapshotPtr spl(ldb, snapshot); //auto release auto it = std::unique_ptr<SIterator>(sscan_internal(keys[i], "", "", sv.version, -1, snapshot)); while (it->next()){ members.insert(it->key); } } return 1; } int SSDBImpl::sunion(const std::vector<Bytes> &keys, std::set<std::string> &members) { Transaction trans(binlogs);//TODO return sunion_internal(keys, 1, members); } int SSDBImpl::sunionstore(const Bytes &destination, const std::vector<Bytes> &keys, int64_t *num) { // RecordLock l(&mutex_record_, key.String());//TODO leveldb::WriteBatch batch; std::set<std::string> members; int ret = sunion_internal(keys, 2, members); if (ret == -1){ return -1; } ret = del_key_internal(batch, destination); if (ret < 0){ return ret; } *num = members.size(); std::set<std::string>::iterator it = members.begin(); std::string val; std::string meta_key = encode_meta_key(destination); leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &val); if(s.IsNotFound()){ for (; it != members.end(); ++it) { std::string hkey = encode_set_key(destination, *it); batch.Put(hkey, slice("")); } std::string size_val = encode_set_meta_val((uint64_t)(*num)); batch.Put(meta_key, size_val); } else if(s.ok()){ uint16_t version = *(uint16_t *)(val.c_str()+1); version = be16toh(version); if (version == UINT16_MAX){ version = 0; } else{ version += 1; } for (; it != members.end(); ++it) { std::string hkey = encode_set_key(destination, *it, version); batch.Put(hkey, slice("")); } std::string size_val = encode_set_meta_val((uint64_t)(*num), version); batch.Put(meta_key, size_val); } else if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return 1; }
// // Created by a1 on 16-11-21. // #include "ssdb_impl.h" int SSDBImpl::GetSetMetaVal(const std::string &meta_key, SetMetaVal &sv){ std::string meta_val; leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &meta_val); if (s.IsNotFound()){ return 0; } else if (!s.ok() && !s.IsNotFound()){ return -1; } else{ int ret = sv.DecodeMetaVal(meta_val); if (ret == -1){ return -1; } else if (sv.del == KEY_DELETE_MASK){ return 0; } else if (sv.type != DataType::SSIZE){ return -1; } } return 1; } int SSDBImpl::GetSetItemValInternal(const std::string &item_key){ std::string val; leveldb::Status s = ldb->Get(leveldb::ReadOptions(), item_key, &val); if (s.IsNotFound()){ return 0; } else if (!s.ok() && !s.IsNotFound()){ return -1; } return 1; } int SSDBImpl::sadd_one(leveldb::WriteBatch &batch, const Bytes &key, const Bytes &member) { int ret = 0; std::string dbval; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return -1; } else if (ret == 0 && sv.del == KEY_DELETE_MASK){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string hkey = encode_set_key(key, member, version); batch.Put(hkey, slice("")); ret = 1; } else if (ret == 0){ std::string hkey = encode_set_key(key, member); batch.Put(hkey, slice("")); ret = 1; } else{ std::string item_key = encode_set_key(key, member, sv.version); ret = GetSetItemValInternal(item_key); if (ret == -1){ return -1; } else if (ret == 1){ ret = 0; } else{ batch.Put(item_key, slice("")); ret = 1; } } return ret; } int SSDBImpl::srem_one(leveldb::WriteBatch &batch, const Bytes &key, const Bytes &member) { SetMetaVal sv; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (ret != 1){ return ret; } std::string hkey = encode_set_key(key, member, sv.version); ret = GetSetItemValInternal(hkey); if (ret != 1){ return ret; } batch.Delete(hkey); return 1; } int SSDBImpl::incr_ssize(leveldb::WriteBatch &batch, const Bytes &key, int64_t incr){ SetMetaVal sv; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return ret; } else if (ret == 0 && sv.del == KEY_DELETE_MASK){ if (incr > 0){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string size_val = encode_set_meta_val((uint64_t)incr, version); batch.Put(meta_key, size_val); } else{ return -1; } } else if (ret == 0){ if (incr > 0){ std::string size_val = encode_set_meta_val((uint64_t)incr); batch.Put(meta_key, size_val); } else{ return -1; } } else{ uint64_t len = sv.length; if (incr > 0) { len += incr; } else if (incr < 0) { uint64_t u64 = static_cast<uint64_t>(-incr); if (len < u64) { return -1; } len = len - u64; } if (len == 0){ std::string del_key = encode_delete_key(key, sv.version); std::string meta_val = encode_set_meta_val(sv.length, sv.version, KEY_DELETE_MASK); batch.Put(del_key, ""); batch.Put(meta_key, meta_val); this->edel_one(batch, key); //del expire ET key } else{ std::string size_val = encode_set_meta_val(len, sv.version); batch.Put(meta_key, size_val); } } return 0; } SIterator* SSDBImpl::sscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit, const leveldb::Snapshot *snapshot) { std::string key_start, key_end; key_start = encode_set_key(name, start, version); if(!end.empty()){ key_end = encode_set_key(name, end, version); } return new SIterator(this->iterator(key_start, key_end, limit, snapshot), name, version); } SIterator* SSDBImpl::sscan(const Bytes &key, const Bytes &start, const Bytes &end, uint64_t limit) { SetMetaVal sv; uint16_t version; std::string meta_key = encode_meta_key(key); int ret = GetSetMetaVal(meta_key, sv); if (0 == ret && sv.del == KEY_DELETE_MASK){ version = sv.version + (uint16_t)1; } else if (ret > 0){ version = sv.version; } else { version = 0; } return sscan_internal(key, start, end, version, limit, nullptr); } int SSDBImpl::sadd(const Bytes &key, const Bytes &member){ RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = sadd_one(batch, key, member); if (ret >= 0){ if(ret > 0){ if(incr_ssize(batch, key, ret) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } } return ret; } int SSDBImpl::saddNoLock(const Bytes &key, const std::set<Bytes> &mem_set, int64_t *num) { leveldb::WriteBatch batch; int ret = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret == -1){ return -1; } *num = 0; std::set<Bytes>::iterator it = mem_set.begin(); for (; it != mem_set.end(); ++it) { const Bytes& member= *it; int change = 0; if (ret == 0 && sv.del == KEY_DELETE_MASK){ uint16_t version; if (sv.version == UINT16_MAX){ version = 0; } else{ version = (uint16_t)(sv.version+1); } std::string hkey = encode_set_key(key, member, version); batch.Put(hkey, slice("")); change = 1; } else if (ret == 0){ std::string hkey = encode_set_key(key, member); batch.Put(hkey, slice("")); change = 1; } else{ std::string item_key = encode_set_key(key, member, sv.version); int s = GetSetItemValInternal(item_key); if (s == -1){ return -1; } else if (s == 1){ change = 0; } else{ batch.Put(item_key, slice("")); change = 1; } } *num += change; } if (*num > 0){ if(incr_ssize(batch, key, *num) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return 1; } int SSDBImpl::multi_sadd(const Bytes &key, const std::set<Bytes> &mem_set, int64_t *num) { RecordLock l(&mutex_record_, key.String()); return saddNoLock(key, mem_set, num); } int SSDBImpl::multi_srem(const Bytes &key, const std::vector<Bytes> &members, int64_t *num) { RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = 0; *num = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); ret = GetSetMetaVal(meta_key, sv); if (ret != 1){ return ret; } for (int i = 2; i < members.size(); ++i){ const Bytes& member= members[i]; std::string hkey = encode_set_key(key, member, sv.version); int s = GetSetItemValInternal(hkey); if (s == 1){ *num += 1; batch.Delete(hkey); } else if (s == -1){ return -1; } } if (*num > 0){ if(incr_ssize(batch, key, (-1)*(*num)) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return ret; } int SSDBImpl::srem(const Bytes &key, const Bytes &member) { RecordLock l(&mutex_record_, key.String()); leveldb::WriteBatch batch; int ret = srem_one(batch, key, member); if(ret >= 0){ if(ret > 0){ if(incr_ssize(batch, key, -ret) == -1){ return -1; } } leveldb::Status s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } } return ret; } int SSDBImpl::scard(const Bytes &key, uint64_t *llen) { *llen = 0; SetMetaVal sv; std::string meta_key = encode_meta_key(key); int s = GetSetMetaVal(meta_key, sv); if (1 == s){ *llen = sv.length; } return s; } int SSDBImpl::sismember(const Bytes &key, const Bytes &member) { SetMetaVal sv; std::string meta_key = encode_meta_key(key); int s = GetSetMetaVal(meta_key, sv); if (1 == s){ std::string hkey = encode_set_key(key, member, sv.version); s = GetSetItemValInternal(hkey); } return s; } int SSDBImpl::smembers(const Bytes &key, std::vector<std::string> &members) { members.clear(); const leveldb::Snapshot* snapshot = nullptr; SetMetaVal sv; int s; { RecordLock l(&mutex_record_, key.String()); std::string meta_key = encode_meta_key(key); s = GetSetMetaVal(meta_key, sv); if (s != 1){ return s; } snapshot = ldb->GetSnapshot(); } SnapshotPtr spl(ldb, snapshot); //auto release auto it = std::unique_ptr<SIterator>(sscan_internal(key, "", "", sv.version, -1, snapshot)); while (it->next()){ members.push_back(it->key); } return s; } int SSDBImpl::sunion_internal(const std::vector<Bytes> &keys, int offset, std::set<std::string> &members) { members.clear(); int size = (int)keys.size(); for (int i = offset; i < size; ++i) { const leveldb::Snapshot* snapshot = nullptr; SetMetaVal sv; { RecordLock l(&mutex_record_, keys[i].String()); std::string meta_key = encode_meta_key(keys[i]); int s = GetSetMetaVal(meta_key, sv); if (s == -1){ members.clear(); return -1; } else if (s == 0){ continue; } snapshot = ldb->GetSnapshot(); } SnapshotPtr spl(ldb, snapshot); //auto release auto it = std::unique_ptr<SIterator>(sscan_internal(keys[i], "", "", sv.version, -1, snapshot)); while (it->next()){ members.insert(it->key); } } return 1; } int SSDBImpl::sunion(const std::vector<Bytes> &keys, std::set<std::string> &members) { Transaction trans(binlogs);//TODO return sunion_internal(keys, 1, members); } int SSDBImpl::sunionstore(const Bytes &destination, const std::vector<Bytes> &keys, int64_t *num) { // RecordLock l(&mutex_record_, key.String());//TODO leveldb::WriteBatch batch; std::set<std::string> members; int ret = sunion_internal(keys, 2, members); if (ret == -1){ return -1; } ret = del_key_internal(batch, destination); if (ret < 0){ return ret; } *num = members.size(); if (*num == 0) { leveldb::Status ss = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!ss.ok()){ return -1; } return 1; } std::set<std::string>::iterator it = members.begin(); std::string val; std::string meta_key = encode_meta_key(destination); leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &val); if(s.IsNotFound()){ for (; it != members.end(); ++it) { std::string hkey = encode_set_key(destination, *it); batch.Put(hkey, slice("")); } std::string size_val = encode_set_meta_val((uint64_t)(*num)); batch.Put(meta_key, size_val); } else if(s.ok()){ uint16_t version = *(uint16_t *)(val.c_str()+1); version = be16toh(version); if (version == UINT16_MAX){ version = 0; } else{ version += 1; } for (; it != members.end(); ++it) { std::string hkey = encode_set_key(destination, *it, version); batch.Put(hkey, slice("")); } std::string size_val = encode_set_meta_val((uint64_t)(*num), version); batch.Put(meta_key, size_val); } else if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } s = ldb->Write(leveldb::WriteOptions(), &(batch)); if(!s.ok()){ return -1; } return 1; }
修改sunionstore 接口
修改sunionstore 接口
C++
bsd-2-clause
JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb,JRHZRD/swapdb
5f08c86930554c68836c7d0089c11b5d19a22304
src/gnoproj.hpp
src/gnoproj.hpp
/* * gnoproj * * Copyright (c) 2013-2014 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * * Author(s): * * Stéphane Flotron <[email protected]> * * Contributor(s): * * Luc Deschenaux <[email protected]> * * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ #ifndef GNOPROJ_HPP_ #define GNOPROJ_HPP_ #include <iostream> #include <elphelphg/cameraArray.hpp> #include <elphelphg/camera.hpp> #include <elphelphg/channel.hpp> #include <elphelphg/file.hpp> #include <elphelphg/xml.hpp> #include <elphelphg/eqrData.hpp> #include <elphelphg/sensorData.hpp> #include <elphelphg/utils.hpp> #include <iomanip> #include <gnomonic-all.h> #include <inter-all.h> #include <ctype.h> #include <unistd.h> #include <string.h> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv/cv.h> #include <opencv/highgui.h> #define DEBUG 0 #endif /* GNOPROJ_HPP_ */
/* * gnoproj * * Copyright (c) 2013-2014 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * * Author(s): * * Stéphane Flotron <[email protected]> * * Contributor(s): * * Luc Deschenaux <[email protected]> * * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ #ifndef GNOPROJ_HPP_ #define GNOPROJ_HPP_ #include <iostream> #include <elphelphg/cameraArray.hpp> #include <elphelphg/camera.hpp> #include <elphelphg/channel.hpp> #include <elphelphg/file.hpp> #include <elphelphg/xml.hpp> #include <elphelphg/eqrData.hpp> #include <elphelphg/sensorData.hpp> #include <elphelphg/utils.hpp> #include <iomanip> #include <gnomonic-all.h> #include <inter-all.h> #include <ctype.h> #include <unistd.h> #include <string.h> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgcodecs/imgcodecs_c.h> #include <opencv/cv.h> #include <opencv/highgui.h> #define DEBUG 0 #endif /* GNOPROJ_HPP_ */
add include for opencv backward compatibility
add include for opencv backward compatibility
C++
agpl-3.0
FoxelSA/gnoproj,FoxelSA/gnoproj
e471a3055ec22823c9d46edb40277faaa1111427
src/i2c/i2c.cxx
src/i2c/i2c.cxx
/* * Copyright (C) Intel Corporation. * * Author: Brendan Le Foll * * Copyright © 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "i2c.h" #include "smbus.h" using namespace maa; I2C::I2C(unsigned int sda, unsigned int scl) { // Galileo only has one I2C device which is always /dev/i2c-0 // reliability is a fickle friend! if (i2c_handle = open("/dev/i2c-0", O_RDWR) < 1) { fprintf(stderr, "Failed to open requested i2c port"); } } void I2C::frequency(int hz) { _hz = hz; } int I2C::read(int address, char *data, int length, bool repeated) { return 0; } int I2C::read(int ack) { int byte; if (byte = i2c_smbus_read_byte(i2c_handle) < 0) { return -1; } return byte; } int I2C::write(int address, const char *data, int length, bool repeated) { if (i2c_smbus_write_i2c_block_data(i2c_handle, data[0], length, (uint8_t*) data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } int I2C::write(int data) { if (i2c_smbus_write_byte(i2c_handle, data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } void I2C::start() { } void I2C::stop() { } void I2C::aquire() { }
/* * Copyright (C) Intel Corporation. * * Author: Brendan Le Foll * * Copyright © 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "i2c.h" using namespace maa; I2C::I2C(unsigned int sda, unsigned int scl) { // Galileo only has one I2C device which is always /dev/i2c-0 // reliability is a fickle friend! if (i2c_handle = open("/dev/i2c-0", O_RDWR) < 1) { fprintf(stderr, "Failed to open requested i2c port"); } } void I2C::frequency(int hz) { _hz = hz; } int I2C::read(int address, char *data, int length, bool repeated) { return 0; } int I2C::read(int ack) { int byte; if (byte = i2c_smbus_read_byte(i2c_handle) < 0) { return -1; } return byte; } int I2C::write(int address, const char *data, int length, bool repeated) { if (i2c_smbus_write_i2c_block_data(i2c_handle, data[0], length, (uint8_t*) data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } int I2C::write(int data) { if (i2c_smbus_write_byte(i2c_handle, data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } void I2C::start() { } void I2C::stop() { } void I2C::aquire() { }
remove unecessary include
i2c.cxx: remove unecessary include Signed-off-by: Brendan Le Foll <[email protected]>
C++
mit
arunlee77/mraa,Pillar1989/mraa,yongli3/mraa,spitfire88/mraa,pctj101/mraa,stefan-andritoiu/mraa,allela-roy/mraa,yoyojacky/mraa,tripzero/mraa,yongli3/mraa,intel-iot-devkit/mraa,g-vidal/mraa,yongli3/mraa,nioinnovation/mraa,malikabhi05/mraa,noahchense/mraa,allela-roy/mraa,ProfFan/mraa,smileboywtu/mraa,Kiritoalex/mraa,arfoll/mraa,yongli3/mraa,timrtoo/Intel,Kiritoalex/mraa,KurtE/mraa,Pillar1989/mraa,pctj101/mraa,Meirtz/mraa,arunlee77/mraa,nioinnovation/mraa,andreivasiliu2211/mraa,smileboywtu/mraa,ncrastanaren/mraa,stefan-andritoiu/mraa-gpio-chardev,sergev/mraa,jontrulson/mraa,Propanu/mraa,STANAPO/mraa,SyrianSpock/mraa,petreeftime/mraa,whbruce/mraa,Propanu/mraa,neuberfran/mraa,damcclos/mraa,whbruce/mraa,malikabhi05/mraa,stefan-andritoiu/mraa,stefan-andritoiu/mraa,jontrulson/mraa,yangjae/mraa,alexandru-elisei/mraa,sundw2014/mraa,alext-mkrs/mraa,Propanu/mraa,malikabhi05/mraa,andreivasiliu2211/mraa,KurtE/mraa,g-vidal/mraa,Meirtz/mraa,yangjae/mraa,g-vidal/mraa,Jon-ICS/mraa,sergev/mraa,anonymouse64/mraa,noahchense/mraa,alex1818/mraa,w4ilun/mraa,alext-mkrs/mraa,malikabhi05/mraa,Propanu/mraa,anonymouse64/mraa,ProfFan/mraa,intel-iot-devkit/mraa,seem-sky/mraa,Hbrinj/mraa,matt-auld/mraa,noahchense/mraa,pctj101/mraa,Propanu/mraa,zBMNForks/mraa,STANAPO/mraa,neuroidss/mraa,KurtE/mraa,mircea/mraa,intel-iot-devkit/mraa,neuberfran/mraa,timrtoo/Intel,smileboywtu/mraa,timrtoo/Intel,anonymouse64/mraa,arunlee77/mraa,neuberfran/mraa,Pillar1989/mraa,w4ilun/mraa,Hbrinj/mraa,yoyojacky/mraa,petreeftime/mraa,seem-sky/mraa,neuroidss/mraa,alexandru-elisei/mraa,alext-mkrs/mraa,sundw2014/mraa,sergev/mraa,arfoll/mraa,Hbrinj/mraa,stefan-andritoiu/mraa,w4ilun/mraa,Kiritoalex/mraa,SyrianSpock/mraa,whbruce/mraa,ProfFan/mraa,ncrastanaren/mraa,stefan-andritoiu/mraa-gpio-chardev,arfoll/mraa,alext-mkrs/mraa,jontrulson/mraa,pctj101/mraa,timrtoo/Intel,damcclos/mraa,w4ilun/mraa,intel-iot-devkit/mraa,yangjae/mraa,seem-sky/mraa,g-vidal/mraa,arfoll/mraa,KurtE/mraa,sundw2014/mraa,timrtoo/Intel,yoyojacky/mraa,intel-iot-devkit/mraa,ncrastanaren/mraa,sergev/mraa,seem-sky/mraa,alex1818/mraa,noahchense/mraa,spitfire88/mraa,Jon-ICS/mraa,matt-auld/mraa,alexandru-elisei/mraa,yangjae/mraa,sergev/mraa,stefan-andritoiu/mraa-gpio-chardev,allela-roy/mraa,tripzero/mraa,nioinnovation/mraa,Meirtz/mraa,SyrianSpock/mraa,alext-mkrs/mraa,spitfire88/mraa,damcclos/mraa,ncrastanaren/mraa,mircea/mraa,petreeftime/mraa,andreivasiliu2211/mraa,alex1818/mraa,matt-auld/mraa,stefan-andritoiu/mraa-gpio-chardev,ProfFan/mraa,sundw2014/mraa,yongli3/mraa,Jon-ICS/mraa,whbruce/mraa,arfoll/mraa,zBMNForks/mraa,neuberfran/mraa,jontrulson/mraa,pctj101/mraa,stefan-andritoiu/mraa,g-vidal/mraa,alexandru-elisei/mraa,Hbrinj/mraa,mircea/mraa,zBMNForks/mraa,noahchense/mraa,sundw2014/mraa,andreivasiliu2211/mraa,alexandru-elisei/mraa,neuroidss/mraa,KurtE/mraa,neuberfran/mraa,spitfire88/mraa,arunlee77/mraa,seem-sky/mraa,tripzero/mraa,STANAPO/mraa,petreeftime/mraa,ncrastanaren/mraa,stefan-andritoiu/mraa-gpio-chardev,malikabhi05/mraa,jontrulson/mraa
01c72674a4db50f61e783e3934f0e29ad5eb2d23
src/python.cc
src/python.cc
/* * python.cc * * This python module lets us easily test libchecksieve using python. The * 'test' target will automatically compile this against libchecksieve.a */ #include <Python.h> #include "checksieve.h" #include "sieve_driver.hh" static PyObject *parse_string(PyObject *self, PyObject *args) { const char *sieve; PyObject *quiet; if (!PyArg_ParseTuple(args, "sO:parse_string", &sieve, &quiet)) return NULL; sieve::driver driver(PyObject_IsTrue(quiet)); return Py_BuildValue("i", driver.parse_string(sieve)); } static PyMethodDef checksieve_methods[] = { {"parse_string", parse_string, METH_VARARGS, "guhhh"}, {NULL, NULL} }; PyMODINIT_FUNC initchecksieve(void) { Py_InitModule3( "checksieve", checksieve_methods, "syntax-check a sieve"); }
/* * python.cc * * This python module lets us easily test libchecksieve using python. The * 'test' target will automatically compile this against libchecksieve.a */ #include <Python.h> #include "checksieve.h" #include "sieve_driver.hh" static PyObject *parse_string(PyObject *, PyObject *); static PyMethodDef checksieve_methods[] = { {"parse_string", parse_string, METH_VARARGS, "guhhh"}, {NULL, NULL} }; #define PY_MODNAME "checksieve" #define PY_MODDESC "syntax-check a mail sieve" #if PY_MAJOR_VERSION >= 3 #define PY_MODINIT(name) PyMODINIT_FUNC PyInit_##name(void) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, PY_MODNAME, PY_MODDESC, -1, checksieve_methods, NULL, NULL, NULL, NULL, }; #define PY_MODCREATE() PyModule_Create(&moduledef) #else #define PY_MODINIT(name) PyMODINIT_FUNC init##name(void) #define PY_MODCREATE() Py_InitModule3( PY_MODNAME, checksieve_methods, PY_MODDESC ) #endif // PY_MAJOR_VERSION >= 3 static PyObject *parse_string(PyObject *self, PyObject *args) { const char *sieve; PyObject *quiet; if (!PyArg_ParseTuple(args, "sO:parse_string", &sieve, &quiet)) return NULL; sieve::driver driver(PyObject_IsTrue(quiet)); return Py_BuildValue("i", driver.parse_string(sieve)); } PY_MODINIT(checksieve) { PY_MODCREATE(); }
Add support for python 3 in unit test C extension.
Add support for python 3 in unit test C extension.
C++
mit
dburkart/check-sieve,dburkart/check-sieve,dburkart/mail-sieve-verifier,dburkart/mail-sieve-verifier,dburkart/check-sieve
c6226c43d7f3e52550f1bb7e0be581dead7d357e
src/iterator.cc
src/iterator.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "libforestdb/forestdb.h" #include "hbtrie.h" #include "docio.h" #include "btreeblock.h" #include "common.h" #include "wal.h" #include "avltree.h" #include "list.h" #include "memleak.h" #ifdef __DEBUG #ifndef __DEBUG_FDB #undef DBG #undef DBGCMD #undef DBGSW #define DBG(...) #define DBGCMD(...) #define DBGSW(n, ...) #endif #endif struct iterator_wal_entry{ void *key; wal_item_action action; uint16_t keylen; uint64_t offset; struct avl_node avl; }; // lexicographically compares two variable-length binary streams int _fdb_keycmp(void *key1, size_t keylen1, void *key2, size_t keylen2) { if (keylen1 == keylen2) { return memcmp(key1, key2, keylen1); }else { size_t len = MIN(keylen1, keylen2); int cmp = memcmp(key1, key2, len); if (cmp != 0) return cmp; else { return (int)((int)keylen1 - (int)keylen2); } } } int _fdb_wal_cmp(struct avl_node *a, struct avl_node *b, void *aux) { struct iterator_wal_entry *aa, *bb; aa = _get_entry(a, struct iterator_wal_entry, avl); bb = _get_entry(b, struct iterator_wal_entry, avl); if (aux) { // custom compare function fdb_custom_cmp func = (fdb_custom_cmp)aux; return func(aa->key, bb->key); } else { return _fdb_keycmp(aa->key, aa->keylen, bb->key, bb->keylen); } } fdb_status fdb_iterator_init(fdb_handle *handle, fdb_iterator *iterator, const void *start_key, size_t start_keylen, const void *end_key, size_t end_keylen, fdb_iterator_opt_t opt) { int cmp; hbtrie_result hr; struct list_elem *e; struct wal_item *wal_item; struct iterator_wal_entry *snap_item; if (handle == NULL || iterator == NULL) { return FDB_RESULT_INVALID_ARGS; } iterator->handle = *handle; iterator->hbtrie_iterator = (struct hbtrie_iterator *)malloc(sizeof(struct hbtrie_iterator)); iterator->opt = opt; iterator->_key = (void*)malloc(FDB_MAX_KEYLEN); iterator->_keylen = 0; iterator->_offset = BLK_NOT_FOUND; if (start_key == NULL) start_keylen = 0; if (end_key == NULL) { iterator->end_key = NULL; end_keylen = 0; }else{ iterator->end_key = (void*)malloc(end_keylen); memcpy(iterator->end_key, end_key, end_keylen); } iterator->end_keylen = end_keylen; // create an iterator handle for hb-trie hr = hbtrie_iterator_init(handle->trie, iterator->hbtrie_iterator, (void *)start_key, start_keylen); if (hr == HBTRIE_RESULT_FAIL) return FDB_RESULT_FAIL; // create a snapshot for WAL (avl-tree) // (from the beginning to the last committed element) // init tree iterator->wal_tree = (struct avl_tree*)malloc(sizeof(struct avl_tree)); avl_init(iterator->wal_tree, (void*)(handle->cmp_func)); spin_lock(&handle->file->wal->lock); e = list_begin(&handle->file->wal->list); while(e) { wal_item = _get_entry(e, struct wal_item, list_elem); if (start_key) { if (handle->cmp_func) { // custom compare function cmp = handle->cmp_func((void *)start_key, wal_item->key); } else { cmp = _fdb_keycmp((void *)start_key, start_keylen, wal_item->key, wal_item->keylen); } }else{ cmp = 0; } if (cmp <= 0) { // copy from WAL_ITEM snap_item = (struct iterator_wal_entry*)malloc(sizeof(struct iterator_wal_entry)); snap_item->keylen = wal_item->keylen; snap_item->key = (void*)malloc(snap_item->keylen); memcpy(snap_item->key, wal_item->key, snap_item->keylen); snap_item->action = wal_item->action; snap_item->offset = wal_item->offset; // insert into tree avl_insert(iterator->wal_tree, &snap_item->avl, _fdb_wal_cmp); } if (e == handle->file->wal->last_commit) break; e = list_next(e); } iterator->tree_cursor = avl_first(iterator->wal_tree); spin_unlock(&handle->file->wal->lock); return FDB_RESULT_SUCCESS; } // DOC returned by this function must be freed using 'fdb_doc_free' fdb_status fdb_iterator_next_offset(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { int cmp; void *key; size_t keylen; uint64_t offset; hbtrie_result hr = HBTRIE_RESULT_SUCCESS; fdb_status fs; struct docio_object _doc; struct iterator_wal_entry *snap_item = NULL; start: key = iterator->_key; // retrieve from hb-trie if (iterator->_offset == BLK_NOT_FOUND) { // no key waiting for being returned // get next key from hb-trie hr = hbtrie_next( iterator->hbtrie_iterator, key, &iterator->_keylen, (void*)&iterator->_offset); btreeblk_end(iterator->handle.bhandle); } keylen = iterator->_keylen; offset = iterator->_offset; if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_FAIL; } while (iterator->tree_cursor) { // get the current item of rb-tree snap_item = _get_entry(iterator->tree_cursor, struct iterator_wal_entry, avl); if (hr != HBTRIE_RESULT_FAIL) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(snap_item->key, key); } else { cmp = _fdb_keycmp(snap_item->key, snap_item->keylen, key, keylen); } }else{ // no more docs in hb-trie cmp = -1; } if (cmp <= 0) { // key[WAL] <= key[hb-trie] .. take key[WAL] first iterator->tree_cursor = avl_next(iterator->tree_cursor); if (cmp < 0) { if (snap_item->action == WAL_ACT_REMOVE) { // this key is removed .. get next key[WAL] continue; } }else{ iterator->_offset = BLK_NOT_FOUND; if (snap_item->action == WAL_ACT_REMOVE) { // the key is removed .. start over again goto start; } } key = snap_item->key; keylen = snap_item->keylen; offset = snap_item->offset; } break; } if (offset == iterator->_offset) { // take key[hb-trie] & and fetch the next key[hb-trie] at next turn iterator->_offset = BLK_NOT_FOUND; } if (iterator->end_key) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(iterator->end_key, key); } else { cmp = _fdb_keycmp(iterator->end_key, iterator->end_keylen, key, keylen); } if (cmp < 0) { // current key (KEY) is lexicographically greater than END_KEY // terminate the iteration return FDB_RESULT_FAIL; } } if (doc_offset_out) *doc_offset_out = offset; _doc.key = key; _doc.length.keylen = keylen; _doc.meta = NULL; _doc.body = NULL; if (iterator->opt == FDB_ITR_METAONLY) { docio_read_doc_key_meta(iterator->handle.dhandle, offset, &_doc); }else{ docio_read_doc(iterator->handle.dhandle, offset, &_doc); } fs = fdb_doc_create(doc, key, keylen, NULL, 0, NULL, 0); if (fs == FDB_RESULT_FAIL) { return FDB_RESULT_INVALID_ARGS; } (*doc)->meta = _doc.meta; (*doc)->metalen = _doc.length.metalen; if (iterator->opt != FDB_ITR_METAONLY) { (*doc)->body = _doc.body; (*doc)->bodylen = _doc.length.bodylen; } return FDB_RESULT_SUCCESS; } fdb_status fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc) { return fdb_iterator_next_offset(iterator, doc, NULL); } fdb_status fdb_iterator_close(fdb_iterator *iterator) { hbtrie_result hr; struct avl_node *a; struct iterator_wal_entry *snap_item; hr = hbtrie_iterator_free(iterator->hbtrie_iterator); free(iterator->hbtrie_iterator); if (iterator->end_key) free(iterator->end_key); a = avl_first(iterator->wal_tree); while(a) { snap_item = _get_entry(a, struct iterator_wal_entry, avl); a = avl_next(a); avl_remove(iterator->wal_tree, &snap_item->avl); free(snap_item->key); free(snap_item); } free(iterator->wal_tree); free(iterator->_key); return FDB_RESULT_SUCCESS; }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "libforestdb/forestdb.h" #include "hbtrie.h" #include "docio.h" #include "btreeblock.h" #include "common.h" #include "wal.h" #include "avltree.h" #include "list.h" #include "memleak.h" #ifdef __DEBUG #ifndef __DEBUG_FDB #undef DBG #undef DBGCMD #undef DBGSW #define DBG(...) #define DBGCMD(...) #define DBGSW(n, ...) #endif #endif struct iterator_wal_entry{ void *key; wal_item_action action; uint16_t keylen; uint64_t offset; struct avl_node avl; }; // lexicographically compares two variable-length binary streams int _fdb_keycmp(void *key1, size_t keylen1, void *key2, size_t keylen2) { if (keylen1 == keylen2) { return memcmp(key1, key2, keylen1); }else { size_t len = MIN(keylen1, keylen2); int cmp = memcmp(key1, key2, len); if (cmp != 0) return cmp; else { return (int)((int)keylen1 - (int)keylen2); } } } int _fdb_wal_cmp(struct avl_node *a, struct avl_node *b, void *aux) { struct iterator_wal_entry *aa, *bb; aa = _get_entry(a, struct iterator_wal_entry, avl); bb = _get_entry(b, struct iterator_wal_entry, avl); if (aux) { // custom compare function fdb_custom_cmp func = (fdb_custom_cmp)aux; return func(aa->key, bb->key); } else { return _fdb_keycmp(aa->key, aa->keylen, bb->key, bb->keylen); } } fdb_status fdb_iterator_init(fdb_handle *handle, fdb_iterator *iterator, const void *start_key, size_t start_keylen, const void *end_key, size_t end_keylen, fdb_iterator_opt_t opt) { int cmp; hbtrie_result hr; struct list_elem *e; struct wal_item *wal_item; struct iterator_wal_entry *snap_item; if (handle == NULL || iterator == NULL) { return FDB_RESULT_INVALID_ARGS; } iterator->handle = *handle; iterator->hbtrie_iterator = (struct hbtrie_iterator *)malloc(sizeof(struct hbtrie_iterator)); iterator->opt = opt; iterator->_key = (void*)malloc(FDB_MAX_KEYLEN); iterator->_keylen = 0; iterator->_offset = BLK_NOT_FOUND; if (start_key == NULL) start_keylen = 0; if (end_key == NULL) { iterator->end_key = NULL; end_keylen = 0; }else{ iterator->end_key = (void*)malloc(end_keylen); memcpy(iterator->end_key, end_key, end_keylen); } iterator->end_keylen = end_keylen; // create an iterator handle for hb-trie hr = hbtrie_iterator_init(handle->trie, iterator->hbtrie_iterator, (void *)start_key, start_keylen); if (hr == HBTRIE_RESULT_FAIL) return FDB_RESULT_FAIL; // create a snapshot for WAL (avl-tree) // (from the beginning to the last committed element) // init tree iterator->wal_tree = (struct avl_tree*)malloc(sizeof(struct avl_tree)); avl_init(iterator->wal_tree, (void*)(handle->cmp_func)); spin_lock(&handle->file->wal->lock); e = list_begin(&handle->file->wal->list); while(e) { wal_item = _get_entry(e, struct wal_item, list_elem); if (start_key) { if (handle->cmp_func) { // custom compare function cmp = handle->cmp_func((void *)start_key, wal_item->key); } else { cmp = _fdb_keycmp((void *)start_key, start_keylen, wal_item->key, wal_item->keylen); } }else{ cmp = 0; } if (cmp <= 0) { // copy from WAL_ITEM snap_item = (struct iterator_wal_entry*)malloc(sizeof(struct iterator_wal_entry)); snap_item->keylen = wal_item->keylen; snap_item->key = (void*)malloc(snap_item->keylen); memcpy(snap_item->key, wal_item->key, snap_item->keylen); snap_item->action = wal_item->action; snap_item->offset = wal_item->offset; // insert into tree avl_insert(iterator->wal_tree, &snap_item->avl, _fdb_wal_cmp); } if (e == handle->file->wal->last_commit) break; e = list_next(e); } iterator->tree_cursor = avl_first(iterator->wal_tree); spin_unlock(&handle->file->wal->lock); return FDB_RESULT_SUCCESS; } // DOC returned by this function must be freed using 'fdb_doc_free' fdb_status fdb_iterator_next_offset(fdb_iterator *iterator, fdb_doc **doc, uint64_t *doc_offset_out) { int cmp; void *key; size_t keylen; uint64_t offset; hbtrie_result hr = HBTRIE_RESULT_SUCCESS; fdb_status fs; struct docio_object _doc; struct iterator_wal_entry *snap_item = NULL; start: key = iterator->_key; // retrieve from hb-trie if (iterator->_offset == BLK_NOT_FOUND) { // no key waiting for being returned // get next key from hb-trie hr = hbtrie_next( iterator->hbtrie_iterator, key, &iterator->_keylen, (void*)&iterator->_offset); btreeblk_end(iterator->handle.bhandle); } keylen = iterator->_keylen; offset = iterator->_offset; if (hr == HBTRIE_RESULT_FAIL && iterator->tree_cursor == NULL) { return FDB_RESULT_FAIL; } while (iterator->tree_cursor) { // get the current item of rb-tree snap_item = _get_entry(iterator->tree_cursor, struct iterator_wal_entry, avl); if (hr != HBTRIE_RESULT_FAIL) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(snap_item->key, key); } else { cmp = _fdb_keycmp(snap_item->key, snap_item->keylen, key, keylen); } }else{ // no more docs in hb-trie cmp = -1; } if (cmp <= 0) { // key[WAL] <= key[hb-trie] .. take key[WAL] first iterator->tree_cursor = avl_next(iterator->tree_cursor); if (cmp < 0) { if (snap_item->action == WAL_ACT_REMOVE) { // this key is removed .. get next key[WAL] continue; } }else{ iterator->_offset = BLK_NOT_FOUND; if (snap_item->action == WAL_ACT_REMOVE) { // the key is removed .. start over again goto start; } } key = snap_item->key; keylen = snap_item->keylen; offset = snap_item->offset; } break; } if (offset == iterator->_offset) { // take key[hb-trie] & and fetch the next key[hb-trie] at next turn iterator->_offset = BLK_NOT_FOUND; } if (iterator->end_key) { if (iterator->handle.cmp_func) { // custom compare function cmp = iterator->handle.cmp_func(iterator->end_key, key); } else { cmp = _fdb_keycmp(iterator->end_key, iterator->end_keylen, key, keylen); } if (cmp < 0) { // current key (KEY) is lexicographically greater than END_KEY // terminate the iteration return FDB_RESULT_FAIL; } } if (doc_offset_out) *doc_offset_out = offset; _doc.key = key; _doc.length.keylen = keylen; _doc.meta = NULL; _doc.body = NULL; if (iterator->opt == FDB_ITR_METAONLY) { docio_read_doc_key_meta(iterator->handle.dhandle, offset, &_doc); }else{ docio_read_doc(iterator->handle.dhandle, offset, &_doc); } fs = fdb_doc_create(doc, key, keylen, NULL, 0, NULL, 0); if (fs == FDB_RESULT_FAIL) { return FDB_RESULT_INVALID_ARGS; } (*doc)->meta = _doc.meta; (*doc)->metalen = _doc.length.metalen; if (iterator->opt != FDB_ITR_METAONLY) { (*doc)->body = _doc.body; (*doc)->bodylen = _doc.length.bodylen; } #ifdef __FDB_SEQTREE (*doc)->seqnum = _doc.seqnum; #endif return FDB_RESULT_SUCCESS; } fdb_status fdb_iterator_next(fdb_iterator *iterator, fdb_doc **doc) { return fdb_iterator_next_offset(iterator, doc, NULL); } fdb_status fdb_iterator_close(fdb_iterator *iterator) { hbtrie_result hr; struct avl_node *a; struct iterator_wal_entry *snap_item; hr = hbtrie_iterator_free(iterator->hbtrie_iterator); free(iterator->hbtrie_iterator); if (iterator->end_key) free(iterator->end_key); a = avl_first(iterator->wal_tree); while(a) { snap_item = _get_entry(a, struct iterator_wal_entry, avl); a = avl_next(a); avl_remove(iterator->wal_tree, &snap_item->avl); free(snap_item->key); free(snap_item); } free(iterator->wal_tree); free(iterator->_key); return FDB_RESULT_SUCCESS; }
return seqnum in fdb_iterator_next
MB-10676: return seqnum in fdb_iterator_next Change-Id: I7d5ee7af37face7ed5e13402b14c02f0a7ce5651
C++
apache-2.0
nvoron23/forestdb,joliss/forestdb,sushmaad/forestdb,uvenum/forestdb,wurikiji/forestdb,nvoron23/forestdb,seem-sky/forestdb,sushmaad/forestdb,couchbase/forestdb,jinxuan/forestdb,hisundar/forestdb,seem-sky/forestdb,yyangpan/forestdb,jinxuan/forestdb,joliss/forestdb,yyangpan/forestdb,wurikiji/forestdb,zhaog/forestdb,hisundar/forestdb,zhaog/forestdb,couchbase/forestdb,uvenum/forestdb
80c89a8f1cc039b82457285ecb4566a60aec2505
common/cmt_io.hpp
common/cmt_io.hpp
#pragma once //=====================================================================// /*! @file @brief RX62N, RX621, RX63T, RX64M グループ・CMT I/O 制御 @n Copyright 2013 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief CMT I/O クラス @param[in] CMT チャネルクラス @param[in] TASK タイマー動作クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CMT, class TASK> class cmt_io { uint32_t clock_; uint8_t level_; void sleep_() const { asm("nop"); } static TASK task_; static volatile uint32_t counter_; static INTERRUPT_FUNC void cmt_task_() { ++counter_; task_(); switch(CMT::get_chanel()) { case 0: ICU::IR.CMI0 = 0; break; case 1: ICU::IR.CMI1 = 0; break; case 2: /// ICU::IR.CMI2 = 0; break; case 3: /// ICU::IR.CMI3 = 0; break; } } void set_vector_(ICU::VECTOR vec) { set_interrupt_task(cmt_task_, static_cast<uint32_t>(vec)); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// cmt_io() : clock_(0), level_(0) { } //-----------------------------------------------------------------// /*! @brief ベースクロックの設定 @param[in] clock ベース周波数 */ //-----------------------------------------------------------------// void set_clock(uint32_t clock) { clock_ = clock; } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] freq タイマー周波数 @param[in] level 割り込みレベル @return レンジオーバーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint32_t freq, uint8_t level) { level_ = level; if(freq == 0 || clock_ == 0) return false; uint32_t cmcor = clock_ / freq / 8; uint8_t cks = 0; while(cmcor > 65536) { cmcor >>= 2; ++cks; } if(cks > 3 || cmcor == 0) { return false; } power_cfg::turn(CMT::get_peripheral()); auto chanel = CMT::get_chanel(); switch(chanel) { case 0: set_vector_(ICU::VECTOR::CMI0); CMT::CMSTR0.STR0 = 0; break; case 1: set_vector_(ICU::VECTOR::CMI1); CMT::CMSTR0.STR1 = 0; break; case 2: // set_vector_(ICU::VECTOR::CMI2); CMT::CMSTR1.STR2 = 0; break; case 3: // set_vector_(ICU::VECTOR::CMI3); CMT::CMSTR1.STR3 = 0; break; } icu_mgr::set_level(CMT::get_peripheral(), level_); CMT::CMCR = CMT::CMCR.CMIE.b() | CMT::CMCR.CKS.b(cks); CMT::CMCOR = cmcor - 1; switch(chanel) { case 0: CMT::CMSTR0.STR0 = 1; break; case 1: CMT::CMSTR0.STR1 = 1; break; case 2: CMT::CMSTR1.STR2 = 1; break; case 3: CMT::CMSTR1.STR3 = 1; break; } return true; } //-----------------------------------------------------------------// /*! @brief 割り込みと同期 */ //-----------------------------------------------------------------// void sync() const { volatile uint32_t cnt = counter_; while(cnt == counter_) sleep_(); } //-----------------------------------------------------------------// /*! @brief 割り込みカウンターの値を取得 */ //-----------------------------------------------------------------// uint32_t get_count() const { return counter_; } //-----------------------------------------------------------------// /*! @brief CMT カウンターの値を取得 */ //-----------------------------------------------------------------// uint16_t get_cmt_count() const { return CMT::CMCNT(); } }; template <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0; }
#pragma once //=====================================================================// /*! @file @brief RX62N, RX621, RX63T, RX64M グループ・CMT I/O 制御 @n Copyright 2013 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief CMT I/O クラス @param[in] CMT チャネルクラス @param[in] TASK タイマー動作クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CMT, class TASK> class cmt_io { uint32_t clock_; uint8_t level_; void sleep_() const { asm("nop"); } static TASK task_; static volatile uint32_t counter_; static INTERRUPT_FUNC void cmt_task_() { ++counter_; task_(); switch(CMT::get_chanel()) { case 0: // ICU::IR.CMI0 = 0; break; case 1: // ICU::IR.CMI1 = 0; break; case 2: /// ICU::IR.CMI2 = 0; break; case 3: /// ICU::IR.CMI3 = 0; break; } } void set_vector_(ICU::VECTOR vec) { set_interrupt_task(cmt_task_, static_cast<uint32_t>(vec)); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// cmt_io() : clock_(0), level_(0) { } //-----------------------------------------------------------------// /*! @brief ベースクロックの設定 @param[in] clock ベース周波数 */ //-----------------------------------------------------------------// void set_clock(uint32_t clock) { clock_ = clock; } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] freq タイマー周波数 @param[in] level 割り込みレベル @return レンジオーバーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint32_t freq, uint8_t level) { level_ = level; if(freq == 0 || clock_ == 0) return false; uint32_t cmcor = clock_ / freq / 8; uint8_t cks = 0; while(cmcor > 65536) { cmcor >>= 2; ++cks; } if(cks > 3 || cmcor == 0) { return false; } power_cfg::turn(CMT::get_peripheral()); auto chanel = CMT::get_chanel(); switch(chanel) { case 0: set_vector_(ICU::VECTOR::CMI0); CMT::CMSTR0.STR0 = 0; break; case 1: set_vector_(ICU::VECTOR::CMI1); CMT::CMSTR0.STR1 = 0; break; case 2: // set_vector_(ICU::VECTOR::CMI2); CMT::CMSTR1.STR2 = 0; break; case 3: // set_vector_(ICU::VECTOR::CMI3); CMT::CMSTR1.STR3 = 0; break; } if(level_) { CMT::CMCR = CMT::CMCR.CMIE.b() | CMT::CMCR.CKS.b(cks); } else { CMT::CMCR = CMT::CMCR.CKS.b(cks); } CMT::CMCOR = cmcor - 1; icu_mgr::set_level(CMT::get_peripheral(), level_); switch(chanel) { case 0: CMT::CMSTR0.STR0 = 1; break; case 1: CMT::CMSTR0.STR1 = 1; break; case 2: CMT::CMSTR1.STR2 = 1; break; case 3: CMT::CMSTR1.STR3 = 1; break; } return true; } //-----------------------------------------------------------------// /*! @brief 割り込みと同期 */ //-----------------------------------------------------------------// void sync() const { volatile uint32_t cnt = counter_; while(cnt == counter_) sleep_(); } //-----------------------------------------------------------------// /*! @brief 割り込みカウンターの値を取得 */ //-----------------------------------------------------------------// uint32_t get_count() const { return counter_; } //-----------------------------------------------------------------// /*! @brief CMT カウンターの値を取得 */ //-----------------------------------------------------------------// uint16_t get_cmt_count() const { return CMT::CMCNT(); } }; template <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0; }
update interrupt handling
update interrupt handling
C++
bsd-3-clause
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
d5fc8c2a9ac0e9750afd49b7d14cd00f4c4a41e0
Core/Code/Interactions/mitkDisplayPositionEvent.cpp
Core/Code/Interactions/mitkDisplayPositionEvent.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkDisplayPositionEvent.h" #include "mitkBaseRenderer.h" mitk::DisplayPositionEvent::DisplayPositionEvent( mitk::BaseRenderer *sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition ) : Event( sender, type, button, buttonState, key ), m_DisplayPosition( displPosition ), m_WorldPositionIsSet( false ), m_PickedObjectIsSet( false ) { } const mitk::Point3D& mitk::DisplayPositionEvent::GetWorldPosition() const { // Method performs position picking and sets world position if ( m_WorldPositionIsSet ) return m_WorldPosition; m_WorldPositionIsSet = true; assert( m_Sender != NULL ); m_Sender->PickWorldPoint( m_DisplayPosition, m_WorldPosition ); return m_WorldPosition; } mitk::DataTreeNode *mitk::DisplayPositionEvent::GetPickedObjectNode() const { // Method performs object picking and sets both object and world position if ( m_PickedObjectIsSet ) { return m_PickedObjectNode; } m_PickedObjectIsSet = true; m_WorldPositionIsSet = true; assert( m_Sender != NULL ); m_PickedObjectNode = m_Sender->PickObject( m_DisplayPosition, m_WorldPosition ); return m_PickedObjectNode; } mitk::BaseData *mitk::DisplayPositionEvent::GetPickedObject() const { mitk::DataTreeNode *node = this->GetPickedObjectNode(); if ( node != NULL ) { return node->GetData(); } else { return NULL; } }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkDisplayPositionEvent.h" #include "mitkBaseRenderer.h" mitk::DisplayPositionEvent::DisplayPositionEvent( mitk::BaseRenderer *sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition ) : Event( sender, type, button, buttonState, key ), m_DisplayPosition( displPosition ), m_WorldPositionIsSet( false ), m_PickedObjectIsSet( false ) { } const mitk::Point3D& mitk::DisplayPositionEvent::GetWorldPosition() const { // Method performs position picking and sets world position if ( m_WorldPositionIsSet ) return m_WorldPosition; assert( m_Sender != NULL ); m_Sender->PickWorldPoint( m_DisplayPosition, m_WorldPosition ); m_WorldPositionIsSet = true; return m_WorldPosition; } mitk::DataTreeNode *mitk::DisplayPositionEvent::GetPickedObjectNode() const { // Method performs object picking and sets both object and world position if ( m_PickedObjectIsSet ) { return m_PickedObjectNode; } assert( m_Sender != NULL ); m_PickedObjectNode = m_Sender->PickObject( m_DisplayPosition, m_WorldPosition ); m_PickedObjectIsSet = true; m_WorldPositionIsSet = true; return m_PickedObjectNode; } mitk::BaseData *mitk::DisplayPositionEvent::GetPickedObject() const { mitk::DataTreeNode *node = this->GetPickedObjectNode(); if ( node != NULL ) { return node->GetData(); } else { return NULL; } }
FIX (#2448): Set flag indicating completed position/object picking only after call to picking
FIX (#2448): Set flag indicating completed position/object picking only after call to picking
C++
bsd-3-clause
MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,fmilano/mitk,MITK/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,danielknorr/MITK,RabadanLab/MITKats,iwegner/MITK,RabadanLab/MITKats,rfloca/MITK,nocnokneo/MITK,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,fmilano/mitk,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,rfloca/MITK,nocnokneo/MITK,fmilano/mitk,danielknorr/MITK,iwegner/MITK,fmilano/mitk,rfloca/MITK,iwegner/MITK,rfloca/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,MITK/MITK,rfloca/MITK,MITK/MITK,fmilano/mitk,danielknorr/MITK,nocnokneo/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,rfloca/MITK,NifTK/MITK,danielknorr/MITK,danielknorr/MITK,nocnokneo/MITK,rfloca/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,RabadanLab/MITKats,NifTK/MITK,iwegner/MITK,MITK/MITK,fmilano/mitk,NifTK/MITK,danielknorr/MITK,RabadanLab/MITKats
aa7c62a31dbd08bf65d786aaf297b0b4f40a7bdf
pink/src/pink_cli.cc
pink/src/pink_cli.cc
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "pink/include/pink_cli.h" #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <poll.h> #include <fcntl.h> namespace pink { struct PinkCli::Rep { std::string peer_ip; int peer_port; int send_timeout; int recv_timeout; int connect_timeout; bool keep_alive; bool is_block; int sockfd; bool available; Rep() : send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } Rep(const std::string& ip, int port) : peer_ip(ip), peer_port(port), send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } }; PinkCli::PinkCli(const std::string& ip, const int port) : rep_(new Rep(ip, port)) { } PinkCli::~PinkCli() { Close(); delete rep_; } bool PinkCli::Available() const { return rep_->available; } Status PinkCli::Connect(const std::string &bind_ip) { return Connect(rep_->peer_ip, rep_->peer_port, bind_ip); } Status PinkCli::Connect(const std::string &ip, const int port, const std::string &bind_ip) { Rep* r = rep_; Status s; int rv; char cport[6]; struct addrinfo hints, *servinfo, *p; snprintf(cport, 6, "%d", port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; // We do not handle IPv6 if ((rv = getaddrinfo(ip.c_str(), cport, &hints, &servinfo)) != 0) { return Status::IOError("connect getaddrinfo error for ", ip); } for (p = servinfo; p != NULL; p = p->ai_next) { if ((r->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } // bind if needed if (!bind_ip.empty()) { struct sockaddr_in localaddr; localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = inet_addr(bind_ip.c_str()); localaddr.sin_port = 0; // Any local port will do bind(r->sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr)); } int flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags | O_NONBLOCK); if (connect(r->sockfd, p->ai_addr, p->ai_addrlen) == -1) { if (errno == EHOSTUNREACH) { close(r->sockfd); continue; } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { struct pollfd wfd[1]; wfd[0].fd = r->sockfd; wfd[0].events = POLLOUT; int res; if ((res = poll(wfd, 1, r->connect_timeout)) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect poll error"); } else if (res == 0) { close(r->sockfd); freeaddrinfo(servinfo); return Status::Timeout(""); } int val = 0; socklen_t lon = sizeof(int); if (getsockopt(r->sockfd, SOL_SOCKET, SO_ERROR, &val, &lon) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host getsockopt error"); } if (val) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host error"); } } else { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); getsockname(r->sockfd, (struct sockaddr*) &laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (ip == lip && port == lport) { return Status::IOError("EHOSTUNREACH", "same ip port"); } flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags & ~O_NONBLOCK); freeaddrinfo(servinfo); // connect ok rep_->available = true; return s; } if (p == NULL) { s = Status::IOError(strerror(errno), "Can't create socket "); return s; } freeaddrinfo(servinfo); freeaddrinfo(p); set_tcp_nodelay(); return s; } Status PinkCli::SendRaw(void *buf, size_t count) { char* wbuf = (char *)buf; size_t nleft = count; int pos = 0; ssize_t nwritten; while (nleft > 0) { if ((nwritten = write(rep_->sockfd, wbuf + pos, nleft)) <= 0) { if (errno == EINTR) { nwritten = 0; continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { return Status::IOError("write error " + std::string(strerror(errno))); } } nleft -= nwritten; pos += nwritten; } return Status::OK(); } Status PinkCli::RecvRaw(void *buf, size_t *count) { Rep* r = rep_; char* rbuf = (char *)buf; size_t nleft = *count; size_t pos = 0; ssize_t nread; while (nleft > 0) { if ((nread = read(r->sockfd, rbuf + pos, nleft)) <= 0) { if (errno == EINTR) { continue; // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...) // will return EAGAIN for timeout } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { return Status::IOError("read error " + std::string(strerror(errno))); } } nleft -= nread; pos += nread; } *count = pos; return Status::OK(); }; int PinkCli::fd() const { return rep_->sockfd; } void PinkCli::Close() { if (rep_->available) { close(rep_->sockfd); rep_->available = false; } } void PinkCli::set_connect_timeout(int connect_timeout) { rep_->connect_timeout = connect_timeout; } int PinkCli::set_send_timeout(int send_timeout) { Rep* r = rep_; int ret = 0; if (send_timeout > 0) { r->send_timeout = send_timeout; struct timeval timeout = {r->send_timeout / 1000, (r->send_timeout % 1000) * 1000}; ret = setsockopt(r->sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_recv_timeout(int recv_timeout) { Rep* r = rep_; int ret = 0; if (recv_timeout > 0) { r->recv_timeout = recv_timeout; struct timeval timeout = {r->recv_timeout / 1000, (r->recv_timeout % 1000) * 1000}; ret = setsockopt(r->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_tcp_nodelay() { Rep* r= rep_; int val = 1; int ret = 0; ret = setsockopt(r->sockfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); return ret; } };
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "pink/include/pink_cli.h" #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <poll.h> #include <fcntl.h> namespace pink { struct PinkCli::Rep { std::string peer_ip; int peer_port; int send_timeout; int recv_timeout; int connect_timeout; bool keep_alive; bool is_block; int sockfd; bool available; Rep() : send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } Rep(const std::string& ip, int port) : peer_ip(ip), peer_port(port), send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } }; PinkCli::PinkCli(const std::string& ip, const int port) : rep_(new Rep(ip, port)) { } PinkCli::~PinkCli() { Close(); delete rep_; } bool PinkCli::Available() const { return rep_->available; } Status PinkCli::Connect(const std::string &bind_ip) { return Connect(rep_->peer_ip, rep_->peer_port, bind_ip); } Status PinkCli::Connect(const std::string &ip, const int port, const std::string &bind_ip) { Rep* r = rep_; Status s; int rv; char cport[6]; struct addrinfo hints, *servinfo, *p; snprintf(cport, 6, "%d", port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; // We do not handle IPv6 if ((rv = getaddrinfo(ip.c_str(), cport, &hints, &servinfo)) != 0) { return Status::IOError("connect getaddrinfo error for ", ip); } for (p = servinfo; p != NULL; p = p->ai_next) { if ((r->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } // bind if needed if (!bind_ip.empty()) { struct sockaddr_in localaddr; localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = inet_addr(bind_ip.c_str()); localaddr.sin_port = 0; // Any local port will do bind(r->sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr)); } int flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags | O_NONBLOCK); if (connect(r->sockfd, p->ai_addr, p->ai_addrlen) == -1) { if (errno == EHOSTUNREACH) { close(r->sockfd); continue; } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { struct pollfd wfd[1]; wfd[0].fd = r->sockfd; wfd[0].events = POLLOUT; int res; if ((res = poll(wfd, 1, r->connect_timeout)) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect poll error"); } else if (res == 0) { close(r->sockfd); freeaddrinfo(servinfo); return Status::Timeout(""); } int val = 0; socklen_t lon = sizeof(int); if (getsockopt(r->sockfd, SOL_SOCKET, SO_ERROR, &val, &lon) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host getsockopt error"); } if (val) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host error"); } } else { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); getsockname(r->sockfd, (struct sockaddr*) &laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (ip == lip && port == lport) { return Status::IOError("EHOSTUNREACH", "same ip port"); } flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags & ~O_NONBLOCK); freeaddrinfo(servinfo); // connect ok rep_->available = true; return s; } if (p == NULL) { s = Status::IOError(strerror(errno), "Can't create socket "); return s; } freeaddrinfo(servinfo); freeaddrinfo(p); set_tcp_nodelay(); return s; } Status PinkCli::SendRaw(void *buf, size_t count) { char* wbuf = (char *)buf; size_t nleft = count; int pos = 0; ssize_t nwritten; while (nleft > 0) { if ((nwritten = write(rep_->sockfd, wbuf + pos, nleft)) <= 0) { if (errno == EINTR) { nwritten = 0; continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { rep_->available = false; return Status::IOError("write error " + std::string(strerror(errno))); } } nleft -= nwritten; pos += nwritten; } return Status::OK(); } Status PinkCli::RecvRaw(void *buf, size_t *count) { Rep* r = rep_; char* rbuf = (char *)buf; size_t nleft = *count; size_t pos = 0; ssize_t nread; while (nleft > 0) { if ((nread = read(r->sockfd, rbuf + pos, nleft)) <= 0) { if (errno == EINTR) { continue; // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...) // will return EAGAIN for timeout } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { rep_->available = false; return Status::IOError("read error " + std::string(strerror(errno))); } } nleft -= nread; pos += nread; } *count = pos; return Status::OK(); }; int PinkCli::fd() const { return rep_->sockfd; } void PinkCli::Close() { if (rep_->available) { close(rep_->sockfd); rep_->available = false; } } void PinkCli::set_connect_timeout(int connect_timeout) { rep_->connect_timeout = connect_timeout; } int PinkCli::set_send_timeout(int send_timeout) { Rep* r = rep_; int ret = 0; if (send_timeout > 0) { r->send_timeout = send_timeout; struct timeval timeout = {r->send_timeout / 1000, (r->send_timeout % 1000) * 1000}; ret = setsockopt(r->sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_recv_timeout(int recv_timeout) { Rep* r = rep_; int ret = 0; if (recv_timeout > 0) { r->recv_timeout = recv_timeout; struct timeval timeout = {r->recv_timeout / 1000, (r->recv_timeout % 1000) * 1000}; ret = setsockopt(r->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_tcp_nodelay() { Rep* r= rep_; int val = 1; int ret = 0; ret = setsockopt(r->sockfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); return ret; } };
update PinkCli available when send or recv failed
update PinkCli available when send or recv failed
C++
bsd-3-clause
Qihoo360/pink,Qihoo360/pink,Qihoo360/pink
b0b68785f9855bb26729ebca343d825256a4de4b
base/clipboard_unittest.cc
base/clipboard_unittest.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/basictypes.h" #include "base/clipboard.h" #include "base/platform_test.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "testing/gtest/include/gtest/gtest.h" typedef PlatformTest ClipboardTest; TEST_F(ClipboardTest, ClearTest) { Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteText(std::wstring(L"clear me")); } { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(std::wstring(L"<b>broom</b>"), ""); } EXPECT_FALSE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_FALSE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); } TEST_F(ClipboardTest, TextTest) { Clipboard clipboard; std::wstring text(L"This is a wstring!#$"), text_result; std::string ascii_text; { ScopedClipboardWriter scw(&clipboard); scw.WriteText(text); } EXPECT_TRUE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_TRUE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); clipboard.ReadText(&text_result); EXPECT_EQ(text, text_result); clipboard.ReadAsciiText(&ascii_text); EXPECT_EQ(WideToUTF8(text), ascii_text); } TEST_F(ClipboardTest, HTMLTest) { Clipboard clipboard; std::wstring markup(L"<string>Hi!</string>"), markup_result; std::string url("http://www.example.com/"), url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetHtmlFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif } TEST_F(ClipboardTest, TrickyHTMLTest) { Clipboard clipboard; std::wstring markup(L"<em>Bye!<!--EndFragment --></em>"), markup_result; std::string url, url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetHtmlFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif } // TODO(estade): Port the following test (decide what target we use for urls) #if !defined(OS_LINUX) TEST_F(ClipboardTest, BookmarkTest) { Clipboard clipboard; std::wstring title(L"The Example Company"), title_result; std::string url("http://www.example.com/"), url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteBookmark(title, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType())); clipboard.ReadBookmark(&title_result, &url_result); EXPECT_EQ(title, title_result); EXPECT_EQ(url, url_result); } #endif TEST_F(ClipboardTest, MultiFormatTest) { Clipboard clipboard; std::wstring text(L"Hi!"), text_result; std::wstring markup(L"<strong>Hi!</string>"), markup_result; std::string url("http://www.example.com/"), url_result; std::string ascii_text; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); scw.WriteText(text); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif clipboard.ReadText(&text_result); EXPECT_EQ(text, text_result); clipboard.ReadAsciiText(&ascii_text); EXPECT_EQ(WideToUTF8(text), ascii_text); } // TODO(estade): Port the following tests (decide what targets we use for files) #if !defined(OS_LINUX) // Files for this test don't actually need to exist on the file system, just // don't try to use a non-existent file you've retrieved from the clipboard. TEST_F(ClipboardTest, FileTest) { Clipboard clipboard; #if defined(OS_WIN) std::wstring file = L"C:\\Downloads\\My Downloads\\A Special File.txt"; #else // OS X will print a warning message if we stick a non-existant file on the // clipboard. std::wstring file = L"/usr/bin/make"; #endif { ScopedClipboardWriter scw(&clipboard); scw.WriteFile(file); } std::wstring out_file; clipboard.ReadFile(&out_file); EXPECT_EQ(file, out_file); } TEST_F(ClipboardTest, MultipleFilesTest) { Clipboard clipboard; #if defined(OS_WIN) std::wstring file1 = L"C:\\Downloads\\My Downloads\\File 1.exe"; std::wstring file2 = L"C:\\Downloads\\My Downloads\\File 2.pdf"; std::wstring file3 = L"C:\\Downloads\\My Downloads\\File 3.doc"; #elif defined(OS_MACOSX) // OS X will print a warning message if we stick a non-existant file on the // clipboard. std::wstring file1 = L"/usr/bin/make"; std::wstring file2 = L"/usr/bin/man"; std::wstring file3 = L"/usr/bin/perl"; #endif std::vector<std::wstring> files; files.push_back(file1); files.push_back(file2); files.push_back(file3); { ScopedClipboardWriter scw(&clipboard); scw.WriteFiles(files); } std::vector<std::wstring> out_files; clipboard.ReadFiles(&out_files); EXPECT_EQ(files.size(), out_files.size()); for (size_t i = 0; i < out_files.size(); ++i) EXPECT_EQ(files[i], out_files[i]); } #endif // !defined(OS_LINUX) #if defined(OS_WIN) // Windows only tests. TEST_F(ClipboardTest, HyperlinkTest) { Clipboard clipboard; std::wstring title(L"The Example Company"), title_result; std::string url("http://www.example.com/"), url_result; std::wstring html(L"<a href=\"http://www.example.com/\">" L"The Example Company</a>"), html_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHyperlink(title, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType())); clipboard.ReadBookmark(&title_result, &url_result); EXPECT_EQ(title, title_result); EXPECT_EQ(url, url_result); clipboard.ReadHTML(&html_result, &url_result); EXPECT_EQ(html, html_result); //XXX EXPECT_FALSE(url_result.is_valid()); } TEST_F(ClipboardTest, WebSmartPasteTest) { Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteWebSmartPaste(); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetWebKitSmartPasteFormatType())); } TEST_F(ClipboardTest, BitmapTest) { unsigned int fake_bitmap[] = { 0x46155189, 0xF6A55C8D, 0x79845674, 0xFA57BD89, 0x78FD46AE, 0x87C64F5A, 0x36EDC5AF, 0x4378F568, 0x91E9F63A, 0xC31EA14F, 0x69AB32DF, 0x643A3FD1, }; Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteBitmapFromPixels(fake_bitmap, gfx::Size(3, 4)); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetBitmapFormatType())); } #endif
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/basictypes.h" #include "base/clipboard.h" #include "base/platform_test.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "testing/gtest/include/gtest/gtest.h" typedef PlatformTest ClipboardTest; TEST_F(ClipboardTest, ClearTest) { Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteText(std::wstring(L"clear me")); } { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(std::wstring(L"<b>broom</b>"), ""); } EXPECT_FALSE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_FALSE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); } TEST_F(ClipboardTest, TextTest) { Clipboard clipboard; std::wstring text(L"This is a wstring!#$"), text_result; std::string ascii_text; { ScopedClipboardWriter scw(&clipboard); scw.WriteText(text); } EXPECT_TRUE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_TRUE(clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); clipboard.ReadText(&text_result); EXPECT_EQ(text, text_result); clipboard.ReadAsciiText(&ascii_text); EXPECT_EQ(WideToUTF8(text), ascii_text); } TEST_F(ClipboardTest, DISABLED_HTMLTest) { Clipboard clipboard; std::wstring markup(L"<string>Hi!</string>"), markup_result; std::string url("http://www.example.com/"), url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetHtmlFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif } TEST_F(ClipboardTest, DISABLED_TrickyHTMLTest) { Clipboard clipboard; std::wstring markup(L"<em>Bye!<!--EndFragment --></em>"), markup_result; std::string url, url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetHtmlFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif } // TODO(estade): Port the following test (decide what target we use for urls) #if !defined(OS_LINUX) TEST_F(ClipboardTest, BookmarkTest) { Clipboard clipboard; std::wstring title(L"The Example Company"), title_result; std::string url("http://www.example.com/"), url_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteBookmark(title, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType())); clipboard.ReadBookmark(&title_result, &url_result); EXPECT_EQ(title, title_result); EXPECT_EQ(url, url_result); } #endif TEST_F(ClipboardTest, DISABLED_MultiFormatTest) { Clipboard clipboard; std::wstring text(L"Hi!"), text_result; std::wstring markup(L"<strong>Hi!</string>"), markup_result; std::string url("http://www.example.com/"), url_result; std::string ascii_text; { ScopedClipboardWriter scw(&clipboard); scw.WriteHTML(markup, url); scw.WriteText(text); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetPlainTextWFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetPlainTextFormatType())); clipboard.ReadHTML(&markup_result, &url_result); EXPECT_EQ(markup, markup_result); #if defined(OS_WIN) // TODO(playmobil): It's not clear that non windows clipboards need to support // this. EXPECT_EQ(url, url_result); #endif clipboard.ReadText(&text_result); EXPECT_EQ(text, text_result); clipboard.ReadAsciiText(&ascii_text); EXPECT_EQ(WideToUTF8(text), ascii_text); } // TODO(estade): Port the following tests (decide what targets we use for files) #if !defined(OS_LINUX) // Files for this test don't actually need to exist on the file system, just // don't try to use a non-existent file you've retrieved from the clipboard. TEST_F(ClipboardTest, FileTest) { Clipboard clipboard; #if defined(OS_WIN) std::wstring file = L"C:\\Downloads\\My Downloads\\A Special File.txt"; #else // OS X will print a warning message if we stick a non-existant file on the // clipboard. std::wstring file = L"/usr/bin/make"; #endif { ScopedClipboardWriter scw(&clipboard); scw.WriteFile(file); } std::wstring out_file; clipboard.ReadFile(&out_file); EXPECT_EQ(file, out_file); } TEST_F(ClipboardTest, MultipleFilesTest) { Clipboard clipboard; #if defined(OS_WIN) std::wstring file1 = L"C:\\Downloads\\My Downloads\\File 1.exe"; std::wstring file2 = L"C:\\Downloads\\My Downloads\\File 2.pdf"; std::wstring file3 = L"C:\\Downloads\\My Downloads\\File 3.doc"; #elif defined(OS_MACOSX) // OS X will print a warning message if we stick a non-existant file on the // clipboard. std::wstring file1 = L"/usr/bin/make"; std::wstring file2 = L"/usr/bin/man"; std::wstring file3 = L"/usr/bin/perl"; #endif std::vector<std::wstring> files; files.push_back(file1); files.push_back(file2); files.push_back(file3); { ScopedClipboardWriter scw(&clipboard); scw.WriteFiles(files); } std::vector<std::wstring> out_files; clipboard.ReadFiles(&out_files); EXPECT_EQ(files.size(), out_files.size()); for (size_t i = 0; i < out_files.size(); ++i) EXPECT_EQ(files[i], out_files[i]); } #endif // !defined(OS_LINUX) #if defined(OS_WIN) // Windows only tests. TEST_F(ClipboardTest, HyperlinkTest) { Clipboard clipboard; std::wstring title(L"The Example Company"), title_result; std::string url("http://www.example.com/"), url_result; std::wstring html(L"<a href=\"http://www.example.com/\">" L"The Example Company</a>"), html_result; { ScopedClipboardWriter scw(&clipboard); scw.WriteHyperlink(title, url); } EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType())); EXPECT_EQ(true, clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType())); clipboard.ReadBookmark(&title_result, &url_result); EXPECT_EQ(title, title_result); EXPECT_EQ(url, url_result); clipboard.ReadHTML(&html_result, &url_result); EXPECT_EQ(html, html_result); //XXX EXPECT_FALSE(url_result.is_valid()); } TEST_F(ClipboardTest, WebSmartPasteTest) { Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteWebSmartPaste(); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetWebKitSmartPasteFormatType())); } TEST_F(ClipboardTest, BitmapTest) { unsigned int fake_bitmap[] = { 0x46155189, 0xF6A55C8D, 0x79845674, 0xFA57BD89, 0x78FD46AE, 0x87C64F5A, 0x36EDC5AF, 0x4378F568, 0x91E9F63A, 0xC31EA14F, 0x69AB32DF, 0x643A3FD1, }; Clipboard clipboard; { ScopedClipboardWriter scw(&clipboard); scw.WriteBitmapFromPixels(fake_bitmap, gfx::Size(3, 4)); } EXPECT_EQ(true, clipboard.IsFormatAvailable( Clipboard::GetBitmapFormatType())); } #endif
disable some tests while I debug offline
disable some tests while I debug offline TBR=estade Review URL: http://codereview.chromium.org/11258 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@5664 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Pluto-tv/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,Jonekee/chromium.src,robclark/chromium,dednal/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,robclark/chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,patrickm/chromium.src,patrickm/chromium.src,robclark/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,anirudhSK/chromium,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,patrickm/chromium.src,rogerwang/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,robclark/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,rogerwang/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,littlstar/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,Jonekee/chromium.src,keishi/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,ChromiumWebApps/chromium,anirudhSK/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,ltilve/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,keishi/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,hujiajie/pa-chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,dednal/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,Chilledheart/chromium,patrickm/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,robclark/chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,anirudhSK/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,dushu1203/chromium.src,dednal/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,patrickm/chromium.src,dednal/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,keishi/chromium,robclark/chromium,M4sse/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,dushu1203/chromium.src,keishi/chromium,dednal/chromium.src,dednal/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,robclark/chromium,rogerwang/chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,ondra-novak/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,rogerwang/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,markYoungH/chromium.src,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps
d7a26ab71541f2653ede00db423c07ee00a10ac7
src/skirt.cpp
src/skirt.cpp
/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "skirt.h" #include "support.h" namespace cura { void generateSkirt(SliceDataStorage& storage, int distance, int extrusionWidth, int count, int minLength, int initialLayerHeight) { bool externalOnly = (distance > 0); for(int skirtNr=0; skirtNr<count;skirtNr++) { int offsetDistance = distance + extrusionWidth * skirtNr + extrusionWidth / 2; Polygons skirtPolygons(storage.wipeTower.offset(offsetDistance)); for(unsigned int volumeIdx = 0; volumeIdx < storage.volumes.size(); volumeIdx++) { if (storage.volumes[volumeIdx].layers.size() < 1) continue; SliceLayer* layer = &storage.volumes[volumeIdx].layers[0]; for(unsigned int i=0; i<layer->parts.size(); i++) { if (externalOnly) { Polygons p; p.add(layer->parts[i].outline[0]); skirtPolygons = skirtPolygons.unionPolygons(p.offset(offsetDistance)); } else skirtPolygons = skirtPolygons.unionPolygons(layer->parts[i].outline.offset(offsetDistance)); } } SupportPolyGenerator supportGenerator(storage.support, initialLayerHeight); skirtPolygons = skirtPolygons.unionPolygons(supportGenerator.polygons.offset(offsetDistance)); //Remove small inner skirt holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for(unsigned int n=0; n<skirtPolygons.size(); n++) { double area = skirtPolygons[n].area(); if (area < 0 && area > -extrusionWidth * extrusionWidth * 100) skirtPolygons.remove(n--); } storage.skirt.add(skirtPolygons); int lenght = storage.skirt.polygonLength(); if (skirtNr + 1 >= count && lenght > 0 && lenght < minLength) count++; } } }//namespace cura
/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "skirt.h" #include "support.h" namespace cura { void generateSkirt(SliceDataStorage& storage, int distance, int extrusionWidth, int count, int minLength, int initialLayerHeight) { bool externalOnly = (distance > 0); for(int skirtNr=0; skirtNr<count;skirtNr++) { int offsetDistance = distance + extrusionWidth * skirtNr + extrusionWidth / 2; SupportPolyGenerator supportGenerator(storage.support, initialLayerHeight); Polygons skirtPolygons(storage.wipeTower.offset(offsetDistance)); for(unsigned int volumeIdx = 0; volumeIdx < storage.volumes.size(); volumeIdx++) { if (storage.volumes[volumeIdx].layers.size() < 1) continue; SliceLayer* layer = &storage.volumes[volumeIdx].layers[0]; for(unsigned int i=0; i<layer->parts.size(); i++) { if (externalOnly) { Polygons p; p.add(layer->parts[i].outline[0]); skirtPolygons = skirtPolygons.unionPolygons(p.offset(offsetDistance)); } else skirtPolygons = skirtPolygons.unionPolygons(layer->parts[i].outline.offset(offsetDistance)); supportGenerator.polygons = supportGenerator.polygons.difference(layer->parts[i].outline); } } //Contract and expand the suppory polygons so small sections are removed and the final polygon is smoothed a bit. supportGenerator.polygons = supportGenerator.polygons.offset(-extrusionWidth * 3); supportGenerator.polygons = supportGenerator.polygons.offset(extrusionWidth * 3); skirtPolygons = skirtPolygons.unionPolygons(supportGenerator.polygons.offset(offsetDistance)); //Remove small inner skirt holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for(unsigned int n=0; n<skirtPolygons.size(); n++) { double area = skirtPolygons[n].area(); if (area < 0 && area > -extrusionWidth * extrusionWidth * 100) skirtPolygons.remove(n--); } storage.skirt.add(skirtPolygons); int lenght = storage.skirt.polygonLength(); if (skirtNr + 1 >= count && lenght > 0 && lenght < minLength) count++; } } }//namespace cura
Improve skirt handling with support material
Improve skirt handling with support material
C++
agpl-3.0
pratikshashroff/pcura,alephobjects/CuraEngine,electrocbd/CuraEngine,totalretribution/CuraEngine,foosel/CuraEngine,electrocbd/CuraEngine,phonyphonecall/CuraEngine,Ultimaker/CuraEngine,pratikshashroff/pcura,mspark93/CuraEngine,alephobjects/CuraEngine,markwal/CuraEngine,be3d/CuraEngine,phonyphonecall/CuraEngine,fxtentacle/CuraEngine,patrick3coffee/CuraTinyG,totalretribution/CuraEngine,ROBO3D/CuraEngine,ROBO3D/CuraEngine,markwal/CuraEngine,mspark93/CuraEngine,electrocbd/CuraEngine,uus169/CuraEngine,alex1818/CuraEngine,Jwis921/PersonalCuraEngine,alex1818/CuraEngine,jacobdai/CuraEngine-1,totalretribution/CuraEngine,derekhe/CuraEngine,fxtentacle/CuraEngine,uus169/CuraEngine,Jwis921/PersonalCuraEngine,patrick3coffee/CuraTinyG,foosel/CuraEngine,pratikshashroff/pcura,jacobdai/CuraEngine-1,derekhe/CuraEngine,foosel/CuraEngine,derekhe/CuraEngine,alex1818/CuraEngine,Ultimaker/CuraEngine,Jwis921/PersonalCuraEngine,jacobdai/CuraEngine-1,ROBO3D/CuraEngine,uus169/CuraEngine,be3d/CuraEngine,markwal/CuraEngine,mspark93/CuraEngine,phonyphonecall/CuraEngine,fxtentacle/CuraEngine,alephobjects/CuraEngine,be3d/CuraEngine,patrick3coffee/CuraTinyG
0f14a75da2a7368f93f0a738c2546078eb387840
src/chain.cpp
src/chain.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == nullptr) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == nullptr) { return nullptr; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); return (lower == vChain.end() ? nullptr : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return nullptr; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != nullptr && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for an arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == nullptr) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == nullptr) { return nullptr; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); return (lower == vChain.end() ? nullptr : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return nullptr; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != nullptr && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for an arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (bnTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; }
fix typo in comment of chain.cpp
fix typo in comment of chain.cpp
C++
mit
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
0aa0af8b0f8996a46e95bd34d906ad8076641261
src/sqldb.cpp
src/sqldb.cpp
#include "sqldb.h" #include "exception.h" #include "session.h" #include "session_factory.h" namespace coda { namespace db { namespace impl { std::unordered_map<std::string, std::shared_ptr<session_factory>> factories; } std::shared_ptr<session> create_session(const std::string &uristr) { db::uri uri(uristr); return create_session(uri); } std::shared_ptr<session> create_session(const uri &uri) { auto factory = impl::factories[uri.protocol]; if (factory == nullptr) { throw database_exception("unknown database " + uri.value); } return std::make_shared<session>(factory->create(uri)); } std::shared_ptr<session> open_session(const std::string &uristr) { db::uri uri(uristr); return open_session(uri); } std::shared_ptr<session> open_session(const uri &uri) { auto factory = impl::factories[uri.protocol]; if (factory == nullptr) { throw database_exception("unknown database " + uri.value); } auto value = std::make_shared<session>(factory->create(uri)); value->open(); return value; } void register_session(const std::string &protocol, const std::shared_ptr<session_factory> &factory) { if (protocol.empty()) { throw database_exception("invalid protocol for session factory registration"); } if (factory == nullptr) { throw database_exception("invalid factory for session factory registration"); } impl::factories[protocol] = factory; } } }
#include "sqldb.h" #include "exception.h" #include "session.h" #include "session_factory.h" namespace coda { namespace db { namespace impl { static std::unordered_map<std::string, std::shared_ptr<session_factory>> factories; } std::shared_ptr<session> create_session(const std::string &uristr) { db::uri uri(uristr); return create_session(uri); } std::shared_ptr<session> create_session(const uri &uri) { auto factory = impl::factories[uri.protocol]; if (factory == nullptr) { throw database_exception("unknown database " + uri.value); } return std::make_shared<session>(factory->create(uri)); } std::shared_ptr<session> open_session(const std::string &uristr) { db::uri uri(uristr); return open_session(uri); } std::shared_ptr<session> open_session(const uri &uri) { auto factory = impl::factories[uri.protocol]; if (factory == nullptr) { throw database_exception("unknown database " + uri.value); } auto value = std::make_shared<session>(factory->create(uri)); value->open(); return value; } void register_session(const std::string &protocol, const std::shared_ptr<session_factory> &factory) { if (protocol.empty()) { throw database_exception("invalid protocol for session factory registration"); } if (factory == nullptr) { throw database_exception("invalid factory for session factory registration"); } impl::factories[protocol] = factory; } } }
Update variable
Update variable
C++
mit
ryjen/arg3db,c0der78/arg3db
eebc9748d2ea26a7b5af246dba115103d6bb15db
basic/source/inc/token.hxx
basic/source/inc/token.hxx
/* -*- 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 _TOKEN_HXX #define _TOKEN_HXX #include "scanner.hxx" #include <basic/sbdef.hxx> #if defined( SHARED ) #define SbiTokenSHAREDTMPUNDEF #undef SHARED #endif // The tokenizer is stand-alone, i. e. he can be used from everywhere. // A BASIC-instance is necessary for error messages. Without BASIC the // errors are only counted. The BASIC is also necessary when an advanced // SBX-variable shall be used for recognition of data types etc. enum SbiToken { NIL = 0, // tokens between 0x20 and 0x3F are literals: LPAREN = '(', RPAREN = ')', COMMA = ',', DOT = '.', EXCLAM = '!', HASH = '#', SEMICOLON = ';', // commands: FIRSTKWD = 0x40, AS = FIRSTKWD, ALIAS, ASSIGN, CALL, CASE, CLOSE, COMPARE, _CONST_, DECLARE, DIM, DO, // in the order of the data type enums! DEFINT, DEFLNG, DEFSNG, DEFDBL, DEFCUR, DEFDATE, DEFSTR, DEFOBJ, DEFERR, DEFBOOL, DEFVAR, // in the order of the data type enums! DATATYPE1, TINTEGER = DATATYPE1, TLONG, TSINGLE, TDOUBLE, TCURRENCY, TDATE, TSTRING, TOBJECT, _ERROR_, TBOOLEAN, TVARIANT, TBYTE, DATATYPE2 = TBYTE, EACH, ELSE, ELSEIF, END, ERASE, EXIT, FOR, FUNCTION, GET, GLOBAL, GOSUB, GOTO, IF, _IN_, INPUT, LET, LINE, LINEINPUT, LOCAL, LOOP, LPRINT, LSET, NAME, NEW, NEXT, ON, OPEN, OPTION, ATTRIBUTE, IMPLEMENTS, PRINT, PRIVATE, PROPERTY, PUBLIC, REDIM, REM, RESUME, RETURN, RSET, SELECT, SET, SHARED, STATIC, STEP, STOP, SUB, TEXT, THEN, TO, TYPE, ENUM, UNTIL, WEND, WHILE, WITH, WRITE, ENDENUM, ENDIF, ENDFUNC, ENDPROPERTY, ENDSUB, ENDTYPE, ENDSELECT, ENDWITH, // end of all keywords LASTKWD = ENDWITH, // statement end EOS, EOLN, // operators: EXPON, NEG, MUL, DIV, IDIV, MOD, PLUS, MINUS, EQ, NE, LT, GT, LE, GE, NOT, AND, OR, XOR, EQV, IMP, CAT, LIKE, IS, TYPEOF, // miscellaneous: FIRSTEXTRA, NUMBER=FIRSTEXTRA, FIXSTRING, SYMBOL, _CDECL_, BYVAL, BYREF, OUTPUT, RANDOM, APPEND, BINARY, ACCESS, LOCK, READ, PRESERVE, BASE, ANY, LIB, _OPTIONAL_, EXPLICIT, COMPATIBLE, CLASSMODULE, PARAMARRAY, WITHEVENTS, // from here there are JavaScript-tokens (same enum so that same type) FIRSTJAVA, JS_BREAK=FIRSTJAVA, JS_CONTINUE, JS_FOR, JS_FUNCTION, JS_IF, JS_NEW, JS_RETURN, JS_THIS, JS_VAR, JS_WHILE, JS_WITH, // JavaScript-operators // _ASS_ = Assignment JS_COMMA, JS_ASSIGNMENT, JS_ASS_PLUS, JS_ASS_MINUS, JS_ASS_MUL, JS_ASS_DIV, JS_ASS_MOD, JS_ASS_LSHIFT, JS_ASS_RSHIFT, JS_ASS_RSHIFT_Z, JS_ASS_AND, JS_ASS_XOR, JS_ASS_OR, JS_COND_QUEST, JS_COND_SEL, JS_LOG_OR, JS_LOG_AND, JS_BIT_OR, JS_BIT_XOR, JS_BIT_AND, JS_EQ, JS_NE, JS_LT, JS_LE, JS_GT, JS_GE, JS_LSHIFT, JS_RSHIFT, JS_RSHIFT_Z, JS_PLUS, JS_MINUS, JS_MUL, JS_DIV, JS_MOD, JS_LOG_NOT, JS_BIT_NOT, JS_INC, JS_DEC, JS_LPAREN, JS_RPAREN, JS_LINDEX, JS_RINDEX , VBASUPPORT }; #ifdef SbiTokenSHAREDTMPUNDEF #define SHARED #undef SbiTokenSHAREDTMPUNDEF #endif // #i109076 class TokenLabelInfo { bool* m_pTokenCanBeLabelTab; public: TokenLabelInfo( void ); TokenLabelInfo( const TokenLabelInfo& rInfo ) : m_pTokenCanBeLabelTab( NULL ) { (void)rInfo; } ~TokenLabelInfo(); bool canTokenBeLabel( SbiToken eTok ) { return m_pTokenCanBeLabelTab[eTok]; } }; class SbiTokenizer : public SbiScanner { TokenLabelInfo m_aTokenLabelInfo; protected: SbiToken eCurTok; SbiToken ePush; sal_uInt16 nPLine, nPCol1, nPCol2; // pushback location bool bEof; bool bEos; bool bKeywords; // true, if keywords are parsed bool bAs; // last keyword was AS bool bErrorIsSymbol; // Handle Error token as Symbol, not keyword public: SbiTokenizer( const ::rtl::OUString&, StarBASIC* = NULL ); ~SbiTokenizer(); inline bool IsEof() { return bEof; } inline bool IsEos() { return bEos; } void Push( SbiToken ); const ::rtl::OUString& Symbol( SbiToken ); // reconversion SbiToken Peek(); // read the next token SbiToken Next(); // read a token bool MayBeLabel( bool= false ); void Error( SbError c ) { GenError( c ); } void Error( SbError, SbiToken ); void Error( SbError, const char* ); void Error( SbError, const ::rtl::OUString &); static bool IsEoln( SbiToken t ) { return t == EOS || t == EOLN || t == REM; } static bool IsKwd( SbiToken t ) { return t >= FIRSTKWD && t <= LASTKWD; } static bool IsExtra( SbiToken t ) { return t >= FIRSTEXTRA; } }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- 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 _TOKEN_HXX #define _TOKEN_HXX #include "scanner.hxx" #include <basic/sbdef.hxx> #if defined( SHARED ) #define SbiTokenSHAREDTMPUNDEF #undef SHARED #endif #if defined( EXPLICIT ) #undef EXPLICIT #endif // The tokenizer is stand-alone, i. e. he can be used from everywhere. // A BASIC-instance is necessary for error messages. Without BASIC the // errors are only counted. The BASIC is also necessary when an advanced // SBX-variable shall be used for recognition of data types etc. enum SbiToken { NIL = 0, // tokens between 0x20 and 0x3F are literals: LPAREN = '(', RPAREN = ')', COMMA = ',', DOT = '.', EXCLAM = '!', HASH = '#', SEMICOLON = ';', // commands: FIRSTKWD = 0x40, AS = FIRSTKWD, ALIAS, ASSIGN, CALL, CASE, CLOSE, COMPARE, _CONST_, DECLARE, DIM, DO, // in the order of the data type enums! DEFINT, DEFLNG, DEFSNG, DEFDBL, DEFCUR, DEFDATE, DEFSTR, DEFOBJ, DEFERR, DEFBOOL, DEFVAR, // in the order of the data type enums! DATATYPE1, TINTEGER = DATATYPE1, TLONG, TSINGLE, TDOUBLE, TCURRENCY, TDATE, TSTRING, TOBJECT, _ERROR_, TBOOLEAN, TVARIANT, TBYTE, DATATYPE2 = TBYTE, EACH, ELSE, ELSEIF, END, ERASE, EXIT, FOR, FUNCTION, GET, GLOBAL, GOSUB, GOTO, IF, _IN_, INPUT, LET, LINE, LINEINPUT, LOCAL, LOOP, LPRINT, LSET, NAME, NEW, NEXT, ON, OPEN, OPTION, ATTRIBUTE, IMPLEMENTS, PRINT, PRIVATE, PROPERTY, PUBLIC, REDIM, REM, RESUME, RETURN, RSET, SELECT, SET, SHARED, STATIC, STEP, STOP, SUB, TEXT, THEN, TO, TYPE, ENUM, UNTIL, WEND, WHILE, WITH, WRITE, ENDENUM, ENDIF, ENDFUNC, ENDPROPERTY, ENDSUB, ENDTYPE, ENDSELECT, ENDWITH, // end of all keywords LASTKWD = ENDWITH, // statement end EOS, EOLN, // operators: EXPON, NEG, MUL, DIV, IDIV, MOD, PLUS, MINUS, EQ, NE, LT, GT, LE, GE, NOT, AND, OR, XOR, EQV, IMP, CAT, LIKE, IS, TYPEOF, // miscellaneous: FIRSTEXTRA, NUMBER=FIRSTEXTRA, FIXSTRING, SYMBOL, _CDECL_, BYVAL, BYREF, OUTPUT, RANDOM, APPEND, BINARY, ACCESS, LOCK, READ, PRESERVE, BASE, ANY, LIB, _OPTIONAL_, EXPLICIT, COMPATIBLE, CLASSMODULE, PARAMARRAY, WITHEVENTS, // from here there are JavaScript-tokens (same enum so that same type) FIRSTJAVA, JS_BREAK=FIRSTJAVA, JS_CONTINUE, JS_FOR, JS_FUNCTION, JS_IF, JS_NEW, JS_RETURN, JS_THIS, JS_VAR, JS_WHILE, JS_WITH, // JavaScript-operators // _ASS_ = Assignment JS_COMMA, JS_ASSIGNMENT, JS_ASS_PLUS, JS_ASS_MINUS, JS_ASS_MUL, JS_ASS_DIV, JS_ASS_MOD, JS_ASS_LSHIFT, JS_ASS_RSHIFT, JS_ASS_RSHIFT_Z, JS_ASS_AND, JS_ASS_XOR, JS_ASS_OR, JS_COND_QUEST, JS_COND_SEL, JS_LOG_OR, JS_LOG_AND, JS_BIT_OR, JS_BIT_XOR, JS_BIT_AND, JS_EQ, JS_NE, JS_LT, JS_LE, JS_GT, JS_GE, JS_LSHIFT, JS_RSHIFT, JS_RSHIFT_Z, JS_PLUS, JS_MINUS, JS_MUL, JS_DIV, JS_MOD, JS_LOG_NOT, JS_BIT_NOT, JS_INC, JS_DEC, JS_LPAREN, JS_RPAREN, JS_LINDEX, JS_RINDEX , VBASUPPORT }; #ifdef SbiTokenSHAREDTMPUNDEF #define SHARED #undef SbiTokenSHAREDTMPUNDEF #endif // #i109076 class TokenLabelInfo { bool* m_pTokenCanBeLabelTab; public: TokenLabelInfo( void ); TokenLabelInfo( const TokenLabelInfo& rInfo ) : m_pTokenCanBeLabelTab( NULL ) { (void)rInfo; } ~TokenLabelInfo(); bool canTokenBeLabel( SbiToken eTok ) { return m_pTokenCanBeLabelTab[eTok]; } }; class SbiTokenizer : public SbiScanner { TokenLabelInfo m_aTokenLabelInfo; protected: SbiToken eCurTok; SbiToken ePush; sal_uInt16 nPLine, nPCol1, nPCol2; // pushback location bool bEof; bool bEos; bool bKeywords; // true, if keywords are parsed bool bAs; // last keyword was AS bool bErrorIsSymbol; // Handle Error token as Symbol, not keyword public: SbiTokenizer( const ::rtl::OUString&, StarBASIC* = NULL ); ~SbiTokenizer(); inline bool IsEof() { return bEof; } inline bool IsEos() { return bEos; } void Push( SbiToken ); const ::rtl::OUString& Symbol( SbiToken ); // reconversion SbiToken Peek(); // read the next token SbiToken Next(); // read a token bool MayBeLabel( bool= false ); void Error( SbError c ) { GenError( c ); } void Error( SbError, SbiToken ); void Error( SbError, const char* ); void Error( SbError, const ::rtl::OUString &); static bool IsEoln( SbiToken t ) { return t == EOS || t == EOLN || t == REM; } static bool IsKwd( SbiToken t ) { return t >= FIRSTKWD && t <= LASTKWD; } static bool IsExtra( SbiToken t ) { return t >= FIRSTEXTRA; } }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Fix MSVC build: #undef EXPLICIT (which gets defined as 'explicit' somewhere)
Fix MSVC build: #undef EXPLICIT (which gets defined as 'explicit' somewhere) Change-Id: I83f6dff2a01d6d7806b2d2f4e6415aee10933e14
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
36ee23e71bbe55aa39a95212b673ea484ec77614
modules/planning/toolkits/smoothers/smoother.cc
modules/planning/toolkits/smoothers/smoother.cc
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/toolkits/smoothers/smoother.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Vec2d; bool Smoother::IsCloseStop(const common::VehicleState& vehicle_state, const MainStop& main_stop) { if (!main_stop.has_stop_point()) { ADEBUG << "not close for main stop:" << main_stop.DebugString(); return false; } Vec2d current_car_pos(vehicle_state.x(), vehicle_state.y()); Vec2d stop_pos(main_stop.stop_point().x(), main_stop.stop_point().y()); auto stop_distance = stop_pos.DistanceTo(current_car_pos); if (stop_distance > FLAGS_smoother_stop_distance) { ADEBUG << "distance between ADC position and stop position:" << stop_distance; return false; } return true; } // TODO(all): extend more smooth policies into different objects // when more use cases happens later. apollo::common::Status Smoother::Smooth( const FrameHistory* frame_history, const Frame* current_frame, ADCTrajectory* const current_trajectory_pb) { if (frame_history == nullptr) { std::string msg("frame history is null."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_frame == nullptr) { std::string msg("frame is null."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_trajectory_pb == nullptr) { std::string msg("current trajectory pb is null"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& main_decision = current_trajectory_pb->decision().main_decision(); if (!main_decision.has_stop()) { // skip for current planning is not stop. ADEBUG << "skip smoothing for current planning is not stop"; return Status::OK(); } const auto& vehicle_state = current_frame->vehicle_state(); if (vehicle_state.linear_velocity() > FLAGS_max_stop_speed) { ADEBUG << "vehicle speed:" << vehicle_state.linear_velocity() << " skip smoothing for non-stop scenario"; return Status::OK(); } if (!IsCloseStop(vehicle_state, main_decision.stop())) { ADEBUG << "vehicle state:" << vehicle_state.DebugString() << " skip smoothing for ADC is not close to stop point"; return Status::OK(); } auto previous_frame = frame_history->Latest(); if (previous_frame == nullptr) { std::string msg("previous frame is null"); AWARN << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } auto previous_planning = previous_frame->trajectory(); auto header = current_trajectory_pb->header(); *current_trajectory_pb = previous_planning; current_trajectory_pb->mutable_header()->CopyFrom(header); auto smoother_debug = current_trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_smoother(); smoother_debug->set_is_smoothed(true); smoother_debug->set_type( planning_internal::SmootherDebug::SMOOTHER_CLOSE_STOP); return Status::OK(); } } // namespace planning } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/toolkits/smoothers/smoother.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Vec2d; bool Smoother::IsCloseStop(const common::VehicleState& vehicle_state, const MainStop& main_stop) { if (!main_stop.has_stop_point()) { ADEBUG << "not close for main stop:" << main_stop.DebugString(); return false; } Vec2d current_car_pos(vehicle_state.x(), vehicle_state.y()); Vec2d stop_pos(main_stop.stop_point().x(), main_stop.stop_point().y()); auto stop_distance = stop_pos.DistanceTo(current_car_pos); if (stop_distance > FLAGS_smoother_stop_distance) { ADEBUG << "distance between ADC position and stop position:" << stop_distance; return false; } return true; } // TODO(all): extend more smooth policies into different objects // when more use cases happens later. apollo::common::Status Smoother::Smooth( const FrameHistory* frame_history, const Frame* current_frame, ADCTrajectory* const current_trajectory_pb) { if (frame_history == nullptr) { std::string msg("frame history is null."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_frame == nullptr) { std::string msg("frame is null."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_trajectory_pb == nullptr) { std::string msg("current trajectory pb is null"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& main_decision = current_trajectory_pb->decision().main_decision(); if (!main_decision.has_stop()) { // skip for current planning is not stop. ADEBUG << "skip smoothing for current planning is not stop"; return Status::OK(); } const auto& vehicle_state = current_frame->vehicle_state(); if (vehicle_state.linear_velocity() > FLAGS_max_stop_speed) { ADEBUG << "vehicle speed:" << vehicle_state.linear_velocity() << " skip smoothing for non-stop scenario"; return Status::OK(); } if (!IsCloseStop(vehicle_state, main_decision.stop())) { ADEBUG << "vehicle state:" << vehicle_state.DebugString() << " skip smoothing for ADC is not close to stop point"; return Status::OK(); } auto previous_frame = frame_history->Latest(); if (previous_frame == nullptr) { std::string msg("previous frame is null"); AWARN << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& previous_planning = previous_frame->trajectory(); auto header = current_trajectory_pb->header(); *current_trajectory_pb = previous_planning; current_trajectory_pb->mutable_header()->CopyFrom(header); auto smoother_debug = current_trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_smoother(); smoother_debug->set_is_smoothed(true); smoother_debug->set_type( planning_internal::SmootherDebug::SMOOTHER_CLOSE_STOP); return Status::OK(); } } // namespace planning } // namespace apollo
change previous trajectory to reference to avoid copy.
planning: change previous trajectory to reference to avoid copy.
C++
apache-2.0
wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,xiaoxq/apollo,xiaoxq/apollo,ApolloAuto/apollo,jinghaomiao/apollo,wanglei828/apollo,ApolloAuto/apollo,jinghaomiao/apollo,ycool/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,ApolloAuto/apollo,wanglei828/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,ycool/apollo,wanglei828/apollo,wanglei828/apollo,ApolloAuto/apollo,ApolloAuto/apollo,xiaoxq/apollo,xiaoxq/apollo,ApolloAuto/apollo
f917191d462d9bd07fcee7face1252719decf801
jpegenc/jpegenc/dtc/Arai.cpp
jpegenc/jpegenc/dtc/Arai.cpp
#include "Arai.hpp" #include <math.h> #define A1 0.707107 #define A2 0.541197 #define A3 0.707107 #define A4 1.306563 #define A5 0.382683 #define S0 0.353553 #define S1 0.254898 #define S2 0.270598 #define S3 0.300672 #define S4 0.353553 #define S5 0.449988 #define S6 0.653282 #define S7 1.28146 void Arai::transformLine(float *values) { float x0 = values[0]; float x1 = values[1]; float x2 = values[2]; float x3 = values[3]; float x4 = values[4]; float x5 = values[5]; float x6 = values[6]; float x7 = values[7]; float a0 = x0 + x7; float a1 = x1 + x6; float a2 = x2 + x5; float a3 = x3 + x4; float a4 = x3 - x4; float a5 = x2 - x5; float a6 = x1 - x6; float a7 = x0 - x7; float b0 = a0 + a3; float b1 = a1 + a2; float b2 = a1 - a2; float b3 = a0 - a3; float b4 = -a4 - a5; float b5 = a5 + a6; float b6 = a6 + a7; float c0 = b0 + b1; float c1 = b0 - b1; float c2 = b2 + b3; float d2 = c2 * A1; float d4 = -(b4 * A2) - ((b4 + b6) * A5); float d5 = b5 * A3; float d6 = (b6 * A4) - ((b4 + b6) * A5); float e2 = d2 + b3; float e3 = b3 - d2; float e5 = d5 + a7; float e7 = a7 - d5; float f4 = d4 + e7; float f5 = e5 + d6; float f6 = e5 - d6; float f7 = e7 - d4; values[0] = c0 * S0; values[1] = f5 * S1; values[2] = e2 * S2; values[3] = f7 * S3; values[4] = c1 * S4; values[5] = f4 * S5; values[6] = e3 * S6; values[7] = f6 * S7; }
#include "Arai.hpp" #include <math.h> #define A1 0.707107 #define A2 0.541197 #define A3 0.707107 #define A4 1.306563 #define A5 0.382683 #define S0 0.353553 #define S1 0.254898 #define S2 0.270598 #define S3 0.300672 #define S4 0.353553 #define S5 0.449988 #define S6 0.653282 #define S7 1.28146 /* Effizienz 13 x Multiplikation 15 x Addition 14 x Subtraktion 2 x Komplementbildungen 16 x lesender Zugriff auf Array 8 x schreibender Zugriff auf Array */ void Arai::transformLine(float *values) { float a0 = values[0] + values[7]; float a1 = values[1] + values[6]; float a2 = values[2] + values[5]; float a3 = values[3] + values[4]; float a5 = values[2] - values[5]; float a6 = values[1] - values[6]; float a7 = values[0] - values[7]; float b0 = a0 + a3; float b1 = a1 + a2; float b3 = a0 - a3; float b4 = -(values[3] - values[4]) - a5; float b6 = a6 + a7; float A5_block = (b4 + b6) * A5; float d2 = ((a1 - a2) + b3) * A1; float d4 = -(b4 * A2) - A5_block; float d5 = (a5 + a6) * A3; float d6 = (b6 * A4) - A5_block; float e5 = d5 + a7; float e7 = a7 - d5; values[0] = (b0 + b1) * S0; values[1] = (e5 + d6) * S1; values[2] = (d2 + b3) * S2; values[3] = (e7 - d4) * S3; values[4] = (b0 - b1) * S4; values[5] = (d4 + e7) * S5; values[6] = (b3 - d2) * S6; values[7] = (e5 - d6) * S7; }
Simplify Arai and describe efficiency
Simplify Arai and describe efficiency
C++
mit
relikd/jpeg-encoder,relikd/jpeg-encoder
fdb24976962d3cc8f6397559b222ec96e9642655
p6-Extended-Kalman-Filter/src/kalman_filter.cpp
p6-Extended-Kalman-Filter/src/kalman_filter.cpp
#include "kalman_filter.h" using Eigen::MatrixXd; using Eigen::VectorXd; KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { x_ = x_in; P_ = P_in; F_ = F_in; H_ = H_in; R_ = R_in; Q_ = Q_in; } void KalmanFilter::Predict() { /** TODO: * predict the state */ } void KalmanFilter::Update(const VectorXd &z) { /** TODO: * update the state by using Kalman Filter equations */ } void KalmanFilter::UpdateEKF(const VectorXd &z) { /** TODO: * update the state by using Extended Kalman Filter equations */ }
#include "kalman_filter.h" using Eigen::MatrixXd; using Eigen::VectorXd; KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { x_ = x_in; // object state P_ = P_in; // object covariance matrix F_ = F_in; // state transistion matrix H_ = H_in; // measurement matrix R_ = R_in; // measurement covariance matrix Q_ = Q_in; // process covariance matrix } void KalmanFilter::Predict() { /* * Predict the state */ x_ = (F_ * x_); MatrixXd F_transpose = F_.transpose(); P_ = F_ * P_ * F_transpose + Q_; } void KalmanFilter::Update(const VectorXd &z) { /* * Update the state */ VectorXd z_pred = H_ * x_; VectorXd y_ = z - z_pred; // new filter for error calculation MatrixXd H_transpose = H_.transpose(); MatrixXd S_ = H_ * P_ * H_transpose + R_; MatrixXd S_inverse = S_.inverse(); MatrixXd P_h_transpose = P_ * H_transpose; MatrixXd K_ = P_h_transpose * S_inverse; // new estimate x_ = x_ + (K_ * y_); long x_size = x_.size(); MatrixXd I_ = MatrixXd::Identity(x_size, x_size); P_ = (I_ - K_ * H_) * P_; } void KalmanFilter::UpdateEKF(const VectorXd &z) { /** TODO: * update the state by using Extended Kalman Filter equations VectorXd Hx = VectorXd(3); float ro = z(0); float phi = z(1); float px = ro * cos(phi); float py = ro * sin(phi); float v = z(2); float vx = v * cos(phi); float vy = v * sin(phi); float first = sqrt(pow(px, 2) + pow(py, 2)); float second = atan(py/px); float third = (px*vx + py*vy) / first; Hx << first, second, third; VectorXd x_state = VectorXd(4); x_state << px, py, vx, vy; */ Tools tools = Tools::Tools(); MatrixXd Hj = tools.CalculateJacobian(.x_); VectorXd y = z - Hx; }
update Kalman filter
update Kalman filter --> Add english explanation to variable names --> Predict() --> Update() --> UpdateEKF() // working
C++
mit
swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013,swirlingsand/self-driving-car-nanodegree-nd013
da0f02f9b2359cc2ad7f4a84aebbbeedc6d655a5
bench/MathBench.cpp
bench/MathBench.cpp
#include "SkBenchmark.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRandom.h" #include "SkString.h" #include "SkPaint.h" class MathBench : public SkBenchmark { enum { kBuffer = 100, kLoop = 10000 }; SkString fName; float fSrc[kBuffer], fDst[kBuffer]; public: MathBench(void* param, const char name[]) : INHERITED(param) { fName.printf("math_%s", name); SkRandom rand; for (int i = 0; i < kBuffer; ++i) { fSrc[i] = rand.nextSScalar1(); } } virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) = 0; protected: virtual int mulLoopCount() const { return 1; } virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(kLoop * this->mulLoopCount()); for (int i = 0; i < n; i++) { this->performTest(fDst, fSrc, kBuffer); } } private: typedef SkBenchmark INHERITED; }; class MathBenchU32 : public MathBench { public: MathBenchU32(void* param, const char name[]) : INHERITED(param, name) {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) = 0; virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) SK_OVERRIDE { uint32_t* d = SkTCast<uint32_t*>(dst); const uint32_t* s = SkTCast<const uint32_t*>(src); this->performITest(d, s, count); } private: typedef MathBench INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class NoOpMathBench : public MathBench { public: NoOpMathBench(void* param) : INHERITED(param, "noOp") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = src[i] + 1; } } private: typedef MathBench INHERITED; }; class SlowISqrtMathBench : public MathBench { public: SlowISqrtMathBench(void* param) : INHERITED(param, "slowIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = 1.0f / sk_float_sqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline float SkFastInvSqrt(float x) { float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f-xhalf*x*x); // x = x*(1.5f-xhalf*x*x); // this line takes err from 10^-3 to 10^-6 return x; } class FastISqrtMathBench : public MathBench { public: FastISqrtMathBench(void* param) : INHERITED(param, "fastIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = SkFastInvSqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline uint32_t QMul64(uint32_t value, U8CPU alpha) { SkASSERT((uint8_t)alpha == alpha); const uint32_t mask = 0xFF00FF; uint64_t tmp = value; tmp = (tmp & mask) | ((tmp & ~mask) << 24); tmp *= alpha; return ((tmp >> 8) & mask) | ((tmp >> 32) & ~mask); } class QMul64Bench : public MathBenchU32 { public: QMul64Bench(void* param) : INHERITED(param, "qmul64") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = QMul64(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; class QMul32Bench : public MathBenchU32 { public: QMul32Bench(void* param) : INHERITED(param, "qmul32") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = SkAlphaMulQ(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static bool isFinite_int(float x) { uint32_t bits = SkFloat2Bits(x); // need unsigned for our shifts int exponent = bits << 1 >> 24; return exponent != 0xFF; } static bool isFinite_float(float x) { return SkToBool(sk_float_isfinite(x)); } static bool isFinite_mulzero(float x) { float y = x * 0; return y == y; } static bool isfinite_and_int(const float data[4]) { return isFinite_int(data[0]) && isFinite_int(data[1]) && isFinite_int(data[2]) && isFinite_int(data[3]); } static bool isfinite_and_float(const float data[4]) { return isFinite_float(data[0]) && isFinite_float(data[1]) && isFinite_float(data[2]) && isFinite_float(data[3]); } static bool isfinite_and_mulzero(const float data[4]) { return isFinite_mulzero(data[0]) && isFinite_mulzero(data[1]) && isFinite_mulzero(data[2]) && isFinite_mulzero(data[3]); } #define mulzeroadd(data) (data[0]*0 + data[1]*0 + data[2]*0 + data[3]*0) static bool isfinite_plus_int(const float data[4]) { return isFinite_int(mulzeroadd(data)); } static bool isfinite_plus_float(const float data[4]) { return !sk_float_isnan(mulzeroadd(data)); } static bool isfinite_plus_mulzero(const float data[4]) { float x = mulzeroadd(data); return x == x; } typedef bool (*IsFiniteProc)(const float[]); #define MAKEREC(name) { name, #name } static const struct { IsFiniteProc fProc; const char* fName; } gRec[] = { MAKEREC(isfinite_and_int), MAKEREC(isfinite_and_float), MAKEREC(isfinite_and_mulzero), MAKEREC(isfinite_plus_int), MAKEREC(isfinite_plus_float), MAKEREC(isfinite_plus_mulzero), }; #undef MAKEREC static bool isFinite(const SkRect& r) { // x * 0 will be NaN iff x is infinity or NaN. // a + b will be NaN iff either a or b is NaN. float value = r.fLeft * 0 + r.fTop * 0 + r.fRight * 0 + r.fBottom * 0; // value is either NaN or it is finite (zero). // value==value will be true iff value is not NaN return value == value; } class IsFiniteBench : public SkBenchmark { enum { N = SkBENCHLOOP(1000), NN = SkBENCHLOOP(1000), }; float fData[N]; public: IsFiniteBench(void* param, int index) : INHERITED(param) { SkRandom rand; for (int i = 0; i < N; ++i) { fData[i] = rand.nextSScalar1(); } if (index < 0) { fProc = NULL; fName = "isfinite_rect"; } else { fProc = gRec[index].fProc; fName = gRec[index].fName; } } protected: virtual void onDraw(SkCanvas* canvas) { IsFiniteProc proc = fProc; const float* data = fData; // do this so the compiler won't throw away the function call int counter = 0; if (proc) { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { counter += proc(&data[i]); } } } else { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { const SkRect* r = reinterpret_cast<const SkRect*>(&data[i]); counter += r->isFinite(); } } } SkPaint paint; if (paint.getAlpha() == 0) { SkDebugf("%d\n", counter); } } virtual const char* onGetName() { return fName; } private: IsFiniteProc fProc; const char* fName; typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* M0(void* p) { return new NoOpMathBench(p); } static SkBenchmark* M1(void* p) { return new SlowISqrtMathBench(p); } static SkBenchmark* M2(void* p) { return new FastISqrtMathBench(p); } static SkBenchmark* M3(void* p) { return new QMul64Bench(p); } static SkBenchmark* M4(void* p) { return new QMul32Bench(p); } static SkBenchmark* M5neg1(void* p) { return new IsFiniteBench(p, -1); } static SkBenchmark* M50(void* p) { return new IsFiniteBench(p, 0); } static SkBenchmark* M51(void* p) { return new IsFiniteBench(p, 1); } static SkBenchmark* M52(void* p) { return new IsFiniteBench(p, 2); } static SkBenchmark* M53(void* p) { return new IsFiniteBench(p, 3); } static SkBenchmark* M54(void* p) { return new IsFiniteBench(p, 4); } static SkBenchmark* M55(void* p) { return new IsFiniteBench(p, 5); } static BenchRegistry gReg0(M0); static BenchRegistry gReg1(M1); static BenchRegistry gReg2(M2); static BenchRegistry gReg3(M3); static BenchRegistry gReg4(M4); static BenchRegistry gReg5neg1(M5neg1); static BenchRegistry gReg50(M50); static BenchRegistry gReg51(M51); static BenchRegistry gReg52(M52); static BenchRegistry gReg53(M53); static BenchRegistry gReg54(M54); static BenchRegistry gReg55(M55);
#include "SkBenchmark.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRandom.h" #include "SkString.h" #include "SkPaint.h" static float sk_fsel(float pred, float result_ge, float result_lt) { return pred >= 0 ? result_ge : result_lt; } static float fast_floor(float x) { float big = sk_fsel(x, 0x1.0p+23, -0x1.0p+23); return (x + big) - big; } class MathBench : public SkBenchmark { enum { kBuffer = 100, kLoop = 10000 }; SkString fName; float fSrc[kBuffer], fDst[kBuffer]; public: MathBench(void* param, const char name[]) : INHERITED(param) { fName.printf("math_%s", name); SkRandom rand; for (int i = 0; i < kBuffer; ++i) { fSrc[i] = rand.nextSScalar1(); } } virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) = 0; protected: virtual int mulLoopCount() const { return 1; } virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(kLoop * this->mulLoopCount()); for (int i = 0; i < n; i++) { this->performTest(fDst, fSrc, kBuffer); } } private: typedef SkBenchmark INHERITED; }; class MathBenchU32 : public MathBench { public: MathBenchU32(void* param, const char name[]) : INHERITED(param, name) {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) = 0; virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) SK_OVERRIDE { uint32_t* d = SkTCast<uint32_t*>(dst); const uint32_t* s = SkTCast<const uint32_t*>(src); this->performITest(d, s, count); } private: typedef MathBench INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class NoOpMathBench : public MathBench { public: NoOpMathBench(void* param) : INHERITED(param, "noOp") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = src[i] + 1; } } private: typedef MathBench INHERITED; }; class SlowISqrtMathBench : public MathBench { public: SlowISqrtMathBench(void* param) : INHERITED(param, "slowIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = 1.0f / sk_float_sqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline float SkFastInvSqrt(float x) { float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f-xhalf*x*x); // x = x*(1.5f-xhalf*x*x); // this line takes err from 10^-3 to 10^-6 return x; } class FastISqrtMathBench : public MathBench { public: FastISqrtMathBench(void* param) : INHERITED(param, "fastIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = SkFastInvSqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline uint32_t QMul64(uint32_t value, U8CPU alpha) { SkASSERT((uint8_t)alpha == alpha); const uint32_t mask = 0xFF00FF; uint64_t tmp = value; tmp = (tmp & mask) | ((tmp & ~mask) << 24); tmp *= alpha; return ((tmp >> 8) & mask) | ((tmp >> 32) & ~mask); } class QMul64Bench : public MathBenchU32 { public: QMul64Bench(void* param) : INHERITED(param, "qmul64") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = QMul64(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; class QMul32Bench : public MathBenchU32 { public: QMul32Bench(void* param) : INHERITED(param, "qmul32") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = SkAlphaMulQ(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static bool isFinite_int(float x) { uint32_t bits = SkFloat2Bits(x); // need unsigned for our shifts int exponent = bits << 1 >> 24; return exponent != 0xFF; } static bool isFinite_float(float x) { return SkToBool(sk_float_isfinite(x)); } static bool isFinite_mulzero(float x) { float y = x * 0; return y == y; } static bool isfinite_and_int(const float data[4]) { return isFinite_int(data[0]) && isFinite_int(data[1]) && isFinite_int(data[2]) && isFinite_int(data[3]); } static bool isfinite_and_float(const float data[4]) { return isFinite_float(data[0]) && isFinite_float(data[1]) && isFinite_float(data[2]) && isFinite_float(data[3]); } static bool isfinite_and_mulzero(const float data[4]) { return isFinite_mulzero(data[0]) && isFinite_mulzero(data[1]) && isFinite_mulzero(data[2]) && isFinite_mulzero(data[3]); } #define mulzeroadd(data) (data[0]*0 + data[1]*0 + data[2]*0 + data[3]*0) static bool isfinite_plus_int(const float data[4]) { return isFinite_int(mulzeroadd(data)); } static bool isfinite_plus_float(const float data[4]) { return !sk_float_isnan(mulzeroadd(data)); } static bool isfinite_plus_mulzero(const float data[4]) { float x = mulzeroadd(data); return x == x; } typedef bool (*IsFiniteProc)(const float[]); #define MAKEREC(name) { name, #name } static const struct { IsFiniteProc fProc; const char* fName; } gRec[] = { MAKEREC(isfinite_and_int), MAKEREC(isfinite_and_float), MAKEREC(isfinite_and_mulzero), MAKEREC(isfinite_plus_int), MAKEREC(isfinite_plus_float), MAKEREC(isfinite_plus_mulzero), }; #undef MAKEREC static bool isFinite(const SkRect& r) { // x * 0 will be NaN iff x is infinity or NaN. // a + b will be NaN iff either a or b is NaN. float value = r.fLeft * 0 + r.fTop * 0 + r.fRight * 0 + r.fBottom * 0; // value is either NaN or it is finite (zero). // value==value will be true iff value is not NaN return value == value; } class IsFiniteBench : public SkBenchmark { enum { N = SkBENCHLOOP(1000), NN = SkBENCHLOOP(1000), }; float fData[N]; public: IsFiniteBench(void* param, int index) : INHERITED(param) { SkRandom rand; for (int i = 0; i < N; ++i) { fData[i] = rand.nextSScalar1(); } if (index < 0) { fProc = NULL; fName = "isfinite_rect"; } else { fProc = gRec[index].fProc; fName = gRec[index].fName; } } protected: virtual void onDraw(SkCanvas* canvas) { IsFiniteProc proc = fProc; const float* data = fData; // do this so the compiler won't throw away the function call int counter = 0; if (proc) { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { counter += proc(&data[i]); } } } else { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { const SkRect* r = reinterpret_cast<const SkRect*>(&data[i]); counter += r->isFinite(); } } } SkPaint paint; if (paint.getAlpha() == 0) { SkDebugf("%d\n", counter); } } virtual const char* onGetName() { return fName; } private: IsFiniteProc fProc; const char* fName; typedef SkBenchmark INHERITED; }; class FloorBench : public SkBenchmark { enum { ARRAY = SkBENCHLOOP(1000), LOOP = SkBENCHLOOP(1000), }; float fData[ARRAY]; bool fFast; public: FloorBench(void* param, bool fast) : INHERITED(param), fFast(fast) { SkRandom rand; for (int i = 0; i < ARRAY; ++i) { fData[i] = rand.nextSScalar1(); } if (fast) { fName = "floor_fast"; } else { fName = "floor_std"; } } virtual void process(float) {} protected: virtual void onDraw(SkCanvas* canvas) { SkRandom rand; float accum = 0; const float* data = fData; float tmp[ARRAY] = {}; if (fFast) { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += fast_floor(data[i]); } this->process(accum); } } else { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += sk_float_floor(data[i]); } this->process(accum); } } } virtual const char* onGetName() { return fName; } private: const char* fName; typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* M0(void* p) { return new NoOpMathBench(p); } static SkBenchmark* M1(void* p) { return new SlowISqrtMathBench(p); } static SkBenchmark* M2(void* p) { return new FastISqrtMathBench(p); } static SkBenchmark* M3(void* p) { return new QMul64Bench(p); } static SkBenchmark* M4(void* p) { return new QMul32Bench(p); } static SkBenchmark* M5neg1(void* p) { return new IsFiniteBench(p, -1); } static SkBenchmark* M50(void* p) { return new IsFiniteBench(p, 0); } static SkBenchmark* M51(void* p) { return new IsFiniteBench(p, 1); } static SkBenchmark* M52(void* p) { return new IsFiniteBench(p, 2); } static SkBenchmark* M53(void* p) { return new IsFiniteBench(p, 3); } static SkBenchmark* M54(void* p) { return new IsFiniteBench(p, 4); } static SkBenchmark* M55(void* p) { return new IsFiniteBench(p, 5); } static SkBenchmark* F0(void* p) { return new FloorBench(p, false); } static SkBenchmark* F1(void* p) { return new FloorBench(p, true); } static BenchRegistry gReg0(M0); static BenchRegistry gReg1(M1); static BenchRegistry gReg2(M2); static BenchRegistry gReg3(M3); static BenchRegistry gReg4(M4); static BenchRegistry gReg5neg1(M5neg1); static BenchRegistry gReg50(M50); static BenchRegistry gReg51(M51); static BenchRegistry gReg52(M52); static BenchRegistry gReg53(M53); static BenchRegistry gReg54(M54); static BenchRegistry gReg55(M55); static BenchRegistry gRF0(F0); static BenchRegistry gRF1(F1);
add bench for floor variants
add bench for floor variants git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4065 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
MatChung/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,Hankuo/color-emoji.skia
5c2e3b25facf878cafff7499d901de27a27645ff
src/window.cc
src/window.cc
#include "window.hh" #include "assert.hh" #include "context.hh" #include "highlighter.hh" #include "hook_manager.hh" #include <algorithm> #include <sstream> namespace Kakoune { // Implementation in highlighters.cc void highlight_selections(const Window& window, DisplayBuffer& display_buffer); void expand_tabulations(const Window& window, DisplayBuffer& display_buffer); void expand_unprintable(const Window& window, DisplayBuffer& display_buffer); Window::Window(Buffer& buffer) : Editor(buffer), m_hooks(buffer.hooks()), m_options(buffer.options()) { Context hook_context{*this}; m_hooks.run_hook("WinCreate", buffer.name(), hook_context); m_options.register_watcher(*this); m_builtin_highlighters.append({"tabulations", expand_tabulations}); m_builtin_highlighters.append({"unprintable", expand_unprintable}); m_builtin_highlighters.append({"selections", highlight_selections}); for (auto& option : m_options.flatten_options()) on_option_changed(*option); } Window::~Window() { m_options.unregister_watcher(*this); } void Window::display_selection_at(LineCount line) { if (line >= 0 or line < m_dimensions.line) { auto cursor_line = main_selection().last().line; m_position.line = std::max(0_line, cursor_line - line); } } void Window::center_selection() { display_selection_at(m_dimensions.line/2_line); } void Window::scroll(LineCount offset) { m_position.line = std::max(0_line, m_position.line + offset); } void Window::update_display_buffer() { scroll_to_keep_cursor_visible_ifn(); DisplayBuffer::LineList& lines = m_display_buffer.lines(); lines.clear(); for (LineCount line = 0; line < m_dimensions.line; ++line) { LineCount buffer_line = m_position.line + line; if (buffer_line >= buffer().line_count()) break; BufferCoord limit{buffer_line+1, 0}; auto begin = std::min(buffer().char_advance(buffer_line, m_position.column), limit); auto end = std::min(buffer().char_advance(begin, m_dimensions.column), limit); lines.push_back(DisplayLine(buffer_line)); lines.back().push_back(DisplayAtom(AtomContent(buffer(), begin, end))); } m_display_buffer.compute_range(); m_highlighters(*this, m_display_buffer); m_builtin_highlighters(*this, m_display_buffer); m_display_buffer.optimize(); m_timestamp = buffer().timestamp(); } void Window::set_position(const DisplayCoord& position) { m_position.line = std::max(0_line, position.line); m_position.column = std::max(0_char, position.column); } void Window::set_dimensions(const DisplayCoord& dimensions) { m_dimensions = dimensions; } static LineCount adapt_view_pos(LineCount line, LineCount offset, LineCount view_pos, LineCount view_size, LineCount buffer_size) { if (line - offset < view_pos) return std::max(0_line, line - offset); else if (line + offset >= view_pos + view_size) return std::min(buffer_size - view_size, line + offset - (view_size - 1)); return view_pos; } void Window::scroll_to_keep_cursor_visible_ifn() { const auto& first = main_selection().first(); const auto& last = main_selection().last(); const LineCount offset = std::min<LineCount>(options()["scrolloff"].get<int>(), (m_dimensions.line - 1) / 2); // scroll lines if needed, try to get as much of the selection visible as possible m_position.line = adapt_view_pos(first.line, offset, m_position.line, m_dimensions.line, buffer().line_count()); m_position.line = adapt_view_pos(last.line, offset, m_position.line, m_dimensions.line, buffer().line_count()); // highlight only the line containing the cursor DisplayBuffer display_buffer; DisplayBuffer::LineList& lines = display_buffer.lines(); lines.push_back(DisplayLine(last.line)); lines.back().push_back(DisplayAtom(AtomContent(buffer(), last.line, last.line+1))); display_buffer.compute_range(); m_highlighters(*this, display_buffer); m_builtin_highlighters(*this, display_buffer); // now we can compute where the cursor is in display columns // (this is only valid if highlighting one line and multiple lines put // the cursor in the same position, however I do not find any sane example // of highlighters not doing that) CharCount column = 0; for (auto& atom : lines.back()) { if (atom.content.has_buffer_range() and atom.content.begin() <= last and atom.content.end() > last) { if (atom.content.type() == AtomContent::BufferRange) column += buffer().char_distance(atom.content.begin(), last); else column += atom.content.content().char_length(); CharCount first_col = first.line == last.line ? buffer().char_distance(last.line, first) : 0_char; if (first_col < m_position.column) m_position.column = first_col; else if (column >= m_position.column + m_dimensions.column) m_position.column = column - (m_dimensions.column - 1); CharCount last_col = buffer().char_distance(last.line, last); if (last_col < m_position.column) m_position.column = last_col; else if (column >= m_position.column + m_dimensions.column) m_position.column = column - (m_dimensions.column - 1); return; } column += atom.content.content().char_length(); } if (not buffer().is_end(last)) { // the cursor should always be visible. kak_assert(false); } } DisplayCoord Window::display_position(const BufferCoord& coord) { DisplayCoord res{0,0}; for (auto& line : m_display_buffer.lines()) { if (line.buffer_line() == coord.line) { for (auto& atom : line) { auto& content = atom.content; if (content.has_buffer_range() and coord >= content.begin() and coord < content.end()) { res.column += utf8::distance(buffer().iterator_at(content.begin()), buffer().iterator_at(coord)); return res; } res.column += content.length(); } } ++res.line; } return { 0, 0 }; } void Window::on_option_changed(const Option& option) { String desc = option.name() + "=" + option.get_as_string(); Context hook_context{*this}; m_hooks.run_hook("WinSetOption", desc, hook_context); } }
#include "window.hh" #include "assert.hh" #include "context.hh" #include "highlighter.hh" #include "hook_manager.hh" #include <algorithm> #include <sstream> namespace Kakoune { // Implementation in highlighters.cc void highlight_selections(const Window& window, DisplayBuffer& display_buffer); void expand_tabulations(const Window& window, DisplayBuffer& display_buffer); void expand_unprintable(const Window& window, DisplayBuffer& display_buffer); Window::Window(Buffer& buffer) : Editor(buffer), m_hooks(buffer.hooks()), m_options(buffer.options()) { Context hook_context{*this}; m_hooks.run_hook("WinCreate", buffer.name(), hook_context); m_options.register_watcher(*this); m_builtin_highlighters.append({"tabulations", expand_tabulations}); m_builtin_highlighters.append({"unprintable", expand_unprintable}); m_builtin_highlighters.append({"selections", highlight_selections}); for (auto& option : m_options.flatten_options()) on_option_changed(*option); } Window::~Window() { m_options.unregister_watcher(*this); } void Window::display_selection_at(LineCount line) { if (line >= 0 or line < m_dimensions.line) { auto cursor_line = main_selection().last().line; m_position.line = std::max(0_line, cursor_line - line); } } void Window::center_selection() { display_selection_at(m_dimensions.line/2_line); } void Window::scroll(LineCount offset) { m_position.line = std::max(0_line, m_position.line + offset); } void Window::update_display_buffer() { scroll_to_keep_cursor_visible_ifn(); DisplayBuffer::LineList& lines = m_display_buffer.lines(); lines.clear(); for (LineCount line = 0; line < m_dimensions.line; ++line) { LineCount buffer_line = m_position.line + line; if (buffer_line >= buffer().line_count()) break; BufferCoord limit{buffer_line+1, 0}; auto begin = std::min(buffer().char_advance(buffer_line, m_position.column), limit); auto end = std::min(buffer().char_advance(begin, m_dimensions.column), limit); lines.push_back(DisplayLine(buffer_line)); lines.back().push_back(DisplayAtom(AtomContent(buffer(), begin, end))); } m_display_buffer.compute_range(); m_highlighters(*this, m_display_buffer); m_builtin_highlighters(*this, m_display_buffer); m_display_buffer.optimize(); m_timestamp = buffer().timestamp(); } void Window::set_position(const DisplayCoord& position) { m_position.line = std::max(0_line, position.line); m_position.column = std::max(0_char, position.column); } void Window::set_dimensions(const DisplayCoord& dimensions) { m_dimensions = dimensions; } static LineCount adapt_view_pos(LineCount line, LineCount offset, LineCount view_pos, LineCount view_size, LineCount buffer_size) { if (line - offset < view_pos) return std::max(0_line, line - offset); else if (line + offset >= view_pos + view_size) return std::min(buffer_size - view_size, line + offset - (view_size - 1)); return view_pos; } void Window::scroll_to_keep_cursor_visible_ifn() { const auto& first = main_selection().first(); const auto& last = main_selection().last(); const LineCount offset = std::min<LineCount>(options()["scrolloff"].get<int>(), (m_dimensions.line - 1) / 2); // scroll lines if needed, try to get as much of the selection visible as possible m_position.line = adapt_view_pos(first.line, offset, m_position.line, m_dimensions.line, buffer().line_count()); m_position.line = adapt_view_pos(last.line, offset, m_position.line, m_dimensions.line, buffer().line_count()); // highlight only the line containing the cursor DisplayBuffer display_buffer; DisplayBuffer::LineList& lines = display_buffer.lines(); lines.push_back(DisplayLine(last.line)); lines.back().push_back(DisplayAtom(AtomContent(buffer(), last.line, last.line+1))); display_buffer.compute_range(); m_highlighters(*this, display_buffer); m_builtin_highlighters(*this, display_buffer); // now we can compute where the cursor is in display columns // (this is only valid if highlighting one line and multiple lines put // the cursor in the same position, however I do not find any sane example // of highlighters not doing that) CharCount column = 0; for (auto& atom : lines.back()) { if (atom.content.has_buffer_range() and atom.content.begin() <= last and atom.content.end() > last) { column += atom.content.length(); CharCount first_col = first.line == last.line ? buffer().char_distance(last.line, first) : 0_char; if (first_col < m_position.column) m_position.column = first_col; else if (column >= m_position.column + m_dimensions.column) m_position.column = column - (m_dimensions.column - 1); CharCount last_col = buffer().char_distance(last.line, last); if (last_col < m_position.column) m_position.column = last_col; else if (column >= m_position.column + m_dimensions.column) m_position.column = column - (m_dimensions.column - 1); return; } column += atom.content.content().char_length(); } if (not buffer().is_end(last)) { // the cursor should always be visible. kak_assert(false); } } DisplayCoord Window::display_position(const BufferCoord& coord) { DisplayCoord res{0,0}; for (auto& line : m_display_buffer.lines()) { if (line.buffer_line() == coord.line) { for (auto& atom : line) { auto& content = atom.content; if (content.has_buffer_range() and coord >= content.begin() and coord < content.end()) { res.column += utf8::distance(buffer().iterator_at(content.begin()), buffer().iterator_at(coord)); return res; } res.column += content.length(); } } ++res.line; } return { 0, 0 }; } void Window::on_option_changed(const Option& option) { String desc = option.name() + "=" + option.get_as_string(); Context hook_context{*this}; m_hooks.run_hook("WinSetOption", desc, hook_context); } }
use AtomContent::length in scroll_to_keep_cursor_visible_ifn
Window: use AtomContent::length in scroll_to_keep_cursor_visible_ifn
C++
unlicense
flavius/kakoune,Asenar/kakoune,alexherbo2/kakoune,mawww/kakoune,elegios/kakoune,ekie/kakoune,alexherbo2/kakoune,danr/kakoune,mawww/kakoune,alpha123/kakoune,alexherbo2/kakoune,casimir/kakoune,ekie/kakoune,Asenar/kakoune,zakgreant/kakoune,occivink/kakoune,jjthrash/kakoune,casimir/kakoune,Asenar/kakoune,jjthrash/kakoune,xificurC/kakoune,Somasis/kakoune,Somasis/kakoune,casimir/kakoune,elegios/kakoune,mawww/kakoune,occivink/kakoune,mawww/kakoune,zakgreant/kakoune,flavius/kakoune,zakgreant/kakoune,lenormf/kakoune,flavius/kakoune,rstacruz/kakoune,casimir/kakoune,jkonecny12/kakoune,Asenar/kakoune,rstacruz/kakoune,danielma/kakoune,Somasis/kakoune,lenormf/kakoune,jkonecny12/kakoune,occivink/kakoune,lenormf/kakoune,jjthrash/kakoune,jjthrash/kakoune,occivink/kakoune,danielma/kakoune,danr/kakoune,Somasis/kakoune,elegios/kakoune,ekie/kakoune,rstacruz/kakoune,xificurC/kakoune,alexherbo2/kakoune,alpha123/kakoune,danr/kakoune,xificurC/kakoune,zakgreant/kakoune,elegios/kakoune,alpha123/kakoune,jkonecny12/kakoune,lenormf/kakoune,rstacruz/kakoune,flavius/kakoune,xificurC/kakoune,danr/kakoune,alpha123/kakoune,danielma/kakoune,jkonecny12/kakoune,ekie/kakoune,danielma/kakoune
4833621f9b137824296d2c024862b23e0bb9f38a
src/worker.cc
src/worker.cc
#include <node.h> #include <nan.h> #include "./pow.h" using node::Buffer; using v8::Handle; using v8::Local; using v8::FunctionTemplate; using v8::Function; using v8::Value; using v8::Object; using v8::String; using v8::Number; static const uint64_t MAX_SAFE_INTEGER = 9007199254740991ULL; class PowWorker : public NanAsyncWorker { public: PowWorker(NanCallback* callback, size_t pool_size, uint64_t target, uint8_t* initial_hash) : NanAsyncWorker(callback), pool_size(pool_size), target(target), initial_hash(initial_hash) {} ~PowWorker() { delete[] initial_hash; } // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute () { error = pow(pool_size, target, initial_hash, MAX_SAFE_INTEGER, &nonce); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback () { NanScope(); if (error) { Local<Value> argv[1]; if (error == -1) { argv[0] = NanError("Max safe integer overflow"); } else { argv[0] = NanError("Internal error"); } callback->Call(1, argv); } else { Local<Value> argv[] = {NanNull(), NanNew<Number>(nonce)}; callback->Call(2, argv); } } private: size_t pool_size; uint64_t target; uint8_t* initial_hash; uint64_t nonce; int error; }; NAN_METHOD(PowAsync) { NanScope(); if (args.Length() != 4 || !args[0]->IsNumber() || // pool_size !args[1]->IsNumber() || // target !args[2]->IsObject() || // initial_hash !args[3]->IsFunction()) { // cb return NanThrowError("Bad input"); } size_t pool_size = args[0]->Uint32Value(); uint64_t target = args[1]->IntegerValue(); char* buf = Buffer::Data(args[2]->ToObject()); size_t length = Buffer::Length(args[2]->ToObject()); if (pool_size < 1 || pool_size > MAX_POOL_SIZE || buf == NULL || length != HASH_SIZE) { return NanThrowError("Bad input"); } // TODO(Kagami): Do we need to process `std::bad_alloc`? uint8_t* initial_hash = new uint8_t[length]; memcpy(initial_hash, buf, length); NanCallback* callback = new NanCallback(args[3].As<Function>()); NanAsyncQueueWorker(new PowWorker(callback, pool_size, target, initial_hash)); NanReturnUndefined(); } void InitAll(Handle<Object> exports) { exports->Set( NanNew<String>("powAsync"), NanNew<FunctionTemplate>(PowAsync)->GetFunction()); } NODE_MODULE(worker, InitAll)
#include <node.h> #include <nan.h> #include "./pow.h" using v8::Handle; using v8::Local; using v8::FunctionTemplate; using v8::Function; using v8::Value; using v8::Object; using v8::String; using v8::Number; static const uint64_t MAX_SAFE_INTEGER = 9007199254740991ULL; class PowWorker : public NanAsyncWorker { public: PowWorker(NanCallback* callback, size_t pool_size, uint64_t target, uint8_t* initial_hash) : NanAsyncWorker(callback), pool_size(pool_size), target(target), initial_hash(initial_hash) {} ~PowWorker() { delete[] initial_hash; } // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute () { error = pow(pool_size, target, initial_hash, MAX_SAFE_INTEGER, &nonce); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback () { NanScope(); if (error) { Local<Value> argv[1]; if (error == -1) { argv[0] = NanError("Max safe integer overflow"); } else { argv[0] = NanError("Internal error"); } callback->Call(1, argv); } else { Local<Value> argv[] = {NanNull(), NanNew<Number>(nonce)}; callback->Call(2, argv); } } private: size_t pool_size; uint64_t target; uint8_t* initial_hash; uint64_t nonce; int error; }; NAN_METHOD(PowAsync) { NanScope(); if (args.Length() != 4 || !args[0]->IsNumber() || // pool_size !args[1]->IsNumber() || // target !node::Buffer::HasInstance(args[2]) || // initial_hash !args[3]->IsFunction()) { // cb return NanThrowError("Bad input"); } size_t pool_size = args[0]->Uint32Value(); uint64_t target = args[1]->IntegerValue(); char* buf = node::Buffer::Data(args[2]); size_t length = node::Buffer::Length(args[2]); if (pool_size < 1 || pool_size > MAX_POOL_SIZE || buf == NULL || length != HASH_SIZE) { return NanThrowError("Bad input"); } // TODO(Kagami): Do we need to process `std::bad_alloc`? uint8_t* initial_hash = new uint8_t[length]; memcpy(initial_hash, buf, length); NanCallback* callback = new NanCallback(args[3].As<Function>()); NanAsyncQueueWorker(new PowWorker(callback, pool_size, target, initial_hash)); NanReturnUndefined(); } void InitAll(Handle<Object> exports) { exports->Set( NanNew<String>("powAsync"), NanNew<FunctionTemplate>(PowAsync)->GetFunction()); } NODE_MODULE(worker, InitAll)
Use node::Buffer directly, fix arg check
Use node::Buffer directly, fix arg check It was failing on node 0.12.
C++
cc0-1.0
bitchan/bitmessage,bitchan/bitmessage,bitchan/bitmessage,bitchan/bitmessage
89f331076e1fc1e8906f47e7d9533d4e20fb5818
src/xSW01.cpp
src/xSW01.cpp
/* This is a library for the SW01 DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR The board uses I2C for communication. The board communicates with the following I2C device: - BME280 Data Sheets: BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf */ #include "xSW01.h" #include <math.h> /*--Public Class Function--*/ /******************************************************** Constructor *********************************************************/ xSW01::xSW01(void) { tempcal = 0.0; temperature = 0.0; humidity = 0.0; pressure = 0.0; altitude = 0.0; dewpoint = 0.0; BME280_I2C_ADDRESS = 0x76; } xSW01::xSW01(uint8_t addr) { tempcal = 0.0; temperature = 0.0; humidity = 0.0; pressure = 0.0; altitude = 0.0; dewpoint = 0.0; BME280_I2C_ADDRESS = addr; } /******************************************************** Configure Sensor *********************************************************/ bool xSW01::begin(void) { readSensorCoefficients(); xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01); xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F); return true; } /******************************************************** Read Data from BME280 Sensor *********************************************************/ void xSW01::poll(void) { readTemperature(); readHumidity(); readPressure(); } /******************************************************** Read Pressure from BME280 Sensor in Pa *********************************************************/ float xSW01::getPressure(void) { return pressure; } /******************************************************** Read Altitude based on standard sea-level pressure *********************************************************/ float xSW01::getQNE(void) { float atmospheric = pressure / 100.0; altitude = 44330.0 * (1.0 - pow((atmospheric/1013.25), 1/5.255)); return altitude; } /******************************************************** Read Altitude from BME280 Sensor in meters *********************************************************/ float xSW01::getAltitude(float sea_level_pressure) { float atmospheric = pressure / 100.0; altitude = 44330.0 * (1.0 - pow((atmospheric/(sea_level_pressure/100.0)), 1/5.255)); return altitude; } /******************************************************** Temperature from BME280 Sensor in Celcuis *********************************************************/ float xSW01::getTempC(void) { temperature = temperature + tempcal; return temperature; } /******************************************************** Convert Temperature from BME280 Sensor to Farenhied *********************************************************/ float xSW01::getTempF(void) { temperature = temperature + tempcal; return temperature * 1.8 + 32; } /******************************************************** Read Humidity from BME280 Sensor *********************************************************/ float xSW01::getHumidity(void) { return humidity; } /******************************************************** Set temperature calibration data *********************************************************/ void xSW01::setTempCal(float offset) { tempcal = offset; } /******************************************************** Read Dew Point from BME280 Sensor in Celcuis *********************************************************/ float xSW01::getDewPoint(void) { dewpoint = 243.04 * (log(humidity/100.0) + ((17.625 * temperature)/(243.04 + temperature))) /(17.625 - log(humidity/100.0) - ((17.625 * temperature)/(243.04 + temperature))); return dewpoint; } /*--Private Class Function--*/ /******************************************************** Read Temperature from BME280 Sensor *********************************************************/ void xSW01::readTemperature(void) { int32_t var1, var2; int32_t rawTemp = ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 12); rawTemp |= ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4); rawTemp |= ((xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 4) & 0x0F); var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1)))*((int32_t)cal_data.dig_T2)) >> 11; var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1))*((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12)*((int32_t)cal_data.dig_T3)) >> 14; t_fine = var1 + var2; temperature = (t_fine * 5 + 128) >> 8; temperature = temperature / 100; } /******************************************************** Read Pressure from BME280 Sensor *********************************************************/ void xSW01::readPressure(void) { int64_t var1, var2, p; int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE); rawPressure >>= 4; var1 = ((int64_t)t_fine) - 128000; var2 = var1 * var1 * (int64_t)cal_data.dig_P6; var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17); var2 = var2 + (((int64_t)cal_data.dig_P4)<<35); var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) + ((var1 * (int64_t)cal_data.dig_P2)<<12); var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33; if (var1 == 0) { pressure = 0.0; } p = 1048576 - rawPressure; p = (((p<<31) - var2)*3125) / var1; var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25; var2 = (((int64_t)cal_data.dig_P8) * p) >> 19; p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4); pressure = (float)p/256; } /******************************************************** Read Humidity from BME280 Sensor *********************************************************/ void xSW01::readHumidity(void) { int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID); int32_t v_x1_u32r; v_x1_u32r = (t_fine - ((int32_t)76800)); v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) - (((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) * (((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r * ((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14)); v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((int32_t)cal_data.dig_H1)) >> 4)); v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r; v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r; float h = (v_x1_u32r>>12); humidity = h / 1024.0; } /******************************************************** Read Sensor Cailbration Data from BME280 Sensor *********************************************************/ void xSW01::readSensorCoefficients(void) { cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG); cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG); cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG); cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG); cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG); cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG); cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG); cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG); cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG); cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG); cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG); cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG); cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG); cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG); cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG); cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF); cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4); cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG); }
/* This is a library for the SW01 DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR The board uses I2C for communication. The board communicates with the following I2C device: - BME280 Data Sheets: BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf */ #include "xSW01.h" #include <math.h> /*--Public Class Function--*/ /******************************************************** Constructor *********************************************************/ xSW01::xSW01(void) { tempcal = 0.0; temperature = 0.0; humidity = 0.0; pressure = 0.0; altitude = 0.0; dewpoint = 0.0; BME280_I2C_ADDRESS = 0x76; } xSW01::xSW01(uint8_t addr) { tempcal = 0.0; temperature = 0.0; humidity = 0.0; pressure = 0.0; altitude = 0.0; dewpoint = 0.0; BME280_I2C_ADDRESS = addr; } /******************************************************** Configure Sensor *********************************************************/ bool xSW01::begin(void) { readSensorCoefficients(); xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01); xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F); return true; } /******************************************************** Read Data from BME280 Sensor *********************************************************/ void xSW01::poll(void) { readTemperature(); readHumidity(); readPressure(); } /******************************************************** Read Pressure from BME280 Sensor in Pa *********************************************************/ float xSW01::getPressure(void) { return pressure; } /******************************************************** Read Altitude based on standard sea-level pressure *********************************************************/ float xSW01::getQNE(void) { float atmospheric = pressure / 100.0; altitude = 44330.0 * (1.0 - pow((atmospheric/1013.25), 1/5.255)); return altitude; } /******************************************************** Read Altitude from BME280 Sensor in meters *********************************************************/ float xSW01::getAltitude(float sea_level_pressure) { float atmospheric = pressure / 100.0; altitude = 44330.0 * (1.0 - pow((atmospheric/(sea_level_pressure/100.0)), 1/5.255)); return altitude; } /******************************************************** Temperature from BME280 Sensor in Celcuis *********************************************************/ float xSW01::getTempC(void) { temperature = temperature + tempcal; return temperature; } /******************************************************** Convert Temperature from BME280 Sensor to Farenhied *********************************************************/ float xSW01::getTempF(void) { temperature = temperature + tempcal; return temperature * 1.8 + 32; } /******************************************************** Read Humidity from BME280 Sensor *********************************************************/ float xSW01::getHumidity(void) { return humidity; } /******************************************************** Set temperature calibration data *********************************************************/ void xSW01::setTempCal(float offset) { tempcal = offset; } /******************************************************** Read Dew Point from BME280 Sensor in Celcuis *********************************************************/ float xSW01::getDewPoint(void) { dewpoint = 243.04 * (log(humidity/100.0) + ((17.625 * temperature)/(243.04 + temperature))) /(17.625 - log(humidity/100.0) - ((17.625 * temperature)/(243.04 + temperature))); return dewpoint; } /*--Private Class Function--*/ /******************************************************** Read Temperature from BME280 Sensor *********************************************************/ void xSW01::readTemperature(void) { int32_t var1, var2; int32_t rawTemp = ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_MSB) << 12); rawTemp |= ((uint32_t)xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_CSB) << 4); rawTemp |= ((xCore.read8(BME280_I2C_ADDRESS, BME280_REG_TEMP_LSB) << 4) & 0x0F); var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1)))*((int32_t)cal_data.dig_T2)) >> 11; var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1))*((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12)*((int32_t)cal_data.dig_T3)) >> 14; t_fine = var1 + var2; temperature = (t_fine * 5 + 128) >> 8; temperature = temperature / 100; } /******************************************************** Read Pressure from BME280 Sensor *********************************************************/ void xSW01::readPressure(void) { int64_t var1, var2, p; int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE); rawPressure >>= 4; var1 = ((int64_t)t_fine) - 128000; var2 = var1 * var1 * (int64_t)cal_data.dig_P6; var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17); var2 = var2 + (((int64_t)cal_data.dig_P4)<<35); var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) + ((var1 * (int64_t)cal_data.dig_P2)<<12); var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33; if (var1 == 0) { pressure = 0.0; } p = 1048576 - rawPressure; p = (((p<<31) - var2)*3125) / var1; var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25; var2 = (((int64_t)cal_data.dig_P8) * p) >> 19; p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4); pressure = (float)p/256; } /******************************************************** Read Humidity from BME280 Sensor *********************************************************/ void xSW01::readHumidity(void) { int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID); int32_t v_x1_u32r; v_x1_u32r = (t_fine - ((int32_t)76800)); v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) - (((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) * (((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r * ((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14)); v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((int32_t)cal_data.dig_H1)) >> 4)); v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r; v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r; float h = (v_x1_u32r>>12); humidity = h / 1024.0; } /******************************************************** Read Sensor Cailbration Data from BME280 Sensor *********************************************************/ void xSW01::readSensorCoefficients(void) { cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG); cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG); cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG); cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG); cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG); cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG); cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG); cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG); cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG); cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG); cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG); cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG); cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG); cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG); cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG); cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF); cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4); cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG); }
Update xSW01.cpp
Update xSW01.cpp
C++
mit
xinabox/xSW01
c1d67393d9efe86a581058521a850f4e435500a2
src2/main.cpp
src2/main.cpp
#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%d, stop=%d\n", eventCount, stop); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883", false, "tcp://localhost:1883", "string", cmd); TCLAP::ValueArg<std::string> topicName("t", "destinationName", "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("Z", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 5, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); return 0; }
#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%d, stop=%d\n", eventCount, stop); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883", false, "tcp://localhost:1883", "string", cmd); TCLAP::ValueArg<std::string> topicName("t", "destinationName", "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("Z", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::SwitchArg generateTestData("T", "generateTestData", "Indicate that test data should be generated", false); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 5, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); cmd.add(generateTestData); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); command.setGenerateTestData(generateTestData.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); return 0; }
Add a generateTestData flag
Add a generateTestData flag
C++
apache-2.0
starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser
091b215041ca3b552bdbf0c50bfc2e55afa29bfd
apps/ConnectionHost.cpp
apps/ConnectionHost.cpp
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <ogvr/PluginKit/RegistrationContext.h> #include <ogvr/PluginKit/Connection.h> // Library/third-party includes // - none // Standard includes #include <iostream> #include <exception> int main(int argc, char * argv[]) { if (argc < 2) { std::cerr << "Must supply a plugin name to load." << std::endl; return 1; } ogvr::RegistrationContext ctx; ogvr::ConnectionPtr conn = ogvr::Connection::createLocalConnection(); ogvr::Connection::storeConnection(ctx, conn); try { std::cout << "Trying to load plugin " << argv[1] << std::endl; ctx.loadPlugin(argv[1]); std::cout << "Successfully loaded plugin, control returned to host application!" << std::endl; } catch (std::exception & e) { std::cerr << "Caught exception tring to load " << argv[1] << ": " << e.what() << std::endl; return 1; } std::cout << "Running connection processing 500 times" << std::endl; for (int i = 0; i < 500; ++i) { conn->process(); } return 0; }
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <ogvr/PluginKit/RegistrationContext.h> #include <ogvr/PluginKit/Connection.h> // Library/third-party includes // - none // Standard includes #include <iostream> #include <exception> int main(int argc, char * argv[]) { if (argc < 2) { std::cerr << "Must supply a plugin name to load." << std::endl; return 1; } ogvr::RegistrationContext ctx; ogvr::ConnectionPtr conn = ogvr::Connection::createLocalConnection(); ogvr::Connection::storeConnection(ctx, conn); try { std::cout << "Trying to load plugin " << argv[1] << std::endl; ctx.loadPlugin(argv[1]); std::cout << "Successfully loaded plugin, control returned to host application!" << std::endl; } catch (std::exception & e) { std::cerr << "Caught exception tring to load " << argv[1] << ": " << e.what() << std::endl; return 1; } int count = 20; std::cout << "Running connection processing " << count << " times" << std::endl; for (int i = 0; i < count; ++i) { conn->process(); } return 0; }
Reduce the number of loops for debugging.
Reduce the number of loops for debugging.
C++
apache-2.0
OSVR/OSVR-Core,feilen/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,leemichaelRazer/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core
3d8b3708771343e7120718fef9866ddda9d230d5
audio/audio_decoder.cpp
audio/audio_decoder.cpp
// This file is part of Playslave-C++. // Playslave-C++ is licenced under the MIT license: see LICENSE.txt. /** * @file * Implementation of the AudioDecoder class. * @see audio/audio_decoder.hpp */ #include <functional> #include <string> #include <memory> #include <cstdlib> #include <cstdint> #include <iostream> #include <sstream> #include <map> /* ffmpeg */ extern "C" { #ifdef WIN32 #define inline __inline #endif #include <libavcodec/avcodec.h> #include <libavcodec/version.h> /* For old version patchups */ #include <libavformat/avformat.h> #include <libavutil/opt.h> } #include "../errors.hpp" #include "../constants.h" #include "../messages.h" #include "../sample_formats.hpp" #include "audio_decoder.hpp" #include "audio_resample.hpp" AudioDecoder::AudioDecoder(const std::string &path) { this->buffer = std::unique_ptr<unsigned char[]>( new unsigned char[BUFFER_SIZE]); Open(path); InitialiseStream(); InitialisePacket(); InitialiseFrame(); InitialiseResampler(); Debug("stream id:", this->stream_id); Debug("codec:", this->stream->codec->codec->long_name); } AudioDecoder::~AudioDecoder() { } /* @return The number of channels this decoder outputs. */ std::uint8_t AudioDecoder::ChannelCount() const { return this->stream->codec->channels; } /* @return The size of this decoder's buffer, in samples. */ size_t AudioDecoder::BufferSampleCapacity() const { return SampleCountForByteCount(BUFFER_SIZE); } /* @return The sample rate. */ double AudioDecoder::SampleRate() const { return (double)this->stream->codec->sample_rate; } /* Converts stream position (in microseconds) to estimated sample count. */ std::uint64_t AudioDecoder::SampleCountForPositionMicroseconds( std::chrono::microseconds usec) const { auto sample_micros = usec * SampleRate(); return std::chrono::duration_cast<std::chrono::seconds>(sample_micros) .count(); } /* Converts sample count to estimated stream position (in microseconds). */ std::chrono::microseconds AudioDecoder::PositionMicrosecondsForSampleCount( std::uint64_t samples) const { auto position_secs = std::chrono::seconds(samples) / SampleRate(); return std::chrono::duration_cast<std::chrono::microseconds>( position_secs); } /* Converts buffer size (in bytes) to sample count (in samples). */ std::uint64_t AudioDecoder::SampleCountForByteCount(std::uint64_t bytes) const { return (bytes / ChannelCount()) / BytesPerSample(); } /* Converts sample count (in samples) to buffer size (in bytes). */ std::uint64_t AudioDecoder::ByteCountForSampleCount(std::uint64_t samples) const { return (samples * ChannelCount()) * BytesPerSample(); } /* Returns the current number of bytes per sample. */ size_t AudioDecoder::BytesPerSample() const { return av_get_bytes_per_sample(this->resampler->AVOutputFormat()); } /* Attempts to seek to the position 'usec' milliseconds into the file. */ void AudioDecoder::SeekToPositionMicroseconds( std::chrono::microseconds position) { std::int64_t ffmpeg_position = AvPositionFromMicroseconds(position); Debug("Seeking to:", ffmpeg_position); if (av_seek_frame(this->context.get(), this->stream_id, ffmpeg_position, AVSEEK_FLAG_ANY) != 0) { throw InternalError(MSG_SEEK_FAIL); } } std::int64_t AudioDecoder::AvPositionFromMicroseconds( std::chrono::microseconds position) { auto position_timebase_microseconds = (position * this->stream->time_base.den) / this->stream->time_base.num; auto position_timebase_seconds = std::chrono::duration_cast<std::chrono::seconds>( position_timebase_microseconds); return position_timebase_seconds.count(); } /* Tries to decode an entire frame and returns a vector of its contents. * * If successful, returns a pointer to the resulting vector of decoded data, * which is owned by the caller. If the return value is nullptr, we have run * out of frames to decode. */ std::vector<char> AudioDecoder::Decode() { bool complete = false; bool more = true; std::vector<char> vec; while (!complete && more) { if (av_read_frame(this->context.get(), this->packet.get()) < 0) { more = false; } else if (this->packet->stream_index == this->stream_id) { complete = DecodePacket(); if (complete) { vec = Resample(); } } } return vec; } std::vector<char> AudioDecoder::Resample() { return this->resampler->Resample(this->frame.get()); } static std::map<AVSampleFormat, SampleFormat> sf_from_av = { {AV_SAMPLE_FMT_U8, SampleFormat::PACKED_UNSIGNED_INT_8}, {AV_SAMPLE_FMT_S16, SampleFormat::PACKED_SIGNED_INT_16}, {AV_SAMPLE_FMT_S32, SampleFormat::PACKED_SIGNED_INT_32}, {AV_SAMPLE_FMT_FLT, SampleFormat::PACKED_FLOAT_32}}; /** * @return The sample format of the data returned by this decoder. */ SampleFormat AudioDecoder::OutputSampleFormat() const { try { return sf_from_av.at(this->resampler->AVOutputFormat()); } catch (std::out_of_range) { throw FileError(MSG_DECODE_BADRATE); } } void AudioDecoder::Open(const std::string &path) { AVFormatContext *ctx = nullptr; if (avformat_open_input(&ctx, path.c_str(), NULL, NULL) < 0) { std::ostringstream os; os << "couldn't open " << path; throw FileError(os.str()); } auto free_context = [](AVFormatContext *ctx) { avformat_close_input(&ctx); }; this->context = std::unique_ptr<AVFormatContext, decltype(free_context)>(ctx, free_context); } void AudioDecoder::InitialiseStream() { FindStreamInfo(); FindStreamAndInitialiseCodec(); } void AudioDecoder::FindStreamInfo() { if (avformat_find_stream_info(this->context.get(), NULL) < 0) { throw FileError(MSG_DECODE_NOAUDIO); } } void AudioDecoder::FindStreamAndInitialiseCodec() { AVCodec *codec; int stream = av_find_best_stream(this->context.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); if (stream < 0) { throw FileError(MSG_DECODE_NOSTREAM); } InitialiseCodec(stream, codec); } void AudioDecoder::InitialiseCodec(int stream, AVCodec *codec) { AVCodecContext *codec_context = this->context->streams[stream]->codec; if (avcodec_open2(codec_context, codec, NULL) < 0) { throw FileError(MSG_DECODE_NOCODEC); } this->stream = this->context->streams[stream]; this->stream_id = stream; } void AudioDecoder::InitialiseFrame() { auto frame_deleter = [](AVFrame *frame) { av_frame_free(&frame); }; this->frame = std::unique_ptr<AVFrame, decltype(frame_deleter)>( av_frame_alloc(), frame_deleter); if (this->frame == nullptr) { throw std::bad_alloc(); } } void AudioDecoder::InitialisePacket() { auto packet_deleter = [](AVPacket *packet) { av_free_packet(packet); delete packet; }; this->packet = std::unique_ptr<AVPacket, decltype(packet_deleter)>( new AVPacket, packet_deleter); AVPacket *pkt = this->packet.get(); av_init_packet(pkt); pkt->data = this->buffer.get(); pkt->size = BUFFER_SIZE; } void AudioDecoder::InitialiseResampler() { std::function<Resampler *(const SampleByteConverter &, AVCodecContext *)> rs; if (UsingPlanarSampleFormat()) { rs = [](const SampleByteConverter &s, AVCodecContext *c) { return new PlanarResampler(s, c); }; } else { rs = [](const SampleByteConverter &s, AVCodecContext *c) { return new PackedResampler(s, c); }; } this->resampler = std::unique_ptr<Resampler>( rs(*this, this->stream->codec)); } bool AudioDecoder::UsingPlanarSampleFormat() { return av_sample_fmt_is_planar(this->stream->codec->sample_fmt); } bool AudioDecoder::DecodePacket() { int frame_finished = 0; if (avcodec_decode_audio4(this->stream->codec, this->frame.get(), &frame_finished, this->packet.get()) < 0) { throw FileError(MSG_DECODE_FAIL); } return frame_finished; }
// This file is part of Playslave-C++. // Playslave-C++ is licenced under the MIT license: see LICENSE.txt. /** * @file * Implementation of the AudioDecoder class. * @see audio/audio_decoder.hpp */ #include <functional> #include <string> #include <memory> #include <cstdlib> #include <cstdint> #include <iostream> #include <sstream> #include <map> /* ffmpeg */ extern "C" { #ifdef WIN32 #define inline __inline #endif #include <libavcodec/avcodec.h> #include <libavcodec/version.h> /* For old version patchups */ #include <libavformat/avformat.h> #include <libavutil/opt.h> } #include "../errors.hpp" #include "../constants.h" #include "../messages.h" #include "../sample_formats.hpp" #include "audio_decoder.hpp" #include "audio_resample.hpp" AudioDecoder::AudioDecoder(const std::string &path) { this->buffer = std::unique_ptr<unsigned char[]>( new unsigned char[BUFFER_SIZE]); Open(path); InitialiseStream(); InitialisePacket(); InitialiseFrame(); InitialiseResampler(); Debug("stream id:", this->stream_id); Debug("codec:", this->stream->codec->codec->long_name); } AudioDecoder::~AudioDecoder() { } /* @return The number of channels this decoder outputs. */ std::uint8_t AudioDecoder::ChannelCount() const { return this->stream->codec->channels; } /* @return The size of this decoder's buffer, in samples. */ size_t AudioDecoder::BufferSampleCapacity() const { return SampleCountForByteCount(BUFFER_SIZE); } /* @return The sample rate. */ double AudioDecoder::SampleRate() const { return (double)this->stream->codec->sample_rate; } /* Converts stream position (in microseconds) to estimated sample count. */ std::uint64_t AudioDecoder::SampleCountForPositionMicroseconds( std::chrono::microseconds usec) const { auto sample_micros = usec * SampleRate(); return std::chrono::duration_cast<std::chrono::seconds>(sample_micros) .count(); } /* Converts sample count to estimated stream position (in microseconds). */ std::chrono::microseconds AudioDecoder::PositionMicrosecondsForSampleCount( std::uint64_t samples) const { auto position_secs = std::chrono::seconds(samples) / SampleRate(); return std::chrono::duration_cast<std::chrono::microseconds>( position_secs); } /* Converts buffer size (in bytes) to sample count (in samples). */ std::uint64_t AudioDecoder::SampleCountForByteCount(std::uint64_t bytes) const { return (bytes / ChannelCount()) / BytesPerSample(); } /* Converts sample count (in samples) to buffer size (in bytes). */ std::uint64_t AudioDecoder::ByteCountForSampleCount(std::uint64_t samples) const { return (samples * ChannelCount()) * BytesPerSample(); } /* Returns the current number of bytes per sample. */ size_t AudioDecoder::BytesPerSample() const { return av_get_bytes_per_sample(this->resampler->AVOutputFormat()); } /* Attempts to seek to the position 'usec' milliseconds into the file. */ void AudioDecoder::SeekToPositionMicroseconds( std::chrono::microseconds position) { std::int64_t ffmpeg_position = AvPositionFromMicroseconds(position); Debug("Seeking to:", ffmpeg_position); if (av_seek_frame(this->context.get(), this->stream_id, ffmpeg_position, AVSEEK_FLAG_ANY) != 0) { throw InternalError(MSG_SEEK_FAIL); } } std::int64_t AudioDecoder::AvPositionFromMicroseconds( std::chrono::microseconds position) { auto position_timebase_microseconds = (position * this->stream->time_base.den) / this->stream->time_base.num; auto position_timebase_seconds = std::chrono::duration_cast<std::chrono::seconds>( position_timebase_microseconds); return position_timebase_seconds.count(); } std::vector<char> AudioDecoder::Decode() { bool complete = false; bool more = true; std::vector<char> vec; while (!complete && more) { if (av_read_frame(this->context.get(), this->packet.get()) < 0) { more = false; } else if (this->packet->stream_index == this->stream_id) { complete = DecodePacket(); if (complete) { vec = Resample(); } } } return vec; } std::vector<char> AudioDecoder::Resample() { return this->resampler->Resample(this->frame.get()); } static std::map<AVSampleFormat, SampleFormat> sf_from_av = { {AV_SAMPLE_FMT_U8, SampleFormat::PACKED_UNSIGNED_INT_8}, {AV_SAMPLE_FMT_S16, SampleFormat::PACKED_SIGNED_INT_16}, {AV_SAMPLE_FMT_S32, SampleFormat::PACKED_SIGNED_INT_32}, {AV_SAMPLE_FMT_FLT, SampleFormat::PACKED_FLOAT_32}}; /** * @return The sample format of the data returned by this decoder. */ SampleFormat AudioDecoder::OutputSampleFormat() const { try { return sf_from_av.at(this->resampler->AVOutputFormat()); } catch (std::out_of_range) { throw FileError(MSG_DECODE_BADRATE); } } void AudioDecoder::Open(const std::string &path) { AVFormatContext *ctx = nullptr; if (avformat_open_input(&ctx, path.c_str(), NULL, NULL) < 0) { std::ostringstream os; os << "couldn't open " << path; throw FileError(os.str()); } auto free_context = [](AVFormatContext *ctx) { avformat_close_input(&ctx); }; this->context = std::unique_ptr<AVFormatContext, decltype(free_context)>(ctx, free_context); } void AudioDecoder::InitialiseStream() { FindStreamInfo(); FindStreamAndInitialiseCodec(); } void AudioDecoder::FindStreamInfo() { if (avformat_find_stream_info(this->context.get(), NULL) < 0) { throw FileError(MSG_DECODE_NOAUDIO); } } void AudioDecoder::FindStreamAndInitialiseCodec() { AVCodec *codec; int stream = av_find_best_stream(this->context.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); if (stream < 0) { throw FileError(MSG_DECODE_NOSTREAM); } InitialiseCodec(stream, codec); } void AudioDecoder::InitialiseCodec(int stream, AVCodec *codec) { AVCodecContext *codec_context = this->context->streams[stream]->codec; if (avcodec_open2(codec_context, codec, NULL) < 0) { throw FileError(MSG_DECODE_NOCODEC); } this->stream = this->context->streams[stream]; this->stream_id = stream; } void AudioDecoder::InitialiseFrame() { auto frame_deleter = [](AVFrame *frame) { av_frame_free(&frame); }; this->frame = std::unique_ptr<AVFrame, decltype(frame_deleter)>( av_frame_alloc(), frame_deleter); if (this->frame == nullptr) { throw std::bad_alloc(); } } void AudioDecoder::InitialisePacket() { auto packet_deleter = [](AVPacket *packet) { av_free_packet(packet); delete packet; }; this->packet = std::unique_ptr<AVPacket, decltype(packet_deleter)>( new AVPacket, packet_deleter); AVPacket *pkt = this->packet.get(); av_init_packet(pkt); pkt->data = this->buffer.get(); pkt->size = BUFFER_SIZE; } void AudioDecoder::InitialiseResampler() { std::function<Resampler *(const SampleByteConverter &, AVCodecContext *)> rs; if (UsingPlanarSampleFormat()) { rs = [](const SampleByteConverter &s, AVCodecContext *c) { return new PlanarResampler(s, c); }; } else { rs = [](const SampleByteConverter &s, AVCodecContext *c) { return new PackedResampler(s, c); }; } this->resampler = std::unique_ptr<Resampler>( rs(*this, this->stream->codec)); } bool AudioDecoder::UsingPlanarSampleFormat() { return av_sample_fmt_is_planar(this->stream->codec->sample_fmt); } bool AudioDecoder::DecodePacket() { int frame_finished = 0; if (avcodec_decode_audio4(this->stream->codec, this->frame.get(), &frame_finished, this->packet.get()) < 0) { throw FileError(MSG_DECODE_FAIL); } return frame_finished; }
Remove erroneous comment.
Remove erroneous comment.
C++
mit
LordAro/ury-playd,LordAro/ury-playd,LordAro/ury-playd
53185fde11cfd97fdd2f5c4787b3f7d1d6031461
paddle/fluid/operators/math/sequence_pooling.cc
paddle/fluid/operators/math/sequence_pooling.cc
/* Copyright (c) 2016 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 "paddle/fluid/operators/math/sequence_pooling.h" #include <string> #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { namespace math { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenVector = framework::EigenVector<T, MajorType, IndexType>; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; template <typename T> class MaxSeqPoolFunctor { public: void operator()(const platform::CPUDeviceContext& context, const framework::LoDTensor& input, framework::Tensor* output, framework::Tensor* index) { auto in_dims = input.dims(); auto out_dims = output->dims(); auto idx_dims = index->dims(); PADDLE_ENFORCE_GT(in_dims.size(), 1); PADDLE_ENFORCE_GT(out_dims.size(), 1); for (int64_t i = 1; i < in_dims.size(); ++i) { PADDLE_ENFORCE_EQ(in_dims[i], out_dims[i]); } PADDLE_ENFORCE_EQ(idx_dims, out_dims); auto starts = input.lod()[0]; const T* in_data = input.data<T>(); T* out_data = output->data<T>(); int* max_index = index->data<int>(); int64_t num_seq = out_dims[0]; int64_t dim = output->numel() / num_seq; for (int64_t i = 0; i < num_seq; ++i) { for (int64_t k = 0; k < dim; ++k) { out_data[i * dim + k] = in_data[starts[i] * dim + k]; max_index[i * dim + k] = starts[i]; } for (size_t j = starts[i] + 1; j < starts[i + 1]; ++j) { for (int64_t k = 0; k < dim; ++k) { if (in_data[j * dim + k] > out_data[i * dim + k]) { out_data[i * dim + k] = in_data[j * dim + k]; max_index[i * dim + k] = j; } } } } } }; template <typename T> class MaxSeqPoolGradFunctor { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& out_grad, const framework::Tensor& index, framework::LoDTensor* in_grad) { auto og_dims = out_grad.dims(); auto ig_dims = in_grad->dims(); auto idx_dims = index.dims(); PADDLE_ENFORCE_GT(og_dims.size(), 1); PADDLE_ENFORCE_GT(ig_dims.size(), 1); for (int64_t i = 1; i < og_dims.size(); ++i) { PADDLE_ENFORCE_EQ(og_dims[i], ig_dims[i]); } PADDLE_ENFORCE_EQ(idx_dims, og_dims); const T* og_data = out_grad.data<T>(); const int* max_index = index.data<int>(); T* ig_data = in_grad->data<T>(); SetConstant<platform::CPUDeviceContext, T> set_zero; set_zero(context, in_grad, static_cast<T>(0.0)); int64_t num_seq = og_dims[0]; int64_t dim = out_grad.numel() / num_seq; for (int64_t i = 0; i < num_seq; ++i) { for (int64_t j = 0; j < dim; ++j) { int step_id = max_index[i * dim + j]; ig_data[step_id * dim + j] = og_data[i * dim + j]; } } } }; template <typename T> class SequencePoolFunctor<platform::CPUDeviceContext, T> { public: /* max pool has index output */ void operator()(const platform::CPUDeviceContext& context, const std::string pooltype, const framework::LoDTensor& input, framework::Tensor* output, framework::Tensor* index = nullptr) { if (pooltype == "MAX") { math::MaxSeqPoolFunctor<T> max_pool; max_pool(context, input, output, index); return; } auto lod = input.lod()[0]; auto& place = *context.eigen_device(); for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) { Tensor in_t = input.Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1])); Tensor out_t = output->Slice(i, i + 1); int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]); int64_t w = input.numel() / input.dims()[0]; auto in_e = EigenMatrix<T>::From(in_t, framework::make_ddim({h, w})); auto out_e = EigenVector<T>::Flatten(out_t); if (pooltype == "AVERAGE") { out_e.device(place) = in_e.mean(Eigen::array<int, 1>({{0}})); } else if (pooltype == "SUM") { out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})); } else if (pooltype == "SQRT") { out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})) / std::sqrt(static_cast<T>(h)); } else if (pooltype == "LAST") { out_e.device(place) = in_e.chip(h - 1, 0); } else if (pooltype == "FIRST") { out_e.device(place) = in_e.chip(0, 0); } else { PADDLE_THROW("unsupported pooling pooltype"); } } } }; template <typename T> class SequencePoolGradFunctor<platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const std::string pooltype, const framework::Tensor& out_grad, framework::LoDTensor* in_grad, /* max pool has index */ const framework::Tensor* index = nullptr) { if (pooltype == "MAX") { math::MaxSeqPoolGradFunctor<T> max_pool_grad; max_pool_grad(context, out_grad, *index, in_grad); return; } if (pooltype == "LAST" || pooltype == "FIRST") { // set X@Grad be zero at first when pooltype is LAST/FIRST math::SetConstant<platform::CPUDeviceContext, T> functor; functor(context, in_grad, 0); } auto lod = in_grad->lod()[0]; auto& place = *context.eigen_device(); for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) { auto in_g_t = in_grad->Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1])); auto out_g_t = out_grad.Slice(i, i + 1); int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]); int64_t w = in_grad->numel() / in_grad->dims()[0]; auto in_g_e = EigenMatrix<T>::From(in_g_t, {h, w}); auto out_g_e = EigenMatrix<T>::From(out_g_t, {1, w}); auto out_g_e_v = EigenVector<T>::Flatten(out_g_t); Eigen::DSizes<int, 2> bcast(h, 1); if (pooltype == "AVERAGE") { in_g_e.device(place) = (out_g_e / static_cast<T>(h)).broadcast(bcast); } else if (pooltype == "SUM") { in_g_e.device(place) = (out_g_e).broadcast(bcast); } else if (pooltype == "SQRT") { in_g_e.device(place) = (out_g_e / std::sqrt(static_cast<T>(h))).broadcast(bcast); } else if (pooltype == "LAST") { in_g_e.chip(h - 1, 0).device(place) = out_g_e_v; } else if (pooltype == "FIRST") { in_g_e.chip(0, 0).device(place) = out_g_e_v; } else { PADDLE_THROW("unsupported pooling pooltype"); } } } }; template class SequencePoolFunctor<platform::CPUDeviceContext, float>; template class SequencePoolFunctor<platform::CPUDeviceContext, double>; template class SequencePoolGradFunctor<platform::CPUDeviceContext, float>; template class SequencePoolGradFunctor<platform::CPUDeviceContext, double>; } // namespace math } // namespace operators } // namespace paddle
/* Copyright (c) 2016 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 "paddle/fluid/operators/math/sequence_pooling.h" #include <string> #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { namespace math { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenVector = framework::EigenVector<T, MajorType, IndexType>; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; template <typename T> class MaxSeqPoolFunctor { public: void operator()(const platform::CPUDeviceContext& context, const framework::LoDTensor& input, framework::Tensor* output, framework::Tensor* index) { auto in_dims = input.dims(); auto out_dims = output->dims(); auto idx_dims = index->dims(); PADDLE_ENFORCE_GT(in_dims.size(), 1); PADDLE_ENFORCE_GT(out_dims.size(), 1); for (int64_t i = 1; i < in_dims.size(); ++i) { PADDLE_ENFORCE_EQ(in_dims[i], out_dims[i]); } PADDLE_ENFORCE_EQ(idx_dims, out_dims); auto starts = input.lod()[0]; const T* in_data = input.data<T>(); T* out_data = output->data<T>(); int* max_index = index->data<int>(); int64_t num_seq = out_dims[0]; int64_t dim = output->numel() / num_seq; for (int64_t i = 0; i < num_seq; ++i) { for (int64_t k = 0; k < dim; ++k) { out_data[i * dim + k] = in_data[starts[i] * dim + k]; max_index[i * dim + k] = starts[i]; } for (size_t j = starts[i] + 1; j < starts[i + 1]; ++j) { for (int64_t k = 0; k < dim; ++k) { if (in_data[j * dim + k] > out_data[i * dim + k]) { out_data[i * dim + k] = in_data[j * dim + k]; max_index[i * dim + k] = j; } } } } } }; template <typename T> class MaxSeqPoolGradFunctor { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& out_grad, const framework::Tensor& index, framework::LoDTensor* in_grad) { auto og_dims = out_grad.dims(); auto ig_dims = in_grad->dims(); auto idx_dims = index.dims(); PADDLE_ENFORCE_GT(og_dims.size(), 1); PADDLE_ENFORCE_GT(ig_dims.size(), 1); for (int64_t i = 1; i < og_dims.size(); ++i) { PADDLE_ENFORCE_EQ(og_dims[i], ig_dims[i]); } PADDLE_ENFORCE_EQ(idx_dims, og_dims); const T* og_data = out_grad.data<T>(); const int* max_index = index.data<int>(); T* ig_data = in_grad->data<T>(); SetConstant<platform::CPUDeviceContext, T> set_zero; set_zero(context, in_grad, static_cast<T>(0.0)); int64_t num_seq = og_dims[0]; int64_t dim = out_grad.numel() / num_seq; for (int64_t i = 0; i < num_seq; ++i) { for (int64_t j = 0; j < dim; ++j) { int step_id = max_index[i * dim + j]; ig_data[step_id * dim + j] = og_data[i * dim + j]; } } } }; template <typename T> class LastFirstSeqPoolFunctor { public: void operator()(const platform::CPUDeviceContext& context, const framework::LoDTensor& input, framework::Tensor* output, const std::string pooltype) { auto* in_data = input.data<T>(); auto* out_data = output->data<T>(); int64_t word_len = input.numel() / input.dims()[0]; auto lod = input.lod()[0]; auto dims = input.dims(); if (pooltype == "LAST"){ for (int i=0; i < static_cast<int>(lod.size()) - 1; ++i ){ int64_t seq_len = static_cast<int64_t>(lod[i + 1] - lod[i]); in_data += seq_len* word_len; std::memcpy(out_data,(in_data-word_len),word_len*sizeof(int)); out_data += word_len; } } else if(pooltype == "FIRST"){ for (int i=0; i < static_cast<int>(lod.size()) - 1; ++i ){ int64_t seq_len = static_cast<int64_t>(lod[i + 1] - lod[i]); std::memcpy(out_data,in_data,word_len*sizeof(int)); in_data += seq_len * word_len; out_data += word_len; } } } }; template <typename T> class SequencePoolFunctor<platform::CPUDeviceContext, T> { public: /* max pool has index output */ void operator()(const platform::CPUDeviceContext& context, const std::string pooltype, const framework::LoDTensor& input, framework::Tensor* output, framework::Tensor* index = nullptr) { if (pooltype == "MAX") { math::MaxSeqPoolFunctor<T> max_pool; max_pool(context, input, output, index); return; } if (pooltype == "LAST" || pooltype == "FIRST") { math::LastFirstSeqPoolFunctor<T> lastfirst_pool; lastfirst_pool(context, input, output, pooltype); return; } auto lod = input.lod()[0]; auto& place = *context.eigen_device(); for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) { Tensor in_t = input.Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1])); Tensor out_t = output->Slice(i, i + 1); int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]); int64_t w = input.numel() / input.dims()[0]; auto in_e = EigenMatrix<T>::From(in_t, framework::make_ddim({h, w})); auto out_e = EigenVector<T>::Flatten(out_t); if (pooltype == "AVERAGE") { out_e.device(place) = in_e.mean(Eigen::array<int, 1>({{0}})); } else if (pooltype == "SUM") { out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})); } else if (pooltype == "SQRT") { out_e.device(place) = in_e.sum(Eigen::array<int, 1>({{0}})) / std::sqrt(static_cast<T>(h)); } else { PADDLE_THROW("unsupported pooling pooltype"); } } } }; template <typename T> class SequencePoolGradFunctor<platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const std::string pooltype, const framework::Tensor& out_grad, framework::LoDTensor* in_grad, /* max pool has index */ const framework::Tensor* index = nullptr) { if (pooltype == "MAX") { math::MaxSeqPoolGradFunctor<T> max_pool_grad; max_pool_grad(context, out_grad, *index, in_grad); return; } if (pooltype == "LAST" || pooltype == "FIRST") { // set X@Grad be zero at first when pooltype is LAST/FIRST math::SetConstant<platform::CPUDeviceContext, T> functor; functor(context, in_grad, 0); } auto lod = in_grad->lod()[0]; auto& place = *context.eigen_device(); for (int i = 0; i < static_cast<int>(lod.size()) - 1; ++i) { auto in_g_t = in_grad->Slice(static_cast<int>(lod[i]), static_cast<int>(lod[i + 1])); auto out_g_t = out_grad.Slice(i, i + 1); int64_t h = static_cast<int64_t>(lod[i + 1] - lod[i]); int64_t w = in_grad->numel() / in_grad->dims()[0]; auto in_g_e = EigenMatrix<T>::From(in_g_t, {h, w}); auto out_g_e = EigenMatrix<T>::From(out_g_t, {1, w}); auto out_g_e_v = EigenVector<T>::Flatten(out_g_t); Eigen::DSizes<int, 2> bcast(h, 1); if (pooltype == "AVERAGE") { in_g_e.device(place) = (out_g_e / static_cast<T>(h)).broadcast(bcast); } else if (pooltype == "SUM") { in_g_e.device(place) = (out_g_e).broadcast(bcast); } else if (pooltype == "SQRT") { in_g_e.device(place) = (out_g_e / std::sqrt(static_cast<T>(h))).broadcast(bcast); } else if (pooltype == "LAST") { in_g_e.chip(h - 1, 0).device(place) = out_g_e_v; } else if (pooltype == "FIRST") { in_g_e.chip(0, 0).device(place) = out_g_e_v; } else { PADDLE_THROW("unsupported pooling pooltype"); } } } }; template class SequencePoolFunctor<platform::CPUDeviceContext, float>; template class SequencePoolFunctor<platform::CPUDeviceContext, double>; template class SequencePoolGradFunctor<platform::CPUDeviceContext, float>; template class SequencePoolGradFunctor<platform::CPUDeviceContext, double>; } // namespace math } // namespace operators } // namespace paddle
Rewrite sequence pooling last and first mode with memcpy and clean code
Rewrite sequence pooling last and first mode with memcpy and clean code
C++
apache-2.0
PaddlePaddle/Paddle,reyoung/Paddle,tensor-tang/Paddle,baidu/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,tensor-tang/Paddle,luotao1/Paddle,reyoung/Paddle,tensor-tang/Paddle,chengduoZH/Paddle,luotao1/Paddle,baidu/Paddle,PaddlePaddle/Paddle,reyoung/Paddle,luotao1/Paddle,reyoung/Paddle,chengduoZH/Paddle,reyoung/Paddle,chengduoZH/Paddle,baidu/Paddle,tensor-tang/Paddle,luotao1/Paddle,baidu/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,reyoung/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,chengduoZH/Paddle,baidu/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,chengduoZH/Paddle,luotao1/Paddle
cef3f631cbafe79a733d7e3622de28db10b580ec
platform/shared/common/RhoThread.cpp
platform/shared/common/RhoThread.cpp
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "RhoThread.h" #include "IRhoClassFactory.h" namespace rho { namespace common { CRhoThread::CRhoThread() { m_nState = TS_NONE; m_pImpl = rho_get_RhoClassFactory()->createThreadImpl(); } void CRhoThread::start(EPriority ePriority) { if ( !isAlive() ) { m_pImpl->start(this, ePriority); m_nState = TS_RUNNING; } } } }
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "RhoThread.h" #include "IRhoClassFactory.h" namespace rho { namespace common { CRhoThread::CRhoThread() { m_nState = TS_NONE; m_pImpl = rho_get_RhoClassFactory()->createThreadImpl(); } void CRhoThread::start(EPriority ePriority) { if ( !isAlive() ) { m_nState = TS_RUNNING; m_pImpl->start(this, ePriority); } } } }
fix racing issue in RhoThread
fix racing issue in RhoThread
C++
mit
UIKit0/rhodes,louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,louisatome/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,louisatome/rhodes,UIKit0/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,louisatome/rhodes,louisatome/rhodes,louisatome/rhodes,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,UIKit0/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,louisatome/rhodes,louisatome/rhodes,UIKit0/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes
622fdaed2e92f837eecea358a5c3683041630018
plugin/hdCycles/resourceRegistry.cpp
plugin/hdCycles/resourceRegistry.cpp
// Copyright 2021 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "resourceRegistry.h" #include <pxr/base/work/loops.h> #include <pxr/usd/sdf/path.h> #include <render/scene.h> PXR_NAMESPACE_USING_DIRECTIVE void HdCyclesResourceRegistry::_Commit() { ccl::thread_scoped_lock scene_lock { m_scene->mutex }; // 1) bind objects to the scene for (auto& object_source : m_object_sources) { if (!object_source.second.value->IsValid()) { continue; } object_source.second.value->Resolve(); } // 2) commit all pending resources using ValueType = HdInstanceRegistry<HdCyclesObjectSourceSharedPtr>::const_iterator::value_type; WorkParallelForEach(m_object_sources.begin(), m_object_sources.end(), [](const ValueType& object_source) { // resolve per object object_source.second.value->ResolvePendingSources(); }); } void HdCyclesResourceRegistry::_GarbageCollect() { ccl::thread_scoped_lock scene_lock { m_scene->mutex }; m_object_sources.GarbageCollect(); } HdInstance<HdCyclesObjectSourceSharedPtr> HdCyclesResourceRegistry::GetObjectInstance(const SdfPath& id) { return m_object_sources.GetInstance(id.GetHash()); }
// Copyright 2021 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "resourceRegistry.h" #include <pxr/base/work/loops.h> #include <pxr/usd/sdf/path.h> #include <render/scene.h> PXR_NAMESPACE_USING_DIRECTIVE void HdCyclesResourceRegistry::_Commit() { // This function is under heavy wip. In ideal situation committing all resources to cycles should happen in one // place only. ccl::thread_scoped_lock scene_lock { m_scene->mutex }; // TODO: acquire display lock // State used to control session/scene update reset std::atomic_bool requires_reset { false }; // * bind objects to the scene for (auto& object_source : m_object_sources) { if (!object_source.second.value->IsValid()) { continue; } object_source.second.value->Resolve(); } // * commit all pending object resources using ValueType = HdInstanceRegistry<HdCyclesObjectSourceSharedPtr>::const_iterator::value_type; WorkParallelForEach(m_object_sources.begin(), m_object_sources.end(), [&requires_reset](const ValueType& object_source) { // resolve per object size_t num_resolved_sources = object_source.second.value->ResolvePendingSources(); if (num_resolved_sources > 0) { requires_reset = true; } }); // * notify session that new resources have been committed and reset is required if (requires_reset) { // TODO: After we are done removing scene and session mutations from *::Sync. We can request update and reset } } void HdCyclesResourceRegistry::_GarbageCollect() { ccl::thread_scoped_lock scene_lock { m_scene->mutex }; m_object_sources.GarbageCollect(); } HdInstance<HdCyclesObjectSourceSharedPtr> HdCyclesResourceRegistry::GetObjectInstance(const SdfPath& id) { return m_object_sources.GetInstance(id.GetHash()); }
update resource registry comments
update resource registry comments
C++
apache-2.0
tangent-opensource/hdBlackbird,tangent-opensource/hdBlackbird,tangent-opensource/hdBlackbird
6eb48d4c386b264e8ab00ff27fd3cf3c3b2b6149
graf2d/gviz/src/TGraphEdge.cxx
graf2d/gviz/src/TGraphEdge.cxx
// @(#)root/hist:$Id$ // Author: Olivier Couet 13/07/09 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TGraph.h" #include "TArrow.h" #include "TPolyLine.h" #include "TGraphEdge.h" #include "TGraphNode.h" #include <gvc.h> ClassImp(TGraphEdge); /** \class TGraphEdge \ingroup gviz An edge object connecting two nodes which can be added in a TGraphStruct. */ //////////////////////////////////////////////////////////////////////////////// /// Graph Edge default constructor. TGraphEdge::TGraphEdge(): TObject(), TAttLine() { fNode1 = 0; fNode2 = 0; fGVEdge = 0; fX = 0; fY = 0; fN = 0; fArrX = 0; fArrY = 0; } //////////////////////////////////////////////////////////////////////////////// /// Graph Edge normal constructor. TGraphEdge::TGraphEdge(TGraphNode *n1, TGraphNode *n2) :TObject(), TAttLine() { fNode1 = n1; fNode2 = n2; fGVEdge = 0; fX = 0; fY = 0; fN = 0; fArrX = 0; fArrY = 0; } //////////////////////////////////////////////////////////////////////////////// /// Graph Edge default destructor. TGraphEdge::~TGraphEdge() { if (fNode1) delete fNode1; if (fNode2) delete fNode2; if (fX) { delete [] fX; fX = 0; } if (fY) { delete [] fY; fY = 0; } if (fN) { delete [] fN; fN = 0; } } //////////////////////////////////////////////////////////////////////////////// /// Create the GraphViz edge into the GraphViz data structure gv. void TGraphEdge::CreateGVEdge(GVizAgraph_t *gv) { if (gv) { Agnode_t *n1 = (Agnode_t*)fNode1->GetGVNode(); Agnode_t *n2 = (Agnode_t*)fNode2->GetGVNode(); #ifdef WITH_CGRAPH fGVEdge = (GVizAgedge_t*)agedge((Agraph_t *)gv, n1, n2, NULL, 1); #else fGVEdge = (GVizAgedge_t*)agedge((Agraph_t *)gv, n1, n2); #endif } else { Error("CreateGVEdge","Invalid graphviz graph"); } } //////////////////////////////////////////////////////////////////////////////// /// Compute distance from point px,py to an edge. Int_t TGraphEdge::DistancetoPrimitive(Int_t px, Int_t py) { Int_t i,n,a,dist=999; TPolyLine *polyline; a = 0; for (i=1; i<=fN[0]; i++) { n = fN[i]; polyline = new TPolyLine(n, &fX[a], &fY[a], "L"); dist = polyline->DistancetoPrimitive(px, py); a = a+n; } return dist; } //////////////////////////////////////////////////////////////////////////////// /// Execute action corresponding to one event. void TGraphEdge::ExecuteEvent(Int_t event, Int_t px, Int_t py) { Int_t i,n,a; TPolyLine *polyline; a = 0; for (i=1; i<=fN[0]; i++) { n = fN[i]; polyline = new TPolyLine(n, &fX[a], &fY[a], "L"); polyline->ExecuteEvent(event, px, py); a = a+n; } } //////////////////////////////////////////////////////////////////////////////// /// Layout this edge in the GraphViz space. This is done after gvLayout /// has been performed. void TGraphEdge::Layout() { bezier bz; Int_t i,j; if (fX) { delete [] fX; fX = 0; } if (fY) { delete [] fY; fY = 0; } if (fN) { delete [] fN; fN = 0; } Int_t np = ED_spl((Agedge_t*)fGVEdge)->size; fN = new Int_t[np+1]; fN[0] = np; Int_t nb = 0; // Compute the total size of the splines arrays for (i=0; i<np; i++) { bz = ED_spl((Agedge_t*)fGVEdge)->list[i]; fN[i+1] = bz.size; nb = nb+fN[i+1]; } // Create the vectors holding all the splines' points. fX = new Double_t[nb]; fY = new Double_t[nb]; // Fill the vectors with the splines' points. Int_t k=0; for (i=0; i<np; i++) { bz = ED_spl((Agedge_t*)fGVEdge)->list[i]; fArrX = bz.ep.x; fArrY = bz.ep.y; for (j=0; j<fN[i+1]; j++) { fX[k] = bz.list[j].x; fY[k] = bz.list[j].y; k++; } } } //////////////////////////////////////////////////////////////////////////////// /// Paint this edge with its current attributes. void TGraphEdge::Paint(Option_t *) { Int_t i,n,a; TArrow arrow; TGraph graph; graph.SetLineColor(GetLineColor()); graph.SetLineStyle(GetLineStyle()); graph.SetLineWidth(GetLineWidth()); arrow.SetAngle(38); arrow.SetFillColor(GetLineColor()); arrow.SetLineColor(GetLineColor()); a = 0; for (i=1; i<=fN[0]; i++) { // Draw the edge body n = fN[i]; graph.PaintGraph(n, &fX[a], &fY[a], "L"); // Draw the edge arrow arrow.PaintArrow(fX[a+n-1], fY[a+n-1], fArrX, fArrY, 0.03, "|>"); a = a+n; } } //////////////////////////////////////////////////////////////////////////////// /// Save primitive as a C++ statement(s) on output stream out void TGraphEdge::SavePrimitive(std::ostream &, Option_t *) { } //////////////////////////////////////////////////////////////////////////////// /// Save attributes as a C++ statement(s) on output stream out /// called by TGraphStruct::SavePrimitive. void TGraphEdge::SaveAttributes(std::ostream &out, const char* name) { SaveLineAttributes(out,name,1,1,1); } //////////////////////////////////////////////////////////////////////////////// void TGraphEdge::Streamer(TBuffer &/*b*/) { }
// @(#)root/hist:$Id$ // Author: Olivier Couet 13/07/09 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TGraph.h" #include "TArrow.h" #include "TPolyLine.h" #include "TGraphEdge.h" #include "TGraphNode.h" #include <gvc.h> ClassImp(TGraphEdge); /** \class TGraphEdge \ingroup gviz An edge object connecting two nodes which can be added in a TGraphStruct. */ //////////////////////////////////////////////////////////////////////////////// /// Graph Edge default constructor. TGraphEdge::TGraphEdge(): TObject(), TAttLine() { fNode1 = 0; fNode2 = 0; fGVEdge = 0; fX = 0; fY = 0; fN = 0; fArrX = 0; fArrY = 0; } //////////////////////////////////////////////////////////////////////////////// /// Graph Edge normal constructor. TGraphEdge::TGraphEdge(TGraphNode *n1, TGraphNode *n2) :TObject(), TAttLine() { fNode1 = n1; fNode2 = n2; fGVEdge = 0; fX = 0; fY = 0; fN = 0; fArrX = 0; fArrY = 0; } //////////////////////////////////////////////////////////////////////////////// /// Graph Edge default destructor. TGraphEdge::~TGraphEdge() { if (fNode1) delete fNode1; if (fNode2) delete fNode2; if (fX) { delete [] fX; fX = 0; } if (fY) { delete [] fY; fY = 0; } if (fN) { delete [] fN; fN = 0; } } //////////////////////////////////////////////////////////////////////////////// /// Create the GraphViz edge into the GraphViz data structure gv. void TGraphEdge::CreateGVEdge(GVizAgraph_t *gv) { if (gv) { Agnode_t *n1 = (Agnode_t*)fNode1->GetGVNode(); Agnode_t *n2 = (Agnode_t*)fNode2->GetGVNode(); #ifdef WITH_CGRAPH fGVEdge = (GVizAgedge_t*)agedge((Agraph_t *)gv, n1, n2, NULL, 1); #else fGVEdge = (GVizAgedge_t*)agedge((Agraph_t *)gv, n1, n2); #endif } else { Error("CreateGVEdge","Invalid graphviz graph"); } } //////////////////////////////////////////////////////////////////////////////// /// Compute distance from point px,py to an edge. Int_t TGraphEdge::DistancetoPrimitive(Int_t px, Int_t py) { Int_t a = 0, dist = 999; for (Int_t i = 1; i <= fN[0]; i++) { Int_t n = fN[i]; TPolyLine polyline(n, &fX[a], &fY[a], "L"); auto d = polyline.DistancetoPrimitive(px, py); if (d < dist) dist = d; a += n; } return dist; } //////////////////////////////////////////////////////////////////////////////// /// Execute action corresponding to one event. void TGraphEdge::ExecuteEvent(Int_t event, Int_t px, Int_t py) { Int_t a = 0; for (Int_t i = 1; i <= fN[0]; i++) { Int_t n = fN[i]; TPolyLine polyline(n, &fX[a], &fY[a], "L"); polyline.ExecuteEvent(event, px, py); a += n; } } //////////////////////////////////////////////////////////////////////////////// /// Layout this edge in the GraphViz space. This is done after gvLayout /// has been performed. void TGraphEdge::Layout() { bezier bz; Int_t i,j; if (fX) { delete [] fX; fX = 0; } if (fY) { delete [] fY; fY = 0; } if (fN) { delete [] fN; fN = 0; } Int_t np = ED_spl((Agedge_t*)fGVEdge)->size; fN = new Int_t[np+1]; fN[0] = np; Int_t nb = 0; // Compute the total size of the splines arrays for (i=0; i<np; i++) { bz = ED_spl((Agedge_t*)fGVEdge)->list[i]; fN[i+1] = bz.size; nb = nb+fN[i+1]; } // Create the vectors holding all the splines' points. fX = new Double_t[nb]; fY = new Double_t[nb]; // Fill the vectors with the splines' points. Int_t k=0; for (i=0; i<np; i++) { bz = ED_spl((Agedge_t*)fGVEdge)->list[i]; fArrX = bz.ep.x; fArrY = bz.ep.y; for (j=0; j<fN[i+1]; j++) { fX[k] = bz.list[j].x; fY[k] = bz.list[j].y; k++; } } } //////////////////////////////////////////////////////////////////////////////// /// Paint this edge with its current attributes. void TGraphEdge::Paint(Option_t *) { Int_t i,n,a; TArrow arrow; TGraph graph; graph.SetLineColor(GetLineColor()); graph.SetLineStyle(GetLineStyle()); graph.SetLineWidth(GetLineWidth()); arrow.SetAngle(38); arrow.SetFillColor(GetLineColor()); arrow.SetLineColor(GetLineColor()); a = 0; for (i=1; i<=fN[0]; i++) { // Draw the edge body n = fN[i]; graph.PaintGraph(n, &fX[a], &fY[a], "L"); // Draw the edge arrow arrow.PaintArrow(fX[a+n-1], fY[a+n-1], fArrX, fArrY, 0.03, "|>"); a = a+n; } } //////////////////////////////////////////////////////////////////////////////// /// Save primitive as a C++ statement(s) on output stream out void TGraphEdge::SavePrimitive(std::ostream &, Option_t *) { } //////////////////////////////////////////////////////////////////////////////// /// Save attributes as a C++ statement(s) on output stream out /// called by TGraphStruct::SavePrimitive. void TGraphEdge::SaveAttributes(std::ostream &out, const char* name) { SaveLineAttributes(out,name,1,1,1); } //////////////////////////////////////////////////////////////////////////////// void TGraphEdge::Streamer(TBuffer &/*b*/) { }
Fix memory leak in TGraphEdge
Fix memory leak in TGraphEdge DistanceToPrimitive and ExecuteEvent were leaking lot of memory
C++
lgpl-2.1
olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root
beb753026adc1b14e3ef6f8823395b190d3d159e
lib/Fuzzer/FuzzerUtilWindows.cpp
lib/Fuzzer/FuzzerUtilWindows.cpp
//===- FuzzerUtilWindows.cpp - Misc utils for Windows. --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Misc utils implementation for Windows. //===----------------------------------------------------------------------===// #include "FuzzerDefs.h" #if LIBFUZZER_WINDOWS #include "FuzzerIO.h" #include "FuzzerInternal.h" #include <Psapi.h> #include <cassert> #include <chrono> #include <cstring> #include <errno.h> #include <iomanip> #include <signal.h> #include <sstream> #include <stdio.h> #include <sys/types.h> #include <windows.h> namespace fuzzer { LONG WINAPI SEGVHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: case EXCEPTION_STACK_OVERFLOW: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI BUSHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_DATATYPE_MISALIGNMENT: case EXCEPTION_IN_PAGE_ERROR: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI ILLHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ILLEGAL_INSTRUCTION: case EXCEPTION_PRIV_INSTRUCTION: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI FPEHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_FLT_DENORMAL_OPERAND: case EXCEPTION_FLT_DIVIDE_BY_ZERO: case EXCEPTION_FLT_INEXACT_RESULT: case EXCEPTION_FLT_INVALID_OPERATION: case EXCEPTION_FLT_OVERFLOW: case EXCEPTION_FLT_STACK_CHECK: case EXCEPTION_FLT_UNDERFLOW: case EXCEPTION_INT_DIVIDE_BY_ZERO: case EXCEPTION_INT_OVERFLOW: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } BOOL WINAPI INTHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: Fuzzer::StaticInterruptCallback(); return TRUE; default: return FALSE; } } BOOL WINAPI TERMHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_BREAK_EVENT: Fuzzer::StaticInterruptCallback(); return TRUE; default: return FALSE; } } void SetTimer(int Seconds) { // TODO: Complete this implementation. return; } void SetSigSegvHandler() { if (!AddVectoredExceptionHandler(1, SEGVHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigBusHandler() { if (!AddVectoredExceptionHandler(1, BUSHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } static void CrashHandler(int) { Fuzzer::StaticCrashSignalCallback(); } void SetSigAbrtHandler() { signal(SIGABRT, CrashHandler); } void SetSigIllHandler() { if (!AddVectoredExceptionHandler(1, ILLHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigFpeHandler() { if (!AddVectoredExceptionHandler(1, FPEHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigIntHandler() { if (!SetConsoleCtrlHandler(INTHandler, TRUE)) { DWORD LastError = GetLastError(); Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n", LastError); exit(1); } } void SetSigTermHandler() { if (!SetConsoleCtrlHandler(TERMHandler, TRUE)) { DWORD LastError = GetLastError(); Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n", LastError); exit(1); } } void SleepSeconds(int Seconds) { Sleep(Seconds * 1000); } int GetPid() { return GetCurrentProcessId(); } size_t GetPeakRSSMb() { PROCESS_MEMORY_COUNTERS info; if (!GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info))) return 0; return info.PeakWorkingSetSize >> 20; } FILE *OpenProcessPipe(const char *Command, const char *Mode) { return _popen(Command, Mode); } int ExecuteCommand(const std::string &Command) { return system(Command.c_str()); } const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt, size_t PattLen) { // TODO: make this implementation more efficient. const char *Cdata = (const char *)Data; const char *Cpatt = (const char *)Patt; if (!Data || !Patt || DataLen == 0 || PattLen == 0 || DataLen < PattLen) return NULL; if (PattLen == 1) return memchr(Data, *Cpatt, DataLen); const char *End = Cdata + DataLen - PattLen; for (const char *It = Cdata; It < End; ++It) if (It[0] == Cpatt[0] && memcmp(It, Cpatt, PattLen) == 0) return It; return NULL; } } // namespace fuzzer #endif // LIBFUZZER_WINDOWS
//===- FuzzerUtilWindows.cpp - Misc utils for Windows. --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Misc utils implementation for Windows. //===----------------------------------------------------------------------===// #include "FuzzerDefs.h" #if LIBFUZZER_WINDOWS #include "FuzzerIO.h" #include "FuzzerInternal.h" #include <Psapi.h> #include <cassert> #include <chrono> #include <cstring> #include <errno.h> #include <iomanip> #include <signal.h> #include <sstream> #include <stdio.h> #include <sys/types.h> #include <windows.h> namespace fuzzer { LONG WINAPI SEGVHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: case EXCEPTION_STACK_OVERFLOW: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI BUSHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_DATATYPE_MISALIGNMENT: case EXCEPTION_IN_PAGE_ERROR: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI ILLHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_ILLEGAL_INSTRUCTION: case EXCEPTION_PRIV_INSTRUCTION: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI FPEHandler(PEXCEPTION_POINTERS ExceptionInfo) { switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { case EXCEPTION_FLT_DENORMAL_OPERAND: case EXCEPTION_FLT_DIVIDE_BY_ZERO: case EXCEPTION_FLT_INEXACT_RESULT: case EXCEPTION_FLT_INVALID_OPERATION: case EXCEPTION_FLT_OVERFLOW: case EXCEPTION_FLT_STACK_CHECK: case EXCEPTION_FLT_UNDERFLOW: case EXCEPTION_INT_DIVIDE_BY_ZERO: case EXCEPTION_INT_OVERFLOW: Fuzzer::StaticCrashSignalCallback(); break; } return EXCEPTION_CONTINUE_SEARCH; } BOOL WINAPI INTHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: Fuzzer::StaticInterruptCallback(); return TRUE; default: return FALSE; } } BOOL WINAPI TERMHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_BREAK_EVENT: Fuzzer::StaticInterruptCallback(); return TRUE; default: return FALSE; } } void CALLBACK AlarmHandler(PVOID, BOOLEAN) { Fuzzer::StaticAlarmCallback(); } class TimerQ { HANDLE TimerQueue; public: TimerQ() : TimerQueue(NULL) {}; ~TimerQ() { if (TimerQueue) DeleteTimerQueueEx(TimerQueue, NULL); }; void SetTimer(int Seconds) { if (!TimerQueue) { TimerQueue = CreateTimerQueue(); if (!TimerQueue) { Printf("libFuzzer: CreateTimerQueue failed.\n"); exit(1); } } HANDLE Timer; if (!CreateTimerQueueTimer(&Timer, TimerQueue, AlarmHandler, NULL, Seconds*1000, Seconds*1000, 0)) { Printf("libFuzzer: CreateTimerQueueTimer failed.\n"); exit(1); } }; }; static TimerQ Timer; void SetTimer(int Seconds) { Timer.SetTimer(Seconds); return; } void SetSigSegvHandler() { if (!AddVectoredExceptionHandler(1, SEGVHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigBusHandler() { if (!AddVectoredExceptionHandler(1, BUSHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } static void CrashHandler(int) { Fuzzer::StaticCrashSignalCallback(); } void SetSigAbrtHandler() { signal(SIGABRT, CrashHandler); } void SetSigIllHandler() { if (!AddVectoredExceptionHandler(1, ILLHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigFpeHandler() { if (!AddVectoredExceptionHandler(1, FPEHandler)) { Printf("libFuzzer: AddVectoredExceptionHandler failed.\n"); exit(1); } } void SetSigIntHandler() { if (!SetConsoleCtrlHandler(INTHandler, TRUE)) { DWORD LastError = GetLastError(); Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n", LastError); exit(1); } } void SetSigTermHandler() { if (!SetConsoleCtrlHandler(TERMHandler, TRUE)) { DWORD LastError = GetLastError(); Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n", LastError); exit(1); } } void SleepSeconds(int Seconds) { Sleep(Seconds * 1000); } int GetPid() { return GetCurrentProcessId(); } size_t GetPeakRSSMb() { PROCESS_MEMORY_COUNTERS info; if (!GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info))) return 0; return info.PeakWorkingSetSize >> 20; } FILE *OpenProcessPipe(const char *Command, const char *Mode) { return _popen(Command, Mode); } int ExecuteCommand(const std::string &Command) { return system(Command.c_str()); } const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt, size_t PattLen) { // TODO: make this implementation more efficient. const char *Cdata = (const char *)Data; const char *Cpatt = (const char *)Patt; if (!Data || !Patt || DataLen == 0 || PattLen == 0 || DataLen < PattLen) return NULL; if (PattLen == 1) return memchr(Data, *Cpatt, DataLen); const char *End = Cdata + DataLen - PattLen; for (const char *It = Cdata; It < End; ++It) if (It[0] == Cpatt[0] && memcmp(It, Cpatt, PattLen) == 0) return It; return NULL; } } // namespace fuzzer #endif // LIBFUZZER_WINDOWS
Implement Timers for Windows.
[libFuzzer] Implement Timers for Windows. Implemented timeouts for Windows using TimerQueueTimers. Timers are used to supervise the time of execution of the callback function that is being fuzzed. Differential Revision: https://reviews.llvm.org/D27237 git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@289495 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
7deff4c690d468abcce33ef3656cb94d3b614cf4
lib/ReaderWriter/FileArchive.cpp
lib/ReaderWriter/FileArchive.cpp
//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. File *find(StringRef name, bool dataSymbolOnly) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; if (ci->getError()) return nullptr; // Don't return a member already returned ErrorOr<StringRef> buf = (*ci)->getBuffer(); if (!buf) return nullptr; const char *memberStart = buf->data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(ci, name)) return nullptr; _membersInstantiated.insert(memberStart); std::unique_ptr<File> result; if (instantiateMember(ci, result)) return nullptr; File *file = result.get(); _filesReturned.push_back(std::move(result)); // Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive return file; } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const AtomRange<DefinedAtom> defined() const override { return _noDefinedAtoms; } const AtomRange<UndefinedAtom> undefined() const override { return _noUndefinedAtoms; } const AtomRange<SharedLibraryAtom> sharedLibrary() const override { return _noSharedLibraryAtoms; } const AtomRange<AbsoluteAtom> absolute() const override { return _noAbsoluteAtoms; } void clearAtoms() override { _noDefinedAtoms.clear(); _noUndefinedAtoms.clear(); _noSharedLibraryAtoms.clear(); _noAbsoluteAtoms.clear(); } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; return std::error_code(); } private: std::error_code instantiateMember(Archive::child_iterator cOrErr, std::unique_ptr<File> &result) const { if (std::error_code ec = cOrErr->getError()) return ec; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); ErrorOr<std::unique_ptr<File>> fileOrErr = _registry.loadFile(std::move(memberMB)); if (std::error_code ec = fileOrErr.getError()) return ec; result = std::move(fileOrErr.get()); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(Archive::child_iterator cOrErr, StringRef symbol) const { if (cOrErr->getError()) return false; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> buf = (*member)->getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. ErrorOr<StringRef> name = sym.getName(); if (!name) return false; if (*name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. SymbolRef::Type type = sym.getType(); if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", (*member)->getBuffer()->data()) << "'" << name << "'\n"); _symbolMemberMap.insert(std::make_pair(name, member)); } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; MemberMap _symbolMemberMap; InstantiatedSet _membersInstantiated; bool _logLoading; std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; std::vector<std::unique_ptr<File>> _filesReturned; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, MemoryBufferRef) const override { return magic == llvm::sys::fs::file_magic::archive; } ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<File> ret = llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading); return std::move(ret); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld
//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. File *find(StringRef name, bool dataSymbolOnly) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; if (ci->getError()) return nullptr; // Don't return a member already returned ErrorOr<StringRef> buf = (*ci)->getBuffer(); if (!buf) return nullptr; const char *memberStart = buf->data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(ci, name)) return nullptr; _membersInstantiated.insert(memberStart); std::unique_ptr<File> result; if (instantiateMember(ci, result)) return nullptr; File *file = result.get(); _filesReturned.push_back(std::move(result)); // Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive return file; } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const AtomRange<DefinedAtom> defined() const override { return _noDefinedAtoms; } const AtomRange<UndefinedAtom> undefined() const override { return _noUndefinedAtoms; } const AtomRange<SharedLibraryAtom> sharedLibrary() const override { return _noSharedLibraryAtoms; } const AtomRange<AbsoluteAtom> absolute() const override { return _noAbsoluteAtoms; } void clearAtoms() override { _noDefinedAtoms.clear(); _noUndefinedAtoms.clear(); _noSharedLibraryAtoms.clear(); _noAbsoluteAtoms.clear(); } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; return std::error_code(); } private: std::error_code instantiateMember(Archive::child_iterator cOrErr, std::unique_ptr<File> &result) const { if (std::error_code ec = cOrErr->getError()) return ec; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); ErrorOr<std::unique_ptr<File>> fileOrErr = _registry.loadFile(std::move(memberMB)); if (std::error_code ec = fileOrErr.getError()) return ec; result = std::move(fileOrErr.get()); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(Archive::child_iterator cOrErr, StringRef symbol) const { if (cOrErr->getError()) return false; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> buf = (*member)->getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. ErrorOr<StringRef> name = sym.getName(); if (!name) return false; if (*name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. ErrorOr<SymbolRef::Type> typeOrErr = sym.getType(); if (typeOrErr.getError()) return false; SymbolRef::Type type = *typeOrErr; if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", (*member)->getBuffer()->data()) << "'" << name << "'\n"); _symbolMemberMap.insert(std::make_pair(name, member)); } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; MemberMap _symbolMemberMap; InstantiatedSet _membersInstantiated; bool _logLoading; std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; std::vector<std::unique_ptr<File>> _filesReturned; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, MemoryBufferRef) const override { return magic == llvm::sys::fs::file_magic::archive; } ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<File> ret = llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading); return std::move(ret); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld
Add the needed lld change for r264187 in llvm.
Add the needed lld change for r264187 in llvm. Sorry had this fixed in my check out but failed mention it in my commit message for r264187. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@264188 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
683fec947867eb491a235d13b5f999c7f33727c1
lib/ReaderWriter/FileArchive.cpp
lib/ReaderWriter/FileArchive.cpp
//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Core/Parallel.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <mutex> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. const File *find(StringRef name, bool dataSymbolOnly) const override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; // Don't return a member already returned const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(*ci, name)) return nullptr; _membersInstantiated.insert(memberStart); // Check if a file is preloaded. { std::lock_guard<std::mutex> lock(_mutex); auto it = _preloaded.find(memberStart); if (it != _preloaded.end()) { std::unique_ptr<Future<const File *>> &p = it->second; Future<const File *> *future = p.get(); return future->get(); } } std::unique_ptr<File> result; if (instantiateMember(*ci, result)) return nullptr; // give up the pointer so that this object no longer manages it return result.release(); } // Instantiate a member file containing a given symbol name. void preload(TaskGroup &group, StringRef name) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return; Archive::child_iterator ci = member->second; // Do nothing if a member is already instantiated. const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return; std::lock_guard<std::mutex> lock(_mutex); if (_preloaded.find(memberStart) != _preloaded.end()) return; // Instantiate the member auto *future = new Future<const File *>(); _preloaded[memberStart] = std::unique_ptr<Future<const File *>>(future); group.spawn([=] { std::unique_ptr<File> result; std::error_code ec = instantiateMember(*ci, result); future->set(ec ? nullptr : result.release()); }); } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(*mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const atom_collection<DefinedAtom> &defined() const override { return _definedAtoms; } const atom_collection<UndefinedAtom> &undefined() const override { return _undefinedAtoms; } const atom_collection<SharedLibraryAtom> &sharedLibrary() const override { return _sharedLibraryAtoms; } const atom_collection<AbsoluteAtom> &absolute() const override { return _absoluteAtoms; } /// Returns a set of all defined symbols in the archive. std::set<StringRef> getDefinedSymbols() override { parse(); std::set<StringRef> ret; for (const auto &e : _symbolMemberMap) ret.insert(e.first); return ret; } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; buildParallelArray(); return std::error_code(); } private: void buildParallelArray() { size_t len = 0; for (const Archive::Child &child : _archive->children()) { _children.push_back(child); len++; } _futures.resize(len); } std::error_code instantiateMember(const Archive::Child &member, std::unique_ptr<File> &result) const { ErrorOr<llvm::MemoryBufferRef> mbOrErr = member.getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); std::vector<std::unique_ptr<File>> files; if (std::error_code ec = _registry.loadFile(std::move(memberMB), files)) return ec; assert(files.size() == 1); result = std::move(files[0]); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(const Archive::Child &member, StringRef symbol) const { ErrorOr<llvm::MemoryBufferRef> buf = member.getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. StringRef name; if (sym.getName(name)) return false; if (name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. SymbolRef::Type type; if (sym.getType(type)) return false; if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE( "FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", member->getBuffer().data()) << "'" << name << "'\n"); _symbolMemberMap[name] = member; } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; mutable MemberMap _symbolMemberMap; mutable InstantiatedSet _membersInstantiated; atom_collection_vector<DefinedAtom> _definedAtoms; atom_collection_vector<UndefinedAtom> _undefinedAtoms; atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms; atom_collection_vector<AbsoluteAtom> _absoluteAtoms; bool _logLoading; mutable std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; mutable std::map<const char *, std::unique_ptr<Future<const File *>>> _preloaded; mutable std::mutex _mutex; mutable std::vector<Archive::Child> _children; mutable std::vector<std::unique_ptr<Future<const File *>>> _futures; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, StringRef, const MemoryBuffer &) const override { return (magic == llvm::sys::fs::file_magic::archive); } std::error_code loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, std::vector<std::unique_ptr<File>> &result) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<FileArchive> file( new FileArchive(std::move(mb), reg, path, _logLoading)); result.push_back(std::move(file)); return std::error_code(); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld
//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Core/Parallel.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <mutex> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. const File *find(StringRef name, bool dataSymbolOnly) const override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; // Don't return a member already returned const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(ci, name)) return nullptr; _membersInstantiated.insert(memberStart); // Check if a file is preloaded. { std::lock_guard<std::mutex> lock(_mutex); auto it = _preloaded.find(memberStart); if (it != _preloaded.end()) { std::unique_ptr<Future<const File *>> &p = it->second; Future<const File *> *future = p.get(); return future->get(); } } std::unique_ptr<File> result; if (instantiateMember(ci, result)) return nullptr; // give up the pointer so that this object no longer manages it return result.release(); } // Instantiate a member file containing a given symbol name. void preload(TaskGroup &group, StringRef name) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return; Archive::child_iterator ci = member->second; // Do nothing if a member is already instantiated. const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return; std::lock_guard<std::mutex> lock(_mutex); if (_preloaded.find(memberStart) != _preloaded.end()) return; // Instantiate the member auto *future = new Future<const File *>(); _preloaded[memberStart] = std::unique_ptr<Future<const File *>>(future); group.spawn([=] { std::unique_ptr<File> result; std::error_code ec = instantiateMember(ci, result); future->set(ec ? nullptr : result.release()); }); } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const atom_collection<DefinedAtom> &defined() const override { return _definedAtoms; } const atom_collection<UndefinedAtom> &undefined() const override { return _undefinedAtoms; } const atom_collection<SharedLibraryAtom> &sharedLibrary() const override { return _sharedLibraryAtoms; } const atom_collection<AbsoluteAtom> &absolute() const override { return _absoluteAtoms; } /// Returns a set of all defined symbols in the archive. std::set<StringRef> getDefinedSymbols() override { parse(); std::set<StringRef> ret; for (const auto &e : _symbolMemberMap) ret.insert(e.first); return ret; } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; return std::error_code(); } private: std::error_code instantiateMember(Archive::child_iterator member, std::unique_ptr<File> &result) const { ErrorOr<llvm::MemoryBufferRef> mbOrErr = member->getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); std::vector<std::unique_ptr<File>> files; if (std::error_code ec = _registry.loadFile(std::move(memberMB), files)) return ec; assert(files.size() == 1); result = std::move(files[0]); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(Archive::child_iterator member, StringRef symbol) const { ErrorOr<llvm::MemoryBufferRef> buf = member->getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. StringRef name; if (sym.getName(name)) return false; if (name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. SymbolRef::Type type; if (sym.getType(type)) return false; if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE( "FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", member->getBuffer().data()) << "'" << name << "'\n"); _symbolMemberMap[name] = member; } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; mutable MemberMap _symbolMemberMap; mutable InstantiatedSet _membersInstantiated; atom_collection_vector<DefinedAtom> _definedAtoms; atom_collection_vector<UndefinedAtom> _undefinedAtoms; atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms; atom_collection_vector<AbsoluteAtom> _absoluteAtoms; bool _logLoading; mutable std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; mutable std::map<const char *, std::unique_ptr<Future<const File *>>> _preloaded; mutable std::mutex _mutex; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, StringRef, const MemoryBuffer &) const override { return (magic == llvm::sys::fs::file_magic::archive); } std::error_code loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, std::vector<std::unique_ptr<File>> &result) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<FileArchive> file( new FileArchive(std::move(mb), reg, path, _logLoading)); result.push_back(std::move(file)); return std::error_code(); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld
Revert "temporary"
Revert "temporary" This reverts accidental commit r231205. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@231208 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
c3f99ee8df9bdfad0ec053722d6e40b384f745c4
BimDexter/BimDexter.cpp
BimDexter/BimDexter.cpp
// BimDexter.cpp // Main program. #include <string> #include <iostream> #include <locale> #include <exception> #include "Pixmap.h" #include "PixelBlock.h" using namespace std; void usage() { cerr << "Usage: BimDexter [-b | -d] [-q] [-u] {input file} {output file}\n"; cerr << "Converts between .BMP (24-bit uncompressed) and .DDS (DXT1) files.\n"; cerr << "If not specified, the mode is chosen based on the extension of the input file.\n"; cerr << "Options:\n"; cerr << " -b Set mode: input BMP and output DDS.\n"; cerr << " -d Set mode: input DDS and output BMP.\n"; cerr << " -q Suppress diagnostic output to stderr.\n"; cerr << " -u Choose uniform color component weighting. Default is (3, 4, 2) (R, G, B).\n"; } // Checks whether the string has the (proper) suffix. // The suffix must be non-empty. Ignores case differences. bool has_suffix(string const& s, string const& suffix) { bool found = false; for(auto i = s.rbegin(), j = suffix.rbegin(); i != s.rend(); ++i) { if (tolower(*i) != tolower(*j)) break; if (++j == suffix.rend()) { found = true; break; } } return found; } int main(int argc, char** argv) { string filename[2]; int filenames = 0; bool verbose = true; bool bmp_to_dds; bool mode_specified = false; // Parse command line arguments. for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "-b") { bmp_to_dds = true; mode_specified = true; } else if (arg == "-d") { bmp_to_dds = false; mode_specified = true; } else if (arg == "-q") { verbose = false; } else if (arg == "-u") { DxtPalette::setColorImportance(Vec3(1.0f)); } else if (filenames < 2) { filename[filenames++] = arg; } else { usage(); return 0; } } if (filenames < 2) { usage(); return 0; } if (!mode_specified) { if (has_suffix(filename[0], ".dds")) { bmp_to_dds = false; } else if (has_suffix(filename[0], ".bmp")) { bmp_to_dds = true; } else { cerr << "Error: Cannot deduce mode from input file extension.\n"; return 1; } } Pixmap pixmap; ifstream infile; ofstream outfile; if (bmp_to_dds) { try { infile.open(filename[0], ios::binary); if (!infile.is_open()) throw runtime_error("Cannot open input file."); pixmap.read_bmp(infile, verbose); infile.close(); outfile.open(filename[1], ios::binary); if (!outfile.is_open()) throw runtime_error("Cannot open output file."); pixmap.export_dxt1(outfile, verbose); outfile.close(); } catch(runtime_error e) { cerr << "Error: " << e.what(); return 1; } } else { try { infile.open(filename[0], ios::binary); if (!infile.is_open()) throw runtime_error("Cannot open input file."); pixmap.read_dxt1(infile, verbose); infile.close(); outfile.open(filename[1], ios::binary); if (!outfile.is_open()) throw runtime_error("Cannot open output file."); pixmap.export_bmp(outfile, verbose); outfile.close(); } catch(runtime_error e) { cerr << "Error: " << e.what(); return 1; } } return 0; }
// BimDexter.cpp // Main program. #include <string> #include <iostream> #include <locale> #include <exception> #include <chrono> #include "Pixmap.h" #include "PixelBlock.h" using namespace std; using namespace std::chrono; void usage() { cerr << "Usage: BimDexter [-b | -d] [-q] [-u] {input file} {output file}\n"; cerr << "Converts between .BMP (24-bit uncompressed) and .DDS (DXT1) files.\n"; cerr << "If not specified, the mode is chosen based on the extension of the input file.\n"; cerr << "Options:\n"; cerr << " -b Set mode: input BMP and output DDS.\n"; cerr << " -d Set mode: input DDS and output BMP.\n"; cerr << " -q Suppress diagnostic output to stderr.\n"; cerr << " -u Choose uniform color component weighting. Default is (3, 4, 2) (R, G, B).\n"; } // Checks whether the string has the (proper) suffix. // The suffix must be non-empty. Ignores case differences. bool has_suffix(string const& s, string const& suffix) { bool found = false; for(auto i = s.rbegin(), j = suffix.rbegin(); i != s.rend(); ++i) { if (tolower(*i) != tolower(*j)) break; if (++j == suffix.rend()) { found = true; break; } } return found; } int main(int argc, char** argv) { string filename[2]; int filenames = 0; bool verbose = true; bool bmp_to_dds; bool mode_specified = false; // Parse command line arguments. for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "-b") { bmp_to_dds = true; mode_specified = true; } else if (arg == "-d") { bmp_to_dds = false; mode_specified = true; } else if (arg == "-q") { verbose = false; } else if (arg == "-u") { DxtPalette::setColorImportance(Vec3(1.0f)); } else if (filenames < 2) { filename[filenames++] = arg; } else { usage(); return 0; } } if (filenames < 2) { usage(); return 0; } if (!mode_specified) { if (has_suffix(filename[0], ".dds")) { bmp_to_dds = false; } else if (has_suffix(filename[0], ".bmp")) { bmp_to_dds = true; } else { cerr << "Error: Cannot deduce mode from input file extension.\n"; return 1; } } Pixmap pixmap; ifstream infile; ofstream outfile; if (bmp_to_dds) { try { infile.open(filename[0], ios::binary); if (!infile.is_open()) throw runtime_error("Cannot open input file."); pixmap.read_bmp(infile, verbose); infile.close(); outfile.open(filename[1], ios::binary); if (!outfile.is_open()) throw runtime_error("Cannot open output file."); double time0 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); pixmap.export_dxt1(outfile, verbose); double time1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); if (verbose) cerr << "Time taken: " << (time1 - time0) * 0.001 << " seconds.\n"; outfile.close(); } catch(runtime_error e) { cerr << "Error: " << e.what() << "\n"; return 1; } } else { try { infile.open(filename[0], ios::binary); if (!infile.is_open()) throw runtime_error("Cannot open input file."); pixmap.read_dxt1(infile, verbose); infile.close(); outfile.open(filename[1], ios::binary); if (!outfile.is_open()) throw runtime_error("Cannot open output file."); pixmap.export_bmp(outfile, verbose); outfile.close(); } catch(runtime_error e) { cerr << "Error: " << e.what() << "\n"; return 1; } } return 0; }
Add compression time reporting.
Add compression time reporting.
C++
mit
SamiPerttu/BimDexter
264f0b942ac9eeb914b75dbc6fc9afd2286ef510
C++/reverse-integer.cpp
C++/reverse-integer.cpp
// Time: O(logn) // Space: O(1) class Solution { public: /** * @param n the integer to be reversed * @return the reversed integer */ int reverseInteger(int n) { long long result = 0; unsigned int temp = abs(n); while (temp > 0) { result *= 10; result += temp % 10; temp /= 10; } result = (n >= 0)? result : -result; result = (result > INT_MAX || result < INT_MIN)? 0 : result; return result; } };
// Time: O(logn) // Space: O(1) class Solution { public: /** * @param n the integer to be reversed * @return the reversed integer */ int reverseInteger(int n) { long long result = 0; unsigned int temp = abs(n); while (temp > 0) { result *= 10; result += temp % 10; temp /= 10; } result = (n >= 0)? result : -result; result = (result > INT_MAX || result < INT_MIN) ? 0 : result; return result; } };
Update reverse-integer.cpp
Update reverse-integer.cpp
C++
mit
jaredkoontz/lintcode,kamyu104/LintCode,kamyu104/LintCode,kamyu104/LintCode,jaredkoontz/lintcode,jaredkoontz/lintcode
746d96524f0279ef0aab7bbbe90939006b9bfc9d
lib/Support/PrettyStackTrace.cpp
lib/Support/PrettyStackTrace.cpp
//===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines some helpful functions for dealing with the possibility of // Unix signals occurring while your program is running. // //===----------------------------------------------------------------------===// #include "llvm/Support/PrettyStackTrace.h" #include "llvm-c/ErrorHandling.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" // Get autoconf configuration settings #include "llvm/Support/Compiler.h" #include "llvm/Support/Signals.h" #include "llvm/Support/Watchdog.h" #include "llvm/Support/raw_ostream.h" #include <tuple> #ifdef HAVE_CRASHREPORTERCLIENT_H #include <CrashReporterClient.h> #endif using namespace llvm; // If backtrace support is not enabled, compile out support for pretty stack // traces. This has the secondary effect of not requiring thread local storage // when backtrace support is disabled. #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // We need a thread local pointer to manage the stack of our stack trace // objects, but we *really* cannot tolerate destructors running and do not want // to pay any overhead of synchronizing. As a consequence, we use a raw // thread-local variable. static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr; namespace llvm { PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) { PrettyStackTraceEntry *Prev = nullptr; while (Head) std::tie(Prev, Head, Head->NextEntry) = std::make_tuple(Head, Head->NextEntry, Prev); return Prev; } } static void PrintStack(raw_ostream &OS) { // Print out the stack in reverse order. To avoid recursion (which is likely // to fail if we crashed due to stack overflow), we do an up-front pass to // reverse the stack, then print it, then reverse it again. unsigned ID = 0; PrettyStackTraceEntry *ReversedStack = llvm::ReverseStackTrace(PrettyStackTraceHead); for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry; Entry = Entry->getNextEntry()) { OS << ID++ << ".\t"; sys::Watchdog W(5); Entry->print(OS); } llvm::ReverseStackTrace(ReversedStack); } /// PrintCurStackTrace - Print the current stack trace to the specified stream. static void PrintCurStackTrace(raw_ostream &OS) { // Don't print an empty trace. if (!PrettyStackTraceHead) return; // If there are pretty stack frames registered, walk and emit them. OS << "Stack dump:\n"; PrintStack(OS); OS.flush(); } // Integrate with crash reporter libraries. #if defined (__APPLE__) && HAVE_CRASHREPORTERCLIENT_H // If any clients of llvm try to link to libCrashReporterClient.a themselves, // only one crash info struct will be used. extern "C" { CRASH_REPORTER_CLIENT_HIDDEN struct crashreporter_annotations_t gCRAnnotations __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 }; } #elif defined (__APPLE__) && HAVE_CRASHREPORTER_INFO static const char *__crashreporter_info__ = 0; asm(".desc ___crashreporter_info__, 0x10"); #endif /// CrashHandler - This callback is run if a fatal signal is delivered to the /// process, it prints the pretty stack trace. static void CrashHandler(void *) { #ifndef __APPLE__ // On non-apple systems, just emit the crash stack trace to stderr. PrintCurStackTrace(errs()); #else // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also // put it into __crashreporter_info__. SmallString<2048> TmpStr; { raw_svector_ostream Stream(TmpStr); PrintCurStackTrace(Stream); } if (!TmpStr.empty()) { #ifdef HAVE_CRASHREPORTERCLIENT_H // Cast to void to avoid warning. (void)CRSetCrashLogMessage(std::string(TmpStr.str()).c_str()); #elif HAVE_CRASHREPORTER_INFO __crashreporter_info__ = strdup(std::string(TmpStr.str()).c_str()); #endif errs() << TmpStr.str(); } #endif } // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES #endif PrettyStackTraceEntry::PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // Link ourselves. NextEntry = PrettyStackTraceHead; PrettyStackTraceHead = this; #endif } PrettyStackTraceEntry::~PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES assert(PrettyStackTraceHead == this && "Pretty stack trace entry destruction is out of order"); PrettyStackTraceHead = NextEntry; #endif } void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; } void PrettyStackTraceProgram::print(raw_ostream &OS) const { OS << "Program arguments: "; // Print the argument list. for (unsigned i = 0, e = ArgC; i != e; ++i) OS << ArgV[i] << ' '; OS << '\n'; } #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES static bool RegisterCrashPrinter() { sys::AddSignalHandler(CrashHandler, nullptr); return false; } #endif void llvm::EnablePrettyStackTrace() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // The first time this is called, we register the crash printer. static bool HandlerRegistered = RegisterCrashPrinter(); (void)HandlerRegistered; #endif } const void *llvm::SavePrettyStackState() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES return PrettyStackTraceHead; #else return nullptr; #endif } void llvm::RestorePrettyStackState(const void *Top) { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES PrettyStackTraceHead = static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top)); #endif } void LLVMEnablePrettyStackTrace() { EnablePrettyStackTrace(); }
//===- PrettyStackTrace.cpp - Pretty Crash Handling -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines some helpful functions for dealing with the possibility of // Unix signals occurring while your program is running. // //===----------------------------------------------------------------------===// #include "llvm/Support/PrettyStackTrace.h" #include "llvm-c/ErrorHandling.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" // Get autoconf configuration settings #include "llvm/Support/Compiler.h" #include "llvm/Support/Signals.h" #include "llvm/Support/Watchdog.h" #include "llvm/Support/raw_ostream.h" #include <tuple> #ifdef HAVE_CRASHREPORTERCLIENT_H #include <CrashReporterClient.h> #endif using namespace llvm; // If backtrace support is not enabled, compile out support for pretty stack // traces. This has the secondary effect of not requiring thread local storage // when backtrace support is disabled. #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // We need a thread local pointer to manage the stack of our stack trace // objects, but we *really* cannot tolerate destructors running and do not want // to pay any overhead of synchronizing. As a consequence, we use a raw // thread-local variable. static LLVM_THREAD_LOCAL PrettyStackTraceEntry *PrettyStackTraceHead = nullptr; namespace llvm { PrettyStackTraceEntry *ReverseStackTrace(PrettyStackTraceEntry *Head) { PrettyStackTraceEntry *Prev = nullptr; while (Head) std::tie(Prev, Head, Head->NextEntry) = std::make_tuple(Head, Head->NextEntry, Prev); return Prev; } } static void PrintStack(raw_ostream &OS) { // Print out the stack in reverse order. To avoid recursion (which is likely // to fail if we crashed due to stack overflow), we do an up-front pass to // reverse the stack, then print it, then reverse it again. unsigned ID = 0; PrettyStackTraceEntry *ReversedStack = llvm::ReverseStackTrace(PrettyStackTraceHead); for (const PrettyStackTraceEntry *Entry = ReversedStack; Entry; Entry = Entry->getNextEntry()) { OS << ID++ << ".\t"; sys::Watchdog W(5); Entry->print(OS); } llvm::ReverseStackTrace(ReversedStack); } /// PrintCurStackTrace - Print the current stack trace to the specified stream. static void PrintCurStackTrace(raw_ostream &OS) { // Don't print an empty trace. if (!PrettyStackTraceHead) return; // If there are pretty stack frames registered, walk and emit them. OS << "Stack dump:\n"; PrintStack(OS); OS.flush(); } // Integrate with crash reporter libraries. #if defined (__APPLE__) && defined(HAVE_CRASHREPORTERCLIENT_H) // If any clients of llvm try to link to libCrashReporterClient.a themselves, // only one crash info struct will be used. extern "C" { CRASH_REPORTER_CLIENT_HIDDEN struct crashreporter_annotations_t gCRAnnotations __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 }; } #elif defined (__APPLE__) && HAVE_CRASHREPORTER_INFO static const char *__crashreporter_info__ = 0; asm(".desc ___crashreporter_info__, 0x10"); #endif /// CrashHandler - This callback is run if a fatal signal is delivered to the /// process, it prints the pretty stack trace. static void CrashHandler(void *) { #ifndef __APPLE__ // On non-apple systems, just emit the crash stack trace to stderr. PrintCurStackTrace(errs()); #else // Otherwise, emit to a smallvector of chars, send *that* to stderr, but also // put it into __crashreporter_info__. SmallString<2048> TmpStr; { raw_svector_ostream Stream(TmpStr); PrintCurStackTrace(Stream); } if (!TmpStr.empty()) { #ifdef HAVE_CRASHREPORTERCLIENT_H // Cast to void to avoid warning. (void)CRSetCrashLogMessage(std::string(TmpStr.str()).c_str()); #elif HAVE_CRASHREPORTER_INFO __crashreporter_info__ = strdup(std::string(TmpStr.str()).c_str()); #endif errs() << TmpStr.str(); } #endif } // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES #endif PrettyStackTraceEntry::PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // Link ourselves. NextEntry = PrettyStackTraceHead; PrettyStackTraceHead = this; #endif } PrettyStackTraceEntry::~PrettyStackTraceEntry() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES assert(PrettyStackTraceHead == this && "Pretty stack trace entry destruction is out of order"); PrettyStackTraceHead = NextEntry; #endif } void PrettyStackTraceString::print(raw_ostream &OS) const { OS << Str << "\n"; } void PrettyStackTraceProgram::print(raw_ostream &OS) const { OS << "Program arguments: "; // Print the argument list. for (unsigned i = 0, e = ArgC; i != e; ++i) OS << ArgV[i] << ' '; OS << '\n'; } #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES static bool RegisterCrashPrinter() { sys::AddSignalHandler(CrashHandler, nullptr); return false; } #endif void llvm::EnablePrettyStackTrace() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES // The first time this is called, we register the crash printer. static bool HandlerRegistered = RegisterCrashPrinter(); (void)HandlerRegistered; #endif } const void *llvm::SavePrettyStackState() { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES return PrettyStackTraceHead; #else return nullptr; #endif } void llvm::RestorePrettyStackState(const void *Top) { #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES PrettyStackTraceHead = static_cast<PrettyStackTraceEntry *>(const_cast<void *>(Top)); #endif } void LLVMEnablePrettyStackTrace() { EnablePrettyStackTrace(); }
Fix the apple build issue caused by r288956
Fix the apple build issue caused by r288956 Should be checking if HAVE_CRASHREPORTERCLIENT_H is defined not relying on it having a value. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@288963 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm
6fecba4a8810b6cecba55328b301e36afd7412a2
system/LocaleSharedMemory.hpp
system/LocaleSharedMemory.hpp
#pragma once // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __LOCALE_SHARED_MEMORY_HPP__ #define __LOCALE_SHARED_MEMORY_HPP__ #include <gflags/gflags.h> #include <glog/logging.h> #include <string> #include <boost/interprocess/managed_shared_memory.hpp> #include "Communicator.hpp" namespace Grappa { namespace impl { class LocaleSharedMemory { private: size_t region_size; std::string region_name; void * base_address; void create(); void attach(); void destroy(); public: boost::interprocess::fixed_managed_shared_memory segment; public: LocaleSharedMemory(); ~LocaleSharedMemory(); // called before gasnet is ready to operate void init(); // called after gasnet is ready to operate, but before user_main void activate(); // clean up before shutting down void finish(); // make sure an address is in the locale shared memory inline void validate_address( void * addr ) { //#ifndef NDEBUG char * char_base = reinterpret_cast< char* >( base_address ); char * char_addr = reinterpret_cast< char* >( addr ); if( !( (char_base <= addr) && (addr < (char_base + region_size)) ) ) { CHECK_EQ( false, true ) << "Address " << addr << " out of locale shared range!"; } //#endif } void * allocate( size_t size ); void * allocate_aligned( size_t size, size_t alignment ); void deallocate( void * ptr ); }; /// global LocaleSharedMemory instance extern LocaleSharedMemory locale_shared_memory; } // namespace impl } // namespace Grappa #endif
#pragma once // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __LOCALE_SHARED_MEMORY_HPP__ #define __LOCALE_SHARED_MEMORY_HPP__ #include <gflags/gflags.h> #include <glog/logging.h> #include <string> #include <boost/interprocess/managed_shared_memory.hpp> #include "Communicator.hpp" namespace Grappa { namespace impl { class LocaleSharedMemory { private: size_t region_size; std::string region_name; void * base_address; void create(); void attach(); void destroy(); public: boost::interprocess::fixed_managed_shared_memory segment; public: LocaleSharedMemory(); ~LocaleSharedMemory(); // called before gasnet is ready to operate void init(); // called after gasnet is ready to operate, but before user_main void activate(); // clean up before shutting down void finish(); // make sure an address is in the locale shared memory inline void validate_address( void * addr ) { //#ifndef NDEBUG char * char_base = reinterpret_cast< char* >( base_address ); char * char_addr = reinterpret_cast< char* >( addr ); if( !( (char_base <= addr) && (addr < (char_base + region_size)) ) ) { CHECK_EQ( false, true ) << "Address " << addr << " out of locale shared range!"; } //#endif } void * allocate( size_t size ); void * allocate_aligned( size_t size, size_t alignment ); void deallocate( void * ptr ); size_t get_free_memory() { return segment.get_free_memory(); } size_t get_size() { return segment.get_size(); } }; /// global LocaleSharedMemory instance extern LocaleSharedMemory locale_shared_memory; } // namespace impl } // namespace Grappa #endif
add total size and free memory calls to locale shared heap
add total size and free memory calls to locale shared heap
C++
bsd-3-clause
uwsampa/grappa,uwsampa/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa,uwsampa/grappa,alexfrolov/grappa,buaasun/grappa,buaasun/grappa,buaasun/grappa,buaasun/grappa,alexfrolov/grappa,uwsampa/grappa,uwsampa/grappa,uwsampa/grappa,buaasun/grappa,buaasun/grappa,alexfrolov/grappa
ddf9ecc9ad3c6c2802507bdb79a35d8be0b2a1d4
src/mjolnir.cpp
src/mjolnir.cpp
#include <mjolnir/core/Simulator.hpp> #include <mjolnir/core/Observer.hpp> #include <mjolnir/core/DefaultTraits.hpp> #include <mjolnir/io/toml.hpp> typedef mjolnir::DefaultTraits traits; int main(int argc, char** argv) { if(argc != 2) { std::cerr << "Usage: " << argv[0] << " <input.toml>" << std::endl; return 1; } std::ifstream ifs(argv[1]); if(!ifs.good()) { std::cerr << "file open error: " << argv[1] << std::endl; return 1; } // read input file auto input = toml::parse(ifs); // read [simulator] block auto sim = toml::get<toml::Table>(input.at("simulator")); auto pcon = mjolnir::read_particles<traits>(sim); auto rng = mjolnir::read_random_number_generator<traits>(sim); auto integr = mjolnir::read_time_integrator<traits>(sim, rng); const std::size_t total_step = toml::get<toml::Integer>(sim.at("total_step")); const std::size_t save_step = toml::get<toml::Integer>(sim.at("save_step")); const std::string filename = toml::get<toml::String>(sim.at("file_name")); const std::string trajname = filename + ".xyz"; const std::string ene_name = filename + ".ene"; mjolnir::Observer<traits> obs(trajname, ene_name); mjolnir::ForceField<traits> ff = mjolnir::read_force_field<traits>(input); mjolnir::Simulator<traits> simulator(std::move(pcon), std::move(ff), std::move(integr)); // run md simulator.initialize(); const auto start = std::chrono::system_clock::now(); std::cerr << "start running simulation" << std::endl; for(std::size_t i=0; i<total_step; ++i) { if(i % save_step == 0) { obs.output_coordinate(simulator); obs.output_energy(simulator); } simulator.step(); } // output last state obs.output_coordinate(simulator); obs.output_energy(simulator); const auto stop = std::chrono::system_clock::now(); std::cout << "elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>( stop - start).count() << " [msec]" << std::endl; return 0; }
#include <mjolnir/input/read_input_file.hpp> int main(int argc, char** argv) { if(argc != 2) { std::cerr << "Usage: " << argv[0] << " <input.toml>" << std::endl; return 1; } auto simulator = mjolnir::read_input_file(std::string(argv[1])); simulator->initialize(); const auto start = std::chrono::system_clock::now(); std::cerr << "start running simulation" << std::endl; while(simulator->step()){/* do nothing */;} const auto stop = std::chrono::system_clock::now(); std::cout << "elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>( stop - start).count() << " [msec]" << std::endl; simulator->finalize(); return 0; }
update main source
update main source
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
e351322433c0461d2f7c0536904b6f5b9eec06fe
src/mutscan.cpp
src/mutscan.cpp
#include "mutscan.h" #include "fastqreader.h" MutScan::MutScan(string mutationFile, string read1File, string read2File){ mRead1File = read1File; mRead2File = read2File; mMutationFile = mutationFile; } bool MutScan::scan(){ FastqReader reader1(mRead1File); FastqReader reader2(mRead2File); vector<Mutation> mutationList = Mutation::parseFile(mMutationFile); vector<Match*> *mutationMatches = new vector<Match*>[mutationList.size()]; for(int i=0;i<mutationList.size();i++){ mutationMatches[i] = vector<Match*>(); } int processed = 0; while(true){ Read* r1 = reader1.read(); Read* r2 = reader2.read(); if(!r1 || !r2) break; Read* rcr1 = r1->reverseComplement(); Read* rcr2 = r2->reverseComplement(); for(int i=0;i<mutationList.size();i++){ Match* matchR1 = mutationList[i].searchInRead(r1); if(matchR1) mutationMatches[i].push_back(matchR1); Match* matchR2 = mutationList[i].searchInRead(r2); if(matchR2) mutationMatches[i].push_back(matchR2); Match* matchRcr1 = mutationList[i].searchInRead(rcr1); if(matchRcr1){ matchRcr1->setReversed(true); mutationMatches[i].push_back(matchRcr1); } Match* matchRcr2 = mutationList[i].searchInRead(rcr2); if(matchRcr2){ matchRcr2->setReversed(true); mutationMatches[i].push_back(matchRcr2); } } delete r1; delete r2; delete rcr1; delete rcr2; processed += 1; if(processed % 1000000 == 0) { cout<<"processed "<<processed<<" reads"<<endl; } } //output result for(int i=0;i<mutationList.size();i++){ vector<Match*> matches = mutationMatches[i]; if(matches.size()>0){ cout<<endl<<"---------------"<<endl; mutationList[i].print(); for(int m=0; m<matches.size(); m++){ cout<<m+1<<", "; matches[m]->print(); } } } return true; }
#include "mutscan.h" #include "fastqreader.h" MutScan::MutScan(string mutationFile, string read1File, string read2File){ mRead1File = read1File; mRead2File = read2File; mMutationFile = mutationFile; } bool MutScan::scan(){ FastqReader reader1(mRead1File); FastqReader reader2(mRead2File); vector<Mutation> mutationList = Mutation::parseFile(mMutationFile); vector<Match*> *mutationMatches = new vector<Match*>[mutationList.size()]; for(int i=0;i<mutationList.size();i++){ mutationMatches[i] = vector<Match*>(); } int processed = 0; while(true){ Read* r1 = reader1.read(); Read* r2 = reader2.read(); if(!r1 || !r2) break; Read* rcr1 = r1->reverseComplement(); Read* rcr2 = r2->reverseComplement(); for(int i=0;i<mutationList.size();i++){ Match* matchR1 = mutationList[i].searchInRead(r1); if(matchR1) mutationMatches[i].push_back(matchR1); Match* matchR2 = mutationList[i].searchInRead(r2); if(matchR2) mutationMatches[i].push_back(matchR2); Match* matchRcr1 = mutationList[i].searchInRead(rcr1); if(matchRcr1){ matchRcr1->setReversed(true); mutationMatches[i].push_back(matchRcr1); } Match* matchRcr2 = mutationList[i].searchInRead(rcr2); if(matchRcr2){ matchRcr2->setReversed(true); mutationMatches[i].push_back(matchRcr2); } } delete r1; delete r2; delete rcr1; delete rcr2; processed += 1; if(processed % 1000000 == 0) { //cout<<"processed "<<processed<<" reads"<<endl; } } //output result for(int i=0;i<mutationList.size();i++){ vector<Match*> matches = mutationMatches[i]; if(matches.size()>0){ cout<<endl<<"---------------"<<endl; mutationList[i].print(); for(int m=0; m<matches.size(); m++){ cout<<m+1<<", "; matches[m]->print(); } } } return true; }
comment the print of processed reads
comment the print of processed reads
C++
mit
OpenGene/MutScan,OpenGene/MutScan
e07ccfad79231966d56570986ec639985389a4c9
src/nao_spy.cpp
src/nao_spy.cpp
/** * @file * @author Antonio Paolillo * @author Dimitar Dimitrov * @author Alexander Sherikov */ #include "nao_spy.h" /** * Constructor for nao_spy object * @param broker The parent broker * @param name The name of the module */ nao_spy::nao_spy(ALPtr<ALBroker> broker, const string& name) : ALModule(broker, name), accessSensorValues (ALPtr<ALMemoryFastAccess>(new ALMemoryFastAccess())), accessActuatorValues (ALPtr<ALMemoryFastAccess>(new ALMemoryFastAccess())) { setModuleDescription("Collect sensor values while a robot is walking."); functionName( "spy", getName() , "spy"); BIND_METHOD( nao_spy::spy ); } /** * Destructor for nao_spy object */ nao_spy::~nao_spy() { } // Initialisation of ALmemory fast access, DCM commands, Alias, stiffness, ... /** * @brief */ void nao_spy::init() { bool isDCMRunning; // Is the DCM running ? try { isDCMRunning = getParentBroker()->getProxy("ALLauncher")->call<bool>("isModulePresent", std::string("DCM")); } catch (ALError& e) { throw ALERROR(getName(), __FUNCTION__, "Error when connecting to DCM : " + e.toString()); } if (!isDCMRunning) { throw ALERROR(getName(), __FUNCTION__, "Error no DCM running "); } // proxies try { // Get the DCM proxy dcmProxy = getParentBroker()->getDcmProxy(); } catch (ALError& e) { throw ALERROR(getName(), __FUNCTION__, "Impossible to create DCM Proxy : " + e.toString()); } try { motionProxy = getParentBroker()->getMotionProxy(); } catch(AL::ALError &e) { throw ALERROR(getName(), __FUNCTION__, "Impossible to create Motion Proxy : " + e.toString()); } initFastRead(); } void nao_spy::spy() { spy_log_instance = new spy_log; try { fDCMPostProcessConnection = getParentBroker()->getProxy("DCM")->getModule()->atPostProcess (boost::bind(&nao_spy::callbackEveryCycle_walk, this)); } catch (const AL::ALError &e) { throw ALERROR(getName(), __FUNCTION__, "Error when connecting to DCM postProccess: " + e.toString()); } motionProxy->setStiffnesses("Body", 1.0f); motionProxy->walkInit(); motionProxy->walkTo(0.4f, 0.0f, 0.0f); motionProxy->setStiffnesses("Body", 0.0f); // Remove the postProcess call back connection fDCMPostProcessConnection.disconnect(); delete spy_log_instance; } /** * @brief */ void nao_spy::callbackEveryCycle_walk() { spy_timer timer; spy_log_instance->logJointValues(accessSensorValues, accessActuatorValues); spy_log_instance->logCoM(motionProxy, accessSensorValues); spy_log_instance->logFoot(motionProxy, accessSensorValues); }
/** * @file * @author Antonio Paolillo * @author Dimitar Dimitrov * @author Alexander Sherikov */ #include "nao_spy.h" /** * Constructor for nao_spy object * @param broker The parent broker * @param name The name of the module */ nao_spy::nao_spy(ALPtr<ALBroker> broker, const string& name) : ALModule(broker, name), accessSensorValues (ALPtr<ALMemoryFastAccess>(new ALMemoryFastAccess())), accessActuatorValues (ALPtr<ALMemoryFastAccess>(new ALMemoryFastAccess())) { setModuleDescription("Collect sensor values while a robot is walking."); functionName( "spy", getName() , "spy"); BIND_METHOD( nao_spy::spy ); } /** * Destructor for nao_spy object */ nao_spy::~nao_spy() { } // Initialisation of ALmemory fast access, DCM commands, Alias, stiffness, ... /** * @brief */ void nao_spy::init() { bool isDCMRunning; // Is the DCM running ? try { isDCMRunning = getParentBroker()->getProxy("ALLauncher")->call<bool>("isModulePresent", std::string("DCM")); } catch (ALError& e) { throw ALERROR(getName(), __FUNCTION__, "Error when connecting to DCM : " + e.toString()); } if (!isDCMRunning) { throw ALERROR(getName(), __FUNCTION__, "Error no DCM running "); } // proxies try { // Get the DCM proxy dcmProxy = getParentBroker()->getDcmProxy(); } catch (ALError& e) { throw ALERROR(getName(), __FUNCTION__, "Impossible to create DCM Proxy : " + e.toString()); } try { motionProxy = getParentBroker()->getMotionProxy(); } catch(AL::ALError &e) { throw ALERROR(getName(), __FUNCTION__, "Impossible to create Motion Proxy : " + e.toString()); } initFastRead(); } void nao_spy::spy() { spy_log_instance = new spy_log; try { fDCMPostProcessConnection = getParentBroker()->getProxy("DCM")->getModule()->atPostProcess (boost::bind(&nao_spy::callbackEveryCycle_walk, this)); } catch (const AL::ALError &e) { throw ALERROR(getName(), __FUNCTION__, "Error when connecting to DCM postProccess: " + e.toString()); } // motionProxy->setStiffnesses("Body", 1.0f); motionProxy->stiffnessInterpolation("Body", 1.0, 0.1); motionProxy->walkInit(); motionProxy->walkTo(0.4f, 0.0f, 0.0f); motionProxy->setStiffnesses("Body", 0.0f); // Remove the postProcess call back connection fDCMPostProcessConnection.disconnect(); delete spy_log_instance; } /** * @brief */ void nao_spy::callbackEveryCycle_walk() { spy_timer timer; spy_log_instance->logJointValues(accessSensorValues, accessActuatorValues); spy_log_instance->logCoM(motionProxy, accessSensorValues); spy_log_instance->logFoot(motionProxy, accessSensorValues); }
Set stiffness using a different function.
Set stiffness using a different function.
C++
bsd-2-clause
asherikov/nao_spy,asherikov/nao_spy,asherikov/nao_spy,asherikov/nao_spy
6ae17982e62999bcb2e53615eb450525155d26c8
src/bridge.cc
src/bridge.cc
#include <node.h> #include <v8.h> #include <phidget21.h> using namespace v8; // ------------------------------------------ // Globals // ------------------------------------------ CPhidgetBridgeHandle bridge = 0; // ------------------------------------------ // Event handlers // ------------------------------------------ int CCONV AttachHandler(CPhidgetHandle ADVSERVO, void *userptr) { int serialNo; const char *name; CPhidget_getDeviceName (ADVSERVO, &name); CPhidget_getSerialNumber(ADVSERVO, &serialNo); printf("%s %10d attached!\n", name, serialNo); return 0; } int CCONV DetachHandler(CPhidgetHandle ADVSERVO, void *userptr) { int serialNo; const char *name; CPhidget_getDeviceName (ADVSERVO, &name); CPhidget_getSerialNumber(ADVSERVO, &serialNo); printf("%s %10d detached!\n", name, serialNo); return 0; } int CCONV ErrorHandler(CPhidgetHandle ADVSERVO, void *userptr, int ErrorCode, const char *Description) { printf("Error handled. %d - %s\n", ErrorCode, Description); return 0; } int CCONV BridgeDataHandler(CPhidgetBridgeHandle ADVSERVO, void *usrptr, int Index, double Value) { printf("Bridge: %d > Current Data: %f\n", Index, Value); return 0; } int display_properties(CPhidgetBridgeHandle phid) { int serialNo, version; int numSensor, rateMax, rateMin; const char* ptr; CPhidget_getDeviceType((CPhidgetHandle)phid, &ptr); CPhidget_getSerialNumber((CPhidgetHandle)phid, &serialNo); CPhidget_getDeviceVersion((CPhidgetHandle)phid, &version); CPhidgetBridge_getInputCount((CPhidgetBridgeHandle) phid, &numSensor); CPhidgetBridge_getDataRateMax((CPhidgetBridgeHandle) phid, &rateMax); CPhidgetBridge_getDataRateMin((CPhidgetBridgeHandle) phid, &rateMin); printf("%s\n", ptr); printf("Serial Number: %10d\nVersion: %8d\n# Sensor: %d\nData Rate: %d ~ %d\n", serialNo, version, numSensor, rateMax, rateMin); return 0; } // ------------------------------------------ // Method abstractions // ------------------------------------------ Handle<Value> attach(const Arguments& args) { HandleScope scope; int result; const char *err; CPhidgetBridgeHandle bridge; //CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL); CPhidgetBridge_create(&bridge); CPhidget_set_OnAttach_Handler((CPhidgetHandle)bridge, AttachHandler, NULL); CPhidget_set_OnDetach_Handler((CPhidgetHandle)bridge, DetachHandler, NULL); CPhidget_set_OnError_Handler((CPhidgetHandle)bridge, ErrorHandler, NULL); CPhidgetBridge_set_OnBridgeData_Handler(bridge, data, NULL); CPhidget_open((CPhidgetHandle)bridge, -1); //Wait for 10 seconds, otherwise exit if(result = CPhidget_waitForAttachment((CPhidgetHandle)bridge, 10000)) { CPhidget_getErrorDescription(result, &err); printf("Problem waiting for attachment: %s\n", err); return; } // Display the properties of the attached device display_properties(bridge); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> close(const Arguments& args) { HandleScope scope; CPhidget_close((CPhidgetHandle)bridge); CPhidget_delete((CPhidgetHandle)bridge); printf("Phidget Bridge is closed.\n"); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getValue(const Arguments& args) { double value; HandleScope scope; CPhidgetBridge_getBridgeValue(bridge, args[0]->Int32Value(), &value); return scope.Close(Number::New(value)); } Handle<Value> getMax(const Arguments& args) { double max; HandleScope scope; CPhidgetBridge_getBridgeMax(bridge, args[0]->Int32Value(), &max); return scope.Close(Integer::NewFromUnsigned(max)); } Handle<Value> getMin(const Arguments& args) { double min; HandleScope scope; CPhidgetBridge_getBridgeMin(bridge, args[0]->Int32Value(), &min); return scope.Close(Integer::NewFromUnsigned(min)); } Handle<Value> setEnabled(const Arguments& args) { HandleScope scope; CPhidgetBridge_setEnabled(bridge, args[0]->Int32Value(), args[1]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getEnabled(const Arguments& args) { int enabled; HandleScope scope; CPhidgetBridge_getEnabled(bridge, args[0]->Int32Value(), &enabled); if(enabled) return scope.Close(Boolean::New(true)); else return scope.Close(Boolean::New(false)); } Handle<Value> setGain(const Arguments& args) { CPhidgetBridge_Gain gain; switch(args[1]->Int32Value()) { case 1: gain = PHIDGET_BRIDGE_GAIN_1; break; case 2: gain = PHIDGET_BRIDGE_GAIN_8; break; case 3: gain = PHIDGET_BRIDGE_GAIN_16; break; case 4: gain = PHIDGET_BRIDGE_GAIN_32; break; case 5: gain = PHIDGET_BRIDGE_GAIN_64; break; case 6: gain = PHIDGET_BRIDGE_GAIN_128; break; default: gain = PHIDGET_BRIDGE_GAIN_UNKNOWN; } HandleScope scope; CPhidgetBridge_setGain(bridge, args[0]->Int32Value(), gain); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getGain(const Arguments& args) { CPhidgetBridge_Gain gain; HandleScope scope; CPhidgetBridge_getGain(bridge, args[0]->Int32Value(), &gain); return scope.Close(Integer::NewFromUnsigned(gain)); } Handle<Value> setDataRate(const Arguments& args) { HandleScope scope; CPhidgetBridge_setDataRate(bridge, args[0]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getDataRate(const Arguments& args) { int dataRate; HandleScope scope; CPhidgetBridge_getDataRate(bridge, &dataRate); return scope.Close(Integer::NewFromUnsigned(dataRate)); } // ------------------------------------------ // Module // ------------------------------------------ void init(Handle<Object> target) { // Connection target->Set(String::New("attach"), FunctionTemplate::New(attach)->GetFunction()); target->Set(String::New("close"), FunctionTemplate::New(close)->GetFunction()); // Bridge manipulation target->Set(String::New("setEnabled"), FunctionTemplate::New(setEnabled)->GetFunction()); target->Set(String::New("setGain"), FunctionTemplate::New(setGain)->GetFunction()); target->Set(String::New("setDataRate"), FunctionTemplate::New(setDataRate)->GetFunction()); // Status target->Set(String::New("getValue"), FunctionTemplate::New(getValue)->GetFunction()); target->Set(String::New("getMax"), FunctionTemplate::New(getMax)->GetFunction()); target->Set(String::New("getMin"), FunctionTemplate::New(getMin)->GetFunction()); target->Set(String::New("getEnabled"), FunctionTemplate::New(getEnabled)->GetFunction()); target->Set(String::New("getGain"), FunctionTemplate::New(getGain)->GetFunction()); target->Set(String::New("getDataRate"), FunctionTemplate::New(getDataRate)->GetFunction()); } NODE_MODULE(binding_bridge, init);
#include <node.h> #include <v8.h> #include <phidget21.h> using namespace v8; // ------------------------------------------ // Globals // ------------------------------------------ CPhidgetBridgeHandle bridge = 0; // ------------------------------------------ // Event handlers // ------------------------------------------ int CCONV AttachHandler(CPhidgetHandle ADVSERVO, void *userptr) { int serialNo; const char *name; CPhidget_getDeviceName (ADVSERVO, &name); CPhidget_getSerialNumber(ADVSERVO, &serialNo); printf("%s %10d attached!\n", name, serialNo); return 0; } int CCONV DetachHandler(CPhidgetHandle ADVSERVO, void *userptr) { int serialNo; const char *name; CPhidget_getDeviceName (ADVSERVO, &name); CPhidget_getSerialNumber(ADVSERVO, &serialNo); printf("%s %10d detached!\n", name, serialNo); return 0; } int CCONV ErrorHandler(CPhidgetHandle ADVSERVO, void *userptr, int ErrorCode, const char *Description) { printf("Error handled. %d - %s\n", ErrorCode, Description); return 0; } int CCONV BridgeDataHandler(CPhidgetBridgeHandle ADVSERVO, void *usrptr, int Index, double Value) { printf("Bridge: %d > Current Data: %f\n", Index, Value); return 0; } int display_properties(CPhidgetBridgeHandle phid) { int serialNo, version; int numSensor, rateMax, rateMin; const char* ptr; CPhidget_getDeviceType((CPhidgetHandle)phid, &ptr); CPhidget_getSerialNumber((CPhidgetHandle)phid, &serialNo); CPhidget_getDeviceVersion((CPhidgetHandle)phid, &version); CPhidgetBridge_getInputCount((CPhidgetBridgeHandle) phid, &numSensor); CPhidgetBridge_getDataRateMax((CPhidgetBridgeHandle) phid, &rateMax); CPhidgetBridge_getDataRateMin((CPhidgetBridgeHandle) phid, &rateMin); printf("%s\n", ptr); printf("Serial Number: %10d\nVersion: %8d\n# Sensor: %d\nData Rate: %d ~ %d\n", serialNo, version, numSensor, rateMax, rateMin); return 0; } // ------------------------------------------ // Method abstractions // ------------------------------------------ Handle<Value> attach(const Arguments& args) { HandleScope scope; int result; const char *err; CPhidgetBridgeHandle bridge; //CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL); CPhidgetBridge_create(&bridge); CPhidget_set_OnAttach_Handler((CPhidgetHandle)bridge, AttachHandler, NULL); CPhidget_set_OnDetach_Handler((CPhidgetHandle)bridge, DetachHandler, NULL); CPhidget_set_OnError_Handler((CPhidgetHandle)bridge, ErrorHandler, NULL); // CPhidgetBridge_set_OnBridgeData_Handler(bridge, data, NULL); CPhidget_open((CPhidgetHandle)bridge, -1); //Wait for 10 seconds, otherwise exit if(result = CPhidget_waitForAttachment((CPhidgetHandle)bridge, 10000)) { CPhidget_getErrorDescription(result, &err); printf("Problem waiting for attachment: %s\n", err); return; } // Display the properties of the attached device display_properties(bridge); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> close(const Arguments& args) { HandleScope scope; CPhidget_close((CPhidgetHandle)bridge); CPhidget_delete((CPhidgetHandle)bridge); printf("Phidget Bridge is closed.\n"); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getValue(const Arguments& args) { double value; HandleScope scope; CPhidgetBridge_getBridgeValue(bridge, args[0]->Int32Value(), &value); return scope.Close(Number::New(value)); } Handle<Value> getMax(const Arguments& args) { double max; HandleScope scope; CPhidgetBridge_getBridgeMax(bridge, args[0]->Int32Value(), &max); return scope.Close(Integer::NewFromUnsigned(max)); } Handle<Value> getMin(const Arguments& args) { double min; HandleScope scope; CPhidgetBridge_getBridgeMin(bridge, args[0]->Int32Value(), &min); return scope.Close(Integer::NewFromUnsigned(min)); } Handle<Value> setEnabled(const Arguments& args) { HandleScope scope; CPhidgetBridge_setEnabled(bridge, args[0]->Int32Value(), args[1]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getEnabled(const Arguments& args) { int enabled; HandleScope scope; CPhidgetBridge_getEnabled(bridge, args[0]->Int32Value(), &enabled); if(enabled) return scope.Close(Boolean::New(true)); else return scope.Close(Boolean::New(false)); } Handle<Value> setGain(const Arguments& args) { CPhidgetBridge_Gain gain; switch(args[1]->Int32Value()) { case 1: gain = PHIDGET_BRIDGE_GAIN_1; break; case 2: gain = PHIDGET_BRIDGE_GAIN_8; break; case 3: gain = PHIDGET_BRIDGE_GAIN_16; break; case 4: gain = PHIDGET_BRIDGE_GAIN_32; break; case 5: gain = PHIDGET_BRIDGE_GAIN_64; break; case 6: gain = PHIDGET_BRIDGE_GAIN_128; break; default: gain = PHIDGET_BRIDGE_GAIN_UNKNOWN; } HandleScope scope; CPhidgetBridge_setGain(bridge, args[0]->Int32Value(), gain); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getGain(const Arguments& args) { CPhidgetBridge_Gain gain; HandleScope scope; CPhidgetBridge_getGain(bridge, args[0]->Int32Value(), &gain); return scope.Close(Integer::NewFromUnsigned(gain)); } Handle<Value> setDataRate(const Arguments& args) { HandleScope scope; CPhidgetBridge_setDataRate(bridge, args[0]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(0)); } Handle<Value> getDataRate(const Arguments& args) { int dataRate; HandleScope scope; CPhidgetBridge_getDataRate(bridge, &dataRate); return scope.Close(Integer::NewFromUnsigned(dataRate)); } // ------------------------------------------ // Module // ------------------------------------------ void init(Handle<Object> target) { // Connection target->Set(String::New("attach"), FunctionTemplate::New(attach)->GetFunction()); target->Set(String::New("close"), FunctionTemplate::New(close)->GetFunction()); // Bridge manipulation target->Set(String::New("setEnabled"), FunctionTemplate::New(setEnabled)->GetFunction()); target->Set(String::New("setGain"), FunctionTemplate::New(setGain)->GetFunction()); target->Set(String::New("setDataRate"), FunctionTemplate::New(setDataRate)->GetFunction()); // Status target->Set(String::New("getValue"), FunctionTemplate::New(getValue)->GetFunction()); target->Set(String::New("getMax"), FunctionTemplate::New(getMax)->GetFunction()); target->Set(String::New("getMin"), FunctionTemplate::New(getMin)->GetFunction()); target->Set(String::New("getEnabled"), FunctionTemplate::New(getEnabled)->GetFunction()); target->Set(String::New("getGain"), FunctionTemplate::New(getGain)->GetFunction()); target->Set(String::New("getDataRate"), FunctionTemplate::New(getDataRate)->GetFunction()); } NODE_MODULE(binding_bridge, init);
add library
add library
C++
mit
andrest/phidget,andrest/phidget,andrest/phidget
26649ddef7feceb12100df3fed62c33476d5ca97
test/PluginParametersTest.cpp
test/PluginParametersTest.cpp
/* * Copyright (c) 2013 Teragon Audio. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "PluginParameters.h" using namespace teragon; #define ADD_TEST(name, func) { \ printf("Test %s: ", name); \ if(func) printf("success\n"); \ else printf("FAIL\n"); \ } #define ASSERT(result) { \ if(!result) return false; \ } #define ASSERT_NOT_NULL(result) { \ if(result == NULL) return false; \ } #define ASSERT_FALSE(result) { \ if(result) return false; \ } #define ASSERT_EQUALS(expected, result) { \ if(abs(fabs(result) - fabs(expected)) > 0.001) { \ printf("Expected %f, got %f. ", expected, result); \ return false; \ } \ } #define ASSERT_INT_EQUALS(expected, result) { \ if(result != expected) { \ printf("Expected %d, got %d. ", expected, result); \ return false; \ } \ } #define ASSERT_STRING(expected, result) { \ std::string e(expected); \ if(e.compare(result) != 0) { \ printf("Expected '%s', got '%s'. ", expected, result.c_str()); \ return false; \ } \ } static bool testCreateBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); ASSERT_EQUALS(0.0, p.getScaledValue()); ASSERT_STRING("test", p.getName()); ASSERT_EQUALS(0.0, p.getDisplayValue()); ASSERT_STRING("false", p.getDisplayText()); ASSERT_STRING("test", p.getSafeName()); return true; } static bool testSetBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); p.setValue(1.0); ASSERT(p.getValue()); return true; } static bool testCreateDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, 0.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); return true; } static bool testSetDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, -10.0); ASSERT_STRING("-10.0 dB", p.getDisplayText()); p.setValue(1.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); p.setScaledValue(0.5); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_EQUALS(0.706769, p.getValue()); ASSERT_STRING("-3.0 dB", p.getDisplayText()); return true; } static bool testCreateFloatParameter() { FloatParameter p("test", 0.0, 50.0, 25.0); ASSERT_EQUALS(25.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_STRING("25.0", p.getDisplayText()); return true; } static bool testSetFloatParameter() { FloatParameter p("test", 0.0, 60.0, 0.0); p.setValue(30.0); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.25); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); return true; } static bool testCreateFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); ASSERT_EQUALS(10000.0, p.getValue()); ASSERT_EQUALS(0.899657, p.getScaledValue()); ASSERT_STRING("10.0 kHz", p.getDisplayText()); return true; } static bool testSetFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); p.setValue(666.0); ASSERT_EQUALS(666.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(3556.559, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateIntegerParameter() { IntegerParameter p("test", 0, 60, 15); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); ASSERT_STRING("15", p.getDisplayText()); return true; } static bool testSetIntegerParameter() { IntegerParameter p("test", 0, 60, 15); p.setValue(30); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(45.0, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateParameterWithBadName() { // NOTE: This test will succeed, I'd rather not throw from the ctor! // So use your head and don't make any weird parameter names. Just know // that the library isn't going to protect you from yourself. :) BooleanParameter p(""); return true; } static bool testCreateParameterWithBadRange() { // NOTE: This test will also succeed, PluginParameters doesn't check for bad ranges // Just be aware of this behavior rather than trying to abuse the library. IntegerParameter p("bad", 100.0, 0.0, 300.0); return true; } static bool testAddParameterToSet() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 1", s.get(0)->getName()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testAddNullParameterToSet() { PluginParameterSet s; ASSERT_FALSE(s.add(NULL)); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testAddDuplicateParameterToSet() { BooleanParameter p("test"); PluginParameterSet s; ASSERT(s.add(&p)); ASSERT_FALSE(s.add(&p)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testAddDuplicateSafeNameParameterToSet() { BooleanParameter p1("Parameter1"); BooleanParameter p2("Parameter 1"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT_FALSE(s.add(&p2)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testClearParameterSet() { BooleanParameter *p1 = new BooleanParameter("Parameter1"); BooleanParameter *p2 = new BooleanParameter("Parameter2"); PluginParameterSet s; ASSERT(s.add(p1)); ASSERT(s.add(p2)); ASSERT_INT_EQUALS(2, s.size()); s.clear(); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testGetParameterByName() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); PluginParameter *pe = s.get("Parameter 2"); ASSERT_NOT_NULL(pe); ASSERT_STRING("Parameter 2", pe->getName()); return true; } static bool testGetParameterByIndex() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testGetParameterByNameOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s["Parameter 2"]->getName()); return true; } static bool testGetParameterByIndexOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s[1]->getName()); return true; } static bool testGetSafeName() { BooleanParameter p("hi there"); ASSERT_STRING("hithere", p.getSafeName()); return true; } class TestObserver : public PluginParameterObserver { public: TestObserver(bool &inB) : b(inB) {} void onParameterUpdated(const PluginParameter* parameter) { b = true; } private: bool& b; }; static bool testAddObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.setValue(1.0); ASSERT(b); return true; } static bool testRemoveObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.removeObserver(&t); p.setValue(1.0); ASSERT_FALSE(b); return true; } static bool testParameterType() { BooleanParameter p("test"); ASSERT_INT_EQUALS(0, p.getType()); p.setType(1234); ASSERT_INT_EQUALS(1234, p.getType()); return true; } static bool testGetMinValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(0.123, p.getMinValue()); return true; } static bool testGetMaxValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.23, p.getMaxValue()); return true; } static bool testGetDefaultValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.0, p.getDefaultValue()); return true; } static bool testSetParameterUnit() { FloatParameter p("test", 0.0, 1.0, 0.0); ASSERT_STRING("0.0", p.getDisplayText()); p.setUnit("foo"); ASSERT_STRING("0.0 foo", p.getDisplayText()); return true; } static bool testSetPrecision() { FloatParameter p("test", 0.0, 1.0, 0.123456); ASSERT_STRING("0.1", p.getDisplayText()); p.setDisplayPrecision(3); ASSERT_STRING("0.123", p.getDisplayText()); // Rounding! p.setDisplayPrecision(5); ASSERT_STRING("0.12346", p.getDisplayText()); return true; } static bool testCreateStringParameter() { StringParameter p("test", "whatever"); ASSERT_EQUALS(0.0, p.getValue()); ASSERT_STRING("whatever", p.getDisplayText()); return true; } static bool testSetStringParameter() { StringParameter p("test", "whatever"); ASSERT_EQUALS(0.0, p.getValue()); ASSERT_STRING("whatever", p.getDisplayText()); p.setValue("something"); ASSERT_STRING("something", p.getDisplayText()); return true; } int main(int argc, char* argv[]) { ADD_TEST("CreateBoolParameter", testCreateBoolParameter()); ADD_TEST("SetBoolParameter", testSetBoolParameter()); ADD_TEST("CreateDecibelParameter", testCreateDecibelParameter()); ADD_TEST("SetDecibelParameter", testSetDecibelParameter()); ADD_TEST("CreateFloatParameter", testCreateFloatParameter()); ADD_TEST("SetFloatParameter", testSetFloatParameter()); ADD_TEST("CreateFrequencyParameter", testCreateFrequencyParameter()); ADD_TEST("SetFrequencyParameter", testSetFrequencyParameter()); ADD_TEST("CreateIntegerParameter", testCreateIntegerParameter()); ADD_TEST("SetIntegerParameter", testSetIntegerParameter()); ADD_TEST("CreateParameterWithBadName", testCreateParameterWithBadName()); ADD_TEST("CreateParameterWithBadRange", testCreateParameterWithBadRange()); ADD_TEST("AddParameterToSet", testAddParameterToSet()); ADD_TEST("AddNullParameterToSet", testAddNullParameterToSet()); ADD_TEST("AddDuplicateParameterToSet", testAddDuplicateParameterToSet()); ADD_TEST("AddDuplicateSafeNameParameterToSet", testAddDuplicateSafeNameParameterToSet()); ADD_TEST("ClearParameterSet", testClearParameterSet()); ADD_TEST("GetParameterByName", testGetParameterByName()); ADD_TEST("GetParameterByIndex", testGetParameterByIndex()); ADD_TEST("GetParameterByNameOperator", testGetParameterByNameOperator()); ADD_TEST("GetParameterByIndexOperator", testGetParameterByIndexOperator()); ADD_TEST("GetSafeName", testGetSafeName()); ADD_TEST("AddObserver", testAddObserver()); ADD_TEST("RemoveObserver", testRemoveObserver()); ADD_TEST("ParameterType", testParameterType()); ADD_TEST("GetMinValue", testGetMinValue()); ADD_TEST("GetMaxValue", testGetMaxValue()); ADD_TEST("GetDefaultValue", testGetDefaultValue()); ADD_TEST("SetParameterUnit", testSetParameterUnit()); ADD_TEST("SetPrecision", testSetPrecision()); ADD_TEST("CreateStringParameter", testCreateStringParameter()); ADD_TEST("SetStringParameter", testSetStringParameter()); return 0; }
/* * Copyright (c) 2013 Teragon Audio. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "PluginParameters.h" using namespace teragon; #define ADD_TEST(name, func) { \ printf("Test %s: ", name); \ if(func) printf("success\n"); \ else printf("FAIL\n"); \ } #define ASSERT(result) { \ if(!result) return false; \ } #define ASSERT_NOT_NULL(result) { \ if(result == NULL) return false; \ } #define ASSERT_FALSE(result) { \ if(result) return false; \ } #define ASSERT_EQUALS(expected, result) { \ if(fabs(fabs(result) - fabs(expected)) > 0.001) { \ printf("Expected %f, got %f. ", expected, result); \ return false; \ } \ } #define ASSERT_INT_EQUALS(expected, result) { \ if(result != expected) { \ printf("Expected %d, got %d. ", expected, result); \ return false; \ } \ } #define ASSERT_STRING(expected, result) { \ std::string e(expected); \ if(e.compare(result) != 0) { \ printf("Expected '%s', got '%s'. ", expected, result.c_str()); \ return false; \ } \ } static bool testCreateBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); ASSERT_EQUALS(0.0, p.getScaledValue()); ASSERT_STRING("test", p.getName()); ASSERT_EQUALS(0.0, p.getDisplayValue()); ASSERT_STRING("false", p.getDisplayText()); ASSERT_STRING("test", p.getSafeName()); return true; } static bool testSetBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); p.setValue(1.0); ASSERT(p.getValue()); return true; } static bool testCreateDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, 0.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); return true; } static bool testSetDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, -10.0); ASSERT_STRING("-10.0 dB", p.getDisplayText()); p.setValue(1.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); p.setScaledValue(0.5); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_EQUALS(0.706769, p.getValue()); ASSERT_STRING("-3.0 dB", p.getDisplayText()); return true; } static bool testCreateFloatParameter() { FloatParameter p("test", 0.0, 50.0, 25.0); ASSERT_EQUALS(25.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_STRING("25.0", p.getDisplayText()); return true; } static bool testSetFloatParameter() { FloatParameter p("test", 0.0, 60.0, 0.0); p.setValue(30.0); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.25); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); return true; } static bool testCreateFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); ASSERT_EQUALS(10000.0, p.getValue()); ASSERT_EQUALS(0.899657, p.getScaledValue()); ASSERT_STRING("10.0 kHz", p.getDisplayText()); return true; } static bool testSetFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); p.setValue(666.0); ASSERT_EQUALS(666.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(3556.559, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateIntegerParameter() { IntegerParameter p("test", 0, 60, 15); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); ASSERT_STRING("15", p.getDisplayText()); return true; } static bool testSetIntegerParameter() { IntegerParameter p("test", 0, 60, 15); p.setValue(30); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(45.0, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateParameterWithBadName() { // NOTE: This test will succeed, I'd rather not throw from the ctor! // So use your head and don't make any weird parameter names. Just know // that the library isn't going to protect you from yourself. :) BooleanParameter p(""); return true; } static bool testCreateParameterWithBadRange() { // NOTE: This test will also succeed, PluginParameters doesn't check for bad ranges // Just be aware of this behavior rather than trying to abuse the library. IntegerParameter p("bad", 100.0, 0.0, 300.0); return true; } static bool testAddParameterToSet() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 1", s.get(0)->getName()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testAddNullParameterToSet() { PluginParameterSet s; ASSERT_FALSE(s.add(NULL)); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testAddDuplicateParameterToSet() { BooleanParameter p("test"); PluginParameterSet s; ASSERT(s.add(&p)); ASSERT_FALSE(s.add(&p)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testAddDuplicateSafeNameParameterToSet() { BooleanParameter p1("Parameter1"); BooleanParameter p2("Parameter 1"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT_FALSE(s.add(&p2)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testClearParameterSet() { BooleanParameter *p1 = new BooleanParameter("Parameter1"); BooleanParameter *p2 = new BooleanParameter("Parameter2"); PluginParameterSet s; ASSERT(s.add(p1)); ASSERT(s.add(p2)); ASSERT_INT_EQUALS(2, s.size()); s.clear(); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testGetParameterByName() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); PluginParameter *pe = s.get("Parameter 2"); ASSERT_NOT_NULL(pe); ASSERT_STRING("Parameter 2", pe->getName()); return true; } static bool testGetParameterByIndex() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testGetParameterByNameOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s["Parameter 2"]->getName()); return true; } static bool testGetParameterByIndexOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s[1]->getName()); return true; } static bool testGetSafeName() { BooleanParameter p("hi there"); ASSERT_STRING("hithere", p.getSafeName()); return true; } class TestObserver : public PluginParameterObserver { public: TestObserver(bool &inB) : b(inB) {} void onParameterUpdated(const PluginParameter* parameter) { b = true; } private: bool& b; }; static bool testAddObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.setValue(1.0); ASSERT(b); return true; } static bool testRemoveObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.removeObserver(&t); p.setValue(1.0); ASSERT_FALSE(b); return true; } static bool testParameterType() { BooleanParameter p("test"); ASSERT_INT_EQUALS(0, p.getType()); p.setType(1234); ASSERT_INT_EQUALS(1234, p.getType()); return true; } static bool testGetMinValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(0.123, p.getMinValue()); return true; } static bool testGetMaxValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.23, p.getMaxValue()); return true; } static bool testGetDefaultValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.0, p.getDefaultValue()); return true; } static bool testSetParameterUnit() { FloatParameter p("test", 0.0, 1.0, 0.0); ASSERT_STRING("0.0", p.getDisplayText()); p.setUnit("foo"); ASSERT_STRING("0.0 foo", p.getDisplayText()); return true; } static bool testSetPrecision() { FloatParameter p("test", 0.0, 1.0, 0.123456); ASSERT_STRING("0.1", p.getDisplayText()); p.setDisplayPrecision(3); ASSERT_STRING("0.123", p.getDisplayText()); // Rounding! p.setDisplayPrecision(5); ASSERT_STRING("0.12346", p.getDisplayText()); return true; } static bool testCreateStringParameter() { StringParameter p("test", "whatever"); ASSERT_EQUALS(0.0, p.getValue()); ASSERT_STRING("whatever", p.getDisplayText()); return true; } static bool testSetStringParameter() { StringParameter p("test", "whatever"); ASSERT_EQUALS(0.0, p.getValue()); ASSERT_STRING("whatever", p.getDisplayText()); p.setValue("something"); ASSERT_STRING("something", p.getDisplayText()); return true; } int main(int argc, char* argv[]) { ADD_TEST("CreateBoolParameter", testCreateBoolParameter()); ADD_TEST("SetBoolParameter", testSetBoolParameter()); ADD_TEST("CreateDecibelParameter", testCreateDecibelParameter()); ADD_TEST("SetDecibelParameter", testSetDecibelParameter()); ADD_TEST("CreateFloatParameter", testCreateFloatParameter()); ADD_TEST("SetFloatParameter", testSetFloatParameter()); ADD_TEST("CreateFrequencyParameter", testCreateFrequencyParameter()); ADD_TEST("SetFrequencyParameter", testSetFrequencyParameter()); ADD_TEST("CreateIntegerParameter", testCreateIntegerParameter()); ADD_TEST("SetIntegerParameter", testSetIntegerParameter()); ADD_TEST("CreateParameterWithBadName", testCreateParameterWithBadName()); ADD_TEST("CreateParameterWithBadRange", testCreateParameterWithBadRange()); ADD_TEST("AddParameterToSet", testAddParameterToSet()); ADD_TEST("AddNullParameterToSet", testAddNullParameterToSet()); ADD_TEST("AddDuplicateParameterToSet", testAddDuplicateParameterToSet()); ADD_TEST("AddDuplicateSafeNameParameterToSet", testAddDuplicateSafeNameParameterToSet()); ADD_TEST("ClearParameterSet", testClearParameterSet()); ADD_TEST("GetParameterByName", testGetParameterByName()); ADD_TEST("GetParameterByIndex", testGetParameterByIndex()); ADD_TEST("GetParameterByNameOperator", testGetParameterByNameOperator()); ADD_TEST("GetParameterByIndexOperator", testGetParameterByIndexOperator()); ADD_TEST("GetSafeName", testGetSafeName()); ADD_TEST("AddObserver", testAddObserver()); ADD_TEST("RemoveObserver", testRemoveObserver()); ADD_TEST("ParameterType", testParameterType()); ADD_TEST("GetMinValue", testGetMinValue()); ADD_TEST("GetMaxValue", testGetMaxValue()); ADD_TEST("GetDefaultValue", testGetDefaultValue()); ADD_TEST("SetParameterUnit", testSetParameterUnit()); ADD_TEST("SetPrecision", testSetPrecision()); ADD_TEST("CreateStringParameter", testCreateStringParameter()); ADD_TEST("SetStringParameter", testSetStringParameter()); return 0; }
Fix bug with integer truncation in ASSERT_EQUALS
Fix bug with integer truncation in ASSERT_EQUALS
C++
bsd-2-clause
teragonaudio/PluginParameters,teragonaudio/PluginParameters,alessandrostone/PluginParameters,alessandrostone/PluginParameters
82b7e37f6eeb554332b2f0bc30bd218c65281f48
table/table_reader_bench.cc
table/table_reader_bench.cc
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <gflags/gflags.h> #include "rocksdb/db.h" #include "rocksdb/table.h" #include "db/db_impl.h" #include "table/block_based_table_factory.h" #include "util/histogram.h" #include "util/testharness.h" #include "util/testutil.h" namespace rocksdb { // Make a key that i determines the first 4 characters and j determines the // last 4 characters. static std::string MakeKey(int i, int j) { char buf[100]; snprintf(buf, sizeof(buf), "%04d__key___%04d ", i, j); return std::string(buf); } static bool DummySaveValue(void* arg, const Slice& ikey, const Slice& v, bool didIO) { return false; } // A very simple benchmark that. // Create a table with roughly numKey1 * numKey2 keys, // where there are numKey1 prefixes of the key, each has numKey2 number of // distinguished key, differing in the suffix part. // If if_query_empty_keys = false, query the existing keys numKey1 * numKey2 // times randomly. // If if_query_empty_keys = true, query numKey1 * numKey2 random empty keys. // Print out the total time. // // If for_terator=true, instead of just query one key each time, it queries // a range sharing the same prefix. void TableReaderBenchmark(Options& opts, EnvOptions& env_options, ReadOptions& read_options, TableFactory* tf, int num_keys1, int num_keys2, int num_iter, bool if_query_empty_keys, bool for_iterator) { std::string file_name = test::TmpDir() + "/rocksdb_table_reader_benchmark"; ReadOptions ro; unique_ptr<WritableFile> file; Env* env = Env::Default(); env->NewWritableFile(file_name, &file, env_options); TableBuilder* tb = tf->GetTableBuilder(opts, file.get(), CompressionType::kNoCompression); // Populate slightly more than 1M keys for (int i = 0; i < num_keys1; i++) { for (int j = 0; j < num_keys2; j++) { std::string key = MakeKey(i * 2, j); tb->Add(key, key); } } tb->Finish(); file->Close(); unique_ptr<TableReader> table_reader; unique_ptr<RandomAccessFile> raf; Status s = env->NewRandomAccessFile(file_name, &raf, env_options); uint64_t file_size; env->GetFileSize(file_name, &file_size); s = tf->GetTableReader(opts, env_options, std::move(raf), file_size, &table_reader); Random rnd(301); HistogramImpl hist; void* arg = nullptr; for (int it = 0; it < num_iter; it++) { for (int i = 0; i < num_keys1; i++) { for (int j = 0; j < num_keys2; j++) { int r1 = rnd.Uniform(num_keys1) * 2; int r2 = rnd.Uniform(num_keys2); if (!for_iterator) { if (if_query_empty_keys) { r1++; r2 = num_keys2 * 2 - r2; } // Query one existing key; std::string key = MakeKey(r1, r2); uint64_t start_micros = env->NowMicros(); s = table_reader->Get(ro, key, arg, DummySaveValue, nullptr); hist.Add(env->NowMicros() - start_micros); } else { int r2_len = rnd.Uniform(num_keys2) + 1; if (r2_len + r2 > num_keys2) { r2_len = num_keys2 - r2; } std::string start_key = MakeKey(r1, r2); std::string end_key = MakeKey(r1, r2 + r2_len); uint64_t first_part_time = 0; uint64_t start_micros = env->NowMicros(); Iterator* iter = table_reader->NewIterator(read_options); int count = 0; for(iter->Seek(start_key); iter->Valid(); iter->Next()) { // verify key; first_part_time = env->NowMicros() - start_micros; assert(Slice(MakeKey(r1, r2 + count)) == iter->key()); start_micros = env->NowMicros(); if (++count >= r2_len) { break; } } if (count != r2_len) { fprintf( stderr, "Iterator cannot iterate expected number of entries. " "Expected %d but got %d\n", r2_len, count); assert(false); } delete iter; hist.Add(first_part_time + env->NowMicros() - start_micros); } } } } fprintf( stderr, "===================================================" "====================================================\n" "InMemoryTableSimpleBenchmark: %20s num_key1: %5d " "num_key2: %5d %10s\n" "===================================================" "====================================================" "\nHistogram (unit: nanoseconds): \n%s", tf->Name(), num_keys1, num_keys2, for_iterator? "iterator" : (if_query_empty_keys ? "empty" : "non_empty"), hist.ToString().c_str()); env->DeleteFile(file_name); } } // namespace rocksdb DEFINE_bool(query_empty, false, "query non-existing keys instead of existing " "ones."); DEFINE_int32(num_keys1, 4096, "number of distinguish prefix of keys"); DEFINE_int32(num_keys2, 512, "number of distinguish keys for each prefix"); DEFINE_int32(iter, 3, "query non-existing keys instead of existing ones"); DEFINE_bool(iterator, false, "For test iterator"); int main(int argc, char** argv) { google::SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) + " [OPTIONS]..."); google::ParseCommandLineFlags(&argc, &argv, true); rocksdb::TableFactory* tf; rocksdb::Options options; rocksdb::ReadOptions ro; rocksdb::EnvOptions env_options; tf = new rocksdb::BlockBasedTableFactory(); TableReaderBenchmark(options, env_options, ro, tf, FLAGS_num_keys1, FLAGS_num_keys2, FLAGS_iter, FLAGS_query_empty, FLAGS_iterator); delete tf; return 0; }
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <gflags/gflags.h> #include "rocksdb/db.h" #include "rocksdb/table.h" #include "db/db_impl.h" #include "table/block_based_table_factory.h" #include "util/histogram.h" #include "util/testharness.h" #include "util/testutil.h" namespace rocksdb { // Make a key that i determines the first 4 characters and j determines the // last 4 characters. static std::string MakeKey(int i, int j) { char buf[100]; snprintf(buf, sizeof(buf), "%04d__key___%04d ", i, j); return std::string(buf); } static bool DummySaveValue(void* arg, const Slice& ikey, const Slice& v, bool didIO) { return false; } // A very simple benchmark that. // Create a table with roughly numKey1 * numKey2 keys, // where there are numKey1 prefixes of the key, each has numKey2 number of // distinguished key, differing in the suffix part. // If if_query_empty_keys = false, query the existing keys numKey1 * numKey2 // times randomly. // If if_query_empty_keys = true, query numKey1 * numKey2 random empty keys. // Print out the total time. // // If for_terator=true, instead of just query one key each time, it queries // a range sharing the same prefix. void TableReaderBenchmark(Options& opts, EnvOptions& env_options, ReadOptions& read_options, TableFactory* tf, int num_keys1, int num_keys2, int num_iter, bool if_query_empty_keys, bool for_iterator) { std::string file_name = test::TmpDir() + "/rocksdb_table_reader_benchmark"; ReadOptions ro; unique_ptr<WritableFile> file; Env* env = Env::Default(); env->NewWritableFile(file_name, &file, env_options); TableBuilder* tb = tf->GetTableBuilder(opts, file.get(), CompressionType::kNoCompression); // Populate slightly more than 1M keys for (int i = 0; i < num_keys1; i++) { for (int j = 0; j < num_keys2; j++) { std::string key = MakeKey(i * 2, j); tb->Add(key, key); } } tb->Finish(); file->Close(); unique_ptr<TableReader> table_reader; unique_ptr<RandomAccessFile> raf; Status s = env->NewRandomAccessFile(file_name, &raf, env_options); uint64_t file_size; env->GetFileSize(file_name, &file_size); s = tf->GetTableReader(opts, env_options, std::move(raf), file_size, &table_reader); Random rnd(301); HistogramImpl hist; void* arg = nullptr; for (int it = 0; it < num_iter; it++) { for (int i = 0; i < num_keys1; i++) { for (int j = 0; j < num_keys2; j++) { int r1 = rnd.Uniform(num_keys1) * 2; int r2 = rnd.Uniform(num_keys2); if (!for_iterator) { if (if_query_empty_keys) { r1++; r2 = num_keys2 * 2 - r2; } // Query one existing key; std::string key = MakeKey(r1, r2); uint64_t start_micros = env->NowMicros(); s = table_reader->Get(ro, key, arg, DummySaveValue, nullptr); hist.Add(env->NowMicros() - start_micros); } else { int r2_len = rnd.Uniform(num_keys2) + 1; if (r2_len + r2 > num_keys2) { r2_len = num_keys2 - r2; } std::string start_key = MakeKey(r1, r2); std::string end_key = MakeKey(r1, r2 + r2_len); uint64_t total_time = 0; uint64_t start_micros = env->NowMicros(); Iterator* iter = table_reader->NewIterator(read_options); int count = 0; for(iter->Seek(start_key); iter->Valid(); iter->Next()) { // verify key; total_time += env->NowMicros() - start_micros; assert(Slice(MakeKey(r1, r2 + count)) == iter->key()); start_micros = env->NowMicros(); if (++count >= r2_len) { break; } } if (count != r2_len) { fprintf( stderr, "Iterator cannot iterate expected number of entries. " "Expected %d but got %d\n", r2_len, count); assert(false); } delete iter; total_time += env->NowMicros() - start_micros; hist.Add(total_time); } } } } fprintf( stderr, "===================================================" "====================================================\n" "InMemoryTableSimpleBenchmark: %20s num_key1: %5d " "num_key2: %5d %10s\n" "===================================================" "====================================================" "\nHistogram (unit: microseconds): \n%s", tf->Name(), num_keys1, num_keys2, for_iterator? "iterator" : (if_query_empty_keys ? "empty" : "non_empty"), hist.ToString().c_str()); env->DeleteFile(file_name); } } // namespace rocksdb DEFINE_bool(query_empty, false, "query non-existing keys instead of existing " "ones."); DEFINE_int32(num_keys1, 4096, "number of distinguish prefix of keys"); DEFINE_int32(num_keys2, 512, "number of distinguish keys for each prefix"); DEFINE_int32(iter, 3, "query non-existing keys instead of existing ones"); DEFINE_bool(iterator, false, "For test iterator"); int main(int argc, char** argv) { google::SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) + " [OPTIONS]..."); google::ParseCommandLineFlags(&argc, &argv, true); rocksdb::TableFactory* tf; rocksdb::Options options; rocksdb::ReadOptions ro; rocksdb::EnvOptions env_options; tf = new rocksdb::BlockBasedTableFactory(); TableReaderBenchmark(options, env_options, ro, tf, FLAGS_num_keys1, FLAGS_num_keys2, FLAGS_iter, FLAGS_query_empty, FLAGS_iterator); delete tf; return 0; }
Fix a bug of table_reader_bench
Fix a bug of table_reader_bench Summary: Iterator benchmark case is timed incorrectly. Fix it Test Plan: Run the benchmark Reviewers: haobo, dhruba Reviewed By: haobo CC: leveldb Differential Revision: https://reviews.facebook.net/D13845
C++
bsd-3-clause
kaschaeffer/rocksdb,rDSN-Projects/rocksdb.replicated,lgscofield/rocksdb,SunguckLee/RocksDB,skunkwerks/rocksdb,geraldoandradee/rocksdb,vashstorm/rocksdb,geraldoandradee/rocksdb,ylong/rocksdb,kaschaeffer/rocksdb,jalexanderqed/rocksdb,tizzybec/rocksdb,facebook/rocksdb,JohnPJenkins/rocksdb,zhangpng/rocksdb,vmx/rocksdb,NickCis/rocksdb,temicai/rocksdb,kaschaeffer/rocksdb,facebook/rocksdb,Vaisman/rocksdb,Andymic/rocksdb,tsheasha/rocksdb,sorphi/rocksdb,wenduo/rocksdb,ryneli/rocksdb,skunkwerks/rocksdb,tsheasha/rocksdb,wlqGit/rocksdb,caijieming-baidu/rocksdb,vashstorm/rocksdb,JoeWoo/rocksdb,tsheasha/rocksdb,Vaisman/rocksdb,sorphi/rocksdb,vashstorm/rocksdb,jalexanderqed/rocksdb,fengshao0907/rocksdb,tschottdorf/rocksdb,flabby/rocksdb,wenduo/rocksdb,sorphi/rocksdb,wskplho/rocksdb,amyvmiwei/rocksdb,vmx/rocksdb,SunguckLee/RocksDB,kaschaeffer/rocksdb,virtdb/rocksdb,biddyweb/rocksdb,Vaisman/rocksdb,makelivedotnet/rocksdb,caijieming-baidu/rocksdb,wlqGit/rocksdb,virtdb/rocksdb,wenduo/rocksdb,Andymic/rocksdb,skunkwerks/rocksdb,geraldoandradee/rocksdb,dkorolev/rocksdb,tsheasha/rocksdb,JackLian/rocksdb,RyanTech/rocksdb,caijieming-baidu/rocksdb,norton/rocksdb,virtdb/rocksdb,biddyweb/rocksdb,geraldoandradee/rocksdb,wskplho/rocksdb,Applied-Duality/rocksdb,geraldoandradee/rocksdb,IMCG/RcoksDB,wenduo/rocksdb,fengshao0907/rocksdb,anagav/rocksdb,msb-at-yahoo/rocksdb,wat-ze-hex/rocksdb,JoeWoo/rocksdb,ylong/rocksdb,makelivedotnet/rocksdb,rDSN-Projects/rocksdb.replicated,norton/rocksdb,vmx/rocksdb,lgscofield/rocksdb,Applied-Duality/rocksdb,hobinyoon/rocksdb,skunkwerks/rocksdb,flabby/rocksdb,wskplho/rocksdb,tschottdorf/rocksdb,hobinyoon/rocksdb,bbiao/rocksdb,facebook/rocksdb,fengshao0907/rocksdb,bbiao/rocksdb,tizzybec/rocksdb,hobinyoon/rocksdb,rDSN-Projects/rocksdb.replicated,virtdb/rocksdb,makelivedotnet/rocksdb,alihalabyah/rocksdb,tschottdorf/rocksdb,vashstorm/rocksdb,luckywhu/rocksdb,facebook/rocksdb,makelivedotnet/rocksdb,lgscofield/rocksdb,JohnPJenkins/rocksdb,msb-at-yahoo/rocksdb,bbiao/rocksdb,OverlordQ/rocksdb,Applied-Duality/rocksdb,hobinyoon/rocksdb,ylong/rocksdb,tsheasha/rocksdb,vmx/rocksdb,IMCG/RcoksDB,anagav/rocksdb,wenduo/rocksdb,Andymic/rocksdb,msb-at-yahoo/rocksdb,Vaisman/rocksdb,JoeWoo/rocksdb,flabby/rocksdb,ryneli/rocksdb,IMCG/RcoksDB,mbarbon/rocksdb,NickCis/rocksdb,sorphi/rocksdb,wenduo/rocksdb,JoeWoo/rocksdb,JackLian/rocksdb,JackLian/rocksdb,tizzybec/rocksdb,alihalabyah/rocksdb,hobinyoon/rocksdb,dkorolev/rocksdb,JackLian/rocksdb,luckywhu/rocksdb,caijieming-baidu/rocksdb,dkorolev/rocksdb,fengshao0907/rocksdb,amyvmiwei/rocksdb,anagav/rocksdb,norton/rocksdb,SunguckLee/RocksDB,tsheasha/rocksdb,wenduo/rocksdb,kaschaeffer/rocksdb,sorphi/rocksdb,IMCG/RcoksDB,mbarbon/rocksdb,OverlordQ/rocksdb,tizzybec/rocksdb,makelivedotnet/rocksdb,siddhartharay007/rocksdb,mbarbon/rocksdb,hobinyoon/rocksdb,facebook/rocksdb,wat-ze-hex/rocksdb,fengshao0907/rocksdb,caijieming-baidu/rocksdb,tizzybec/rocksdb,JoeWoo/rocksdb,NickCis/rocksdb,dkorolev/rocksdb,wlqGit/rocksdb,SunguckLee/RocksDB,bbiao/rocksdb,dkorolev/rocksdb,geraldoandradee/rocksdb,JohnPJenkins/rocksdb,tizzybec/rocksdb,Andymic/rocksdb,skunkwerks/rocksdb,jalexanderqed/rocksdb,alihalabyah/rocksdb,siddhartharay007/rocksdb,virtdb/rocksdb,fengshao0907/rocksdb,norton/rocksdb,zhangpng/rocksdb,caijieming-baidu/rocksdb,SunguckLee/RocksDB,anagav/rocksdb,siddhartharay007/rocksdb,RyanTech/rocksdb,makelivedotnet/rocksdb,luckywhu/rocksdb,dkorolev/rocksdb,luckywhu/rocksdb,IMCG/RcoksDB,rDSN-Projects/rocksdb.replicated,Andymic/rocksdb,rDSN-Projects/rocksdb.replicated,hobinyoon/rocksdb,zhangpng/rocksdb,temicai/rocksdb,amyvmiwei/rocksdb,ryneli/rocksdb,bbiao/rocksdb,norton/rocksdb,ylong/rocksdb,Applied-Duality/rocksdb,alihalabyah/rocksdb,mbarbon/rocksdb,biddyweb/rocksdb,lgscofield/rocksdb,mbarbon/rocksdb,lgscofield/rocksdb,ryneli/rocksdb,jalexanderqed/rocksdb,zhangpng/rocksdb,jalexanderqed/rocksdb,Andymic/rocksdb,bbiao/rocksdb,Andymic/rocksdb,facebook/rocksdb,flabby/rocksdb,JoeWoo/rocksdb,msb-at-yahoo/rocksdb,ylong/rocksdb,wat-ze-hex/rocksdb,wlqGit/rocksdb,biddyweb/rocksdb,vmx/rocksdb,OverlordQ/rocksdb,sorphi/rocksdb,tschottdorf/rocksdb,ylong/rocksdb,SunguckLee/RocksDB,caijieming-baidu/rocksdb,NickCis/rocksdb,JohnPJenkins/rocksdb,ryneli/rocksdb,RyanTech/rocksdb,jalexanderqed/rocksdb,temicai/rocksdb,amyvmiwei/rocksdb,RyanTech/rocksdb,wat-ze-hex/rocksdb,OverlordQ/rocksdb,alihalabyah/rocksdb,vmx/rocksdb,luckywhu/rocksdb,biddyweb/rocksdb,RyanTech/rocksdb,anagav/rocksdb,tschottdorf/rocksdb,tschottdorf/rocksdb,flabby/rocksdb,JackLian/rocksdb,JohnPJenkins/rocksdb,lgscofield/rocksdb,kaschaeffer/rocksdb,temicai/rocksdb,JackLian/rocksdb,vashstorm/rocksdb,hobinyoon/rocksdb,SunguckLee/RocksDB,bbiao/rocksdb,tsheasha/rocksdb,NickCis/rocksdb,skunkwerks/rocksdb,siddhartharay007/rocksdb,biddyweb/rocksdb,Vaisman/rocksdb,Applied-Duality/rocksdb,siddhartharay007/rocksdb,biddyweb/rocksdb,wat-ze-hex/rocksdb,alihalabyah/rocksdb,amyvmiwei/rocksdb,facebook/rocksdb,JackLian/rocksdb,NickCis/rocksdb,msb-at-yahoo/rocksdb,wskplho/rocksdb,flabby/rocksdb,virtdb/rocksdb,Applied-Duality/rocksdb,zhangpng/rocksdb,NickCis/rocksdb,siddhartharay007/rocksdb,Andymic/rocksdb,tizzybec/rocksdb,tsheasha/rocksdb,facebook/rocksdb,lgscofield/rocksdb,norton/rocksdb,temicai/rocksdb,Applied-Duality/rocksdb,vashstorm/rocksdb,wlqGit/rocksdb,amyvmiwei/rocksdb,temicai/rocksdb,ryneli/rocksdb,kaschaeffer/rocksdb,wat-ze-hex/rocksdb,geraldoandradee/rocksdb,JohnPJenkins/rocksdb,virtdb/rocksdb,temicai/rocksdb,anagav/rocksdb,siddhartharay007/rocksdb,dkorolev/rocksdb,wlqGit/rocksdb,SunguckLee/RocksDB,IMCG/RcoksDB,wlqGit/rocksdb,vashstorm/rocksdb,zhangpng/rocksdb,OverlordQ/rocksdb,flabby/rocksdb,OverlordQ/rocksdb,RyanTech/rocksdb,wat-ze-hex/rocksdb,amyvmiwei/rocksdb,zhangpng/rocksdb,luckywhu/rocksdb,RyanTech/rocksdb,rDSN-Projects/rocksdb.replicated,norton/rocksdb,anagav/rocksdb,JoeWoo/rocksdb,jalexanderqed/rocksdb,alihalabyah/rocksdb,vmx/rocksdb,Vaisman/rocksdb,msb-at-yahoo/rocksdb,wat-ze-hex/rocksdb,ylong/rocksdb,OverlordQ/rocksdb,luckywhu/rocksdb,JohnPJenkins/rocksdb,Vaisman/rocksdb,mbarbon/rocksdb,fengshao0907/rocksdb,rDSN-Projects/rocksdb.replicated,skunkwerks/rocksdb,IMCG/RcoksDB,vmx/rocksdb,sorphi/rocksdb,wskplho/rocksdb,wenduo/rocksdb,makelivedotnet/rocksdb,mbarbon/rocksdb,wskplho/rocksdb,norton/rocksdb,bbiao/rocksdb,wskplho/rocksdb,ryneli/rocksdb
b3aa2603b87cb07a4e5cfce5456c3cd76e2c1095
src/cache.cxx
src/cache.cxx
/* * Generic cache class. * * author: Max Kellermann <[email protected]> */ #include "cache.hxx" #include "hashmap.h" #include "pool.h" #include "cleanup_timer.h" #include "clock.h" #include "util/Cast.hxx" #include <assert.h> #include <time.h> #include <event.h> /* #define ENABLE_EXCESSIVE_CACHE_CHECKS */ struct cache { struct pool *pool; const struct cache_class *cls; size_t max_size, size; struct hashmap *items; /** * A linked list of all cache items, sorted by last_accessed, * newest first. */ struct list_head sorted_items; struct cleanup_timer cleanup_timer; }; static bool cache_expire_callback(void *ctx); struct cache * cache_new(struct pool *pool, const struct cache_class *cls, unsigned hashtable_capacity, size_t max_size) { assert(cls != nullptr); auto cache = NewFromPool<struct cache>(pool); cache->pool = pool; cache->cls = cls; cache->max_size = max_size; cache->size = 0; cache->items = hashmap_new(pool, hashtable_capacity); list_init(&cache->sorted_items); cleanup_timer_init(&cache->cleanup_timer, 60, cache_expire_callback, cache); return cache; } static void cache_check(const struct cache *cache); void cache_close(struct cache *cache) { cleanup_timer_deinit(&cache->cleanup_timer); cache_check(cache); if (cache->cls->destroy != nullptr) { hashmap_rewind(cache->items); const struct hashmap_pair *pair; while ((pair = hashmap_next(cache->items)) != nullptr) { struct cache_item *item = (struct cache_item *)pair->value; assert(item->lock == 0); assert(cache->size >= item->size); cache->size -= item->size; #ifndef NDEBUG list_remove(&item->sorted_siblings); #endif cache->cls->destroy(item); } assert(cache->size == 0); assert(list_empty(&cache->sorted_items)); } } void cache_get_stats(const struct cache *cache, struct cache_stats *data) { data->netto_size = pool_children_netto_size(cache->pool); data->brutto_size = pool_children_brutto_size(cache->pool); } static inline struct cache_item * list_head_to_cache_item(struct list_head *list_head) { return ContainerCast(list_head, struct cache_item, sorted_siblings); } static void cache_check(const struct cache *cache) { #if !defined(NDEBUG) && defined(ENABLE_EXCESSIVE_CACHE_CHECKS) const struct hashmap_pair *pair; size_t size = 0; assert(cache != nullptr); assert(cache->size <= cache->max_size); hashmap_rewind(cache->items); while ((pair = hashmap_next(cache->items)) != nullptr) { struct cache_item *item = pair->value; size += item->size; assert(size <= cache->size); } assert(size == cache->size); #else (void)cache; #endif } static void cache_destroy_item(struct cache *cache, struct cache_item *item) { if (cache->cls->destroy != nullptr) cache->cls->destroy(item); } static void cache_item_removed(struct cache *cache, struct cache_item *item) { assert(cache != nullptr); assert(item != nullptr); assert(item->size > 0); assert(item->lock > 0 || !item->removed); assert(cache->size >= item->size); list_remove(&item->sorted_siblings); cache->size -= item->size; if (item->lock == 0) cache_destroy_item(cache, item); else /* this item is locked - postpone the destroy() call */ item->removed = true; if (cache->size == 0) cleanup_timer_disable(&cache->cleanup_timer); } void cache_flush(struct cache *cache) { struct cache_item *item; cache_check(cache); for (item = (struct cache_item *)cache->sorted_items.next; &item->sorted_siblings != &cache->sorted_items; item = (struct cache_item *)item->sorted_siblings.next) { struct cache_item *item2; hashmap_remove_existing(cache->items, item->key, item); item2 = item; item = (struct cache_item *)item->sorted_siblings.prev; cache_item_removed(cache, item2); } cache_check(cache); } static bool cache_item_validate(const struct cache *cache, struct cache_item *item, unsigned now) { return now < item->expires && (cache->cls->validate == nullptr || cache->cls->validate(item)); } static void cache_refresh_item(struct cache *cache, struct cache_item *item, unsigned now) { item->last_accessed = now; /* move to the front of the linked list */ list_remove(&item->sorted_siblings); list_add(&item->sorted_siblings, &cache->sorted_items); } struct cache_item * cache_get(struct cache *cache, const char *key) { struct cache_item *item = (struct cache_item *) hashmap_get(cache->items, key); if (item == nullptr) return nullptr; const unsigned now = now_s(); if (!cache_item_validate(cache, item, now)) { cache_check(cache); hashmap_remove_existing(cache->items, key, item); cache_item_removed(cache, item); cache_check(cache); return nullptr; } cache_refresh_item(cache, item, now); return item; } struct cache_item * cache_get_match(struct cache *cache, const char *key, bool (*match)(const struct cache_item *, void *), void *ctx) { const unsigned now = now_s(); const struct hashmap_pair *pair = nullptr; while (true) { if (pair != nullptr) { struct cache_item *item = (struct cache_item *)pair->value; if (!cache_item_validate(cache, item, now)) { /* expired cache item: delete it, and re-start the search */ cache_check(cache); hashmap_remove_existing(cache->items, key, item); cache_item_removed(cache, item); cache_check(cache); pair = nullptr; continue; } if (match(item, ctx)) { /* this one matches: return it to the caller */ cache_refresh_item(cache, item, now); return item; } /* find the next cache_item for this key */ pair = hashmap_lookup_next(pair); } else { /* find the first cache_item for this key */ pair = hashmap_lookup_first(cache->items, key); } if (pair == nullptr) /* no match */ return nullptr; }; } static void cache_destroy_oldest_item(struct cache *cache) { struct cache_item *item; if (list_empty(&cache->sorted_items)) return; item = list_head_to_cache_item(cache->sorted_items.prev); cache_check(cache); hashmap_remove_existing(cache->items, item->key, item); cache_item_removed(cache, item); cache_check(cache); } static bool cache_need_room(struct cache *cache, size_t size) { if (size > cache->max_size) return false; while (1) { if (cache->size + size <= cache->max_size) return true; cache_destroy_oldest_item(cache); } } void cache_add(struct cache *cache, const char *key, struct cache_item *item) { /* XXX size constraints */ if (!cache_need_room(cache, item->size)) { if (cache->cls->destroy != nullptr) cache->cls->destroy(item); return; } cache_check(cache); item->key = key; hashmap_add(cache->items, key, item); list_add(&item->sorted_siblings, &cache->sorted_items); cache->size += item->size; item->last_accessed = now_s(); cache_check(cache); cleanup_timer_enable(&cache->cleanup_timer); } void cache_put(struct cache *cache, const char *key, struct cache_item *item) { /* XXX size constraints */ assert(item != nullptr); assert(item->size > 0); assert(item->lock == 0); assert(!item->removed); if (!cache_need_room(cache, item->size)) { if (cache->cls->destroy != nullptr) cache->cls->destroy(item); return; } cache_check(cache); item->key = key; struct cache_item *old = (struct cache_item *) hashmap_set(cache->items, key, item); if (old != nullptr) cache_item_removed(cache, old); cache->size += item->size; item->last_accessed = now_s(); list_add(&item->sorted_siblings, &cache->sorted_items); cache_check(cache); cleanup_timer_enable(&cache->cleanup_timer); } void cache_put_match(struct cache *cache, const char *key, struct cache_item *item, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_item *old = cache_get_match(cache, key, match, ctx); assert(item != nullptr); assert(item->size > 0); assert(item->lock == 0); assert(!item->removed); assert(old == nullptr || !old->removed); if (old != nullptr) cache_remove_item(cache, key, old); cache_add(cache, key, item); } void cache_remove(struct cache *cache, const char *key) { struct cache_item *item; while ((item = (struct cache_item *)hashmap_remove(cache->items, key)) != nullptr) cache_item_removed(cache, item); cache_check(cache); } struct cache_remove_match_data { struct cache *cache; bool (*match)(const struct cache_item *, void *); void *ctx; }; static bool cache_remove_match_callback(void *value, void *ctx) { const struct cache_remove_match_data *data = (const struct cache_remove_match_data *)ctx; struct cache_item *item = (struct cache_item *)value; if (data->match(item, data->ctx)) { cache_item_removed(data->cache, item); return true; } else return false; } void cache_remove_match(struct cache *cache, const char *key, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_remove_match_data data = { .cache = cache, .match = match, .ctx = ctx, }; cache_check(cache); hashmap_remove_match(cache->items, key, cache_remove_match_callback, &data); cache_check(cache); } void cache_remove_item(struct cache *cache, const char *key, struct cache_item *item) { if (item->removed) { /* item has already been removed by somebody else */ assert(item->lock > 0); return; } bool found = hashmap_remove_value(cache->items, key, item); if (!found) { /* the specified item has been removed before */ cache_check(cache); return; } cache_item_removed(cache, item); cache_check(cache); } struct cache_remove_all_match_data { struct cache *cache; bool (*match)(const struct cache_item *, void *); void *ctx; }; static bool cache_remove_all_match_callback(gcc_unused const char *key, void *value, void *ctx) { const struct cache_remove_all_match_data *data = (const struct cache_remove_all_match_data *)ctx; struct cache_item *item = (struct cache_item *)value; if (data->match(item, data->ctx)) { cache_item_removed(data->cache, item); return true; } else return false; } unsigned cache_remove_all_match(struct cache *cache, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_remove_all_match_data data = { .cache = cache, .match = match, .ctx = ctx, }; unsigned removed; cache_check(cache); removed = hashmap_remove_all_match(cache->items, cache_remove_all_match_callback, &data); cache_check(cache); return removed; } void cache_item_init_absolute(struct cache_item *item, time_t expires, size_t size) { time_t now = time(nullptr); unsigned monotonic_expires = expires > now ? now_s() + (expires - now) : 1; cache_item_init(item, monotonic_expires, size); } void cache_item_init_relative(struct cache_item *item, unsigned max_age, size_t size) { cache_item_init(item, now_s() + max_age, size); } void cache_item_lock(struct cache_item *item) { assert(item != nullptr); ++item->lock; } void cache_item_unlock(struct cache *cache, struct cache_item *item) { assert(item != nullptr); assert(item->lock > 0); if (--item->lock == 0 && item->removed) /* postponed destroy */ cache_destroy_item(cache, item); } /** clean up expired cache items every 60 seconds */ static bool cache_expire_callback(void *ctx) { struct cache *cache = (struct cache *)ctx; struct cache_item *item; const unsigned now = now_s(); cache_check(cache); for (item = (struct cache_item *)cache->sorted_items.next; &item->sorted_siblings != &cache->sorted_items; item = (struct cache_item *)item->sorted_siblings.next) { struct cache_item *item2; if (item->expires > now) /* not yet expired */ continue; hashmap_remove_existing(cache->items, item->key, item); item2 = item; item = (struct cache_item *)item->sorted_siblings.prev; cache_item_removed(cache, item2); } cache_check(cache); return cache->size > 0; } void cache_event_add(struct cache *cache) { if (cache->size > 0) cleanup_timer_enable(&cache->cleanup_timer); } void cache_event_del(struct cache *cache) { cleanup_timer_disable(&cache->cleanup_timer); }
/* * Generic cache class. * * author: Max Kellermann <[email protected]> */ #include "cache.hxx" #include "hashmap.h" #include "pool.h" #include "cleanup_timer.h" #include "clock.h" #include "util/Cast.hxx" #include <assert.h> #include <time.h> #include <event.h> /* #define ENABLE_EXCESSIVE_CACHE_CHECKS */ struct cache { struct pool &pool; const struct cache_class &cls; const size_t max_size; size_t size; struct hashmap *const items; /** * A linked list of all cache items, sorted by last_accessed, * newest first. */ struct list_head sorted_items; struct cleanup_timer cleanup_timer; cache(struct pool &_pool, const struct cache_class &_cls, unsigned hashtable_capacity, size_t _max_size) :pool(_pool), cls(_cls), max_size(_max_size), size(0), items(hashmap_new(&_pool, hashtable_capacity)) { list_init(&sorted_items); cleanup_timer_init(&cleanup_timer, 60, ExpireCallback, this); } ~cache(); void Delete() { DeleteFromPool(&pool, this); } static bool ExpireCallback(void *ctx); void Check() const; void ItemRemoved(struct cache_item *item); }; struct cache * cache_new(struct pool *pool, const struct cache_class *cls, unsigned hashtable_capacity, size_t max_size) { assert(cls != nullptr); return NewFromPool<struct cache>(pool, *pool, *cls, hashtable_capacity, max_size); } inline cache::~cache() { cleanup_timer_deinit(&cleanup_timer); Check(); if (cls.destroy != nullptr) { hashmap_rewind(items); const struct hashmap_pair *pair; while ((pair = hashmap_next(items)) != nullptr) { struct cache_item *item = (struct cache_item *)pair->value; assert(item->lock == 0); assert(size >= item->size); size -= item->size; #ifndef NDEBUG list_remove(&item->sorted_siblings); #endif cls.destroy(item); } assert(size == 0); assert(list_empty(&sorted_items)); } } void cache_close(struct cache *cache) { cache->Delete(); } void cache_get_stats(const struct cache *cache, struct cache_stats *data) { data->netto_size = pool_children_netto_size(&cache->pool); data->brutto_size = pool_children_brutto_size(&cache->pool); } static inline struct cache_item * list_head_to_cache_item(struct list_head *list_head) { return ContainerCast(list_head, struct cache_item, sorted_siblings); } inline void cache::Check() const { #if !defined(NDEBUG) && defined(ENABLE_EXCESSIVE_CACHE_CHECKS) const struct hashmap_pair *pair; size_t s = 0; assert(size <= max_size); hashmap_rewind(items); while ((pair = hashmap_next(items)) != nullptr) { struct cache_item *item = (struct cache_item *)pair->value; s += item->size; assert(s <= size); } assert(s == size); #endif } static void cache_destroy_item(struct cache *cache, struct cache_item *item) { if (cache->cls.destroy != nullptr) cache->cls.destroy(item); } void cache::ItemRemoved(struct cache_item *item) { assert(item != nullptr); assert(item->size > 0); assert(item->lock > 0 || !item->removed); assert(size >= item->size); list_remove(&item->sorted_siblings); size -= item->size; if (item->lock == 0) cache_destroy_item(this, item); else /* this item is locked - postpone the destroy() call */ item->removed = true; if (size == 0) cleanup_timer_disable(&cleanup_timer); } void cache_flush(struct cache *cache) { struct cache_item *item; cache->Check(); for (item = (struct cache_item *)cache->sorted_items.next; &item->sorted_siblings != &cache->sorted_items; item = (struct cache_item *)item->sorted_siblings.next) { struct cache_item *item2; hashmap_remove_existing(cache->items, item->key, item); item2 = item; item = (struct cache_item *)item->sorted_siblings.prev; cache->ItemRemoved(item2); } cache->Check(); } static bool cache_item_validate(const struct cache *cache, struct cache_item *item, unsigned now) { return now < item->expires && (cache->cls.validate == nullptr || cache->cls.validate(item)); } static void cache_refresh_item(struct cache *cache, struct cache_item *item, unsigned now) { item->last_accessed = now; /* move to the front of the linked list */ list_remove(&item->sorted_siblings); list_add(&item->sorted_siblings, &cache->sorted_items); } struct cache_item * cache_get(struct cache *cache, const char *key) { struct cache_item *item = (struct cache_item *) hashmap_get(cache->items, key); if (item == nullptr) return nullptr; const unsigned now = now_s(); if (!cache_item_validate(cache, item, now)) { cache->Check(); hashmap_remove_existing(cache->items, key, item); cache->ItemRemoved(item); cache->Check(); return nullptr; } cache_refresh_item(cache, item, now); return item; } struct cache_item * cache_get_match(struct cache *cache, const char *key, bool (*match)(const struct cache_item *, void *), void *ctx) { const unsigned now = now_s(); const struct hashmap_pair *pair = nullptr; while (true) { if (pair != nullptr) { struct cache_item *item = (struct cache_item *)pair->value; if (!cache_item_validate(cache, item, now)) { /* expired cache item: delete it, and re-start the search */ cache->Check(); hashmap_remove_existing(cache->items, key, item); cache->ItemRemoved(item); cache->Check(); pair = nullptr; continue; } if (match(item, ctx)) { /* this one matches: return it to the caller */ cache_refresh_item(cache, item, now); return item; } /* find the next cache_item for this key */ pair = hashmap_lookup_next(pair); } else { /* find the first cache_item for this key */ pair = hashmap_lookup_first(cache->items, key); } if (pair == nullptr) /* no match */ return nullptr; }; } static void cache_destroy_oldest_item(struct cache *cache) { struct cache_item *item; if (list_empty(&cache->sorted_items)) return; item = list_head_to_cache_item(cache->sorted_items.prev); cache->Check(); hashmap_remove_existing(cache->items, item->key, item); cache->ItemRemoved(item); cache->Check(); } static bool cache_need_room(struct cache *cache, size_t size) { if (size > cache->max_size) return false; while (1) { if (cache->size + size <= cache->max_size) return true; cache_destroy_oldest_item(cache); } } void cache_add(struct cache *cache, const char *key, struct cache_item *item) { /* XXX size constraints */ if (!cache_need_room(cache, item->size)) { if (cache->cls.destroy != nullptr) cache->cls.destroy(item); return; } cache->Check(); item->key = key; hashmap_add(cache->items, key, item); list_add(&item->sorted_siblings, &cache->sorted_items); cache->size += item->size; item->last_accessed = now_s(); cache->Check(); cleanup_timer_enable(&cache->cleanup_timer); } void cache_put(struct cache *cache, const char *key, struct cache_item *item) { /* XXX size constraints */ assert(item != nullptr); assert(item->size > 0); assert(item->lock == 0); assert(!item->removed); if (!cache_need_room(cache, item->size)) { if (cache->cls.destroy != nullptr) cache->cls.destroy(item); return; } cache->Check(); item->key = key; struct cache_item *old = (struct cache_item *) hashmap_set(cache->items, key, item); if (old != nullptr) cache->ItemRemoved(old); cache->size += item->size; item->last_accessed = now_s(); list_add(&item->sorted_siblings, &cache->sorted_items); cache->Check(); cleanup_timer_enable(&cache->cleanup_timer); } void cache_put_match(struct cache *cache, const char *key, struct cache_item *item, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_item *old = cache_get_match(cache, key, match, ctx); assert(item != nullptr); assert(item->size > 0); assert(item->lock == 0); assert(!item->removed); assert(old == nullptr || !old->removed); if (old != nullptr) cache_remove_item(cache, key, old); cache_add(cache, key, item); } void cache_remove(struct cache *cache, const char *key) { struct cache_item *item; while ((item = (struct cache_item *)hashmap_remove(cache->items, key)) != nullptr) cache->ItemRemoved(item); cache->Check(); } struct cache_remove_match_data { struct cache *cache; bool (*match)(const struct cache_item *, void *); void *ctx; }; static bool cache_remove_match_callback(void *value, void *ctx) { const struct cache_remove_match_data *data = (const struct cache_remove_match_data *)ctx; struct cache_item *item = (struct cache_item *)value; if (data->match(item, data->ctx)) { data->cache->ItemRemoved(item); return true; } else return false; } void cache_remove_match(struct cache *cache, const char *key, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_remove_match_data data = { .cache = cache, .match = match, .ctx = ctx, }; cache->Check(); hashmap_remove_match(cache->items, key, cache_remove_match_callback, &data); cache->Check(); } void cache_remove_item(struct cache *cache, const char *key, struct cache_item *item) { if (item->removed) { /* item has already been removed by somebody else */ assert(item->lock > 0); return; } bool found = hashmap_remove_value(cache->items, key, item); if (!found) { /* the specified item has been removed before */ cache->Check(); return; } cache->ItemRemoved(item); cache->Check(); } struct cache_remove_all_match_data { struct cache *cache; bool (*match)(const struct cache_item *, void *); void *ctx; }; static bool cache_remove_all_match_callback(gcc_unused const char *key, void *value, void *ctx) { const struct cache_remove_all_match_data *data = (const struct cache_remove_all_match_data *)ctx; struct cache_item *item = (struct cache_item *)value; if (data->match(item, data->ctx)) { data->cache->ItemRemoved(item); return true; } else return false; } unsigned cache_remove_all_match(struct cache *cache, bool (*match)(const struct cache_item *, void *), void *ctx) { struct cache_remove_all_match_data data = { .cache = cache, .match = match, .ctx = ctx, }; unsigned removed; cache->Check(); removed = hashmap_remove_all_match(cache->items, cache_remove_all_match_callback, &data); cache->Check(); return removed; } void cache_item_init_absolute(struct cache_item *item, time_t expires, size_t size) { time_t now = time(nullptr); unsigned monotonic_expires = expires > now ? now_s() + (expires - now) : 1; cache_item_init(item, monotonic_expires, size); } void cache_item_init_relative(struct cache_item *item, unsigned max_age, size_t size) { cache_item_init(item, now_s() + max_age, size); } void cache_item_lock(struct cache_item *item) { assert(item != nullptr); ++item->lock; } void cache_item_unlock(struct cache *cache, struct cache_item *item) { assert(item != nullptr); assert(item->lock > 0); if (--item->lock == 0 && item->removed) /* postponed destroy */ cache_destroy_item(cache, item); } /** clean up expired cache items every 60 seconds */ bool cache::ExpireCallback(void *ctx) { struct cache *cache = (struct cache *)ctx; struct cache_item *item; const unsigned now = now_s(); cache->Check(); for (item = (struct cache_item *)cache->sorted_items.next; &item->sorted_siblings != &cache->sorted_items; item = (struct cache_item *)item->sorted_siblings.next) { struct cache_item *item2; if (item->expires > now) /* not yet expired */ continue; hashmap_remove_existing(cache->items, item->key, item); item2 = item; item = (struct cache_item *)item->sorted_siblings.prev; cache->ItemRemoved(item2); } cache->Check(); return cache->size > 0; } void cache_event_add(struct cache *cache) { if (cache->size > 0) cleanup_timer_enable(&cache->cleanup_timer); } void cache_event_del(struct cache *cache) { cleanup_timer_disable(&cache->cleanup_timer); }
add constructor and other methods
cache: add constructor and other methods
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
3d6b3fde33ca111145f07acefc1232a674ec6b91
test/functional/printTest.cpp
test/functional/printTest.cpp
#include "bandit/bandit.h" #include "print.h" #include <sstream> using namespace bandit; using StreamT = std::ostringstream; go_bandit([](){ describe("print function", [&]() { const char* hello_world = "Hello world."; it("should prints non-args format message.", [&]() { StreamT out; print(out, "Hello world."); AssertThat(out.str(), Equals(hello_world)); }); it("should prints 1-arg message with a string.", [&]() { StreamT out; print(out, "Hello %."); AssertThat(out.str(), Equals(hello_world)); }); }); });
#include "../bandit_base.h" #include "print.h" #include <sstream> go_bandit([](){ describe("print function", [&]() { std::ostringstream out; before_each([&]() { out.str(""); out.clear(); }); it("prints simple message.", [&]() { print(out, "Hello world."); AssertThat(out.str(), Equals("Hello world.")); }); it("prints message with c strings", [&]() { print(out, "My name is %s. My cat's name is %s.", "OT", "Nini"); AssertThat(out.str(), Equals("My name is OT. My cat's name is Nini.")); }); it("prints message with numbers", [&]() { print(out, "%d + %d = %d", 5, 5, 10); AssertThat(out.str(), Equals("5 + 5 = 10")); }); it("prints message with floating numbers", [&]() { print(out, "The pi is %f. The half is %f.", 3.14, 0.5); AssertThat(out.str(), Equals("The pi is 3.14. The half is 0.5.")); }); it("prints message with mixed arguments.", [&]() { before_each([&]() { out.str(""); out.clear(); }); it("prints weather reports.", [&]() { print(out, "%s! Today is %d/%d. Current degree is %f C.", "Good morning", 12, 8, 24.5); AssertThat(out.str(), Equals("Good morning! Today is 12/8. Current degree is 24.5 C.")); }); it("prints bills", [&]() { print(out, "I have %d %s. It cost me %d dollars.", 3, "apples", 75); AssertThat(out.str(), Equals("I have 3 apples. It cost me 75 dollars.")); }); }); it("prints message with escape arguments %%", [&]() { before_each([&]() { out.str(""); out.clear(); }); it("prints memory usage info", [&]() { print(out, "Memery Usage: %f%%.", 20.8); AssertThat(out.str(), Equals("Memory Usage: 20.8%.")); }); it("prints sentence 4", [&]() { print(out, "%f%% %s juice.", 100.0, "orange"); AssertThat(out.str(), Equals("100.0% orange juice.")); }); }); }); });
add more behavior test for print function
add more behavior test for print function
C++
apache-2.0
ot32em/print
991f47a159f0e169883f06686f13c31688fa2bf0
src/common.cc
src/common.cc
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <[email protected]> #include <stdlib.h> // for getenv and strtol #include "config.h" #include "common.h" #include "system-alloc.h" #include "base/spinlock.h" #include "getenv_safe.h" // TCMallocGetenvSafe namespace tcmalloc { // Define the maximum number of object per classe type to transfer between // thread and central caches. static int32 FLAGS_tcmalloc_transfer_num_objects; static const int32 kDefaultTransferNumObjecs = 512; // The init function is provided to explicit initialize the variable value // from the env. var to avoid C++ global construction that might defer its // initialization after a malloc/new call. static inline void InitTCMallocTransferNumObjects() { if (FLAGS_tcmalloc_transfer_num_objects == 0) { const char *envval = TCMallocGetenvSafe("TCMALLOC_TRANSFER_NUM_OBJ"); FLAGS_tcmalloc_transfer_num_objects = !envval ? kDefaultTransferNumObjecs : strtol(envval, NULL, 10); } } // Note: the following only works for "n"s that fit in 32-bits, but // that is fine since we only use it for small sizes. static inline int LgFloor(size_t n) { int log = 0; for (int i = 4; i >= 0; --i) { int shift = (1 << i); size_t x = n >> shift; if (x != 0) { n = x; log += shift; } } ASSERT(n == 1); return log; } int AlignmentForSize(size_t size) { int alignment = kAlignment; if (size > kMaxSize) { // Cap alignment at kPageSize for large sizes. alignment = kPageSize; } else if (size >= 128) { // Space wasted due to alignment is at most 1/8, i.e., 12.5%. alignment = (1 << LgFloor(size)) / 8; } else if (size >= kMinAlign) { // We need an alignment of at least 16 bytes to satisfy // requirements for some SSE types. alignment = kMinAlign; } // Maximum alignment allowed is page size alignment. if (alignment > kPageSize) { alignment = kPageSize; } CHECK_CONDITION(size < kMinAlign || alignment >= kMinAlign); CHECK_CONDITION((alignment & (alignment - 1)) == 0); return alignment; } int SizeMap::NumMoveSize(size_t size) { if (size == 0) return 0; // Use approx 64k transfers between thread and central caches. int num = static_cast<int>(64.0 * 1024.0 / size); if (num < 2) num = 2; // Avoid bringing too many objects into small object free lists. // If this value is too large: // - We waste memory with extra objects sitting in the thread caches. // - The central freelist holds its lock for too long while // building a linked list of objects, slowing down the allocations // of other threads. // If this value is too small: // - We go to the central freelist too often and we have to acquire // its lock each time. // This value strikes a balance between the constraints above. if (num > FLAGS_tcmalloc_transfer_num_objects) num = FLAGS_tcmalloc_transfer_num_objects; return num; } // Initialize the mapping arrays void SizeMap::Init() { InitTCMallocTransferNumObjects(); // Do some sanity checking on add_amount[]/shift_amount[]/class_array[] if (ClassIndex(0) != 0) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for size 0", ClassIndex(0)); } if (ClassIndex(kMaxSize) >= sizeof(class_array_)) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for kMaxSize", ClassIndex(kMaxSize)); } // Compute the size classes we want to use int sc = 1; // Next size class to assign int alignment = kAlignment; CHECK_CONDITION(kAlignment <= kMinAlign); for (size_t size = kAlignment; size <= kMaxSize; size += alignment) { alignment = AlignmentForSize(size); CHECK_CONDITION((size % alignment) == 0); int blocks_to_move = NumMoveSize(size) / 4; size_t psize = 0; do { psize += kPageSize; // Allocate enough pages so leftover is less than 1/8 of total. // This bounds wasted space to at most 12.5%. while ((psize % size) > (psize >> 3)) { psize += kPageSize; } // Continue to add pages until there are at least as many objects in // the span as are needed when moving objects from the central // freelists and spans to the thread caches. } while ((psize / size) < (blocks_to_move)); const size_t my_pages = psize >> kPageShift; if (sc > 1 && my_pages == class_to_pages_[sc-1]) { // See if we can merge this into the previous class without // increasing the fragmentation of the previous class. const size_t my_objects = (my_pages << kPageShift) / size; const size_t prev_objects = (class_to_pages_[sc-1] << kPageShift) / class_to_size_[sc-1]; if (my_objects == prev_objects) { // Adjust last class to include this size class_to_size_[sc-1] = size; continue; } } // Add new class class_to_pages_[sc] = my_pages; class_to_size_[sc] = size; sc++; } num_size_classes = sc; if (sc > kClassSizesMax) { Log(kCrash, __FILE__, __LINE__, "too many size classes: (found vs. max)", sc, kClassSizesMax); } // Initialize the mapping arrays int next_size = 0; for (int c = 1; c < num_size_classes; c++) { const int max_size_in_class = class_to_size_[c]; for (int s = next_size; s <= max_size_in_class; s += kAlignment) { class_array_[ClassIndex(s)] = c; } next_size = max_size_in_class + kAlignment; } // Double-check sizes just to be safe for (size_t size = 0; size <= kMaxSize;) { const int sc = SizeClass(size); if (sc <= 0 || sc >= num_size_classes) { Log(kCrash, __FILE__, __LINE__, "Bad size class (class, size)", sc, size); } if (sc > 1 && size <= class_to_size_[sc-1]) { Log(kCrash, __FILE__, __LINE__, "Allocating unnecessarily large class (class, size)", sc, size); } const size_t s = class_to_size_[sc]; if (size > s || s == 0) { Log(kCrash, __FILE__, __LINE__, "Bad (class, size, requested)", sc, s, size); } if (size <= kMaxSmallSize) { size += 8; } else { size += 128; } } // Initialize the num_objects_to_move array. for (size_t cl = 1; cl < num_size_classes; ++cl) { num_objects_to_move_[cl] = NumMoveSize(ByteSizeForClass(cl)); } } // Metadata allocator -- keeps stats about how many bytes allocated. static uint64_t metadata_system_bytes_ = 0; static const size_t kMetadataAllocChunkSize = 8*1024*1024; // As ThreadCache objects are allocated with MetaDataAlloc, and also // CACHELINE_ALIGNED, we must use the same alignment as TCMalloc_SystemAlloc. static const size_t kMetadataAllignment = sizeof(MemoryAligner); static char *metadata_chunk_alloc_; static size_t metadata_chunk_avail_; static SpinLock metadata_alloc_lock(SpinLock::LINKER_INITIALIZED); void* MetaDataAlloc(size_t bytes) { if (bytes >= kMetadataAllocChunkSize) { void *rv = TCMalloc_SystemAlloc(bytes, NULL, kMetadataAllignment); if (rv != NULL) { metadata_system_bytes_ += bytes; } return rv; } SpinLockHolder h(&metadata_alloc_lock); // the following works by essentially turning address to integer of // log_2 kMetadataAllignment size and negating it. I.e. negated // value + original value gets 0 and that's what we want modulo // kMetadataAllignment. Note, we negate before masking higher bits // off, otherwise we'd have to mask them off after negation anyways. intptr_t alignment = -reinterpret_cast<intptr_t>(metadata_chunk_alloc_) & (kMetadataAllignment-1); if (metadata_chunk_avail_ < bytes + alignment) { size_t real_size; void *ptr = TCMalloc_SystemAlloc(kMetadataAllocChunkSize, &real_size, kMetadataAllignment); if (ptr == NULL) { return NULL; } metadata_chunk_alloc_ = static_cast<char *>(ptr); metadata_chunk_avail_ = real_size; alignment = 0; } void *rv = static_cast<void *>(metadata_chunk_alloc_ + alignment); bytes += alignment; metadata_chunk_alloc_ += bytes; metadata_chunk_avail_ -= bytes; metadata_system_bytes_ += bytes; return rv; } uint64_t metadata_system_bytes() { return metadata_system_bytes_; } } // namespace tcmalloc
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Sanjay Ghemawat <[email protected]> #include <stdlib.h> // for getenv and strtol #include "config.h" #include "common.h" #include "system-alloc.h" #include "base/spinlock.h" #include "getenv_safe.h" // TCMallocGetenvSafe namespace tcmalloc { // Define the maximum number of object per classe type to transfer between // thread and central caches. static int32 FLAGS_tcmalloc_transfer_num_objects; static const int32 kDefaultTransferNumObjecs = 32; // The init function is provided to explicit initialize the variable value // from the env. var to avoid C++ global construction that might defer its // initialization after a malloc/new call. static inline void InitTCMallocTransferNumObjects() { if (FLAGS_tcmalloc_transfer_num_objects == 0) { const char *envval = TCMallocGetenvSafe("TCMALLOC_TRANSFER_NUM_OBJ"); FLAGS_tcmalloc_transfer_num_objects = !envval ? kDefaultTransferNumObjecs : strtol(envval, NULL, 10); } } // Note: the following only works for "n"s that fit in 32-bits, but // that is fine since we only use it for small sizes. static inline int LgFloor(size_t n) { int log = 0; for (int i = 4; i >= 0; --i) { int shift = (1 << i); size_t x = n >> shift; if (x != 0) { n = x; log += shift; } } ASSERT(n == 1); return log; } int AlignmentForSize(size_t size) { int alignment = kAlignment; if (size > kMaxSize) { // Cap alignment at kPageSize for large sizes. alignment = kPageSize; } else if (size >= 128) { // Space wasted due to alignment is at most 1/8, i.e., 12.5%. alignment = (1 << LgFloor(size)) / 8; } else if (size >= kMinAlign) { // We need an alignment of at least 16 bytes to satisfy // requirements for some SSE types. alignment = kMinAlign; } // Maximum alignment allowed is page size alignment. if (alignment > kPageSize) { alignment = kPageSize; } CHECK_CONDITION(size < kMinAlign || alignment >= kMinAlign); CHECK_CONDITION((alignment & (alignment - 1)) == 0); return alignment; } int SizeMap::NumMoveSize(size_t size) { if (size == 0) return 0; // Use approx 64k transfers between thread and central caches. int num = static_cast<int>(64.0 * 1024.0 / size); if (num < 2) num = 2; // Avoid bringing too many objects into small object free lists. // If this value is too large: // - We waste memory with extra objects sitting in the thread caches. // - The central freelist holds its lock for too long while // building a linked list of objects, slowing down the allocations // of other threads. // If this value is too small: // - We go to the central freelist too often and we have to acquire // its lock each time. // This value strikes a balance between the constraints above. if (num > FLAGS_tcmalloc_transfer_num_objects) num = FLAGS_tcmalloc_transfer_num_objects; return num; } // Initialize the mapping arrays void SizeMap::Init() { InitTCMallocTransferNumObjects(); // Do some sanity checking on add_amount[]/shift_amount[]/class_array[] if (ClassIndex(0) != 0) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for size 0", ClassIndex(0)); } if (ClassIndex(kMaxSize) >= sizeof(class_array_)) { Log(kCrash, __FILE__, __LINE__, "Invalid class index for kMaxSize", ClassIndex(kMaxSize)); } // Compute the size classes we want to use int sc = 1; // Next size class to assign int alignment = kAlignment; CHECK_CONDITION(kAlignment <= kMinAlign); for (size_t size = kAlignment; size <= kMaxSize; size += alignment) { alignment = AlignmentForSize(size); CHECK_CONDITION((size % alignment) == 0); int blocks_to_move = NumMoveSize(size) / 4; size_t psize = 0; do { psize += kPageSize; // Allocate enough pages so leftover is less than 1/8 of total. // This bounds wasted space to at most 12.5%. while ((psize % size) > (psize >> 3)) { psize += kPageSize; } // Continue to add pages until there are at least as many objects in // the span as are needed when moving objects from the central // freelists and spans to the thread caches. } while ((psize / size) < (blocks_to_move)); const size_t my_pages = psize >> kPageShift; if (sc > 1 && my_pages == class_to_pages_[sc-1]) { // See if we can merge this into the previous class without // increasing the fragmentation of the previous class. const size_t my_objects = (my_pages << kPageShift) / size; const size_t prev_objects = (class_to_pages_[sc-1] << kPageShift) / class_to_size_[sc-1]; if (my_objects == prev_objects) { // Adjust last class to include this size class_to_size_[sc-1] = size; continue; } } // Add new class class_to_pages_[sc] = my_pages; class_to_size_[sc] = size; sc++; } num_size_classes = sc; if (sc > kClassSizesMax) { Log(kCrash, __FILE__, __LINE__, "too many size classes: (found vs. max)", sc, kClassSizesMax); } // Initialize the mapping arrays int next_size = 0; for (int c = 1; c < num_size_classes; c++) { const int max_size_in_class = class_to_size_[c]; for (int s = next_size; s <= max_size_in_class; s += kAlignment) { class_array_[ClassIndex(s)] = c; } next_size = max_size_in_class + kAlignment; } // Double-check sizes just to be safe for (size_t size = 0; size <= kMaxSize;) { const int sc = SizeClass(size); if (sc <= 0 || sc >= num_size_classes) { Log(kCrash, __FILE__, __LINE__, "Bad size class (class, size)", sc, size); } if (sc > 1 && size <= class_to_size_[sc-1]) { Log(kCrash, __FILE__, __LINE__, "Allocating unnecessarily large class (class, size)", sc, size); } const size_t s = class_to_size_[sc]; if (size > s || s == 0) { Log(kCrash, __FILE__, __LINE__, "Bad (class, size, requested)", sc, s, size); } if (size <= kMaxSmallSize) { size += 8; } else { size += 128; } } // Initialize the num_objects_to_move array. for (size_t cl = 1; cl < num_size_classes; ++cl) { num_objects_to_move_[cl] = NumMoveSize(ByteSizeForClass(cl)); } } // Metadata allocator -- keeps stats about how many bytes allocated. static uint64_t metadata_system_bytes_ = 0; static const size_t kMetadataAllocChunkSize = 8*1024*1024; // As ThreadCache objects are allocated with MetaDataAlloc, and also // CACHELINE_ALIGNED, we must use the same alignment as TCMalloc_SystemAlloc. static const size_t kMetadataAllignment = sizeof(MemoryAligner); static char *metadata_chunk_alloc_; static size_t metadata_chunk_avail_; static SpinLock metadata_alloc_lock(SpinLock::LINKER_INITIALIZED); void* MetaDataAlloc(size_t bytes) { if (bytes >= kMetadataAllocChunkSize) { void *rv = TCMalloc_SystemAlloc(bytes, NULL, kMetadataAllignment); if (rv != NULL) { metadata_system_bytes_ += bytes; } return rv; } SpinLockHolder h(&metadata_alloc_lock); // the following works by essentially turning address to integer of // log_2 kMetadataAllignment size and negating it. I.e. negated // value + original value gets 0 and that's what we want modulo // kMetadataAllignment. Note, we negate before masking higher bits // off, otherwise we'd have to mask them off after negation anyways. intptr_t alignment = -reinterpret_cast<intptr_t>(metadata_chunk_alloc_) & (kMetadataAllignment-1); if (metadata_chunk_avail_ < bytes + alignment) { size_t real_size; void *ptr = TCMalloc_SystemAlloc(kMetadataAllocChunkSize, &real_size, kMetadataAllignment); if (ptr == NULL) { return NULL; } metadata_chunk_alloc_ = static_cast<char *>(ptr); metadata_chunk_avail_ = real_size; alignment = 0; } void *rv = static_cast<void *>(metadata_chunk_alloc_ + alignment); bytes += alignment; metadata_chunk_alloc_ += bytes; metadata_chunk_avail_ -= bytes; metadata_system_bytes_ += bytes; return rv; } uint64_t metadata_system_bytes() { return metadata_system_bytes_; } } // namespace tcmalloc
change default transfer batch back to 32
change default transfer batch back to 32 Some tensorflow benchmarks are seeing large regression with elevated values. So lets stick to old safe default until we understand how to make larger values work for all workloads.
C++
bsd-3-clause
alk/gperftools,romange/gperftools,acmorrow/gperftools,alk/gperftools,gperftools/gperftools,rzinsly/gperftools,romange/gperftools,rzinsly/gperftools,xiaoyur347/gperftools,rzinsly/gperftools,acmorrow/gperftools,acmorrow/gperftools,romange/gperftools,xiaoyur347/gperftools,acmorrow/gperftools,gperftools/gperftools,rzinsly/gperftools,gperftools/gperftools,xiaoyur347/gperftools,gperftools/gperftools,alk/gperftools,romange/gperftools,alk/gperftools,xiaoyur347/gperftools